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 'uid' => intval($uinfo[0]['uid']),
544 'cid' => intval($uinfo[0]['cid']),
545 'self' => $uinfo[0]['self'],
546 'network' => $uinfo[0]['network'],
553 function api_item_get_user(&$a, $item) {
555 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
556 dbesc(normalise_link($item['author-link'])));
558 if (count($author) == 0) {
559 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
560 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
562 $author = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
563 dbesc(normalise_link($item['author-link'])));
564 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
565 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
566 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
567 dbesc(normalise_link($item["author-link"])));
570 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
571 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
572 dbesc(normalise_link($item["author-link"])));
575 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
576 dbesc(normalise_link($item['owner-link'])));
578 if (count($owner) == 0) {
579 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
580 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
582 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
583 dbesc(normalise_link($item['owner-link'])));
584 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
585 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
586 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
587 dbesc(normalise_link($item["owner-link"])));
590 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
591 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
592 dbesc(normalise_link($item["owner-link"])));
595 // Comments in threads may appear as wall-to-wall postings.
596 // So only take the owner at the top posting.
597 if ($item["id"] == $item["parent"])
598 $status_user = api_get_user($a,$item["owner-link"]);
600 $status_user = api_get_user($a,$item["author-link"]);
602 $status_user["protected"] = (($item["allow_cid"] != "") OR
603 ($item["allow_gid"] != "") OR
604 ($item["deny_cid"] != "") OR
605 ($item["deny_gid"] != "") OR
608 return ($status_user);
613 * load api $templatename for $type and replace $data array
615 function api_apply_template($templatename, $type, $data){
623 $data = array_xmlify($data);
624 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
626 header ("Content-Type: text/xml");
627 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
630 $ret = replace_macros($tpl, $data);
645 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
646 * returns a 401 status code and an error message if not.
647 * http://developer.twitter.com/doc/get/account/verify_credentials
649 function api_account_verify_credentials(&$a, $type){
650 if (api_user()===false) return false;
652 unset($_REQUEST["user_id"]);
653 unset($_GET["user_id"]);
655 unset($_REQUEST["screen_name"]);
656 unset($_GET["screen_name"]);
658 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
660 $user_info = api_get_user($a);
662 // "verified" isn't used here in the standard
663 unset($user_info["verified"]);
665 // - Adding last status
667 $user_info["status"] = api_status_show($a,"raw");
668 if (!count($user_info["status"]))
669 unset($user_info["status"]);
671 unset($user_info["status"]["user"]);
674 // "uid" and "self" are only needed for some internal stuff, so remove it from here
675 unset($user_info["uid"]);
676 unset($user_info["self"]);
678 return api_apply_template("user", $type, array('$user' => $user_info));
681 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
685 * get data from $_POST or $_GET
687 function requestdata($k){
688 if (isset($_POST[$k])){
691 if (isset($_GET[$k])){
697 /*Waitman Gobble Mod*/
698 function api_statuses_mediap(&$a, $type) {
699 if (api_user()===false) {
700 logger('api_statuses_update: no user');
703 $user_info = api_get_user($a);
705 $_REQUEST['type'] = 'wall';
706 $_REQUEST['profile_uid'] = api_user();
707 $_REQUEST['api_source'] = true;
708 $txt = requestdata('status');
709 //$txt = urldecode(requestdata('status'));
711 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
713 require_once('library/HTMLPurifier.auto.php');
715 $txt = html2bb_video($txt);
716 $config = HTMLPurifier_Config::createDefault();
717 $config->set('Cache.DefinitionImpl', null);
718 $purifier = new HTMLPurifier($config);
719 $txt = $purifier->purify($txt);
721 $txt = html2bbcode($txt);
723 $a->argv[1]=$user_info['screen_name']; //should be set to username?
725 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
726 $bebop = wall_upload_post($a);
728 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
729 $_REQUEST['body']=$txt."\n\n".$bebop;
732 // this should output the last post (the one we just posted).
733 return api_status_show($a,$type);
735 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
736 /*Waitman Gobble Mod*/
739 function api_statuses_update(&$a, $type) {
740 if (api_user()===false) {
741 logger('api_statuses_update: no user');
745 $user_info = api_get_user($a);
747 // convert $_POST array items to the form we use for web posts.
749 // logger('api_post: ' . print_r($_POST,true));
751 if(requestdata('htmlstatus')) {
752 $txt = requestdata('htmlstatus');
753 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
755 require_once('library/HTMLPurifier.auto.php');
757 $txt = html2bb_video($txt);
759 $config = HTMLPurifier_Config::createDefault();
760 $config->set('Cache.DefinitionImpl', null);
762 $purifier = new HTMLPurifier($config);
763 $txt = $purifier->purify($txt);
765 $_REQUEST['body'] = html2bbcode($txt);
769 $_REQUEST['body'] = requestdata('status');
771 $_REQUEST['title'] = requestdata('title');
773 $parent = requestdata('in_reply_to_status_id');
775 // Twidere sends "-1" if it is no reply ...
779 if(ctype_digit($parent))
780 $_REQUEST['parent'] = $parent;
782 $_REQUEST['parent_uri'] = $parent;
784 if(requestdata('lat') && requestdata('long'))
785 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
786 $_REQUEST['profile_uid'] = api_user();
789 $_REQUEST['type'] = 'net-comment';
791 // Check for throttling (maximum posts per day, week and month)
792 $throttle_day = get_config('system','throttle_limit_day');
793 if ($throttle_day > 0) {
794 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
796 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
797 AND `created` > '%s' AND `id` = `parent`",
798 intval(api_user()), dbesc($datefrom));
801 $posts_day = $r[0]["posts_day"];
805 if ($posts_day > $throttle_day) {
806 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
807 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
811 $throttle_week = get_config('system','throttle_limit_week');
812 if ($throttle_week > 0) {
813 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
815 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
816 AND `created` > '%s' AND `id` = `parent`",
817 intval(api_user()), dbesc($datefrom));
820 $posts_week = $r[0]["posts_week"];
824 if ($posts_week > $throttle_week) {
825 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
826 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
830 $throttle_month = get_config('system','throttle_limit_month');
831 if ($throttle_month > 0) {
832 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
834 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
835 AND `created` > '%s' AND `id` = `parent`",
836 intval(api_user()), dbesc($datefrom));
839 $posts_month = $r[0]["posts_month"];
843 if ($posts_month > $throttle_month) {
844 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
845 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
849 $_REQUEST['type'] = 'wall';
852 if(x($_FILES,'media')) {
853 // upload the image if we have one
854 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
855 $media = wall_upload_post($a);
857 $_REQUEST['body'] .= "\n\n".$media;
860 // To-Do: Multiple IDs
861 if (requestdata('media_ids')) {
862 $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",
863 intval(requestdata('media_ids')), api_user());
865 $phototypes = Photo::supportedTypes();
866 $ext = $phototypes[$r[0]['type']];
867 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
868 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
872 // set this so that the item_post() function is quiet and doesn't redirect or emit json
874 $_REQUEST['api_source'] = true;
876 if (!x($_REQUEST, "source"))
877 $_REQUEST["source"] = api_source();
879 // call out normal post function
883 // this should output the last post (the one we just posted).
884 return api_status_show($a,$type);
886 api_register_func('api/statuses/update','api_statuses_update', true);
887 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
890 function api_media_upload(&$a, $type) {
891 if (api_user()===false) {
896 $user_info = api_get_user($a);
898 if(!x($_FILES,'media')) {
903 $media = wall_upload_post($a, false);
909 $returndata = array();
910 $returndata["media_id"] = $media["id"];
911 $returndata["media_id_string"] = (string)$media["id"];
912 $returndata["size"] = $media["size"];
913 $returndata["image"] = array("w" => $media["width"],
914 "h" => $media["height"],
915 "image_type" => $media["type"]);
917 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
919 return array("media" => $returndata);
922 api_register_func('api/media/upload','api_media_upload', true);
924 function api_status_show(&$a, $type){
925 $user_info = api_get_user($a);
927 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
930 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
934 // get last public wall message
935 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
936 FROM `item`, `item` as `i`
937 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
938 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
939 AND `i`.`id` = `item`.`parent`
940 AND `item`.`type`!='activity' $privacy_sql
941 ORDER BY `item`.`created` DESC
943 intval($user_info['cid']),
945 dbesc($user_info['url']),
946 dbesc(normalise_link($user_info['url'])),
947 dbesc($user_info['url']),
948 dbesc(normalise_link($user_info['url']))
951 if (count($lastwall)>0){
952 $lastwall = $lastwall[0];
954 $in_reply_to_status_id = NULL;
955 $in_reply_to_user_id = NULL;
956 $in_reply_to_status_id_str = NULL;
957 $in_reply_to_user_id_str = NULL;
958 $in_reply_to_screen_name = NULL;
959 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
960 $in_reply_to_status_id= intval($lastwall['parent']);
961 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
963 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
965 if ($r[0]['nick'] == "")
966 $r[0]['nick'] = api_get_nick($r[0]["url"]);
968 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
969 $in_reply_to_user_id = intval($r[0]['id']);
970 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
974 // There seems to be situation, where both fields are identical:
975 // https://github.com/friendica/friendica/issues/1010
976 // This is a bugfix for that.
977 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
978 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
979 $in_reply_to_status_id = NULL;
980 $in_reply_to_user_id = NULL;
981 $in_reply_to_status_id_str = NULL;
982 $in_reply_to_user_id_str = NULL;
983 $in_reply_to_screen_name = NULL;
986 $converted = api_convert_item($lastwall);
988 $status_info = array(
989 'created_at' => api_date($lastwall['created']),
990 'id' => intval($lastwall['id']),
991 'id_str' => (string) $lastwall['id'],
992 'text' => $converted["text"],
993 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
994 'truncated' => false,
995 'in_reply_to_status_id' => $in_reply_to_status_id,
996 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
997 'in_reply_to_user_id' => $in_reply_to_user_id,
998 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
999 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1000 'user' => $user_info,
1002 'coordinates' => "",
1004 'contributors' => "",
1005 'is_quote_status' => false,
1006 'retweet_count' => 0,
1007 'favorite_count' => 0,
1008 'favorited' => $lastwall['starred'] ? true : false,
1009 'retweeted' => false,
1010 'possibly_sensitive' => false,
1012 'statusnet_html' => $converted["html"],
1013 'statusnet_conversation_id' => $lastwall['parent'],
1016 if (count($converted["attachments"]) > 0)
1017 $status_info["attachments"] = $converted["attachments"];
1019 if (count($converted["entities"]) > 0)
1020 $status_info["entities"] = $converted["entities"];
1022 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1023 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1024 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1025 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1027 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1028 unset($status_info["user"]["uid"]);
1029 unset($status_info["user"]["self"]);
1032 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1035 return($status_info);
1037 return api_apply_template("status", $type, array('$status' => $status_info));
1046 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1047 * The author's most recent status will be returned inline.
1048 * http://developer.twitter.com/doc/get/users/show
1050 function api_users_show(&$a, $type){
1051 $user_info = api_get_user($a);
1053 $lastwall = q("SELECT `item`.*
1054 FROM `item`, `contact`
1055 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1056 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1057 AND `contact`.`id`=`item`.`contact-id`
1058 AND `type`!='activity'
1059 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1060 ORDER BY `created` DESC
1063 dbesc(ACTIVITY_POST),
1064 intval($user_info['cid']),
1065 dbesc($user_info['url']),
1066 dbesc(normalise_link($user_info['url'])),
1067 dbesc($user_info['url']),
1068 dbesc(normalise_link($user_info['url']))
1070 if (count($lastwall)>0){
1071 $lastwall = $lastwall[0];
1073 $in_reply_to_status_id = NULL;
1074 $in_reply_to_user_id = NULL;
1075 $in_reply_to_status_id_str = NULL;
1076 $in_reply_to_user_id_str = NULL;
1077 $in_reply_to_screen_name = NULL;
1078 if ($lastwall['parent']!=$lastwall['id']) {
1079 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1080 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1081 if (count($reply)>0) {
1082 $in_reply_to_status_id = intval($lastwall['parent']);
1083 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1085 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1087 if ($r[0]['nick'] == "")
1088 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1090 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1091 $in_reply_to_user_id = intval($r[0]['id']);
1092 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1097 $converted = api_convert_item($lastwall);
1099 $user_info['status'] = array(
1100 'text' => $converted["text"],
1101 'truncated' => false,
1102 'created_at' => api_date($lastwall['created']),
1103 'in_reply_to_status_id' => $in_reply_to_status_id,
1104 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1105 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1106 'id' => intval($lastwall['contact-id']),
1107 'id_str' => (string) $lastwall['contact-id'],
1108 'in_reply_to_user_id' => $in_reply_to_user_id,
1109 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1110 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1112 'favorited' => $lastwall['starred'] ? true : false,
1113 'statusnet_html' => $converted["html"],
1114 'statusnet_conversation_id' => $lastwall['parent'],
1117 if (count($converted["attachments"]) > 0)
1118 $user_info["status"]["attachments"] = $converted["attachments"];
1120 if (count($converted["entities"]) > 0)
1121 $user_info["status"]["entities"] = $converted["entities"];
1123 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1124 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1125 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1126 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1130 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1131 unset($user_info["uid"]);
1132 unset($user_info["self"]);
1134 return api_apply_template("user", $type, array('$user' => $user_info));
1137 api_register_func('api/users/show','api_users_show');
1140 function api_users_search(&$a, $type) {
1141 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1143 $userlist = array();
1145 if (isset($_GET["q"])) {
1146 $r = q("SELECT id FROM `unique_contacts` WHERE `name`='%s'", dbesc($_GET["q"]));
1148 $r = q("SELECT `id` FROM `unique_contacts` WHERE `nick`='%s'", dbesc($_GET["q"]));
1151 foreach ($r AS $user) {
1152 $user_info = api_get_user($a, $user["id"]);
1153 //echo print_r($user_info, true)."\n";
1154 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1155 $userlist[] = $userdata["user"];
1157 $userlist = array("users" => $userlist);
1159 die(api_error($a, $type, t("User not found.")));
1161 die(api_error($a, $type, t("User not found.")));
1166 api_register_func('api/users/search','api_users_search');
1170 * http://developer.twitter.com/doc/get/statuses/home_timeline
1172 * TODO: Optional parameters
1173 * TODO: Add reply info
1175 function api_statuses_home_timeline(&$a, $type){
1176 if (api_user()===false) return false;
1178 unset($_REQUEST["user_id"]);
1179 unset($_GET["user_id"]);
1181 unset($_REQUEST["screen_name"]);
1182 unset($_GET["screen_name"]);
1184 $user_info = api_get_user($a);
1185 // get last newtork messages
1189 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1190 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1191 if ($page<0) $page=0;
1192 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1193 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1194 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1195 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1196 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1198 $start = $page*$count;
1202 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1203 if ($exclude_replies > 0)
1204 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1205 if ($conversation_id > 0)
1206 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1208 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1209 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1210 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1211 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1212 FROM `item`, `contact`
1213 WHERE `item`.`uid` = %d AND `verb` = '%s'
1214 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1215 AND `contact`.`id` = `item`.`contact-id`
1216 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1219 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1221 dbesc(ACTIVITY_POST),
1223 intval($start), intval($count)
1226 $ret = api_format_items($r,$user_info);
1228 // Set all posts from the query above to seen
1230 foreach ($r AS $item)
1231 $idarray[] = intval($item["id"]);
1233 $idlist = implode(",", $idarray);
1236 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1239 $data = array('$statuses' => $ret);
1243 $data = api_rss_extra($a, $data, $user_info);
1246 $as = api_format_as($a, $ret, $user_info);
1247 $as['title'] = $a->config['sitename']." Home Timeline";
1248 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1253 return api_apply_template("timeline", $type, $data);
1255 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1256 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1258 function api_statuses_public_timeline(&$a, $type){
1259 if (api_user()===false) return false;
1261 $user_info = api_get_user($a);
1262 // get last newtork messages
1266 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1267 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1268 if ($page<0) $page=0;
1269 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1270 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1271 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1272 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1273 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1275 $start = $page*$count;
1278 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1279 if ($exclude_replies > 0)
1280 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1281 if ($conversation_id > 0)
1282 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1284 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1285 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1286 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1287 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1288 `user`.`nickname`, `user`.`hidewall`
1289 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1290 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1291 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1292 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1293 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1294 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1295 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1298 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1299 dbesc(ACTIVITY_POST),
1304 $ret = api_format_items($r,$user_info);
1307 $data = array('$statuses' => $ret);
1311 $data = api_rss_extra($a, $data, $user_info);
1314 $as = api_format_as($a, $ret, $user_info);
1315 $as['title'] = $a->config['sitename']." Public Timeline";
1316 $as['link']['url'] = $a->get_baseurl()."/";
1321 return api_apply_template("timeline", $type, $data);
1323 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1328 function api_statuses_show(&$a, $type){
1329 if (api_user()===false) return false;
1331 $user_info = api_get_user($a);
1334 $id = intval($a->argv[3]);
1337 $id = intval($_REQUEST["id"]);
1341 $id = intval($a->argv[4]);
1343 logger('API: api_statuses_show: '.$id);
1345 $conversation = (x($_REQUEST,'conversation')?1:0);
1349 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1351 $sql_extra .= " AND `item`.`id` = %d";
1353 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1354 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1355 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1356 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1357 FROM `item`, `contact`
1358 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1359 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1360 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1363 dbesc(ACTIVITY_POST),
1368 die(api_error($a, $type, t("There is no status with this id.")));
1370 $ret = api_format_items($r,$user_info);
1372 if ($conversation) {
1373 $data = array('$statuses' => $ret);
1374 return api_apply_template("timeline", $type, $data);
1376 $data = array('$status' => $ret[0]);
1380 $data = api_rss_extra($a, $data, $user_info);
1382 return api_apply_template("status", $type, $data);
1385 api_register_func('api/statuses/show','api_statuses_show', true);
1391 function api_conversation_show(&$a, $type){
1392 if (api_user()===false) return false;
1394 $user_info = api_get_user($a);
1397 $id = intval($a->argv[3]);
1398 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1399 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1400 if ($page<0) $page=0;
1401 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1402 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1404 $start = $page*$count;
1407 $id = intval($_REQUEST["id"]);
1411 $id = intval($a->argv[4]);
1413 logger('API: api_conversation_show: '.$id);
1415 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1417 $id = $r[0]["parent"];
1422 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1424 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1425 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1426 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1427 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1428 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1429 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1430 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1431 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1432 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1433 AND `item`.`id`>%d $sql_extra
1434 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1435 intval($id), intval(api_user()),
1436 dbesc(ACTIVITY_POST),
1438 intval($start), intval($count)
1442 die(api_error($a, $type, t("There is no conversation with this id.")));
1444 $ret = api_format_items($r,$user_info);
1446 $data = array('$statuses' => $ret);
1447 return api_apply_template("timeline", $type, $data);
1449 api_register_func('api/conversation/show','api_conversation_show', true);
1455 function api_statuses_repeat(&$a, $type){
1458 if (api_user()===false) return false;
1460 $user_info = api_get_user($a);
1463 $id = intval($a->argv[3]);
1466 $id = intval($_REQUEST["id"]);
1470 $id = intval($a->argv[4]);
1472 logger('API: api_statuses_repeat: '.$id);
1474 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1475 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1476 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1477 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1478 FROM `item`, `contact`
1479 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1480 AND `contact`.`id` = `item`.`contact-id`
1481 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1483 AND `item`.`id`=%d",
1487 if ($r[0]['body'] != "") {
1488 if (!intval(get_config('system','old_share'))) {
1489 if (strpos($r[0]['body'], "[/share]") !== false) {
1490 $pos = strpos($r[0]['body'], "[share");
1491 $post = substr($r[0]['body'], $pos);
1493 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1495 $post .= $r[0]['body'];
1496 $post .= "[/share]";
1498 $_REQUEST['body'] = $post;
1500 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1502 $_REQUEST['profile_uid'] = api_user();
1503 $_REQUEST['type'] = 'wall';
1504 $_REQUEST['api_source'] = true;
1506 if (!x($_REQUEST, "source"))
1507 $_REQUEST["source"] = api_source();
1512 // this should output the last post (the one we just posted).
1514 return(api_status_show($a,$type));
1516 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1521 function api_statuses_destroy(&$a, $type){
1522 if (api_user()===false) return false;
1524 $user_info = api_get_user($a);
1527 $id = intval($a->argv[3]);
1530 $id = intval($_REQUEST["id"]);
1534 $id = intval($a->argv[4]);
1536 logger('API: api_statuses_destroy: '.$id);
1538 $ret = api_statuses_show($a, $type);
1540 drop_item($id, false);
1544 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1548 * http://developer.twitter.com/doc/get/statuses/mentions
1551 function api_statuses_mentions(&$a, $type){
1552 if (api_user()===false) return false;
1554 unset($_REQUEST["user_id"]);
1555 unset($_GET["user_id"]);
1557 unset($_REQUEST["screen_name"]);
1558 unset($_GET["screen_name"]);
1560 $user_info = api_get_user($a);
1561 // get last newtork messages
1565 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1566 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1567 if ($page<0) $page=0;
1568 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1569 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1570 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1572 $start = $page*$count;
1574 // Ugly code - should be changed
1575 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1576 $myurl = substr($myurl,strpos($myurl,'://')+3);
1577 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1578 $myurl = str_replace('www.','',$myurl);
1579 $diasp_url = str_replace('/profile/','/u/',$myurl);
1582 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1584 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1585 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1586 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1587 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1588 FROM `item`, `contact`
1589 WHERE `item`.`uid` = %d AND `verb` = '%s'
1590 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1591 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1592 AND `contact`.`id` = `item`.`contact-id`
1593 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1594 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1597 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1599 dbesc(ACTIVITY_POST),
1600 dbesc(protect_sprintf($myurl)),
1601 dbesc(protect_sprintf($myurl)),
1604 intval($start), intval($count)
1607 $ret = api_format_items($r,$user_info);
1610 $data = array('$statuses' => $ret);
1614 $data = api_rss_extra($a, $data, $user_info);
1617 $as = api_format_as($a, $ret, $user_info);
1618 $as["title"] = $a->config['sitename']." Mentions";
1619 $as['link']['url'] = $a->get_baseurl()."/";
1624 return api_apply_template("timeline", $type, $data);
1626 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1627 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1630 function api_statuses_user_timeline(&$a, $type){
1631 if (api_user()===false) return false;
1633 $user_info = api_get_user($a);
1634 // get last network messages
1636 logger("api_statuses_user_timeline: api_user: ". api_user() .
1637 "\nuser_info: ".print_r($user_info, true) .
1638 "\n_REQUEST: ".print_r($_REQUEST, true),
1642 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1643 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1644 if ($page<0) $page=0;
1645 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1646 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1647 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1648 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1650 $start = $page*$count;
1653 if ($user_info['self']==1)
1654 $sql_extra .= " AND `item`.`wall` = 1 ";
1656 if ($exclude_replies > 0)
1657 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1658 if ($conversation_id > 0)
1659 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1661 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1662 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1663 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1664 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1665 FROM `item`, `contact`
1666 WHERE `item`.`uid` = %d AND `verb` = '%s'
1667 AND `item`.`contact-id` = %d
1668 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1669 AND `contact`.`id` = `item`.`contact-id`
1670 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1673 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1675 dbesc(ACTIVITY_POST),
1676 intval($user_info['cid']),
1678 intval($start), intval($count)
1681 $ret = api_format_items($r,$user_info, true);
1683 $data = array('$statuses' => $ret);
1687 $data = api_rss_extra($a, $data, $user_info);
1690 return api_apply_template("timeline", $type, $data);
1693 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1697 * Star/unstar an item
1698 * param: id : id of the item
1700 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1702 function api_favorites_create_destroy(&$a, $type){
1703 if (api_user()===false) return false;
1705 # for versioned api.
1706 # TODO: we need a better global soluton
1708 if ($a->argv[1]=="1.1") $action_argv_id=3;
1710 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1711 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1712 if ($a->argc==$action_argv_id+2) {
1713 $itemid = intval($a->argv[$action_argv_id+1]);
1715 $itemid = intval($_REQUEST['id']);
1718 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1719 $itemid, api_user());
1721 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1725 $item[0]['starred']=1;
1728 $item[0]['starred']=0;
1731 die(api_error($a, $type, t("Invalid action. ".$action)));
1733 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1734 $item[0]['starred'], $itemid, api_user());
1736 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1737 $item[0]['starred'], $itemid, api_user());
1739 if ($r===false) die(api_error($a, $type, t("DB error")));
1742 $user_info = api_get_user($a);
1743 $rets = api_format_items($item,$user_info);
1746 $data = array('$status' => $ret);
1750 $data = api_rss_extra($a, $data, $user_info);
1753 return api_apply_template("status", $type, $data);
1756 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1757 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1759 function api_favorites(&$a, $type){
1762 if (api_user()===false) return false;
1764 $called_api= array();
1766 $user_info = api_get_user($a);
1768 // in friendica starred item are private
1769 // return favorites only for self
1770 logger('api_favorites: self:' . $user_info['self']);
1772 if ($user_info['self']==0) {
1778 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1779 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1780 $count = (x($_GET,'count')?$_GET['count']:20);
1781 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1782 if ($page<0) $page=0;
1784 $start = $page*$count;
1787 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1789 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1790 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1791 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1792 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1793 FROM `item`, `contact`
1794 WHERE `item`.`uid` = %d
1795 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1796 AND `item`.`starred` = 1
1797 AND `contact`.`id` = `item`.`contact-id`
1798 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1801 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1804 intval($start), intval($count)
1807 $ret = api_format_items($r,$user_info);
1811 $data = array('$statuses' => $ret);
1815 $data = api_rss_extra($a, $data, $user_info);
1818 return api_apply_template("timeline", $type, $data);
1821 api_register_func('api/favorites','api_favorites', true);
1826 function api_format_as($a, $ret, $user_info) {
1829 $as['title'] = $a->config['sitename']." Public Timeline";
1831 foreach ($ret as $item) {
1832 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1833 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1834 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1835 $avatar[0]["rel"] = "avatar";
1836 $avatar[0]["type"] = "";
1837 $avatar[0]["width"] = 96;
1838 $avatar[0]["height"] = 96;
1839 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1840 $avatar[1]["rel"] = "avatar";
1841 $avatar[1]["type"] = "";
1842 $avatar[1]["width"] = 48;
1843 $avatar[1]["height"] = 48;
1844 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1845 $avatar[2]["rel"] = "avatar";
1846 $avatar[2]["type"] = "";
1847 $avatar[2]["width"] = 24;
1848 $avatar[2]["height"] = 24;
1849 $singleitem["actor"]["avatarLinks"] = $avatar;
1851 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1852 $singleitem["actor"]["image"]["rel"] = "avatar";
1853 $singleitem["actor"]["image"]["type"] = "";
1854 $singleitem["actor"]["image"]["width"] = 96;
1855 $singleitem["actor"]["image"]["height"] = 96;
1856 $singleitem["actor"]["type"] = "person";
1857 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1858 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1859 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1860 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1861 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1862 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1863 $singleitem["actor"]["contact"]["addresses"] = "";
1865 $singleitem["body"] = $item["text"];
1866 $singleitem["object"]["displayName"] = $item["text"];
1867 $singleitem["object"]["id"] = $item["url"];
1868 $singleitem["object"]["type"] = "note";
1869 $singleitem["object"]["url"] = $item["url"];
1870 //$singleitem["context"] =;
1871 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1872 $singleitem["provider"]["objectType"] = "service";
1873 $singleitem["provider"]["displayName"] = "Test";
1874 $singleitem["provider"]["url"] = "http://test.tld";
1875 $singleitem["title"] = $item["text"];
1876 $singleitem["verb"] = "post";
1877 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1878 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1879 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1880 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1881 //$singleitem["original"] = $item;
1882 $items[] = $singleitem;
1884 $as['items'] = $items;
1885 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1886 $as['link']['rel'] = "alternate";
1887 $as['link']['type'] = "text/html";
1891 function api_format_messages($item, $recipient, $sender) {
1892 // standard meta information
1894 'id' => $item['id'],
1895 'sender_id' => $sender['id'] ,
1897 'recipient_id' => $recipient['id'],
1898 'created_at' => api_date($item['created']),
1899 'sender_screen_name' => $sender['screen_name'],
1900 'recipient_screen_name' => $recipient['screen_name'],
1901 'sender' => $sender,
1902 'recipient' => $recipient,
1905 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1906 unset($ret["sender"]["uid"]);
1907 unset($ret["sender"]["self"]);
1908 unset($ret["recipient"]["uid"]);
1909 unset($ret["recipient"]["self"]);
1911 //don't send title to regular StatusNET requests to avoid confusing these apps
1912 if (x($_GET, 'getText')) {
1913 $ret['title'] = $item['title'] ;
1914 if ($_GET["getText"] == "html") {
1915 $ret['text'] = bbcode($item['body'], false, false);
1917 elseif ($_GET["getText"] == "plain") {
1918 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1919 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1923 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1925 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1926 unset($ret['sender']);
1927 unset($ret['recipient']);
1933 function api_convert_item($item) {
1935 $body = $item['body'];
1936 $attachments = api_get_attachments($body);
1938 // Workaround for ostatus messages where the title is identically to the body
1939 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1940 $statusbody = trim(html2plain($html, 0));
1942 // handle data: images
1943 $statusbody = api_format_items_embeded_images($item,$statusbody);
1945 $statustitle = trim($item['title']);
1947 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1948 $statustext = trim($statusbody);
1950 $statustext = trim($statustitle."\n\n".$statusbody);
1952 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1953 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1955 $statushtml = trim(bbcode($body, false, false));
1957 if ($item['title'] != "")
1958 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1960 $entities = api_get_entitities($statustext, $body);
1962 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1965 function api_get_attachments(&$body) {
1968 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1970 $URLSearchString = "^\[\]";
1971 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1976 $attachments = array();
1978 foreach ($images[1] AS $image) {
1979 $imagedata = get_photo_info($image);
1982 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1985 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1986 foreach ($images[0] AS $orig)
1987 $body = str_replace($orig, "", $body);
1989 return $attachments;
1992 function api_get_entitities(&$text, $bbcode) {
1995 * Links at the first character of the post
2000 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2002 if ($include_entities != "true") {
2004 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2006 foreach ($images[1] AS $image) {
2007 $replace = proxy_url($image);
2008 $text = str_replace($image, $replace, $text);
2013 $bbcode = bb_CleanPictureLinks($bbcode);
2015 // Change pure links in text to bbcode uris
2016 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2018 $entities = array();
2019 $entities["hashtags"] = array();
2020 $entities["symbols"] = array();
2021 $entities["urls"] = array();
2022 $entities["user_mentions"] = array();
2024 $URLSearchString = "^\[\]";
2026 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2028 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2029 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2030 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2032 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2033 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2034 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2036 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2037 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2038 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2040 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2042 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2043 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2045 $ordered_urls = array();
2046 foreach ($urls[1] AS $id=>$url) {
2047 //$start = strpos($text, $url, $offset);
2048 $start = iconv_strpos($text, $url, 0, "UTF-8");
2049 if (!($start === false))
2050 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2053 ksort($ordered_urls);
2056 //foreach ($urls[1] AS $id=>$url) {
2057 foreach ($ordered_urls AS $url) {
2058 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2059 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2060 $display_url = $url["title"];
2062 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2063 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2065 if (strlen($display_url) > 26)
2066 $display_url = substr($display_url, 0, 25)."…";
2069 //$start = strpos($text, $url, $offset);
2070 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2071 if (!($start === false)) {
2072 $entities["urls"][] = array("url" => $url["url"],
2073 "expanded_url" => $url["url"],
2074 "display_url" => $display_url,
2075 "indices" => array($start, $start+strlen($url["url"])));
2076 $offset = $start + 1;
2080 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2081 $ordered_images = array();
2082 foreach ($images[1] AS $image) {
2083 //$start = strpos($text, $url, $offset);
2084 $start = iconv_strpos($text, $image, 0, "UTF-8");
2085 if (!($start === false))
2086 $ordered_images[$start] = $image;
2088 //$entities["media"] = array();
2091 foreach ($ordered_images AS $url) {
2092 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2093 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2095 if (strlen($display_url) > 26)
2096 $display_url = substr($display_url, 0, 25)."…";
2098 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2099 if (!($start === false)) {
2100 $image = get_photo_info($url);
2102 // If image cache is activated, then use the following sizes:
2103 // thumb (150), small (340), medium (600) and large (1024)
2104 if (!get_config("system", "proxy_disabled")) {
2105 $media_url = proxy_url($url);
2108 $scale = scale_image($image[0], $image[1], 150);
2109 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2111 if (($image[0] > 150) OR ($image[1] > 150)) {
2112 $scale = scale_image($image[0], $image[1], 340);
2113 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2116 $scale = scale_image($image[0], $image[1], 600);
2117 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2119 if (($image[0] > 600) OR ($image[1] > 600)) {
2120 $scale = scale_image($image[0], $image[1], 1024);
2121 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2125 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2128 $entities["media"][] = array(
2130 "id_str" => (string)$start+1,
2131 "indices" => array($start, $start+strlen($url)),
2132 "media_url" => normalise_link($media_url),
2133 "media_url_https" => $media_url,
2135 "display_url" => $display_url,
2136 "expanded_url" => $url,
2140 $offset = $start + 1;
2146 function api_format_items_embeded_images($item, $text){
2148 $text = preg_replace_callback(
2149 "|data:image/([^;]+)[^=]+=*|m",
2150 function($match) use ($a, $item) {
2151 return $a->get_baseurl()."/display/".$item['guid'];
2157 function api_format_items($r,$user_info, $filter_user = false) {
2162 foreach($r as $item) {
2163 api_share_as_retweet($item);
2165 localize_item($item);
2166 $status_user = api_item_get_user($a,$item);
2168 // Look if the posts are matching if they should be filtered by user id
2169 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2172 if ($item['thr-parent'] != $item['uri']) {
2173 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2175 dbesc($item['thr-parent']));
2177 $in_reply_to_status_id = intval($r[0]['id']);
2179 $in_reply_to_status_id = intval($item['parent']);
2181 $in_reply_to_status_id_str = (string) intval($item['parent']);
2183 $in_reply_to_screen_name = NULL;
2184 $in_reply_to_user_id = NULL;
2185 $in_reply_to_user_id_str = NULL;
2187 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2189 intval($in_reply_to_status_id));
2191 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2194 if ($r[0]['nick'] == "")
2195 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2197 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2198 $in_reply_to_user_id = intval($r[0]['id']);
2199 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2203 $in_reply_to_screen_name = NULL;
2204 $in_reply_to_user_id = NULL;
2205 $in_reply_to_status_id = NULL;
2206 $in_reply_to_user_id_str = NULL;
2207 $in_reply_to_status_id_str = NULL;
2210 $converted = api_convert_item($item);
2213 'text' => $converted["text"],
2214 'truncated' => False,
2215 'created_at'=> api_date($item['created']),
2216 'in_reply_to_status_id' => $in_reply_to_status_id,
2217 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2218 'source' => (($item['app']) ? $item['app'] : 'web'),
2219 'id' => intval($item['id']),
2220 'id_str' => (string) intval($item['id']),
2221 'in_reply_to_user_id' => $in_reply_to_user_id,
2222 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2223 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2225 'favorited' => $item['starred'] ? true : false,
2226 'user' => $status_user ,
2227 //'entities' => NULL,
2228 'statusnet_html' => $converted["html"],
2229 'statusnet_conversation_id' => $item['parent'],
2232 if (count($converted["attachments"]) > 0)
2233 $status["attachments"] = $converted["attachments"];
2235 if (count($converted["entities"]) > 0)
2236 $status["entities"] = $converted["entities"];
2238 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2239 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2240 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2241 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2244 // Retweets are only valid for top postings
2245 // It doesn't work reliable with the link if its a feed
2246 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2248 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2250 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2251 $retweeted_status = $status;
2252 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2254 $status["retweeted_status"] = $retweeted_status;
2257 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2258 unset($status["user"]["uid"]);
2259 unset($status["user"]["self"]);
2261 if ($item["coord"] != "") {
2262 $coords = explode(' ',$item["coord"]);
2263 if (count($coords) == 2) {
2264 $status["geo"] = array('type' => 'Point',
2265 'coordinates' => array((float) $coords[0],
2266 (float) $coords[1]));
2276 function api_account_rate_limit_status(&$a,$type) {
2279 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2280 'remaining_hits' => (string) 150,
2281 'hourly_limit' => (string) 150,
2282 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2285 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2287 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2290 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2292 function api_help_test(&$a,$type) {
2299 return api_apply_template('test', $type, array("$ok" => $ok));
2302 api_register_func('api/help/test','api_help_test',false);
2304 function api_lists(&$a,$type) {
2309 api_register_func('api/lists','api_lists',true);
2311 function api_lists_list(&$a,$type) {
2316 api_register_func('api/lists/list','api_lists_list',true);
2319 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2320 * This function is deprecated by Twitter
2321 * returns: json, xml
2323 function api_statuses_f(&$a, $type, $qtype) {
2324 if (api_user()===false) return false;
2325 $user_info = api_get_user($a);
2327 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2328 /* this is to stop Hotot to load friends multiple times
2329 * I'm not sure if I'm missing return something or
2330 * is a bug in hotot. Workaround, meantime
2334 return array('$users' => $ret);*/
2338 if($qtype == 'friends')
2339 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2340 if($qtype == 'followers')
2341 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2343 // friends and followers only for self
2344 if ($user_info['self'] == 0)
2345 $sql_extra = " AND false ";
2347 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2352 foreach($r as $cid){
2353 $user = api_get_user($a, $cid['nurl']);
2354 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2355 unset($user["uid"]);
2356 unset($user["self"]);
2362 return array('$users' => $ret);
2365 function api_statuses_friends(&$a, $type){
2366 $data = api_statuses_f($a,$type,"friends");
2367 if ($data===false) return false;
2368 return api_apply_template("friends", $type, $data);
2370 function api_statuses_followers(&$a, $type){
2371 $data = api_statuses_f($a,$type,"followers");
2372 if ($data===false) return false;
2373 return api_apply_template("friends", $type, $data);
2375 api_register_func('api/statuses/friends','api_statuses_friends',true);
2376 api_register_func('api/statuses/followers','api_statuses_followers',true);
2383 function api_statusnet_config(&$a,$type) {
2384 $name = $a->config['sitename'];
2385 $server = $a->get_hostname();
2386 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2387 $email = $a->config['admin_email'];
2388 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2389 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2390 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2391 if($a->config['api_import_size'])
2392 $texlimit = string($a->config['api_import_size']);
2393 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2394 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2397 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2398 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2399 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2400 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2401 'shorturllength' => '30',
2402 'friendica' => array(
2403 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2404 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2405 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2406 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2411 return api_apply_template('config', $type, array('$config' => $config));
2414 api_register_func('api/statusnet/config','api_statusnet_config',false);
2416 function api_statusnet_version(&$a,$type) {
2420 if($type === 'xml') {
2421 header("Content-type: application/xml");
2422 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2425 elseif($type === 'json') {
2426 header("Content-type: application/json");
2431 api_register_func('api/statusnet/version','api_statusnet_version',false);
2434 function api_ff_ids(&$a,$type,$qtype) {
2438 $user_info = api_get_user($a);
2440 if($qtype == 'friends')
2441 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2442 if($qtype == 'followers')
2443 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2445 if (!$user_info["self"])
2446 $sql_extra = " AND false ";
2448 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2450 $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",
2456 if($type === 'xml') {
2457 header("Content-type: application/xml");
2458 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2460 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2461 echo '</ids>' . "\r\n";
2464 elseif($type === 'json') {
2466 header("Content-type: application/json");
2471 $ret[] = intval($rr['id']);
2473 echo json_encode($ret);
2479 function api_friends_ids(&$a,$type) {
2480 api_ff_ids($a,$type,'friends');
2482 function api_followers_ids(&$a,$type) {
2483 api_ff_ids($a,$type,'followers');
2485 api_register_func('api/friends/ids','api_friends_ids',true);
2486 api_register_func('api/followers/ids','api_followers_ids',true);
2489 function api_direct_messages_new(&$a, $type) {
2490 if (api_user()===false) return false;
2492 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2494 $sender = api_get_user($a);
2496 if ($_POST['screen_name']) {
2497 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2499 dbesc($_POST['screen_name']));
2501 // Selecting the id by priority, friendica first
2502 api_best_nickname($r);
2504 $recipient = api_get_user($a, $r[0]['nurl']);
2506 $recipient = api_get_user($a, $_POST['user_id']);
2510 if (x($_REQUEST,'replyto')) {
2511 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2513 intval($_REQUEST['replyto']));
2514 $replyto = $r[0]['parent-uri'];
2515 $sub = $r[0]['title'];
2518 if (x($_REQUEST,'title')) {
2519 $sub = $_REQUEST['title'];
2522 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2526 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2529 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2530 $ret = api_format_messages($r[0], $recipient, $sender);
2533 $ret = array("error"=>$id);
2536 $data = Array('$messages'=>$ret);
2541 $data = api_rss_extra($a, $data, $user_info);
2544 return api_apply_template("direct_messages", $type, $data);
2547 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2549 function api_direct_messages_box(&$a, $type, $box) {
2550 if (api_user()===false) return false;
2554 $count = (x($_GET,'count')?$_GET['count']:20);
2555 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2556 if ($page<0) $page=0;
2558 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2559 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2561 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2562 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2565 unset($_REQUEST["user_id"]);
2566 unset($_GET["user_id"]);
2568 unset($_REQUEST["screen_name"]);
2569 unset($_GET["screen_name"]);
2571 $user_info = api_get_user($a);
2572 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2573 $profile_url = $user_info["url"];
2577 $start = $page*$count;
2580 if ($box=="sentbox") {
2581 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2583 elseif ($box=="conversation") {
2584 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2586 elseif ($box=="all") {
2587 $sql_extra = "true";
2589 elseif ($box=="inbox") {
2590 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2594 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2596 if ($user_id !="") {
2597 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2599 elseif($screen_name !=""){
2600 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2603 $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",
2606 intval($start), intval($count)
2611 foreach($r as $item) {
2612 if ($box == "inbox" || $item['from-url'] != $profile_url){
2613 $recipient = $user_info;
2614 $sender = api_get_user($a,normalise_link($item['contact-url']));
2616 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2617 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2618 $sender = $user_info;
2621 $ret[]=api_format_messages($item, $recipient, $sender);
2625 $data = array('$messages' => $ret);
2629 $data = api_rss_extra($a, $data, $user_info);
2632 return api_apply_template("direct_messages", $type, $data);
2636 function api_direct_messages_sentbox(&$a, $type){
2637 return api_direct_messages_box($a, $type, "sentbox");
2639 function api_direct_messages_inbox(&$a, $type){
2640 return api_direct_messages_box($a, $type, "inbox");
2642 function api_direct_messages_all(&$a, $type){
2643 return api_direct_messages_box($a, $type, "all");
2645 function api_direct_messages_conversation(&$a, $type){
2646 return api_direct_messages_box($a, $type, "conversation");
2648 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2649 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2650 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2651 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2655 function api_oauth_request_token(&$a, $type){
2657 $oauth = new FKOAuth1();
2658 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2659 }catch(Exception $e){
2660 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2665 function api_oauth_access_token(&$a, $type){
2667 $oauth = new FKOAuth1();
2668 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2669 }catch(Exception $e){
2670 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2676 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2677 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2680 function api_fr_photos_list(&$a,$type) {
2681 if (api_user()===false) return false;
2682 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2683 intval(local_user())
2688 $ret[] = $rr['resource-id'];
2689 header("Content-type: application/json");
2690 echo json_encode($ret);
2695 function api_fr_photo_detail(&$a,$type) {
2696 if (api_user()===false) return false;
2697 if(! $_REQUEST['photo_id']) return false;
2698 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2699 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2700 intval(local_user()),
2701 dbesc($_REQUEST['photo_id']),
2705 header("Content-type: application/json");
2706 $r[0]['data'] = base64_encode($r[0]['data']);
2707 echo json_encode($r[0]);
2713 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2714 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2719 * similar as /mod/redir.php
2720 * redirect to 'url' after dfrn auth
2722 * why this when there is mod/redir.php already?
2723 * This use api_user() and api_login()
2726 * c_url: url of remote contact to auth to
2727 * url: string, url to redirect after auth
2729 function api_friendica_remoteauth(&$a) {
2730 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2731 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2733 if ($url === '' || $c_url === '')
2734 die((api_error($a, 'json', "Wrong parameters")));
2736 $c_url = normalise_link($c_url);
2740 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2745 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2746 die((api_error($a, 'json', "Unknown contact")));
2750 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2752 if($r[0]['duplex'] && $r[0]['issued-id']) {
2753 $orig_id = $r[0]['issued-id'];
2754 $dfrn_id = '1:' . $orig_id;
2756 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2757 $orig_id = $r[0]['dfrn-id'];
2758 $dfrn_id = '0:' . $orig_id;
2761 $sec = random_string();
2763 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2764 VALUES( %d, %s, '%s', '%s', %d )",
2772 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2773 $dest = (($url) ? '&destination_url=' . $url : '');
2774 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2775 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2776 . '&type=profile&sec=' . $sec . $dest . $quiet );
2778 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2782 function api_share_as_retweet(&$item) {
2783 $body = trim($item["body"]);
2785 // Skip if it isn't a pure repeated messages
2786 // Does it start with a share?
2787 if (strpos($body, "[share") > 0)
2790 // Does it end with a share?
2791 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2794 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2795 // Skip if there is no shared message in there
2796 if ($body == $attributes)
2800 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2801 if ($matches[1] != "")
2802 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2804 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2805 if ($matches[1] != "")
2806 $author = $matches[1];
2809 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2810 if ($matches[1] != "")
2811 $profile = $matches[1];
2813 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2814 if ($matches[1] != "")
2815 $profile = $matches[1];
2818 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2819 if ($matches[1] != "")
2820 $avatar = $matches[1];
2822 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2823 if ($matches[1] != "")
2824 $avatar = $matches[1];
2827 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2828 if ($matches[1] != "")
2829 $link = $matches[1];
2831 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2832 if ($matches[1] != "")
2833 $link = $matches[1];
2835 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2837 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2840 $item["body"] = $shared_body;
2841 $item["author-name"] = $author;
2842 $item["author-link"] = $profile;
2843 $item["author-avatar"] = $avatar;
2844 $item["plink"] = $link;
2850 function api_get_nick($profile) {
2852 - remove trailing jung from profile url
2853 - pump.io check has to check the website
2858 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2859 if ($friendica != $profile)
2863 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2864 if ($diaspora != $profile)
2869 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2870 if ($twitter != $profile)
2876 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2877 if ($StatusnetHost != $profile) {
2878 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2879 if ($StatusnetUser != $profile) {
2880 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2881 $user = json_decode($UserData);
2883 $nick = $user->screen_name;
2888 // To-Do: look at the page if its really a pumpio site
2889 //if (!$nick == "") {
2890 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2891 // if ($pumpio != $profile)
2893 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2898 q("UPDATE `unique_contacts` SET `nick` = '%s' WHERE `nick` != '%s' AND url = '%s'",
2899 dbesc($nick), dbesc($nick), dbesc(normalise_link($profile)));
2906 function api_clean_plain_items($Text) {
2907 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2909 $Text = bb_CleanPictureLinks($Text);
2911 $URLSearchString = "^\[\]";
2913 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2915 if ($include_entities == "true") {
2916 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2919 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2923 function api_cleanup_share($shared) {
2924 if ($shared[2] != "type-link")
2927 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2933 if (isset($bookmark[2][0]))
2934 $title = $bookmark[2][0];
2936 if (isset($bookmark[1][0]))
2937 $link = $bookmark[1][0];
2939 if (strpos($shared[1],$title) !== false)
2942 if (strpos($shared[1],$link) !== false)
2945 $text = trim($shared[1]);
2947 //if (strlen($text) < strlen($title))
2948 if (($text == "") AND ($title != ""))
2949 $text .= "\n\n".trim($title);
2952 $text .= "\n".trim($link);
2954 return(trim($text));
2957 function api_best_nickname(&$contacts) {
2958 $best_contact = array();
2960 if (count($contact) == 0)
2963 foreach ($contacts AS $contact)
2964 if ($contact["network"] == "") {
2965 $contact["network"] = "dfrn";
2966 $best_contact = array($contact);
2969 if (sizeof($best_contact) == 0)
2970 foreach ($contacts AS $contact)
2971 if ($contact["network"] == "dfrn")
2972 $best_contact = array($contact);
2974 if (sizeof($best_contact) == 0)
2975 foreach ($contacts AS $contact)
2976 if ($contact["network"] == "dspr")
2977 $best_contact = array($contact);
2979 if (sizeof($best_contact) == 0)
2980 foreach ($contacts AS $contact)
2981 if ($contact["network"] == "stat")
2982 $best_contact = array($contact);
2984 if (sizeof($best_contact) == 0)
2985 foreach ($contacts AS $contact)
2986 if ($contact["network"] == "pump")
2987 $best_contact = array($contact);
2989 if (sizeof($best_contact) == 0)
2990 foreach ($contacts AS $contact)
2991 if ($contact["network"] == "twit")
2992 $best_contact = array($contact);
2994 if (sizeof($best_contact) == 1)
2995 $contacts = $best_contact;
2997 $contacts = array($contacts[0]);
3003 [pagename] => api/1.1/statuses/lookup.json
3004 [id] => 605138389168451584
3005 [include_cards] => true
3006 [cards_platform] => Android-12
3007 [include_entities] => true
3008 [include_my_retweet] => 1
3010 [include_reply_count] => true
3011 [include_descendent_reply_count] => true
3015 Not implemented by now:
3016 statuses/retweets_of_me
3021 account/update_location
3022 account/update_profile_background_image
3023 account/update_profile_image
3027 Not implemented in status.net:
3028 statuses/retweeted_to_me
3029 statuses/retweeted_by_me
3030 direct_messages/destroy
3032 account/update_delivery_device
3033 notifications/follow