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");
19 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
20 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
21 // into a page, and visitors will post something without noticing it).
22 // Instead, use this function.
23 if ($_SESSION["allow_api"])
29 function api_source() {
30 if (requestdata('source'))
31 return (requestdata('source'));
33 // Support for known clients that doesn't send a source name
34 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
37 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
42 function api_date($str){
43 //Wed May 23 06:01:13 +0000 2007
44 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
48 function api_register_func($path, $func, $auth=false){
50 $API[$path] = array('func'=>$func, 'auth'=>$auth);
52 // Workaround for hotot
53 $path = str_replace("api/", "api/1.1/", $path);
54 $API[$path] = array('func'=>$func, 'auth'=>$auth);
61 function api_login(&$a){
64 $oauth = new FKOAuth1();
65 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
66 if (!is_null($token)){
67 $oauth->loginUser($token->uid);
68 call_hooks('logged_in', $a->user);
71 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
73 logger(__file__.__line__.__function__."\n".$e);
74 //die(__file__.__line__.__function__."<pre>".$e); die();
79 // workaround for HTTP-auth in CGI mode
80 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
81 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
82 if(strlen($userpass)) {
83 list($name, $password) = explode(':', $userpass);
84 $_SERVER['PHP_AUTH_USER'] = $name;
85 $_SERVER['PHP_AUTH_PW'] = $password;
89 if (!isset($_SERVER['PHP_AUTH_USER'])) {
90 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
91 header('WWW-Authenticate: Basic realm="Friendica"');
92 header('HTTP/1.0 401 Unauthorized');
93 die((api_error($a, 'json', "This api requires login")));
95 //die('This api requires login');
98 $user = $_SERVER['PHP_AUTH_USER'];
99 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
103 * next code from mod/auth.php. needs better solution
106 // process normal login request
108 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
109 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
117 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
118 header('WWW-Authenticate: Basic realm="Friendica"');
119 header('HTTP/1.0 401 Unauthorized');
120 die('This api requires login');
123 require_once('include/security.php');
124 authenticate_success($record); $_SESSION["allow_api"] = true;
126 call_hooks('logged_in', $a->user);
130 /**************************
131 * MAIN API ENTRY POINT *
132 **************************/
133 function api_call(&$a){
134 GLOBAL $API, $called_api;
138 foreach ($API as $p=>$info){
139 if (strpos($a->query_string, $p)===0){
140 $called_api= explode("/",$p);
141 //unset($_SERVER['PHP_AUTH_USER']);
142 if ($info['auth']===true && api_user()===false) {
146 load_contact_links(api_user());
148 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
149 logger('API parameters: ' . print_r($_REQUEST,true));
151 if (strpos($a->query_string, ".xml")>0) $type="xml";
152 if (strpos($a->query_string, ".json")>0) $type="json";
153 if (strpos($a->query_string, ".rss")>0) $type="rss";
154 if (strpos($a->query_string, ".atom")>0) $type="atom";
155 if (strpos($a->query_string, ".as")>0) $type="as";
157 $r = call_user_func($info['func'], $a, $type);
158 if ($r===false) return;
162 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
163 header ("Content-Type: text/xml");
164 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
167 header ("Content-Type: application/json");
169 $json = json_encode($rr);
170 if ($_GET['callback'])
171 $json = $_GET['callback']."(".$json.")";
175 header ("Content-Type: application/rss+xml");
176 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
179 header ("Content-Type: application/atom+xml");
180 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
183 //header ("Content-Type: application/json");
185 // return json_encode($rr);
186 return json_encode($r);
190 //echo "<pre>"; var_dump($r); die();
193 header("HTTP/1.1 404 Not Found");
194 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
195 return(api_error($a, $type, "not implemented"));
199 function api_error(&$a, $type, $error) {
200 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
203 header ("Content-Type: text/xml");
204 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
207 header ("Content-Type: application/json");
208 return json_encode(array('error' => $error, 'request' => $a->query_string));
211 header ("Content-Type: application/rss+xml");
212 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
215 header ("Content-Type: application/atom+xml");
216 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
224 function api_rss_extra(&$a, $arr, $user_info){
225 if (is_null($user_info)) $user_info = api_get_user($a);
226 $arr['$user'] = $user_info;
227 $arr['$rss'] = array(
228 'alternate' => $user_info['url'],
229 'self' => $a->get_baseurl(). "/". $a->query_string,
230 'base' => $a->get_baseurl(),
231 'updated' => api_date(null),
232 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
233 'language' => $user_info['language'],
234 'logo' => $a->get_baseurl()."/images/friendica-32.png",
242 * Unique contact to contact url.
244 function api_unique_id_to_url($id){
245 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
248 return ($r[0]["url"]);
254 * Returns user info array.
256 function api_get_user(&$a, $contact_id = Null, $type = "json"){
263 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
265 // Searching for contact URL
266 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
267 $user = dbesc(normalise_link($contact_id));
269 $extra_query = "AND `contact`.`nurl` = '%s' ";
270 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
273 // Searching for unique contact id
274 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
275 $user = dbesc(api_unique_id_to_url($contact_id));
278 die(api_error($a, $type, t("User not found.")));
281 $extra_query = "AND `contact`.`nurl` = '%s' ";
282 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
285 if(is_null($user) && x($_GET, 'user_id')) {
286 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
289 die(api_error($a, $type, t("User not found.")));
292 $extra_query = "AND `contact`.`nurl` = '%s' ";
293 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
295 if(is_null($user) && x($_GET, 'screen_name')) {
296 $user = dbesc($_GET['screen_name']);
298 $extra_query = "AND `contact`.`nick` = '%s' ";
299 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
302 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
303 $argid = count($called_api);
304 list($user, $null) = explode(".",$a->argv[$argid]);
305 if(is_numeric($user)){
306 $user = dbesc(api_unique_id_to_url($user));
312 $extra_query = "AND `contact`.`nurl` = '%s' ";
313 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
315 $user = dbesc($user);
317 $extra_query = "AND `contact`.`nick` = '%s' ";
318 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
322 logger("api_get_user: user ".$user, LOGGER_DEBUG);
325 if (api_user()===false) {
326 api_login($a); return False;
328 $user = $_SESSION['uid'];
329 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
334 logger('api_user: ' . $extra_query . ', user: ' . $user);
336 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
342 // Selecting the id by priority, friendica first
343 api_best_nickname($uinfo);
345 // if the contact wasn't found, fetch it from the unique contacts
346 if (count($uinfo)==0) {
350 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
352 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
355 // If no nick where given, extract it from the address
356 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
357 $r[0]['nick'] = api_get_nick($r[0]["url"]);
361 'id_str' => (string) $r[0]["id"],
362 'name' => $r[0]["name"],
363 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
365 'description' => NULL,
366 'profile_image_url' => $r[0]["avatar"],
367 'profile_image_url_https' => $r[0]["avatar"],
368 'url' => $r[0]["url"],
369 'protected' => false,
370 'followers_count' => 0,
371 'friends_count' => 0,
372 'created_at' => api_date(0),
373 'favourites_count' => 0,
375 'time_zone' => 'UTC',
376 'statuses_count' => 0,
377 'following' => false,
379 'statusnet_blocking' => false,
380 'notifications' => false,
381 'statusnet_profile_url' => $r[0]["url"],
390 die(api_error($a, $type, t("User not found.")));
394 if($uinfo[0]['self']) {
395 $usr = q("select * from user where uid = %d limit 1",
398 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
402 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
403 // count public wall messages
404 $r = q("SELECT count(*) as `count` FROM `item`
407 intval($uinfo[0]['uid'])
409 $countitms = $r[0]['count'];
412 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
413 $r = q("SELECT count(*) as `count` FROM `item`
414 WHERE `contact-id` = %d",
415 intval($uinfo[0]['id'])
417 $countitms = $r[0]['count'];
421 $r = q("SELECT count(*) as `count` FROM `contact`
422 WHERE `uid` = %d AND `rel` IN ( %d, %d )
423 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
424 intval($uinfo[0]['uid']),
425 intval(CONTACT_IS_SHARING),
426 intval(CONTACT_IS_FRIEND)
428 $countfriends = $r[0]['count'];
430 $r = q("SELECT count(*) as `count` FROM `contact`
431 WHERE `uid` = %d AND `rel` IN ( %d, %d )
432 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
433 intval($uinfo[0]['uid']),
434 intval(CONTACT_IS_FOLLOWER),
435 intval(CONTACT_IS_FRIEND)
437 $countfollowers = $r[0]['count'];
439 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
440 intval($uinfo[0]['uid'])
442 $starred = $r[0]['count'];
445 if(! $uinfo[0]['self']) {
451 // Add a nick if it isn't present there
452 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
453 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
456 // Fetching unique id
457 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
459 // If not there, then add it
460 if (count($r) == 0) {
461 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
462 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
464 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
467 require_once('include/contact_selectors.php');
468 $network_name = network_to_name($uinfo[0]['network']);
471 'id' => intval($r[0]['id']),
472 'id_str' => (string) intval($r[0]['id']),
473 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
474 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
475 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
476 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
477 'profile_image_url' => $uinfo[0]['micro'],
478 'profile_image_url_https' => $uinfo[0]['micro'],
479 'url' => $uinfo[0]['url'],
480 'protected' => false,
481 'followers_count' => intval($countfollowers),
482 'friends_count' => intval($countfriends),
483 'created_at' => api_date($uinfo[0]['created']),
484 'favourites_count' => intval($starred),
486 'time_zone' => 'UTC',
487 'statuses_count' => intval($countitms),
488 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
490 'statusnet_blocking' => false,
491 'notifications' => false,
492 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
493 'uid' => intval($uinfo[0]['uid']),
494 'cid' => intval($uinfo[0]['cid']),
495 'self' => $uinfo[0]['self'],
496 'network' => $uinfo[0]['network'],
503 function api_item_get_user(&$a, $item) {
505 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
506 dbesc(normalise_link($item['author-link'])));
508 if (count($author) == 0) {
509 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
510 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
512 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
513 dbesc(normalise_link($item['author-link'])));
514 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
515 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
516 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
519 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
520 dbesc(normalise_link($item['owner-link'])));
522 if (count($owner) == 0) {
523 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
524 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
526 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
527 dbesc(normalise_link($item['owner-link'])));
528 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
529 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
530 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
533 // Comments in threads may appear as wall-to-wall postings.
534 // So only take the owner at the top posting.
535 if ($item["id"] == $item["parent"])
536 $status_user = api_get_user($a,$item["owner-link"]);
538 $status_user = api_get_user($a,$item["author-link"]);
540 $status_user["protected"] = (($item["allow_cid"] != "") OR
541 ($item["allow_gid"] != "") OR
542 ($item["deny_cid"] != "") OR
543 ($item["deny_gid"] != "") OR
546 return ($status_user);
551 * load api $templatename for $type and replace $data array
553 function api_apply_template($templatename, $type, $data){
561 $data = array_xmlify($data);
562 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
564 header ("Content-Type: text/xml");
565 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
568 $ret = replace_macros($tpl, $data);
583 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
584 * returns a 401 status code and an error message if not.
585 * http://developer.twitter.com/doc/get/account/verify_credentials
587 function api_account_verify_credentials(&$a, $type){
588 if (api_user()===false) return false;
590 unset($_REQUEST["user_id"]);
591 unset($_GET["user_id"]);
593 unset($_REQUEST["screen_name"]);
594 unset($_GET["screen_name"]);
596 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
598 $user_info = api_get_user($a);
600 // "verified" isn't used here in the standard
601 unset($user_info["verified"]);
603 // - Adding last status
605 $user_info["status"] = api_status_show($a,"raw");
606 if (!count($user_info["status"]))
607 unset($user_info["status"]);
609 unset($user_info["status"]["user"]);
612 // "uid" and "self" are only needed for some internal stuff, so remove it from here
613 unset($user_info["uid"]);
614 unset($user_info["self"]);
616 return api_apply_template("user", $type, array('$user' => $user_info));
619 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
623 * get data from $_POST or $_GET
625 function requestdata($k){
626 if (isset($_POST[$k])){
629 if (isset($_GET[$k])){
635 /*Waitman Gobble Mod*/
636 function api_statuses_mediap(&$a, $type) {
637 if (api_user()===false) {
638 logger('api_statuses_update: no user');
641 $user_info = api_get_user($a);
643 $_REQUEST['type'] = 'wall';
644 $_REQUEST['profile_uid'] = api_user();
645 $_REQUEST['api_source'] = true;
646 $txt = requestdata('status');
647 //$txt = urldecode(requestdata('status'));
649 require_once('library/HTMLPurifier.auto.php');
650 require_once('include/html2bbcode.php');
652 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
653 $txt = html2bb_video($txt);
654 $config = HTMLPurifier_Config::createDefault();
655 $config->set('Cache.DefinitionImpl', null);
656 $purifier = new HTMLPurifier($config);
657 $txt = $purifier->purify($txt);
659 $txt = html2bbcode($txt);
661 $a->argv[1]=$user_info['screen_name']; //should be set to username?
663 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
664 require_once('mod/wall_upload.php');
665 $bebop = wall_upload_post($a);
667 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
668 $_REQUEST['body']=$txt."\n\n".$bebop;
669 require_once('mod/item.php');
672 // this should output the last post (the one we just posted).
673 return api_status_show($a,$type);
675 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
676 /*Waitman Gobble Mod*/
679 function api_statuses_update(&$a, $type) {
680 if (api_user()===false) {
681 logger('api_statuses_update: no user');
685 $user_info = api_get_user($a);
687 // convert $_POST array items to the form we use for web posts.
689 // logger('api_post: ' . print_r($_POST,true));
691 if(requestdata('htmlstatus')) {
692 require_once('library/HTMLPurifier.auto.php');
693 require_once('include/html2bbcode.php');
695 $txt = requestdata('htmlstatus');
696 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
698 $txt = html2bb_video($txt);
700 $config = HTMLPurifier_Config::createDefault();
701 $config->set('Cache.DefinitionImpl', null);
704 $purifier = new HTMLPurifier($config);
705 $txt = $purifier->purify($txt);
707 $_REQUEST['body'] = html2bbcode($txt);
712 $_REQUEST['body'] = requestdata('status');
714 $_REQUEST['title'] = requestdata('title');
716 $parent = requestdata('in_reply_to_status_id');
717 if(ctype_digit($parent))
718 $_REQUEST['parent'] = $parent;
720 $_REQUEST['parent_uri'] = $parent;
722 if(requestdata('lat') && requestdata('long'))
723 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
724 $_REQUEST['profile_uid'] = api_user();
727 $_REQUEST['type'] = 'net-comment';
729 // Check for throttling (maximum posts per day, week and month)
730 $throttle_day = get_config('system','throttle_limit_day');
731 if ($throttle_day > 0) {
732 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
734 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
735 AND `created` > '%s' AND `id` = `parent`",
736 intval(api_user()), dbesc($datefrom));
739 $posts_day = $r[0]["posts_day"];
743 if ($posts_day > $throttle_day) {
744 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
745 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
749 $throttle_week = get_config('system','throttle_limit_week');
750 if ($throttle_week > 0) {
751 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
753 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
754 AND `created` > '%s' AND `id` = `parent`",
755 intval(api_user()), dbesc($datefrom));
758 $posts_week = $r[0]["posts_week"];
762 if ($posts_week > $throttle_week) {
763 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
764 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
768 $throttle_month = get_config('system','throttle_limit_month');
769 if ($throttle_month > 0) {
770 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
772 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
773 AND `created` > '%s' AND `id` = `parent`",
774 intval(api_user()), dbesc($datefrom));
777 $posts_month = $r[0]["posts_month"];
781 if ($posts_month > $throttle_month) {
782 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
783 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
787 $_REQUEST['type'] = 'wall';
788 if(x($_FILES,'media')) {
789 // upload the image if we have one
790 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
791 require_once('mod/wall_upload.php');
792 $media = wall_upload_post($a);
794 $_REQUEST['body'] .= "\n\n".$media;
798 // set this so that the item_post() function is quiet and doesn't redirect or emit json
800 $_REQUEST['api_source'] = true;
802 if (!x($_REQUEST, "source"))
803 $_REQUEST["source"] = api_source();
805 // call out normal post function
807 require_once('mod/item.php');
810 // this should output the last post (the one we just posted).
811 return api_status_show($a,$type);
813 api_register_func('api/statuses/update','api_statuses_update', true);
814 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
817 function api_status_show(&$a, $type){
818 $user_info = api_get_user($a);
820 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
822 // get last public wall message
823 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
824 FROM `item`, `item` as `i`
825 WHERE `item`.`contact-id` = %d
826 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
827 AND `i`.`id` = `item`.`parent`
828 AND `item`.`type`!='activity'
829 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
830 ORDER BY `item`.`created` DESC
832 intval($user_info['cid']),
833 dbesc($user_info['url']),
834 dbesc(normalise_link($user_info['url'])),
835 dbesc($user_info['url']),
836 dbesc(normalise_link($user_info['url']))
839 if (count($lastwall)>0){
840 $lastwall = $lastwall[0];
842 $in_reply_to_status_id = NULL;
843 $in_reply_to_user_id = NULL;
844 $in_reply_to_status_id_str = NULL;
845 $in_reply_to_user_id_str = NULL;
846 $in_reply_to_screen_name = NULL;
847 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
848 $in_reply_to_status_id= intval($lastwall['parent']);
849 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
851 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
853 if ($r[0]['nick'] == "")
854 $r[0]['nick'] = api_get_nick($r[0]["url"]);
856 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
857 $in_reply_to_user_id = intval($r[0]['id']);
858 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
862 // There seems to be situation, where both fields are identical:
863 // https://github.com/friendica/friendica/issues/1010
864 // This is a bugfix for that.
865 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
866 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
867 $in_reply_to_status_id = NULL;
868 $in_reply_to_user_id = NULL;
869 $in_reply_to_status_id_str = NULL;
870 $in_reply_to_user_id_str = NULL;
871 $in_reply_to_screen_name = NULL;
874 $status_info = array(
875 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
876 'truncated' => false,
877 'created_at' => api_date($lastwall['created']),
878 'in_reply_to_status_id' => $in_reply_to_status_id,
879 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
880 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
881 'id' => intval($lastwall['id']),
882 'id_str' => (string) $lastwall['id'],
883 'in_reply_to_user_id' => $in_reply_to_user_id,
884 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
885 'in_reply_to_screen_name' => $in_reply_to_screen_name,
887 'favorited' => false,
889 'user' => $user_info,
890 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
891 'statusnet_conversation_id' => $lastwall['parent'],
894 if ($lastwall['title'] != "")
895 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
897 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
898 if (count($entities) > 0)
899 $status_info['entities'] = $entities;
901 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
902 $status_info["source"] = network_to_name($lastwall['item_network']);
903 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
904 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
906 // "uid" and "self" are only needed for some internal stuff, so remove it from here
907 unset($status_info["user"]["uid"]);
908 unset($status_info["user"]["self"]);
912 return($status_info);
914 return api_apply_template("status", $type, array('$status' => $status_info));
923 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
924 * The author's most recent status will be returned inline.
925 * http://developer.twitter.com/doc/get/users/show
927 function api_users_show(&$a, $type){
928 $user_info = api_get_user($a);
930 $lastwall = q("SELECT `item`.*
931 FROM `item`, `contact`
932 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
933 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
934 AND `contact`.`id`=`item`.`contact-id`
935 AND `type`!='activity'
936 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
937 ORDER BY `created` DESC
940 dbesc(ACTIVITY_POST),
941 intval($user_info['cid']),
942 dbesc($user_info['url']),
943 dbesc(normalise_link($user_info['url'])),
944 dbesc($user_info['url']),
945 dbesc(normalise_link($user_info['url']))
947 if (count($lastwall)>0){
948 $lastwall = $lastwall[0];
950 $in_reply_to_status_id = NULL;
951 $in_reply_to_user_id = NULL;
952 $in_reply_to_status_id_str = NULL;
953 $in_reply_to_user_id_str = NULL;
954 $in_reply_to_screen_name = NULL;
955 if ($lastwall['parent']!=$lastwall['id']) {
956 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
957 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
958 if (count($reply)>0) {
959 $in_reply_to_status_id = intval($lastwall['parent']);
960 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
962 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
964 if ($r[0]['nick'] == "")
965 $r[0]['nick'] = api_get_nick($r[0]["url"]);
967 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
968 $in_reply_to_user_id = intval($r[0]['id']);
969 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
973 $user_info['status'] = array(
974 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
975 'truncated' => false,
976 'created_at' => api_date($lastwall['created']),
977 'in_reply_to_status_id' => $in_reply_to_status_id,
978 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
979 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
980 'id' => intval($lastwall['contact-id']),
981 'id_str' => (string) $lastwall['contact-id'],
982 'in_reply_to_user_id' => $in_reply_to_user_id,
983 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
984 'in_reply_to_screen_name' => $in_reply_to_screen_name,
986 'favorited' => false,
987 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
988 'statusnet_conversation_id' => $lastwall['parent'],
991 if ($lastwall['title'] != "")
992 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
994 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
995 if (count($entities) > 0)
996 $user_info['entities'] = $entities;
998 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
999 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1000 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1001 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1005 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1006 unset($user_info["uid"]);
1007 unset($user_info["self"]);
1009 return api_apply_template("user", $type, array('$user' => $user_info));
1012 api_register_func('api/users/show','api_users_show');
1015 function api_users_search(&$a, $type) {
1016 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1018 $userlist = array();
1020 if (isset($_GET["q"])) {
1021 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1023 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1026 foreach ($r AS $user) {
1027 $user_info = api_get_user($a, $user["id"]);
1028 //echo print_r($user_info, true)."\n";
1029 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1030 $userlist[] = $userdata["user"];
1032 $userlist = array("users" => $userlist);
1034 die(api_error($a, $type, t("User not found.")));
1036 die(api_error($a, $type, t("User not found.")));
1041 api_register_func('api/users/search','api_users_search');
1045 * http://developer.twitter.com/doc/get/statuses/home_timeline
1047 * TODO: Optional parameters
1048 * TODO: Add reply info
1050 function api_statuses_home_timeline(&$a, $type){
1051 if (api_user()===false) return false;
1053 unset($_REQUEST["user_id"]);
1054 unset($_GET["user_id"]);
1056 unset($_REQUEST["screen_name"]);
1057 unset($_GET["screen_name"]);
1059 $user_info = api_get_user($a);
1060 // get last newtork messages
1064 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1065 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1066 if ($page<0) $page=0;
1067 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1068 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1069 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1070 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1071 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1073 $start = $page*$count;
1077 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1078 if ($exclude_replies > 0)
1079 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1080 if ($conversation_id > 0)
1081 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1083 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1084 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1085 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1086 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1087 FROM `item`, `contact`
1088 WHERE `item`.`uid` = %d AND `verb` = '%s'
1089 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1090 AND `contact`.`id` = `item`.`contact-id`
1091 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1094 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1096 dbesc(ACTIVITY_POST),
1098 intval($start), intval($count)
1101 $ret = api_format_items($r,$user_info);
1103 // We aren't going to try to figure out at the item, group, and page
1104 // level which items you've seen and which you haven't. If you're looking
1105 // at the network timeline just mark everything seen.
1107 $r = q("UPDATE `item` SET `unseen` = 0
1108 WHERE `unseen` = 1 AND `uid` = %d",
1109 //intval($user_info['uid'])
1114 $data = array('$statuses' => $ret);
1118 $data = api_rss_extra($a, $data, $user_info);
1121 $as = api_format_as($a, $ret, $user_info);
1122 $as['title'] = $a->config['sitename']." Home Timeline";
1123 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1128 return api_apply_template("timeline", $type, $data);
1130 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1131 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1133 function api_statuses_public_timeline(&$a, $type){
1134 if (api_user()===false) return false;
1136 $user_info = api_get_user($a);
1137 // get last newtork messages
1141 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1142 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1143 if ($page<0) $page=0;
1144 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1145 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1146 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1147 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1148 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1150 $start = $page*$count;
1153 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1154 if ($exclude_replies > 0)
1155 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1156 if ($conversation_id > 0)
1157 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1159 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1160 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1161 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1162 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1163 `user`.`nickname`, `user`.`hidewall`
1164 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1165 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1166 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1167 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1168 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1169 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1170 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1173 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1174 dbesc(ACTIVITY_POST),
1179 $ret = api_format_items($r,$user_info);
1182 $data = array('$statuses' => $ret);
1186 $data = api_rss_extra($a, $data, $user_info);
1189 $as = api_format_as($a, $ret, $user_info);
1190 $as['title'] = $a->config['sitename']." Public Timeline";
1191 $as['link']['url'] = $a->get_baseurl()."/";
1196 return api_apply_template("timeline", $type, $data);
1198 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1203 function api_statuses_show(&$a, $type){
1204 if (api_user()===false) return false;
1206 $user_info = api_get_user($a);
1209 $id = intval($a->argv[3]);
1212 $id = intval($_REQUEST["id"]);
1216 $id = intval($a->argv[4]);
1218 logger('API: api_statuses_show: '.$id);
1220 $conversation = (x($_REQUEST,'conversation')?1:0);
1224 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1226 $sql_extra .= " AND `item`.`id` = %d";
1228 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1229 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1230 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1231 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1232 FROM `item`, `contact`
1233 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1234 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1235 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1238 dbesc(ACTIVITY_POST),
1243 die(api_error($a, $type, t("There is no status with this id.")));
1245 $ret = api_format_items($r,$user_info);
1247 if ($conversation) {
1248 $data = array('$statuses' => $ret);
1249 return api_apply_template("timeline", $type, $data);
1251 $data = array('$status' => $ret[0]);
1255 $data = api_rss_extra($a, $data, $user_info);
1257 return api_apply_template("status", $type, $data);
1260 api_register_func('api/statuses/show','api_statuses_show', true);
1266 function api_conversation_show(&$a, $type){
1267 if (api_user()===false) return false;
1269 $user_info = api_get_user($a);
1272 $id = intval($a->argv[3]);
1273 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1274 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1275 if ($page<0) $page=0;
1276 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1277 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1279 $start = $page*$count;
1282 $id = intval($_REQUEST["id"]);
1286 $id = intval($a->argv[4]);
1288 logger('API: api_conversation_show: '.$id);
1293 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1295 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1296 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1297 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1298 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1299 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1300 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1301 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1302 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1303 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1304 AND `item`.`id`>%d $sql_extra
1305 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1306 intval($id), intval(api_user()),
1307 dbesc(ACTIVITY_POST),
1309 intval($start), intval($count)
1313 die(api_error($a, $type, t("There is no conversation with this id.")));
1315 $ret = api_format_items($r,$user_info);
1317 $data = array('$statuses' => $ret);
1318 return api_apply_template("timeline", $type, $data);
1320 api_register_func('api/conversation/show','api_conversation_show', true);
1326 function api_statuses_repeat(&$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_repeat: '.$id);
1345 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1346 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1347 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1348 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1349 FROM `item`, `contact`
1350 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1351 AND `contact`.`id` = `item`.`contact-id`
1352 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1354 AND `item`.`id`=%d",
1358 if ($r[0]['body'] != "") {
1359 if (!intval(get_config('system','old_share'))) {
1360 if (strpos($r[0]['body'], "[/share]") !== false) {
1361 $pos = strpos($r[0]['body'], "[share");
1362 $post = substr($r[0]['body'], $pos);
1364 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1365 "' profile='".$r[0]['author-link'].
1366 "' avatar='".$r[0]['author-avatar'].
1367 "' link='".$r[0]['plink']."']";
1368 $post .= $r[0]['body'];
1369 $post .= "[/share]";
1371 $_REQUEST['body'] = $post;
1373 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1375 $_REQUEST['profile_uid'] = api_user();
1376 $_REQUEST['type'] = 'wall';
1377 $_REQUEST['api_source'] = true;
1379 if (!x($_REQUEST, "source"))
1380 $_REQUEST["source"] = api_source();
1382 require_once('mod/item.php');
1386 // this should output the last post (the one we just posted).
1388 return(api_status_show($a,$type));
1390 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1395 function api_statuses_destroy(&$a, $type){
1396 if (api_user()===false) return false;
1398 $user_info = api_get_user($a);
1401 $id = intval($a->argv[3]);
1404 $id = intval($_REQUEST["id"]);
1408 $id = intval($a->argv[4]);
1410 logger('API: api_statuses_destroy: '.$id);
1412 $ret = api_statuses_show($a, $type);
1414 require_once('include/items.php');
1415 drop_item($id, false);
1419 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1423 * http://developer.twitter.com/doc/get/statuses/mentions
1426 function api_statuses_mentions(&$a, $type){
1427 if (api_user()===false) return false;
1429 unset($_REQUEST["user_id"]);
1430 unset($_GET["user_id"]);
1432 unset($_REQUEST["screen_name"]);
1433 unset($_GET["screen_name"]);
1435 $user_info = api_get_user($a);
1436 // get last newtork messages
1440 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1441 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1442 if ($page<0) $page=0;
1443 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1444 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1445 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1447 $start = $page*$count;
1449 // Ugly code - should be changed
1450 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1451 $myurl = substr($myurl,strpos($myurl,'://')+3);
1452 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1453 $myurl = str_replace('www.','',$myurl);
1454 $diasp_url = str_replace('/profile/','/u/',$myurl);
1457 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1459 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1460 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1461 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1462 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1463 FROM `item`, `contact`
1464 WHERE `item`.`uid` = %d AND `verb` = '%s'
1465 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1466 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1467 AND `contact`.`id` = `item`.`contact-id`
1468 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1469 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1472 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1474 dbesc(ACTIVITY_POST),
1475 dbesc(protect_sprintf($myurl)),
1476 dbesc(protect_sprintf($myurl)),
1479 intval($start), intval($count)
1482 $ret = api_format_items($r,$user_info);
1485 $data = array('$statuses' => $ret);
1489 $data = api_rss_extra($a, $data, $user_info);
1492 $as = api_format_as($a, $ret, $user_info);
1493 $as["title"] = $a->config['sitename']." Mentions";
1494 $as['link']['url'] = $a->get_baseurl()."/";
1499 return api_apply_template("timeline", $type, $data);
1501 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1502 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1505 function api_statuses_user_timeline(&$a, $type){
1506 if (api_user()===false) return false;
1508 $user_info = api_get_user($a);
1509 // get last network messages
1511 logger("api_statuses_user_timeline: api_user: ". api_user() .
1512 "\nuser_info: ".print_r($user_info, true) .
1513 "\n_REQUEST: ".print_r($_REQUEST, true),
1517 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1518 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1519 if ($page<0) $page=0;
1520 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1521 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1522 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1523 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1525 $start = $page*$count;
1528 if ($user_info['self']==1)
1529 $sql_extra .= " AND `item`.`wall` = 1 ";
1531 if ($exclude_replies > 0)
1532 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1533 if ($conversation_id > 0)
1534 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1536 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1537 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1538 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1539 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1540 FROM `item`, `contact`
1541 WHERE `item`.`uid` = %d AND `verb` = '%s'
1542 AND `item`.`contact-id` = %d
1543 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1544 AND `contact`.`id` = `item`.`contact-id`
1545 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1548 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1550 dbesc(ACTIVITY_POST),
1551 intval($user_info['cid']),
1553 intval($start), intval($count)
1556 $ret = api_format_items($r,$user_info, true);
1558 $data = array('$statuses' => $ret);
1562 $data = api_rss_extra($a, $data, $user_info);
1565 return api_apply_template("timeline", $type, $data);
1568 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1571 function api_favorites(&$a, $type){
1574 if (api_user()===false) return false;
1576 $called_api= array();
1578 $user_info = api_get_user($a);
1580 // in friendica starred item are private
1581 // return favorites only for self
1582 logger('api_favorites: self:' . $user_info['self']);
1584 if ($user_info['self']==0) {
1590 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1591 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1592 $count = (x($_GET,'count')?$_GET['count']:20);
1593 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1594 if ($page<0) $page=0;
1596 $start = $page*$count;
1599 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1601 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1602 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1603 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1604 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1605 FROM `item`, `contact`
1606 WHERE `item`.`uid` = %d AND `verb` = '%s'
1607 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1608 AND `item`.`starred` = 1
1609 AND `contact`.`id` = `item`.`contact-id`
1610 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1613 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1615 dbesc(ACTIVITY_POST),
1617 intval($start), intval($count)
1620 $ret = api_format_items($r,$user_info);
1624 $data = array('$statuses' => $ret);
1628 $data = api_rss_extra($a, $data, $user_info);
1631 return api_apply_template("timeline", $type, $data);
1634 api_register_func('api/favorites','api_favorites', true);
1636 function api_format_as($a, $ret, $user_info) {
1639 $as['title'] = $a->config['sitename']." Public Timeline";
1641 foreach ($ret as $item) {
1642 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1643 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1644 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1645 $avatar[0]["rel"] = "avatar";
1646 $avatar[0]["type"] = "";
1647 $avatar[0]["width"] = 96;
1648 $avatar[0]["height"] = 96;
1649 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1650 $avatar[1]["rel"] = "avatar";
1651 $avatar[1]["type"] = "";
1652 $avatar[1]["width"] = 48;
1653 $avatar[1]["height"] = 48;
1654 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1655 $avatar[2]["rel"] = "avatar";
1656 $avatar[2]["type"] = "";
1657 $avatar[2]["width"] = 24;
1658 $avatar[2]["height"] = 24;
1659 $singleitem["actor"]["avatarLinks"] = $avatar;
1661 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1662 $singleitem["actor"]["image"]["rel"] = "avatar";
1663 $singleitem["actor"]["image"]["type"] = "";
1664 $singleitem["actor"]["image"]["width"] = 96;
1665 $singleitem["actor"]["image"]["height"] = 96;
1666 $singleitem["actor"]["type"] = "person";
1667 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1668 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1669 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1670 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1671 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1672 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1673 $singleitem["actor"]["contact"]["addresses"] = "";
1675 $singleitem["body"] = $item["text"];
1676 $singleitem["object"]["displayName"] = $item["text"];
1677 $singleitem["object"]["id"] = $item["url"];
1678 $singleitem["object"]["type"] = "note";
1679 $singleitem["object"]["url"] = $item["url"];
1680 //$singleitem["context"] =;
1681 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1682 $singleitem["provider"]["objectType"] = "service";
1683 $singleitem["provider"]["displayName"] = "Test";
1684 $singleitem["provider"]["url"] = "http://test.tld";
1685 $singleitem["title"] = $item["text"];
1686 $singleitem["verb"] = "post";
1687 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1688 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1689 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1690 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1691 //$singleitem["original"] = $item;
1692 $items[] = $singleitem;
1694 $as['items'] = $items;
1695 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1696 $as['link']['rel'] = "alternate";
1697 $as['link']['type'] = "text/html";
1701 function api_format_messages($item, $recipient, $sender) {
1702 // standard meta information
1704 'id' => $item['id'],
1705 'sender_id' => $sender['id'] ,
1707 'recipient_id' => $recipient['id'],
1708 'created_at' => api_date($item['created']),
1709 'sender_screen_name' => $sender['screen_name'],
1710 'recipient_screen_name' => $recipient['screen_name'],
1711 'sender' => $sender,
1712 'recipient' => $recipient,
1715 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1716 unset($ret["sender"]["uid"]);
1717 unset($ret["sender"]["self"]);
1718 unset($ret["recipient"]["uid"]);
1719 unset($ret["recipient"]["self"]);
1721 //don't send title to regular StatusNET requests to avoid confusing these apps
1722 if (x($_GET, 'getText')) {
1723 $ret['title'] = $item['title'] ;
1724 if ($_GET["getText"] == "html") {
1725 $ret['text'] = bbcode($item['body'], false, false);
1727 elseif ($_GET["getText"] == "plain") {
1728 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1729 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1733 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1735 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1736 unset($ret['sender']);
1737 unset($ret['recipient']);
1743 function api_get_entitities(&$text, $bbcode) {
1746 * Links at the first character of the post
1751 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1753 if ($include_entities != "true") {
1754 require_once("mod/proxy.php");
1756 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1758 foreach ($images[1] AS $image) {
1759 $replace = proxy_url($image);
1760 $text = str_replace($image, $replace, $text);
1765 $bbcode = bb_CleanPictureLinks($bbcode);
1767 // Change pure links in text to bbcode uris
1768 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1770 $entities = array();
1771 $entities["hashtags"] = array();
1772 $entities["symbols"] = array();
1773 $entities["urls"] = array();
1774 $entities["user_mentions"] = array();
1776 $URLSearchString = "^\[\]";
1778 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1780 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1781 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1782 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1784 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1785 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1786 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1788 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1789 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1790 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1792 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1794 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1795 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1797 $ordered_urls = array();
1798 foreach ($urls[1] AS $id=>$url) {
1799 //$start = strpos($text, $url, $offset);
1800 $start = iconv_strpos($text, $url, 0, "UTF-8");
1801 if (!($start === false))
1802 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1805 ksort($ordered_urls);
1808 //foreach ($urls[1] AS $id=>$url) {
1809 foreach ($ordered_urls AS $url) {
1810 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1811 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1812 $display_url = $url["title"];
1814 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1815 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1817 if (strlen($display_url) > 26)
1818 $display_url = substr($display_url, 0, 25)."…";
1821 //$start = strpos($text, $url, $offset);
1822 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1823 if (!($start === false)) {
1824 $entities["urls"][] = array("url" => $url["url"],
1825 "expanded_url" => $url["url"],
1826 "display_url" => $display_url,
1827 "indices" => array($start, $start+strlen($url["url"])));
1828 $offset = $start + 1;
1832 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1833 $ordered_images = array();
1834 foreach ($images[1] AS $image) {
1835 //$start = strpos($text, $url, $offset);
1836 $start = iconv_strpos($text, $image, 0, "UTF-8");
1837 if (!($start === false))
1838 $ordered_images[$start] = $image;
1840 //$entities["media"] = array();
1843 foreach ($ordered_images AS $url) {
1844 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1845 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1847 if (strlen($display_url) > 26)
1848 $display_url = substr($display_url, 0, 25)."…";
1850 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1851 if (!($start === false)) {
1852 require_once("include/Photo.php");
1853 $image = get_photo_info($url);
1855 // If image cache is activated, then use the following sizes:
1856 // thumb (150), small (340), medium (600) and large (1024)
1857 if (!get_config("system", "proxy_disabled")) {
1858 require_once("mod/proxy.php");
1859 $media_url = proxy_url($url);
1862 $scale = scale_image($image[0], $image[1], 150);
1863 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1865 if (($image[0] > 150) OR ($image[1] > 150)) {
1866 $scale = scale_image($image[0], $image[1], 340);
1867 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1870 $scale = scale_image($image[0], $image[1], 600);
1871 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1873 if (($image[0] > 600) OR ($image[1] > 600)) {
1874 $scale = scale_image($image[0], $image[1], 1024);
1875 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1879 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1882 $entities["media"][] = array(
1884 "id_str" => (string)$start+1,
1885 "indices" => array($start, $start+strlen($url)),
1886 "media_url" => normalise_link($media_url),
1887 "media_url_https" => $media_url,
1889 "display_url" => $display_url,
1890 "expanded_url" => $url,
1894 $offset = $start + 1;
1900 function api_format_items_embeded_images($item, $text){
1902 $text = preg_replace_callback(
1903 "|data:image/([^;]+)[^=]+=*|m",
1904 function($match) use ($a, $item) {
1905 return $a->get_baseurl()."/display/".$item['guid'];
1911 function api_format_items($r,$user_info, $filter_user = false) {
1916 foreach($r as $item) {
1917 api_share_as_retweet($a, api_user(), $item);
1919 localize_item($item);
1920 $status_user = api_item_get_user($a,$item);
1922 // Look if the posts are matching if they should be filtered by user id
1923 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1926 if ($item['thr-parent'] != $item['uri']) {
1927 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1929 dbesc($item['thr-parent']));
1931 $in_reply_to_status_id = intval($r[0]['id']);
1933 $in_reply_to_status_id = intval($item['parent']);
1935 $in_reply_to_status_id_str = (string) intval($item['parent']);
1937 $in_reply_to_screen_name = NULL;
1938 $in_reply_to_user_id = NULL;
1939 $in_reply_to_user_id_str = NULL;
1941 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1943 intval($in_reply_to_status_id));
1945 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1948 if ($r[0]['nick'] == "")
1949 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1951 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1952 $in_reply_to_user_id = intval($r[0]['id']);
1953 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1957 $in_reply_to_screen_name = NULL;
1958 $in_reply_to_user_id = NULL;
1959 $in_reply_to_status_id = NULL;
1960 $in_reply_to_user_id_str = NULL;
1961 $in_reply_to_status_id_str = NULL;
1964 // Workaround for ostatus messages where the title is identically to the body
1965 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1966 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1967 $statusbody = trim(html2plain($html, 0));
1969 // handle data: images
1970 $statusbody = api_format_items_embeded_images($item,$statusbody);
1972 $statustitle = trim($item['title']);
1974 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1975 $statustext = trim($statusbody);
1977 $statustext = trim($statustitle."\n\n".$statusbody);
1979 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1980 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1982 $statushtml = trim(bbcode($item['body'], false, false));
1986 'text' => $statustext,
1987 'truncated' => False,
1988 'created_at'=> api_date($item['created']),
1989 'in_reply_to_status_id' => $in_reply_to_status_id,
1990 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1991 'source' => (($item['app']) ? $item['app'] : 'web'),
1992 'id' => intval($item['id']),
1993 'id_str' => (string) intval($item['id']),
1994 'in_reply_to_user_id' => $in_reply_to_user_id,
1995 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1996 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1998 'favorited' => $item['starred'] ? true : false,
1999 //'attachments' => array(),
2000 'user' => $status_user ,
2001 //'entities' => NULL,
2002 'statusnet_html' => $statushtml,
2003 'statusnet_conversation_id' => $item['parent'],
2006 if ($item['title'] != "")
2007 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
2009 $entities = api_get_entitities($status['text'], $item['body']);
2010 if (count($entities) > 0)
2011 $status['entities'] = $entities;
2013 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2014 $status["source"] = network_to_name($item['item_network']);
2015 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2016 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2019 // Retweets are only valid for top postings
2020 // It doesn't work reliable with the link if its a feed
2021 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2023 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2025 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2026 $retweeted_status = $status;
2027 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2029 $status["retweeted_status"] = $retweeted_status;
2032 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2033 unset($status["user"]["uid"]);
2034 unset($status["user"]["self"]);
2036 // 'geo' => array('type' => 'Point',
2037 // 'coordinates' => array((float) $notice->lat,
2038 // (float) $notice->lon));
2046 function api_account_rate_limit_status(&$a,$type) {
2049 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2050 'remaining_hits' => (string) 150,
2051 'hourly_limit' => (string) 150,
2052 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2055 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2057 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2060 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2062 function api_help_test(&$a,$type) {
2069 return api_apply_template('test', $type, array("$ok" => $ok));
2072 api_register_func('api/help/test','api_help_test',false);
2074 function api_lists(&$a,$type) {
2079 api_register_func('api/lists','api_lists',true);
2081 function api_lists_list(&$a,$type) {
2086 api_register_func('api/lists/list','api_lists_list',true);
2089 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2090 * This function is deprecated by Twitter
2091 * returns: json, xml
2093 function api_statuses_f(&$a, $type, $qtype) {
2094 if (api_user()===false) return false;
2095 $user_info = api_get_user($a);
2097 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2098 /* this is to stop Hotot to load friends multiple times
2099 * I'm not sure if I'm missing return something or
2100 * is a bug in hotot. Workaround, meantime
2104 return array('$users' => $ret);*/
2108 if($qtype == 'friends')
2109 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2110 if($qtype == 'followers')
2111 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2113 // friends and followers only for self
2114 if ($user_info['self'] == 0)
2115 $sql_extra = " AND false ";
2117 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2122 foreach($r as $cid){
2123 $user = api_get_user($a, $cid['nurl']);
2124 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2125 unset($user["uid"]);
2126 unset($user["self"]);
2132 return array('$users' => $ret);
2135 function api_statuses_friends(&$a, $type){
2136 $data = api_statuses_f($a,$type,"friends");
2137 if ($data===false) return false;
2138 return api_apply_template("friends", $type, $data);
2140 function api_statuses_followers(&$a, $type){
2141 $data = api_statuses_f($a,$type,"followers");
2142 if ($data===false) return false;
2143 return api_apply_template("friends", $type, $data);
2145 api_register_func('api/statuses/friends','api_statuses_friends',true);
2146 api_register_func('api/statuses/followers','api_statuses_followers',true);
2153 function api_statusnet_config(&$a,$type) {
2154 $name = $a->config['sitename'];
2155 $server = $a->get_hostname();
2156 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2157 $email = $a->config['admin_email'];
2158 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2159 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2160 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2161 if($a->config['api_import_size'])
2162 $texlimit = string($a->config['api_import_size']);
2163 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2164 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2167 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2168 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2169 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2170 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2171 'shorturllength' => '30',
2172 'friendica' => array(
2173 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2174 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2175 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2176 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2181 return api_apply_template('config', $type, array('$config' => $config));
2184 api_register_func('api/statusnet/config','api_statusnet_config',false);
2186 function api_statusnet_version(&$a,$type) {
2190 if($type === 'xml') {
2191 header("Content-type: application/xml");
2192 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2195 elseif($type === 'json') {
2196 header("Content-type: application/json");
2201 api_register_func('api/statusnet/version','api_statusnet_version',false);
2204 function api_ff_ids(&$a,$type,$qtype) {
2208 $user_info = api_get_user($a);
2210 if($qtype == 'friends')
2211 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2212 if($qtype == 'followers')
2213 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2215 if (!$user_info["self"])
2216 $sql_extra = " AND false ";
2218 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2220 $r = q("SELECT unique_contacts.id FROM contact, unique_contacts WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2226 if($type === 'xml') {
2227 header("Content-type: application/xml");
2228 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2230 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2231 echo '</ids>' . "\r\n";
2234 elseif($type === 'json') {
2236 header("Content-type: application/json");
2241 $ret[] = intval($rr['id']);
2243 echo json_encode($ret);
2249 function api_friends_ids(&$a,$type) {
2250 api_ff_ids($a,$type,'friends');
2252 function api_followers_ids(&$a,$type) {
2253 api_ff_ids($a,$type,'followers');
2255 api_register_func('api/friends/ids','api_friends_ids',true);
2256 api_register_func('api/followers/ids','api_followers_ids',true);
2259 function api_direct_messages_new(&$a, $type) {
2260 if (api_user()===false) return false;
2262 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2264 $sender = api_get_user($a);
2266 require_once("include/message.php");
2268 if ($_POST['screen_name']) {
2269 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2271 dbesc($_POST['screen_name']));
2273 // Selecting the id by priority, friendica first
2274 api_best_nickname($r);
2276 $recipient = api_get_user($a, $r[0]['nurl']);
2278 $recipient = api_get_user($a, $_POST['user_id']);
2282 if (x($_REQUEST,'replyto')) {
2283 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2285 intval($_REQUEST['replyto']));
2286 $replyto = $r[0]['parent-uri'];
2287 $sub = $r[0]['title'];
2290 if (x($_REQUEST,'title')) {
2291 $sub = $_REQUEST['title'];
2294 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2298 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2301 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2302 $ret = api_format_messages($r[0], $recipient, $sender);
2305 $ret = array("error"=>$id);
2308 $data = Array('$messages'=>$ret);
2313 $data = api_rss_extra($a, $data, $user_info);
2316 return api_apply_template("direct_messages", $type, $data);
2319 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2321 function api_direct_messages_box(&$a, $type, $box) {
2322 if (api_user()===false) return false;
2326 $count = (x($_GET,'count')?$_GET['count']:20);
2327 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2328 if ($page<0) $page=0;
2330 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2331 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2333 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2334 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2337 unset($_REQUEST["user_id"]);
2338 unset($_GET["user_id"]);
2340 unset($_REQUEST["screen_name"]);
2341 unset($_GET["screen_name"]);
2343 $user_info = api_get_user($a);
2344 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2345 $profile_url = $user_info["url"];
2349 $start = $page*$count;
2352 if ($box=="sentbox") {
2353 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2355 elseif ($box=="conversation") {
2356 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2358 elseif ($box=="all") {
2359 $sql_extra = "true";
2361 elseif ($box=="inbox") {
2362 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2366 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2368 if ($user_id !="") {
2369 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2371 elseif($screen_name !=""){
2372 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2375 $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",
2378 intval($start), intval($count)
2383 foreach($r as $item) {
2384 if ($box == "inbox" || $item['from-url'] != $profile_url){
2385 $recipient = $user_info;
2386 $sender = api_get_user($a,normalise_link($item['contact-url']));
2388 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2389 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2390 $sender = $user_info;
2393 $ret[]=api_format_messages($item, $recipient, $sender);
2397 $data = array('$messages' => $ret);
2401 $data = api_rss_extra($a, $data, $user_info);
2404 return api_apply_template("direct_messages", $type, $data);
2408 function api_direct_messages_sentbox(&$a, $type){
2409 return api_direct_messages_box($a, $type, "sentbox");
2411 function api_direct_messages_inbox(&$a, $type){
2412 return api_direct_messages_box($a, $type, "inbox");
2414 function api_direct_messages_all(&$a, $type){
2415 return api_direct_messages_box($a, $type, "all");
2417 function api_direct_messages_conversation(&$a, $type){
2418 return api_direct_messages_box($a, $type, "conversation");
2420 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2421 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2422 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2423 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2427 function api_oauth_request_token(&$a, $type){
2429 $oauth = new FKOAuth1();
2430 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2431 }catch(Exception $e){
2432 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2437 function api_oauth_access_token(&$a, $type){
2439 $oauth = new FKOAuth1();
2440 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2441 }catch(Exception $e){
2442 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2448 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2449 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2452 function api_fr_photos_list(&$a,$type) {
2453 if (api_user()===false) return false;
2454 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2455 intval(local_user())
2460 $ret[] = $rr['resource-id'];
2461 header("Content-type: application/json");
2462 echo json_encode($ret);
2467 function api_fr_photo_detail(&$a,$type) {
2468 if (api_user()===false) return false;
2469 if(! $_REQUEST['photo_id']) return false;
2470 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2471 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2472 intval(local_user()),
2473 dbesc($_REQUEST['photo_id']),
2477 header("Content-type: application/json");
2478 $r[0]['data'] = base64_encode($r[0]['data']);
2479 echo json_encode($r[0]);
2485 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2486 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2490 function api_share_as_retweet($a, $uid, &$item) {
2491 $body = trim($item["body"]);
2493 // Skip if it isn't a pure repeated messages
2494 // Does it start with a share?
2495 if (strpos($body, "[share") > 0)
2498 // Does it end with a share?
2499 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2502 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2503 // Skip if there is no shared message in there
2504 if ($body == $attributes)
2508 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2509 if ($matches[1] != "")
2510 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2512 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2513 if ($matches[1] != "")
2514 $author = $matches[1];
2517 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2518 if ($matches[1] != "")
2519 $profile = $matches[1];
2521 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2522 if ($matches[1] != "")
2523 $profile = $matches[1];
2526 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2527 if ($matches[1] != "")
2528 $avatar = $matches[1];
2530 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2531 if ($matches[1] != "")
2532 $avatar = $matches[1];
2534 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2536 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2539 $item["body"] = $shared_body;
2540 $item["author-name"] = $author;
2541 $item["author-link"] = $profile;
2542 $item["author-avatar"] = $avatar;
2548 function api_get_nick($profile) {
2550 - remove trailing jung from profile url
2551 - pump.io check has to check the website
2556 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2557 if ($friendica != $profile)
2561 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2562 if ($diaspora != $profile)
2567 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2568 if ($twitter != $profile)
2574 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2575 if ($StatusnetHost != $profile) {
2576 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2577 if ($StatusnetUser != $profile) {
2578 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2579 $user = json_decode($UserData);
2581 $nick = $user->screen_name;
2586 // To-Do: look at the page if its really a pumpio site
2587 //if (!$nick == "") {
2588 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2589 // if ($pumpio != $profile)
2591 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2596 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2597 dbesc($nick), dbesc(normalise_link($profile)));
2604 function api_clean_plain_items($Text) {
2605 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2607 $Text = bb_CleanPictureLinks($Text);
2609 $URLSearchString = "^\[\]";
2611 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2613 if ($include_entities == "true") {
2614 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2617 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2621 function api_cleanup_share($shared) {
2622 if ($shared[2] != "type-link")
2625 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2631 if (isset($bookmark[2][0]))
2632 $title = $bookmark[2][0];
2634 if (isset($bookmark[1][0]))
2635 $link = $bookmark[1][0];
2637 if (strpos($shared[1],$title) !== false)
2640 if (strpos($shared[1],$link) !== false)
2643 $text = trim($shared[1]);
2645 //if (strlen($text) < strlen($title))
2646 if (($text == "") AND ($title != ""))
2647 $text .= "\n\n".trim($title);
2650 $text .= "\n".trim($link);
2652 return(trim($text));
2655 function api_best_nickname(&$contacts) {
2656 $best_contact = array();
2658 if (count($contact) == 0)
2661 foreach ($contacts AS $contact)
2662 if ($contact["network"] == "") {
2663 $contact["network"] = "dfrn";
2664 $best_contact = array($contact);
2667 if (sizeof($best_contact) == 0)
2668 foreach ($contacts AS $contact)
2669 if ($contact["network"] == "dfrn")
2670 $best_contact = array($contact);
2672 if (sizeof($best_contact) == 0)
2673 foreach ($contacts AS $contact)
2674 if ($contact["network"] == "dspr")
2675 $best_contact = array($contact);
2677 if (sizeof($best_contact) == 0)
2678 foreach ($contacts AS $contact)
2679 if ($contact["network"] == "stat")
2680 $best_contact = array($contact);
2682 if (sizeof($best_contact) == 0)
2683 foreach ($contacts AS $contact)
2684 if ($contact["network"] == "pump")
2685 $best_contact = array($contact);
2687 if (sizeof($best_contact) == 0)
2688 foreach ($contacts AS $contact)
2689 if ($contact["network"] == "twit")
2690 $best_contact = array($contact);
2692 if (sizeof($best_contact) == 1)
2693 $contacts = $best_contact;
2695 $contacts = array($contacts[0]);
2699 Not implemented by now:
2703 statuses/retweets_of_me
2708 account/update_location
2709 account/update_profile_background_image
2710 account/update_profile_image
2714 Not implemented in status.net:
2715 statuses/retweeted_to_me
2716 statuses/retweeted_by_me
2717 direct_messages/destroy
2719 account/update_delivery_device
2720 notifications/follow