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 # TODO: https://dev.twitter.com/overview/api/response-codes
201 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
204 header ("Content-Type: text/xml");
205 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
208 header ("Content-Type: application/json");
209 return json_encode(array('error' => $error, 'request' => $a->query_string));
212 header ("Content-Type: application/rss+xml");
213 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
216 header ("Content-Type: application/atom+xml");
217 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
225 function api_rss_extra(&$a, $arr, $user_info){
226 if (is_null($user_info)) $user_info = api_get_user($a);
227 $arr['$user'] = $user_info;
228 $arr['$rss'] = array(
229 'alternate' => $user_info['url'],
230 'self' => $a->get_baseurl(). "/". $a->query_string,
231 'base' => $a->get_baseurl(),
232 'updated' => api_date(null),
233 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
234 'language' => $user_info['language'],
235 'logo' => $a->get_baseurl()."/images/friendica-32.png",
243 * Unique contact to contact url.
245 function api_unique_id_to_url($id){
246 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
249 return ($r[0]["url"]);
255 * Returns user info array.
257 function api_get_user(&$a, $contact_id = Null, $type = "json"){
264 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
266 // Searching for contact URL
267 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
268 $user = dbesc(normalise_link($contact_id));
270 $extra_query = "AND `contact`.`nurl` = '%s' ";
271 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
274 // Searching for unique contact id
275 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
276 $user = dbesc(api_unique_id_to_url($contact_id));
279 die(api_error($a, $type, t("User not found.")));
282 $extra_query = "AND `contact`.`nurl` = '%s' ";
283 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
286 if(is_null($user) && x($_GET, 'user_id')) {
287 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
290 die(api_error($a, $type, t("User not found.")));
293 $extra_query = "AND `contact`.`nurl` = '%s' ";
294 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
296 if(is_null($user) && x($_GET, 'screen_name')) {
297 $user = dbesc($_GET['screen_name']);
299 $extra_query = "AND `contact`.`nick` = '%s' ";
300 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
303 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
304 $argid = count($called_api);
305 list($user, $null) = explode(".",$a->argv[$argid]);
306 if(is_numeric($user)){
307 $user = dbesc(api_unique_id_to_url($user));
313 $extra_query = "AND `contact`.`nurl` = '%s' ";
314 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
316 $user = dbesc($user);
318 $extra_query = "AND `contact`.`nick` = '%s' ";
319 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
323 logger("api_get_user: user ".$user, LOGGER_DEBUG);
326 if (api_user()===false) {
327 api_login($a); return False;
329 $user = $_SESSION['uid'];
330 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
335 logger('api_user: ' . $extra_query . ', user: ' . $user);
337 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
343 // Selecting the id by priority, friendica first
344 api_best_nickname($uinfo);
346 // if the contact wasn't found, fetch it from the unique contacts
347 if (count($uinfo)==0) {
351 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
353 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
356 // If no nick where given, extract it from the address
357 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
358 $r[0]['nick'] = api_get_nick($r[0]["url"]);
362 'id_str' => (string) $r[0]["id"],
363 'name' => $r[0]["name"],
364 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
366 'description' => NULL,
367 'profile_image_url' => $r[0]["avatar"],
368 'profile_image_url_https' => $r[0]["avatar"],
369 'url' => $r[0]["url"],
370 'protected' => false,
371 'followers_count' => 0,
372 'friends_count' => 0,
373 'created_at' => api_date(0),
374 'favourites_count' => 0,
376 'time_zone' => 'UTC',
377 'statuses_count' => 0,
378 'following' => false,
380 'statusnet_blocking' => false,
381 'notifications' => false,
382 'statusnet_profile_url' => $r[0]["url"],
391 die(api_error($a, $type, t("User not found.")));
395 if($uinfo[0]['self']) {
396 $usr = q("select * from user where uid = %d limit 1",
399 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
403 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
404 // count public wall messages
405 $r = q("SELECT count(*) as `count` FROM `item`
408 intval($uinfo[0]['uid'])
410 $countitms = $r[0]['count'];
413 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
414 $r = q("SELECT count(*) as `count` FROM `item`
415 WHERE `contact-id` = %d",
416 intval($uinfo[0]['id'])
418 $countitms = $r[0]['count'];
422 $r = q("SELECT count(*) as `count` FROM `contact`
423 WHERE `uid` = %d AND `rel` IN ( %d, %d )
424 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
425 intval($uinfo[0]['uid']),
426 intval(CONTACT_IS_SHARING),
427 intval(CONTACT_IS_FRIEND)
429 $countfriends = $r[0]['count'];
431 $r = q("SELECT count(*) as `count` FROM `contact`
432 WHERE `uid` = %d AND `rel` IN ( %d, %d )
433 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
434 intval($uinfo[0]['uid']),
435 intval(CONTACT_IS_FOLLOWER),
436 intval(CONTACT_IS_FRIEND)
438 $countfollowers = $r[0]['count'];
440 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
441 intval($uinfo[0]['uid'])
443 $starred = $r[0]['count'];
446 if(! $uinfo[0]['self']) {
452 // Add a nick if it isn't present there
453 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
454 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
457 // Fetching unique id
458 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
460 // If not there, then add it
461 if (count($r) == 0) {
462 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
463 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
465 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
468 require_once('include/contact_selectors.php');
469 $network_name = network_to_name($uinfo[0]['network']);
472 'id' => intval($r[0]['id']),
473 'id_str' => (string) intval($r[0]['id']),
474 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
475 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
476 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
477 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
478 'profile_image_url' => $uinfo[0]['micro'],
479 'profile_image_url_https' => $uinfo[0]['micro'],
480 'url' => $uinfo[0]['url'],
481 'protected' => false,
482 'followers_count' => intval($countfollowers),
483 'friends_count' => intval($countfriends),
484 'created_at' => api_date($uinfo[0]['created']),
485 'favourites_count' => intval($starred),
487 'time_zone' => 'UTC',
488 'statuses_count' => intval($countitms),
489 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
491 'statusnet_blocking' => false,
492 'notifications' => false,
493 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
494 'uid' => intval($uinfo[0]['uid']),
495 'cid' => intval($uinfo[0]['cid']),
496 'self' => $uinfo[0]['self'],
497 'network' => $uinfo[0]['network'],
504 function api_item_get_user(&$a, $item) {
506 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
507 dbesc(normalise_link($item['author-link'])));
509 if (count($author) == 0) {
510 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
511 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
513 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
514 dbesc(normalise_link($item['author-link'])));
515 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
516 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
517 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
520 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
521 dbesc(normalise_link($item['owner-link'])));
523 if (count($owner) == 0) {
524 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
525 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
527 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
528 dbesc(normalise_link($item['owner-link'])));
529 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
530 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
531 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
534 // Comments in threads may appear as wall-to-wall postings.
535 // So only take the owner at the top posting.
536 if ($item["id"] == $item["parent"])
537 $status_user = api_get_user($a,$item["owner-link"]);
539 $status_user = api_get_user($a,$item["author-link"]);
541 $status_user["protected"] = (($item["allow_cid"] != "") OR
542 ($item["allow_gid"] != "") OR
543 ($item["deny_cid"] != "") OR
544 ($item["deny_gid"] != "") OR
547 return ($status_user);
552 * load api $templatename for $type and replace $data array
554 function api_apply_template($templatename, $type, $data){
562 $data = array_xmlify($data);
563 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
565 header ("Content-Type: text/xml");
566 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
569 $ret = replace_macros($tpl, $data);
584 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
585 * returns a 401 status code and an error message if not.
586 * http://developer.twitter.com/doc/get/account/verify_credentials
588 function api_account_verify_credentials(&$a, $type){
589 if (api_user()===false) return false;
591 unset($_REQUEST["user_id"]);
592 unset($_GET["user_id"]);
594 unset($_REQUEST["screen_name"]);
595 unset($_GET["screen_name"]);
597 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
599 $user_info = api_get_user($a);
601 // "verified" isn't used here in the standard
602 unset($user_info["verified"]);
604 // - Adding last status
606 $user_info["status"] = api_status_show($a,"raw");
607 if (!count($user_info["status"]))
608 unset($user_info["status"]);
610 unset($user_info["status"]["user"]);
613 // "uid" and "self" are only needed for some internal stuff, so remove it from here
614 unset($user_info["uid"]);
615 unset($user_info["self"]);
617 return api_apply_template("user", $type, array('$user' => $user_info));
620 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
624 * get data from $_POST or $_GET
626 function requestdata($k){
627 if (isset($_POST[$k])){
630 if (isset($_GET[$k])){
636 /*Waitman Gobble Mod*/
637 function api_statuses_mediap(&$a, $type) {
638 if (api_user()===false) {
639 logger('api_statuses_update: no user');
642 $user_info = api_get_user($a);
644 $_REQUEST['type'] = 'wall';
645 $_REQUEST['profile_uid'] = api_user();
646 $_REQUEST['api_source'] = true;
647 $txt = requestdata('status');
648 //$txt = urldecode(requestdata('status'));
650 require_once('library/HTMLPurifier.auto.php');
651 require_once('include/html2bbcode.php');
653 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
654 $txt = html2bb_video($txt);
655 $config = HTMLPurifier_Config::createDefault();
656 $config->set('Cache.DefinitionImpl', null);
657 $purifier = new HTMLPurifier($config);
658 $txt = $purifier->purify($txt);
660 $txt = html2bbcode($txt);
662 $a->argv[1]=$user_info['screen_name']; //should be set to username?
664 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
665 require_once('mod/wall_upload.php');
666 $bebop = wall_upload_post($a);
668 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
669 $_REQUEST['body']=$txt."\n\n".$bebop;
670 require_once('mod/item.php');
673 // this should output the last post (the one we just posted).
674 return api_status_show($a,$type);
676 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
677 /*Waitman Gobble Mod*/
680 function api_statuses_update(&$a, $type) {
681 if (api_user()===false) {
682 logger('api_statuses_update: no user');
686 $user_info = api_get_user($a);
688 // convert $_POST array items to the form we use for web posts.
690 // logger('api_post: ' . print_r($_POST,true));
692 if(requestdata('htmlstatus')) {
693 require_once('library/HTMLPurifier.auto.php');
694 require_once('include/html2bbcode.php');
696 $txt = requestdata('htmlstatus');
697 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
699 $txt = html2bb_video($txt);
701 $config = HTMLPurifier_Config::createDefault();
702 $config->set('Cache.DefinitionImpl', null);
705 $purifier = new HTMLPurifier($config);
706 $txt = $purifier->purify($txt);
708 $_REQUEST['body'] = html2bbcode($txt);
713 $_REQUEST['body'] = requestdata('status');
715 $_REQUEST['title'] = requestdata('title');
717 $parent = requestdata('in_reply_to_status_id');
718 if(ctype_digit($parent))
719 $_REQUEST['parent'] = $parent;
721 $_REQUEST['parent_uri'] = $parent;
723 if(requestdata('lat') && requestdata('long'))
724 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
725 $_REQUEST['profile_uid'] = api_user();
728 $_REQUEST['type'] = 'net-comment';
730 // Check for throttling (maximum posts per day, week and month)
731 $throttle_day = get_config('system','throttle_limit_day');
732 if ($throttle_day > 0) {
733 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
735 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
736 AND `created` > '%s' AND `id` = `parent`",
737 intval(api_user()), dbesc($datefrom));
740 $posts_day = $r[0]["posts_day"];
744 if ($posts_day > $throttle_day) {
745 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
746 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
750 $throttle_week = get_config('system','throttle_limit_week');
751 if ($throttle_week > 0) {
752 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
754 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
755 AND `created` > '%s' AND `id` = `parent`",
756 intval(api_user()), dbesc($datefrom));
759 $posts_week = $r[0]["posts_week"];
763 if ($posts_week > $throttle_week) {
764 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
765 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
769 $throttle_month = get_config('system','throttle_limit_month');
770 if ($throttle_month > 0) {
771 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
773 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
774 AND `created` > '%s' AND `id` = `parent`",
775 intval(api_user()), dbesc($datefrom));
778 $posts_month = $r[0]["posts_month"];
782 if ($posts_month > $throttle_month) {
783 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
784 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
788 $_REQUEST['type'] = 'wall';
789 if(x($_FILES,'media')) {
790 // upload the image if we have one
791 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
792 require_once('mod/wall_upload.php');
793 $media = wall_upload_post($a);
795 $_REQUEST['body'] .= "\n\n".$media;
799 // set this so that the item_post() function is quiet and doesn't redirect or emit json
801 $_REQUEST['api_source'] = true;
803 if (!x($_REQUEST, "source"))
804 $_REQUEST["source"] = api_source();
806 // call out normal post function
808 require_once('mod/item.php');
811 // this should output the last post (the one we just posted).
812 return api_status_show($a,$type);
814 api_register_func('api/statuses/update','api_statuses_update', true);
815 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
818 function api_status_show(&$a, $type){
819 $user_info = api_get_user($a);
821 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
823 // get last public wall message
824 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
825 FROM `item`, `item` as `i`
826 WHERE `item`.`contact-id` = %d
827 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
828 AND `i`.`id` = `item`.`parent`
829 AND `item`.`type`!='activity'
830 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
831 ORDER BY `item`.`created` DESC
833 intval($user_info['cid']),
834 dbesc($user_info['url']),
835 dbesc(normalise_link($user_info['url'])),
836 dbesc($user_info['url']),
837 dbesc(normalise_link($user_info['url']))
840 if (count($lastwall)>0){
841 $lastwall = $lastwall[0];
843 $in_reply_to_status_id = NULL;
844 $in_reply_to_user_id = NULL;
845 $in_reply_to_status_id_str = NULL;
846 $in_reply_to_user_id_str = NULL;
847 $in_reply_to_screen_name = NULL;
848 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
849 $in_reply_to_status_id= intval($lastwall['parent']);
850 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
852 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
854 if ($r[0]['nick'] == "")
855 $r[0]['nick'] = api_get_nick($r[0]["url"]);
857 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
858 $in_reply_to_user_id = intval($r[0]['id']);
859 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
863 // There seems to be situation, where both fields are identical:
864 // https://github.com/friendica/friendica/issues/1010
865 // This is a bugfix for that.
866 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
867 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
868 $in_reply_to_status_id = NULL;
869 $in_reply_to_user_id = NULL;
870 $in_reply_to_status_id_str = NULL;
871 $in_reply_to_user_id_str = NULL;
872 $in_reply_to_screen_name = NULL;
875 $converted = api_convert_item($item);
877 $status_info = array(
878 'text' => $converted["text"],
879 'truncated' => false,
880 'created_at' => api_date($lastwall['created']),
881 'in_reply_to_status_id' => $in_reply_to_status_id,
882 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
883 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
884 'id' => intval($lastwall['id']),
885 'id_str' => (string) $lastwall['id'],
886 'in_reply_to_user_id' => $in_reply_to_user_id,
887 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
888 'in_reply_to_screen_name' => $in_reply_to_screen_name,
890 'favorited' => $lastwall['starred'] ? true : false,
891 'user' => $user_info,
892 'statusnet_html' => $converted["html"],
893 'statusnet_conversation_id' => $lastwall['parent'],
896 if (count($converted["attachments"]) > 0)
897 $status_info["attachments"] = $converted["attachments"];
899 if (count($converted["entities"]) > 0)
900 $status_info["entities"] = $converted["entities"];
902 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
903 $status_info["source"] = network_to_name($lastwall['item_network']);
904 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
905 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
907 // "uid" and "self" are only needed for some internal stuff, so remove it from here
908 unset($status_info["user"]["uid"]);
909 unset($status_info["user"]["self"]);
913 return($status_info);
915 return api_apply_template("status", $type, array('$status' => $status_info));
924 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
925 * The author's most recent status will be returned inline.
926 * http://developer.twitter.com/doc/get/users/show
928 function api_users_show(&$a, $type){
929 $user_info = api_get_user($a);
931 $lastwall = q("SELECT `item`.*
932 FROM `item`, `contact`
933 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
934 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
935 AND `contact`.`id`=`item`.`contact-id`
936 AND `type`!='activity'
937 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
938 ORDER BY `created` DESC
941 dbesc(ACTIVITY_POST),
942 intval($user_info['cid']),
943 dbesc($user_info['url']),
944 dbesc(normalise_link($user_info['url'])),
945 dbesc($user_info['url']),
946 dbesc(normalise_link($user_info['url']))
948 if (count($lastwall)>0){
949 $lastwall = $lastwall[0];
951 $in_reply_to_status_id = NULL;
952 $in_reply_to_user_id = NULL;
953 $in_reply_to_status_id_str = NULL;
954 $in_reply_to_user_id_str = NULL;
955 $in_reply_to_screen_name = NULL;
956 if ($lastwall['parent']!=$lastwall['id']) {
957 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
958 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
959 if (count($reply)>0) {
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($reply[0]['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']);
975 $converted = api_convert_item($item);
977 $user_info['status'] = array(
978 'text' => $converted["text"],
979 'truncated' => false,
980 'created_at' => api_date($lastwall['created']),
981 'in_reply_to_status_id' => $in_reply_to_status_id,
982 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
983 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
984 'id' => intval($lastwall['contact-id']),
985 'id_str' => (string) $lastwall['contact-id'],
986 'in_reply_to_user_id' => $in_reply_to_user_id,
987 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
988 'in_reply_to_screen_name' => $in_reply_to_screen_name,
990 'favorited' => $lastwall['starred'] ? true : false,
991 'statusnet_html' => $converted["html"],
992 'statusnet_conversation_id' => $lastwall['parent'],
995 if (count($converted["attachments"]) > 0)
996 $user_info["status"]["attachments"] = $converted["attachments"];
998 if (count($converted["entities"]) > 0)
999 $user_info["status"]["entities"] = $converted["entities"];
1001 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1002 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1003 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1004 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1008 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1009 unset($user_info["uid"]);
1010 unset($user_info["self"]);
1012 return api_apply_template("user", $type, array('$user' => $user_info));
1015 api_register_func('api/users/show','api_users_show');
1018 function api_users_search(&$a, $type) {
1019 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1021 $userlist = array();
1023 if (isset($_GET["q"])) {
1024 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1026 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1029 foreach ($r AS $user) {
1030 $user_info = api_get_user($a, $user["id"]);
1031 //echo print_r($user_info, true)."\n";
1032 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1033 $userlist[] = $userdata["user"];
1035 $userlist = array("users" => $userlist);
1037 die(api_error($a, $type, t("User not found.")));
1039 die(api_error($a, $type, t("User not found.")));
1044 api_register_func('api/users/search','api_users_search');
1048 * http://developer.twitter.com/doc/get/statuses/home_timeline
1050 * TODO: Optional parameters
1051 * TODO: Add reply info
1053 function api_statuses_home_timeline(&$a, $type){
1054 if (api_user()===false) return false;
1056 unset($_REQUEST["user_id"]);
1057 unset($_GET["user_id"]);
1059 unset($_REQUEST["screen_name"]);
1060 unset($_GET["screen_name"]);
1062 $user_info = api_get_user($a);
1063 // get last newtork messages
1067 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1068 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1069 if ($page<0) $page=0;
1070 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1071 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1072 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1073 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1074 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1076 $start = $page*$count;
1080 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1081 if ($exclude_replies > 0)
1082 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1083 if ($conversation_id > 0)
1084 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1086 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1087 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1088 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1089 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1090 FROM `item`, `contact`
1091 WHERE `item`.`uid` = %d AND `verb` = '%s'
1092 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1093 AND `contact`.`id` = `item`.`contact-id`
1094 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1097 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1099 dbesc(ACTIVITY_POST),
1101 intval($start), intval($count)
1104 $ret = api_format_items($r,$user_info);
1106 // We aren't going to try to figure out at the item, group, and page
1107 // level which items you've seen and which you haven't. If you're looking
1108 // at the network timeline just mark everything seen.
1110 $r = q("UPDATE `item` SET `unseen` = 0
1111 WHERE `unseen` = 1 AND `uid` = %d",
1112 //intval($user_info['uid'])
1117 $data = array('$statuses' => $ret);
1121 $data = api_rss_extra($a, $data, $user_info);
1124 $as = api_format_as($a, $ret, $user_info);
1125 $as['title'] = $a->config['sitename']." Home Timeline";
1126 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1131 return api_apply_template("timeline", $type, $data);
1133 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1134 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1136 function api_statuses_public_timeline(&$a, $type){
1137 if (api_user()===false) return false;
1139 $user_info = api_get_user($a);
1140 // get last newtork messages
1144 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1145 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1146 if ($page<0) $page=0;
1147 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1148 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1149 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1150 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1151 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1153 $start = $page*$count;
1156 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1157 if ($exclude_replies > 0)
1158 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1159 if ($conversation_id > 0)
1160 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1162 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1163 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1164 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1165 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1166 `user`.`nickname`, `user`.`hidewall`
1167 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1168 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1169 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1170 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1171 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1172 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1173 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1176 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1177 dbesc(ACTIVITY_POST),
1182 $ret = api_format_items($r,$user_info);
1185 $data = array('$statuses' => $ret);
1189 $data = api_rss_extra($a, $data, $user_info);
1192 $as = api_format_as($a, $ret, $user_info);
1193 $as['title'] = $a->config['sitename']." Public Timeline";
1194 $as['link']['url'] = $a->get_baseurl()."/";
1199 return api_apply_template("timeline", $type, $data);
1201 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1206 function api_statuses_show(&$a, $type){
1207 if (api_user()===false) return false;
1209 $user_info = api_get_user($a);
1212 $id = intval($a->argv[3]);
1215 $id = intval($_REQUEST["id"]);
1219 $id = intval($a->argv[4]);
1221 logger('API: api_statuses_show: '.$id);
1223 $conversation = (x($_REQUEST,'conversation')?1:0);
1227 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1229 $sql_extra .= " AND `item`.`id` = %d";
1231 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1232 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1233 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1234 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1235 FROM `item`, `contact`
1236 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1237 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1238 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1241 dbesc(ACTIVITY_POST),
1246 die(api_error($a, $type, t("There is no status with this id.")));
1248 $ret = api_format_items($r,$user_info);
1250 if ($conversation) {
1251 $data = array('$statuses' => $ret);
1252 return api_apply_template("timeline", $type, $data);
1254 $data = array('$status' => $ret[0]);
1258 $data = api_rss_extra($a, $data, $user_info);
1260 return api_apply_template("status", $type, $data);
1263 api_register_func('api/statuses/show','api_statuses_show', true);
1269 function api_conversation_show(&$a, $type){
1270 if (api_user()===false) return false;
1272 $user_info = api_get_user($a);
1275 $id = intval($a->argv[3]);
1276 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1277 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1278 if ($page<0) $page=0;
1279 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1280 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1282 $start = $page*$count;
1285 $id = intval($_REQUEST["id"]);
1289 $id = intval($a->argv[4]);
1291 logger('API: api_conversation_show: '.$id);
1296 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1298 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1299 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1300 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1301 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1302 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1303 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1304 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1305 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1306 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1307 AND `item`.`id`>%d $sql_extra
1308 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1309 intval($id), intval(api_user()),
1310 dbesc(ACTIVITY_POST),
1312 intval($start), intval($count)
1316 die(api_error($a, $type, t("There is no conversation with this id.")));
1318 $ret = api_format_items($r,$user_info);
1320 $data = array('$statuses' => $ret);
1321 return api_apply_template("timeline", $type, $data);
1323 api_register_func('api/conversation/show','api_conversation_show', true);
1329 function api_statuses_repeat(&$a, $type){
1332 if (api_user()===false) return false;
1334 $user_info = api_get_user($a);
1337 $id = intval($a->argv[3]);
1340 $id = intval($_REQUEST["id"]);
1344 $id = intval($a->argv[4]);
1346 logger('API: api_statuses_repeat: '.$id);
1348 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1349 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1350 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1351 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1352 FROM `item`, `contact`
1353 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1354 AND `contact`.`id` = `item`.`contact-id`
1355 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1357 AND `item`.`id`=%d",
1361 if ($r[0]['body'] != "") {
1362 if (!intval(get_config('system','old_share'))) {
1363 if (strpos($r[0]['body'], "[/share]") !== false) {
1364 $pos = strpos($r[0]['body'], "[share");
1365 $post = substr($r[0]['body'], $pos);
1367 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1368 "' profile='".$r[0]['author-link'].
1369 "' avatar='".$r[0]['author-avatar'].
1370 "' link='".$r[0]['plink']."']";
1371 $post .= $r[0]['body'];
1372 $post .= "[/share]";
1374 $_REQUEST['body'] = $post;
1376 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1378 $_REQUEST['profile_uid'] = api_user();
1379 $_REQUEST['type'] = 'wall';
1380 $_REQUEST['api_source'] = true;
1382 if (!x($_REQUEST, "source"))
1383 $_REQUEST["source"] = api_source();
1385 require_once('mod/item.php');
1389 // this should output the last post (the one we just posted).
1391 return(api_status_show($a,$type));
1393 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1398 function api_statuses_destroy(&$a, $type){
1399 if (api_user()===false) return false;
1401 $user_info = api_get_user($a);
1404 $id = intval($a->argv[3]);
1407 $id = intval($_REQUEST["id"]);
1411 $id = intval($a->argv[4]);
1413 logger('API: api_statuses_destroy: '.$id);
1415 $ret = api_statuses_show($a, $type);
1417 require_once('include/items.php');
1418 drop_item($id, false);
1422 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1426 * http://developer.twitter.com/doc/get/statuses/mentions
1429 function api_statuses_mentions(&$a, $type){
1430 if (api_user()===false) return false;
1432 unset($_REQUEST["user_id"]);
1433 unset($_GET["user_id"]);
1435 unset($_REQUEST["screen_name"]);
1436 unset($_GET["screen_name"]);
1438 $user_info = api_get_user($a);
1439 // get last newtork messages
1443 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1444 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1445 if ($page<0) $page=0;
1446 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1447 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1448 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1450 $start = $page*$count;
1452 // Ugly code - should be changed
1453 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1454 $myurl = substr($myurl,strpos($myurl,'://')+3);
1455 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1456 $myurl = str_replace('www.','',$myurl);
1457 $diasp_url = str_replace('/profile/','/u/',$myurl);
1460 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1462 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1463 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1464 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1465 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1466 FROM `item`, `contact`
1467 WHERE `item`.`uid` = %d AND `verb` = '%s'
1468 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1469 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1470 AND `contact`.`id` = `item`.`contact-id`
1471 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1472 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1475 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1477 dbesc(ACTIVITY_POST),
1478 dbesc(protect_sprintf($myurl)),
1479 dbesc(protect_sprintf($myurl)),
1482 intval($start), intval($count)
1485 $ret = api_format_items($r,$user_info);
1488 $data = array('$statuses' => $ret);
1492 $data = api_rss_extra($a, $data, $user_info);
1495 $as = api_format_as($a, $ret, $user_info);
1496 $as["title"] = $a->config['sitename']." Mentions";
1497 $as['link']['url'] = $a->get_baseurl()."/";
1502 return api_apply_template("timeline", $type, $data);
1504 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1505 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1508 function api_statuses_user_timeline(&$a, $type){
1509 if (api_user()===false) return false;
1511 $user_info = api_get_user($a);
1512 // get last network messages
1514 logger("api_statuses_user_timeline: api_user: ". api_user() .
1515 "\nuser_info: ".print_r($user_info, true) .
1516 "\n_REQUEST: ".print_r($_REQUEST, true),
1520 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1521 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1522 if ($page<0) $page=0;
1523 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1524 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1525 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1526 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1528 $start = $page*$count;
1531 if ($user_info['self']==1)
1532 $sql_extra .= " AND `item`.`wall` = 1 ";
1534 if ($exclude_replies > 0)
1535 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1536 if ($conversation_id > 0)
1537 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1539 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1540 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1541 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1542 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1543 FROM `item`, `contact`
1544 WHERE `item`.`uid` = %d AND `verb` = '%s'
1545 AND `item`.`contact-id` = %d
1546 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1547 AND `contact`.`id` = `item`.`contact-id`
1548 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1551 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1553 dbesc(ACTIVITY_POST),
1554 intval($user_info['cid']),
1556 intval($start), intval($count)
1559 $ret = api_format_items($r,$user_info, true);
1561 $data = array('$statuses' => $ret);
1565 $data = api_rss_extra($a, $data, $user_info);
1568 return api_apply_template("timeline", $type, $data);
1571 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1575 * Star/unstar an item
1576 * param: id : id of the item
1578 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1580 function api_favorites_create_destroy(&$a, $type){
1581 if (api_user()===false) return false;
1583 # for versioned api.
1584 # TODO: we need a better global soluton
1586 if ($a->argv[1]=="1.1") $action_argv_id=3;
1588 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1589 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1590 if ($a->argc==$action_argv_id+2) {
1591 $itemid = intval($a->argv[$action_argv_id+1]);
1593 $itemid = intval($_REQUEST['id']);
1596 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1597 $itemid, api_user());
1599 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1603 $item[0]['starred']=1;
1606 $item[0]['starred']=0;
1609 die(api_error($a, $type, t("Invalid action. ".$action)));
1611 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1612 $item[0]['starred'], $itemid, api_user());
1614 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1615 $item[0]['starred'], $itemid, api_user());
1617 if ($r===false) die(api_error($a, $type, t("DB error")));
1620 $user_info = api_get_user($a);
1621 $ret = api_format_items($item,$user_info)[0];
1623 $data = array('$status' => $ret);
1627 $data = api_rss_extra($a, $data, $user_info);
1630 return api_apply_template("status", $type, $data);
1633 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1634 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1636 function api_favorites(&$a, $type){
1639 if (api_user()===false) return false;
1641 $called_api= array();
1643 $user_info = api_get_user($a);
1645 // in friendica starred item are private
1646 // return favorites only for self
1647 logger('api_favorites: self:' . $user_info['self']);
1649 if ($user_info['self']==0) {
1655 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1656 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1657 $count = (x($_GET,'count')?$_GET['count']:20);
1658 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1659 if ($page<0) $page=0;
1661 $start = $page*$count;
1664 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1666 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1667 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1668 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1669 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1670 FROM `item`, `contact`
1671 WHERE `item`.`uid` = %d
1672 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1673 AND `item`.`starred` = 1
1674 AND `contact`.`id` = `item`.`contact-id`
1675 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1678 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1681 intval($start), intval($count)
1684 $ret = api_format_items($r,$user_info);
1688 $data = array('$statuses' => $ret);
1692 $data = api_rss_extra($a, $data, $user_info);
1695 return api_apply_template("timeline", $type, $data);
1698 api_register_func('api/favorites','api_favorites', true);
1703 function api_format_as($a, $ret, $user_info) {
1706 $as['title'] = $a->config['sitename']." Public Timeline";
1708 foreach ($ret as $item) {
1709 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1710 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1711 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1712 $avatar[0]["rel"] = "avatar";
1713 $avatar[0]["type"] = "";
1714 $avatar[0]["width"] = 96;
1715 $avatar[0]["height"] = 96;
1716 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1717 $avatar[1]["rel"] = "avatar";
1718 $avatar[1]["type"] = "";
1719 $avatar[1]["width"] = 48;
1720 $avatar[1]["height"] = 48;
1721 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1722 $avatar[2]["rel"] = "avatar";
1723 $avatar[2]["type"] = "";
1724 $avatar[2]["width"] = 24;
1725 $avatar[2]["height"] = 24;
1726 $singleitem["actor"]["avatarLinks"] = $avatar;
1728 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1729 $singleitem["actor"]["image"]["rel"] = "avatar";
1730 $singleitem["actor"]["image"]["type"] = "";
1731 $singleitem["actor"]["image"]["width"] = 96;
1732 $singleitem["actor"]["image"]["height"] = 96;
1733 $singleitem["actor"]["type"] = "person";
1734 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1735 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1736 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1737 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1738 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1739 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1740 $singleitem["actor"]["contact"]["addresses"] = "";
1742 $singleitem["body"] = $item["text"];
1743 $singleitem["object"]["displayName"] = $item["text"];
1744 $singleitem["object"]["id"] = $item["url"];
1745 $singleitem["object"]["type"] = "note";
1746 $singleitem["object"]["url"] = $item["url"];
1747 //$singleitem["context"] =;
1748 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1749 $singleitem["provider"]["objectType"] = "service";
1750 $singleitem["provider"]["displayName"] = "Test";
1751 $singleitem["provider"]["url"] = "http://test.tld";
1752 $singleitem["title"] = $item["text"];
1753 $singleitem["verb"] = "post";
1754 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1755 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1756 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1757 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1758 //$singleitem["original"] = $item;
1759 $items[] = $singleitem;
1761 $as['items'] = $items;
1762 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1763 $as['link']['rel'] = "alternate";
1764 $as['link']['type'] = "text/html";
1768 function api_format_messages($item, $recipient, $sender) {
1769 // standard meta information
1771 'id' => $item['id'],
1772 'sender_id' => $sender['id'] ,
1774 'recipient_id' => $recipient['id'],
1775 'created_at' => api_date($item['created']),
1776 'sender_screen_name' => $sender['screen_name'],
1777 'recipient_screen_name' => $recipient['screen_name'],
1778 'sender' => $sender,
1779 'recipient' => $recipient,
1782 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1783 unset($ret["sender"]["uid"]);
1784 unset($ret["sender"]["self"]);
1785 unset($ret["recipient"]["uid"]);
1786 unset($ret["recipient"]["self"]);
1788 //don't send title to regular StatusNET requests to avoid confusing these apps
1789 if (x($_GET, 'getText')) {
1790 $ret['title'] = $item['title'] ;
1791 if ($_GET["getText"] == "html") {
1792 $ret['text'] = bbcode($item['body'], false, false);
1794 elseif ($_GET["getText"] == "plain") {
1795 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1796 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1800 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1802 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1803 unset($ret['sender']);
1804 unset($ret['recipient']);
1810 function api_convert_item($item) {
1812 $body = $item['body'];
1813 $attachments = api_get_attachments($body);
1815 // Workaround for ostatus messages where the title is identically to the body
1816 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1817 $statusbody = trim(html2plain($html, 0));
1819 // handle data: images
1820 $statusbody = api_format_items_embeded_images($item,$statusbody);
1822 $statustitle = trim($item['title']);
1824 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1825 $statustext = trim($statusbody);
1827 $statustext = trim($statustitle."\n\n".$statusbody);
1829 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1830 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1832 $statushtml = trim(bbcode($body, false, false));
1834 if ($item['title'] != "")
1835 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1837 $entities = api_get_entitities($statustext, $body);
1839 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1842 function api_get_attachments(&$body) {
1845 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1847 $URLSearchString = "^\[\]";
1848 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1853 require_once("include/Photo.php");
1855 $attachments = array();
1857 foreach ($images[1] AS $image) {
1858 $imagedata = get_photo_info($image);
1861 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1864 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1865 foreach ($images[0] AS $orig)
1866 $body = str_replace($orig, "", $body);
1868 return $attachments;
1871 function api_get_entitities(&$text, $bbcode) {
1874 * Links at the first character of the post
1879 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1881 if ($include_entities != "true") {
1882 require_once("mod/proxy.php");
1884 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1886 foreach ($images[1] AS $image) {
1887 $replace = proxy_url($image);
1888 $text = str_replace($image, $replace, $text);
1893 $bbcode = bb_CleanPictureLinks($bbcode);
1895 // Change pure links in text to bbcode uris
1896 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1898 $entities = array();
1899 $entities["hashtags"] = array();
1900 $entities["symbols"] = array();
1901 $entities["urls"] = array();
1902 $entities["user_mentions"] = array();
1904 $URLSearchString = "^\[\]";
1906 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1908 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1909 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1910 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1912 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1913 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1914 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1916 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1917 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1918 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1920 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1922 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1923 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1925 $ordered_urls = array();
1926 foreach ($urls[1] AS $id=>$url) {
1927 //$start = strpos($text, $url, $offset);
1928 $start = iconv_strpos($text, $url, 0, "UTF-8");
1929 if (!($start === false))
1930 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1933 ksort($ordered_urls);
1936 //foreach ($urls[1] AS $id=>$url) {
1937 foreach ($ordered_urls AS $url) {
1938 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1939 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1940 $display_url = $url["title"];
1942 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1943 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1945 if (strlen($display_url) > 26)
1946 $display_url = substr($display_url, 0, 25)."…";
1949 //$start = strpos($text, $url, $offset);
1950 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1951 if (!($start === false)) {
1952 $entities["urls"][] = array("url" => $url["url"],
1953 "expanded_url" => $url["url"],
1954 "display_url" => $display_url,
1955 "indices" => array($start, $start+strlen($url["url"])));
1956 $offset = $start + 1;
1960 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1961 $ordered_images = array();
1962 foreach ($images[1] AS $image) {
1963 //$start = strpos($text, $url, $offset);
1964 $start = iconv_strpos($text, $image, 0, "UTF-8");
1965 if (!($start === false))
1966 $ordered_images[$start] = $image;
1968 //$entities["media"] = array();
1971 foreach ($ordered_images AS $url) {
1972 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1973 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1975 if (strlen($display_url) > 26)
1976 $display_url = substr($display_url, 0, 25)."…";
1978 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1979 if (!($start === false)) {
1980 require_once("include/Photo.php");
1981 $image = get_photo_info($url);
1983 // If image cache is activated, then use the following sizes:
1984 // thumb (150), small (340), medium (600) and large (1024)
1985 if (!get_config("system", "proxy_disabled")) {
1986 require_once("mod/proxy.php");
1987 $media_url = proxy_url($url);
1990 $scale = scale_image($image[0], $image[1], 150);
1991 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1993 if (($image[0] > 150) OR ($image[1] > 150)) {
1994 $scale = scale_image($image[0], $image[1], 340);
1995 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1998 $scale = scale_image($image[0], $image[1], 600);
1999 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2001 if (($image[0] > 600) OR ($image[1] > 600)) {
2002 $scale = scale_image($image[0], $image[1], 1024);
2003 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2007 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2010 $entities["media"][] = array(
2012 "id_str" => (string)$start+1,
2013 "indices" => array($start, $start+strlen($url)),
2014 "media_url" => normalise_link($media_url),
2015 "media_url_https" => $media_url,
2017 "display_url" => $display_url,
2018 "expanded_url" => $url,
2022 $offset = $start + 1;
2028 function api_format_items_embeded_images($item, $text){
2030 $text = preg_replace_callback(
2031 "|data:image/([^;]+)[^=]+=*|m",
2032 function($match) use ($a, $item) {
2033 return $a->get_baseurl()."/display/".$item['guid'];
2039 function api_format_items($r,$user_info, $filter_user = false) {
2044 foreach($r as $item) {
2045 api_share_as_retweet($a, api_user(), $item);
2047 localize_item($item);
2048 $status_user = api_item_get_user($a,$item);
2050 // Look if the posts are matching if they should be filtered by user id
2051 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2054 if ($item['thr-parent'] != $item['uri']) {
2055 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2057 dbesc($item['thr-parent']));
2059 $in_reply_to_status_id = intval($r[0]['id']);
2061 $in_reply_to_status_id = intval($item['parent']);
2063 $in_reply_to_status_id_str = (string) intval($item['parent']);
2065 $in_reply_to_screen_name = NULL;
2066 $in_reply_to_user_id = NULL;
2067 $in_reply_to_user_id_str = NULL;
2069 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2071 intval($in_reply_to_status_id));
2073 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2076 if ($r[0]['nick'] == "")
2077 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2079 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2080 $in_reply_to_user_id = intval($r[0]['id']);
2081 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2085 $in_reply_to_screen_name = NULL;
2086 $in_reply_to_user_id = NULL;
2087 $in_reply_to_status_id = NULL;
2088 $in_reply_to_user_id_str = NULL;
2089 $in_reply_to_status_id_str = NULL;
2092 $converted = api_convert_item($item);
2095 'text' => $converted["text"],
2096 'truncated' => False,
2097 'created_at'=> api_date($item['created']),
2098 'in_reply_to_status_id' => $in_reply_to_status_id,
2099 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2100 'source' => (($item['app']) ? $item['app'] : 'web'),
2101 'id' => intval($item['id']),
2102 'id_str' => (string) intval($item['id']),
2103 'in_reply_to_user_id' => $in_reply_to_user_id,
2104 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2105 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2107 'favorited' => $item['starred'] ? true : false,
2108 'user' => $status_user ,
2109 //'entities' => NULL,
2110 'statusnet_html' => $converted["html"],
2111 'statusnet_conversation_id' => $item['parent'],
2114 if (count($converted["attachments"]) > 0)
2115 $status["attachments"] = $converted["attachments"];
2117 if (count($converted["entities"]) > 0)
2118 $status["entities"] = $converted["entities"];
2120 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2121 $status["source"] = network_to_name($item['item_network']);
2122 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2123 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2126 // Retweets are only valid for top postings
2127 // It doesn't work reliable with the link if its a feed
2128 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2130 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2132 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2133 $retweeted_status = $status;
2134 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2136 $status["retweeted_status"] = $retweeted_status;
2139 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2140 unset($status["user"]["uid"]);
2141 unset($status["user"]["self"]);
2143 // 'geo' => array('type' => 'Point',
2144 // 'coordinates' => array((float) $notice->lat,
2145 // (float) $notice->lon));
2153 function api_account_rate_limit_status(&$a,$type) {
2156 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2157 'remaining_hits' => (string) 150,
2158 'hourly_limit' => (string) 150,
2159 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2162 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2164 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2167 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2169 function api_help_test(&$a,$type) {
2176 return api_apply_template('test', $type, array("$ok" => $ok));
2179 api_register_func('api/help/test','api_help_test',false);
2181 function api_lists(&$a,$type) {
2186 api_register_func('api/lists','api_lists',true);
2188 function api_lists_list(&$a,$type) {
2193 api_register_func('api/lists/list','api_lists_list',true);
2196 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2197 * This function is deprecated by Twitter
2198 * returns: json, xml
2200 function api_statuses_f(&$a, $type, $qtype) {
2201 if (api_user()===false) return false;
2202 $user_info = api_get_user($a);
2204 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2205 /* this is to stop Hotot to load friends multiple times
2206 * I'm not sure if I'm missing return something or
2207 * is a bug in hotot. Workaround, meantime
2211 return array('$users' => $ret);*/
2215 if($qtype == 'friends')
2216 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2217 if($qtype == 'followers')
2218 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2220 // friends and followers only for self
2221 if ($user_info['self'] == 0)
2222 $sql_extra = " AND false ";
2224 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2229 foreach($r as $cid){
2230 $user = api_get_user($a, $cid['nurl']);
2231 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2232 unset($user["uid"]);
2233 unset($user["self"]);
2239 return array('$users' => $ret);
2242 function api_statuses_friends(&$a, $type){
2243 $data = api_statuses_f($a,$type,"friends");
2244 if ($data===false) return false;
2245 return api_apply_template("friends", $type, $data);
2247 function api_statuses_followers(&$a, $type){
2248 $data = api_statuses_f($a,$type,"followers");
2249 if ($data===false) return false;
2250 return api_apply_template("friends", $type, $data);
2252 api_register_func('api/statuses/friends','api_statuses_friends',true);
2253 api_register_func('api/statuses/followers','api_statuses_followers',true);
2260 function api_statusnet_config(&$a,$type) {
2261 $name = $a->config['sitename'];
2262 $server = $a->get_hostname();
2263 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2264 $email = $a->config['admin_email'];
2265 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2266 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2267 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2268 if($a->config['api_import_size'])
2269 $texlimit = string($a->config['api_import_size']);
2270 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2271 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2274 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2275 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2276 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2277 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2278 'shorturllength' => '30',
2279 'friendica' => array(
2280 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2281 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2282 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2283 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2288 return api_apply_template('config', $type, array('$config' => $config));
2291 api_register_func('api/statusnet/config','api_statusnet_config',false);
2293 function api_statusnet_version(&$a,$type) {
2297 if($type === 'xml') {
2298 header("Content-type: application/xml");
2299 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2302 elseif($type === 'json') {
2303 header("Content-type: application/json");
2308 api_register_func('api/statusnet/version','api_statusnet_version',false);
2311 function api_ff_ids(&$a,$type,$qtype) {
2315 $user_info = api_get_user($a);
2317 if($qtype == 'friends')
2318 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2319 if($qtype == 'followers')
2320 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2322 if (!$user_info["self"])
2323 $sql_extra = " AND false ";
2325 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2327 $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",
2333 if($type === 'xml') {
2334 header("Content-type: application/xml");
2335 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2337 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2338 echo '</ids>' . "\r\n";
2341 elseif($type === 'json') {
2343 header("Content-type: application/json");
2348 $ret[] = intval($rr['id']);
2350 echo json_encode($ret);
2356 function api_friends_ids(&$a,$type) {
2357 api_ff_ids($a,$type,'friends');
2359 function api_followers_ids(&$a,$type) {
2360 api_ff_ids($a,$type,'followers');
2362 api_register_func('api/friends/ids','api_friends_ids',true);
2363 api_register_func('api/followers/ids','api_followers_ids',true);
2366 function api_direct_messages_new(&$a, $type) {
2367 if (api_user()===false) return false;
2369 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2371 $sender = api_get_user($a);
2373 require_once("include/message.php");
2375 if ($_POST['screen_name']) {
2376 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2378 dbesc($_POST['screen_name']));
2380 // Selecting the id by priority, friendica first
2381 api_best_nickname($r);
2383 $recipient = api_get_user($a, $r[0]['nurl']);
2385 $recipient = api_get_user($a, $_POST['user_id']);
2389 if (x($_REQUEST,'replyto')) {
2390 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2392 intval($_REQUEST['replyto']));
2393 $replyto = $r[0]['parent-uri'];
2394 $sub = $r[0]['title'];
2397 if (x($_REQUEST,'title')) {
2398 $sub = $_REQUEST['title'];
2401 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2405 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2408 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2409 $ret = api_format_messages($r[0], $recipient, $sender);
2412 $ret = array("error"=>$id);
2415 $data = Array('$messages'=>$ret);
2420 $data = api_rss_extra($a, $data, $user_info);
2423 return api_apply_template("direct_messages", $type, $data);
2426 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2428 function api_direct_messages_box(&$a, $type, $box) {
2429 if (api_user()===false) return false;
2433 $count = (x($_GET,'count')?$_GET['count']:20);
2434 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2435 if ($page<0) $page=0;
2437 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2438 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2440 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2441 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2444 unset($_REQUEST["user_id"]);
2445 unset($_GET["user_id"]);
2447 unset($_REQUEST["screen_name"]);
2448 unset($_GET["screen_name"]);
2450 $user_info = api_get_user($a);
2451 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2452 $profile_url = $user_info["url"];
2456 $start = $page*$count;
2459 if ($box=="sentbox") {
2460 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2462 elseif ($box=="conversation") {
2463 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2465 elseif ($box=="all") {
2466 $sql_extra = "true";
2468 elseif ($box=="inbox") {
2469 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2473 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2475 if ($user_id !="") {
2476 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2478 elseif($screen_name !=""){
2479 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2482 $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",
2485 intval($start), intval($count)
2490 foreach($r as $item) {
2491 if ($box == "inbox" || $item['from-url'] != $profile_url){
2492 $recipient = $user_info;
2493 $sender = api_get_user($a,normalise_link($item['contact-url']));
2495 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2496 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2497 $sender = $user_info;
2500 $ret[]=api_format_messages($item, $recipient, $sender);
2504 $data = array('$messages' => $ret);
2508 $data = api_rss_extra($a, $data, $user_info);
2511 return api_apply_template("direct_messages", $type, $data);
2515 function api_direct_messages_sentbox(&$a, $type){
2516 return api_direct_messages_box($a, $type, "sentbox");
2518 function api_direct_messages_inbox(&$a, $type){
2519 return api_direct_messages_box($a, $type, "inbox");
2521 function api_direct_messages_all(&$a, $type){
2522 return api_direct_messages_box($a, $type, "all");
2524 function api_direct_messages_conversation(&$a, $type){
2525 return api_direct_messages_box($a, $type, "conversation");
2527 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2528 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2529 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2530 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2534 function api_oauth_request_token(&$a, $type){
2536 $oauth = new FKOAuth1();
2537 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2538 }catch(Exception $e){
2539 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2544 function api_oauth_access_token(&$a, $type){
2546 $oauth = new FKOAuth1();
2547 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2548 }catch(Exception $e){
2549 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2555 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2556 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2559 function api_fr_photos_list(&$a,$type) {
2560 if (api_user()===false) return false;
2561 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2562 intval(local_user())
2567 $ret[] = $rr['resource-id'];
2568 header("Content-type: application/json");
2569 echo json_encode($ret);
2574 function api_fr_photo_detail(&$a,$type) {
2575 if (api_user()===false) return false;
2576 if(! $_REQUEST['photo_id']) return false;
2577 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2578 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2579 intval(local_user()),
2580 dbesc($_REQUEST['photo_id']),
2584 header("Content-type: application/json");
2585 $r[0]['data'] = base64_encode($r[0]['data']);
2586 echo json_encode($r[0]);
2592 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2593 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2597 function api_share_as_retweet($a, $uid, &$item) {
2598 $body = trim($item["body"]);
2600 // Skip if it isn't a pure repeated messages
2601 // Does it start with a share?
2602 if (strpos($body, "[share") > 0)
2605 // Does it end with a share?
2606 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2609 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2610 // Skip if there is no shared message in there
2611 if ($body == $attributes)
2615 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2616 if ($matches[1] != "")
2617 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2619 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2620 if ($matches[1] != "")
2621 $author = $matches[1];
2624 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2625 if ($matches[1] != "")
2626 $profile = $matches[1];
2628 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2629 if ($matches[1] != "")
2630 $profile = $matches[1];
2633 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2634 if ($matches[1] != "")
2635 $avatar = $matches[1];
2637 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2638 if ($matches[1] != "")
2639 $avatar = $matches[1];
2641 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2643 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2646 $item["body"] = $shared_body;
2647 $item["author-name"] = $author;
2648 $item["author-link"] = $profile;
2649 $item["author-avatar"] = $avatar;
2655 function api_get_nick($profile) {
2657 - remove trailing jung from profile url
2658 - pump.io check has to check the website
2663 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2664 if ($friendica != $profile)
2668 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2669 if ($diaspora != $profile)
2674 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2675 if ($twitter != $profile)
2681 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2682 if ($StatusnetHost != $profile) {
2683 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2684 if ($StatusnetUser != $profile) {
2685 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2686 $user = json_decode($UserData);
2688 $nick = $user->screen_name;
2693 // To-Do: look at the page if its really a pumpio site
2694 //if (!$nick == "") {
2695 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2696 // if ($pumpio != $profile)
2698 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2703 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2704 dbesc($nick), dbesc(normalise_link($profile)));
2711 function api_clean_plain_items($Text) {
2712 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2714 $Text = bb_CleanPictureLinks($Text);
2716 $URLSearchString = "^\[\]";
2718 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2720 if ($include_entities == "true") {
2721 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2724 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2728 function api_cleanup_share($shared) {
2729 if ($shared[2] != "type-link")
2732 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2738 if (isset($bookmark[2][0]))
2739 $title = $bookmark[2][0];
2741 if (isset($bookmark[1][0]))
2742 $link = $bookmark[1][0];
2744 if (strpos($shared[1],$title) !== false)
2747 if (strpos($shared[1],$link) !== false)
2750 $text = trim($shared[1]);
2752 //if (strlen($text) < strlen($title))
2753 if (($text == "") AND ($title != ""))
2754 $text .= "\n\n".trim($title);
2757 $text .= "\n".trim($link);
2759 return(trim($text));
2762 function api_best_nickname(&$contacts) {
2763 $best_contact = array();
2765 if (count($contact) == 0)
2768 foreach ($contacts AS $contact)
2769 if ($contact["network"] == "") {
2770 $contact["network"] = "dfrn";
2771 $best_contact = array($contact);
2774 if (sizeof($best_contact) == 0)
2775 foreach ($contacts AS $contact)
2776 if ($contact["network"] == "dfrn")
2777 $best_contact = array($contact);
2779 if (sizeof($best_contact) == 0)
2780 foreach ($contacts AS $contact)
2781 if ($contact["network"] == "dspr")
2782 $best_contact = array($contact);
2784 if (sizeof($best_contact) == 0)
2785 foreach ($contacts AS $contact)
2786 if ($contact["network"] == "stat")
2787 $best_contact = array($contact);
2789 if (sizeof($best_contact) == 0)
2790 foreach ($contacts AS $contact)
2791 if ($contact["network"] == "pump")
2792 $best_contact = array($contact);
2794 if (sizeof($best_contact) == 0)
2795 foreach ($contacts AS $contact)
2796 if ($contact["network"] == "twit")
2797 $best_contact = array($contact);
2799 if (sizeof($best_contact) == 1)
2800 $contacts = $best_contact;
2802 $contacts = array($contacts[0]);
2806 Not implemented by now:
2807 statuses/retweets_of_me
2812 account/update_location
2813 account/update_profile_background_image
2814 account/update_profile_image
2818 Not implemented in status.net:
2819 statuses/retweeted_to_me
2820 statuses/retweeted_by_me
2821 direct_messages/destroy
2823 account/update_delivery_device
2824 notifications/follow