3 - Automatically detect if incoming data is HTML or BBCode
5 require_once("include/bbcode.php");
6 require_once("include/datetime.php");
7 require_once("include/conversation.php");
8 require_once("include/oauth.php");
9 require_once("include/html2plain.php");
10 require_once("mod/share.php");
11 require_once("include/Photo.php");
12 require_once("mod/item.php");
13 require_once('include/security.php');
14 require_once('include/contact_selectors.php');
15 require_once('include/html2bbcode.php');
16 require_once('mod/wall_upload.php');
17 require_once("mod/proxy.php");
18 require_once("include/message.php");
30 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
31 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
32 // into a page, and visitors will post something without noticing it).
33 // Instead, use this function.
34 if ($_SESSION["allow_api"])
40 function api_source() {
41 if (requestdata('source'))
42 return (requestdata('source'));
44 // Support for known clients that doesn't send a source name
45 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
48 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
53 function api_date($str){
54 //Wed May 23 06:01:13 +0000 2007
55 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
59 function api_register_func($path, $func, $auth=false){
61 $API[$path] = array('func'=>$func, 'auth'=>$auth);
63 // Workaround for hotot
64 $path = str_replace("api/", "api/1.1/", $path);
65 $API[$path] = array('func'=>$func, 'auth'=>$auth);
72 function api_login(&$a){
75 $oauth = new FKOAuth1();
76 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
77 if (!is_null($token)){
78 $oauth->loginUser($token->uid);
79 call_hooks('logged_in', $a->user);
82 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
84 logger(__file__.__line__.__function__."\n".$e);
85 //die(__file__.__line__.__function__."<pre>".$e); die();
90 // workaround for HTTP-auth in CGI mode
91 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
92 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
93 if(strlen($userpass)) {
94 list($name, $password) = explode(':', $userpass);
95 $_SERVER['PHP_AUTH_USER'] = $name;
96 $_SERVER['PHP_AUTH_PW'] = $password;
100 if (!isset($_SERVER['PHP_AUTH_USER'])) {
101 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
102 header('WWW-Authenticate: Basic realm="Friendica"');
103 header('HTTP/1.0 401 Unauthorized');
104 die((api_error($a, 'json', "This api requires login")));
106 //die('This api requires login');
109 $user = $_SERVER['PHP_AUTH_USER'];
110 $password = $_SERVER['PHP_AUTH_PW'];
111 $encrypted = hash('whirlpool',trim($password));
113 // allow "user@server" login (but ignore 'server' part)
114 $at=strstr($user, "@", true);
115 if ( $at ) $user=$at;
118 * next code from mod/auth.php. needs better solution
123 'username' => trim($user),
124 'password' => trim($password),
125 'authenticated' => 0,
126 'user_record' => null
131 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
132 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
133 * and later plugins should not interfere with an earlier one that succeeded.
137 call_hooks('authenticate', $addon_auth);
139 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
140 $record = $addon_auth['user_record'];
143 // process normal login request
145 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
146 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
155 if((! $record) || (! count($record))) {
156 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
157 header('WWW-Authenticate: Basic realm="Friendica"');
158 header('HTTP/1.0 401 Unauthorized');
159 die('This api requires login');
162 authenticate_success($record); $_SESSION["allow_api"] = true;
164 call_hooks('logged_in', $a->user);
168 /**************************
169 * MAIN API ENTRY POINT *
170 **************************/
171 function api_call(&$a){
172 GLOBAL $API, $called_api;
176 foreach ($API as $p=>$info){
177 if (strpos($a->query_string, $p)===0){
178 $called_api= explode("/",$p);
179 //unset($_SERVER['PHP_AUTH_USER']);
180 if ($info['auth']===true && api_user()===false) {
184 load_contact_links(api_user());
186 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
187 logger('API parameters: ' . print_r($_REQUEST,true));
189 if (strpos($a->query_string, ".xml")>0) $type="xml";
190 if (strpos($a->query_string, ".json")>0) $type="json";
191 if (strpos($a->query_string, ".rss")>0) $type="rss";
192 if (strpos($a->query_string, ".atom")>0) $type="atom";
193 if (strpos($a->query_string, ".as")>0) $type="as";
195 $stamp = microtime(true);
196 $r = call_user_func($info['func'], $a, $type);
197 $duration = (float)(microtime(true)-$stamp);
198 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
200 if ($r===false) return;
204 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
205 header ("Content-Type: text/xml");
206 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
209 header ("Content-Type: application/json");
211 $json = json_encode($rr);
212 if ($_GET['callback'])
213 $json = $_GET['callback']."(".$json.")";
217 header ("Content-Type: application/rss+xml");
218 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
221 header ("Content-Type: application/atom+xml");
222 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
225 //header ("Content-Type: application/json");
227 // return json_encode($rr);
228 return json_encode($r);
232 //echo "<pre>"; var_dump($r); die();
235 header("HTTP/1.1 404 Not Found");
236 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
237 return(api_error($a, $type, "not implemented"));
241 function api_error(&$a, $type, $error) {
242 # TODO: https://dev.twitter.com/overview/api/response-codes
243 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
246 header ("Content-Type: text/xml");
247 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
250 header ("Content-Type: application/json");
251 return json_encode(array('error' => $error, 'request' => $a->query_string));
254 header ("Content-Type: application/rss+xml");
255 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
258 header ("Content-Type: application/atom+xml");
259 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
267 function api_rss_extra(&$a, $arr, $user_info){
268 if (is_null($user_info)) $user_info = api_get_user($a);
269 $arr['$user'] = $user_info;
270 $arr['$rss'] = array(
271 'alternate' => $user_info['url'],
272 'self' => $a->get_baseurl(). "/". $a->query_string,
273 'base' => $a->get_baseurl(),
274 'updated' => api_date(null),
275 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
276 'language' => $user_info['language'],
277 'logo' => $a->get_baseurl()."/images/friendica-32.png",
285 * Unique contact to contact url.
287 function api_unique_id_to_url($id){
288 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
291 return ($r[0]["url"]);
297 * Returns user info array.
299 function api_get_user(&$a, $contact_id = Null, $type = "json"){
306 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
308 // Searching for contact URL
309 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
310 $user = dbesc(normalise_link($contact_id));
312 $extra_query = "AND `contact`.`nurl` = '%s' ";
313 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
316 // Searching for unique contact id
317 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
318 $user = dbesc(api_unique_id_to_url($contact_id));
321 die(api_error($a, $type, t("User not found.")));
324 $extra_query = "AND `contact`.`nurl` = '%s' ";
325 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
328 if(is_null($user) && x($_GET, 'user_id')) {
329 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
332 die(api_error($a, $type, t("User not found.")));
335 $extra_query = "AND `contact`.`nurl` = '%s' ";
336 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
338 if(is_null($user) && x($_GET, 'screen_name')) {
339 $user = dbesc($_GET['screen_name']);
341 $extra_query = "AND `contact`.`nick` = '%s' ";
342 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
345 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
346 $argid = count($called_api);
347 list($user, $null) = explode(".",$a->argv[$argid]);
348 if(is_numeric($user)){
349 $user = dbesc(api_unique_id_to_url($user));
355 $extra_query = "AND `contact`.`nurl` = '%s' ";
356 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
358 $user = dbesc($user);
360 $extra_query = "AND `contact`.`nick` = '%s' ";
361 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
365 logger("api_get_user: user ".$user, LOGGER_DEBUG);
368 if (api_user()===false) {
369 api_login($a); return False;
371 $user = $_SESSION['uid'];
372 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
377 logger('api_user: ' . $extra_query . ', user: ' . $user);
379 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
385 // Selecting the id by priority, friendica first
386 api_best_nickname($uinfo);
388 // if the contact wasn't found, fetch it from the unique contacts
389 if (count($uinfo)==0) {
393 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
395 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
398 // If no nick where given, extract it from the address
399 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
400 $r[0]['nick'] = api_get_nick($r[0]["url"]);
404 'id_str' => (string) $r[0]["id"],
405 'name' => $r[0]["name"],
406 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
408 'description' => NULL,
409 'url' => $r[0]["url"],
410 'protected' => false,
411 'followers_count' => 0,
412 'friends_count' => 0,
414 'created_at' => api_date(0),
415 'favourites_count' => 0,
417 'time_zone' => 'UTC',
418 'geo_enabled' => false,
420 'statuses_count' => 0,
422 'contributors_enabled' => false,
423 'is_translator' => false,
424 'is_translation_enabled' => false,
425 'profile_image_url' => $r[0]["avatar"],
426 'profile_image_url_https' => $r[0]["avatar"],
427 'following' => false,
428 'follow_request_sent' => false,
429 'notifications' => false,
430 'statusnet_blocking' => false,
431 'notifications' => false,
432 'statusnet_profile_url' => $r[0]["url"],
441 die(api_error($a, $type, t("User not found.")));
445 if($uinfo[0]['self']) {
446 $usr = q("select * from user where uid = %d limit 1",
449 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
453 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
454 // count public wall messages
455 $r = q("SELECT count(*) as `count` FROM `item`
458 intval($uinfo[0]['uid'])
460 $countitms = $r[0]['count'];
463 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
464 $r = q("SELECT count(*) as `count` FROM `item`
465 WHERE `contact-id` = %d",
466 intval($uinfo[0]['id'])
468 $countitms = $r[0]['count'];
472 $r = q("SELECT count(*) as `count` FROM `contact`
473 WHERE `uid` = %d AND `rel` IN ( %d, %d )
474 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
475 intval($uinfo[0]['uid']),
476 intval(CONTACT_IS_SHARING),
477 intval(CONTACT_IS_FRIEND)
479 $countfriends = $r[0]['count'];
481 $r = q("SELECT count(*) as `count` FROM `contact`
482 WHERE `uid` = %d AND `rel` IN ( %d, %d )
483 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
484 intval($uinfo[0]['uid']),
485 intval(CONTACT_IS_FOLLOWER),
486 intval(CONTACT_IS_FRIEND)
488 $countfollowers = $r[0]['count'];
490 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
491 intval($uinfo[0]['uid'])
493 $starred = $r[0]['count'];
496 if(! $uinfo[0]['self']) {
502 // Add a nick if it isn't present there
503 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
504 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
507 // Fetching unique id
508 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
510 // If not there, then add it
511 if (count($r) == 0) {
512 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
513 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
515 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
518 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
521 'id' => intval($r[0]['id']),
522 'id_str' => (string) intval($r[0]['id']),
523 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
524 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
525 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
526 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
527 'profile_image_url' => $uinfo[0]['micro'],
528 'profile_image_url_https' => $uinfo[0]['micro'],
529 'url' => $uinfo[0]['url'],
530 'protected' => false,
531 'followers_count' => intval($countfollowers),
532 'friends_count' => intval($countfriends),
533 'created_at' => api_date($uinfo[0]['created']),
534 'favourites_count' => intval($starred),
536 'time_zone' => 'UTC',
537 'statuses_count' => intval($countitms),
538 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
540 'statusnet_blocking' => false,
541 'notifications' => false,
542 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
543 'uid' => intval($uinfo[0]['uid']),
544 'cid' => intval($uinfo[0]['cid']),
545 'self' => $uinfo[0]['self'],
546 'network' => $uinfo[0]['network'],
553 function api_item_get_user(&$a, $item) {
555 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
556 dbesc(normalise_link($item['author-link'])));
558 if (count($author) == 0) {
559 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
560 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
562 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
563 dbesc(normalise_link($item['author-link'])));
564 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
565 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
566 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
569 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
570 dbesc(normalise_link($item['owner-link'])));
572 if (count($owner) == 0) {
573 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
574 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
576 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
577 dbesc(normalise_link($item['owner-link'])));
578 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
579 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
580 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
583 // Comments in threads may appear as wall-to-wall postings.
584 // So only take the owner at the top posting.
585 if ($item["id"] == $item["parent"])
586 $status_user = api_get_user($a,$item["owner-link"]);
588 $status_user = api_get_user($a,$item["author-link"]);
590 $status_user["protected"] = (($item["allow_cid"] != "") OR
591 ($item["allow_gid"] != "") OR
592 ($item["deny_cid"] != "") OR
593 ($item["deny_gid"] != "") OR
596 return ($status_user);
601 * load api $templatename for $type and replace $data array
603 function api_apply_template($templatename, $type, $data){
611 $data = array_xmlify($data);
612 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
614 header ("Content-Type: text/xml");
615 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
618 $ret = replace_macros($tpl, $data);
633 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
634 * returns a 401 status code and an error message if not.
635 * http://developer.twitter.com/doc/get/account/verify_credentials
637 function api_account_verify_credentials(&$a, $type){
638 if (api_user()===false) return false;
640 unset($_REQUEST["user_id"]);
641 unset($_GET["user_id"]);
643 unset($_REQUEST["screen_name"]);
644 unset($_GET["screen_name"]);
646 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
648 $user_info = api_get_user($a);
650 // "verified" isn't used here in the standard
651 unset($user_info["verified"]);
653 // - Adding last status
655 $user_info["status"] = api_status_show($a,"raw");
656 if (!count($user_info["status"]))
657 unset($user_info["status"]);
659 unset($user_info["status"]["user"]);
662 // "uid" and "self" are only needed for some internal stuff, so remove it from here
663 unset($user_info["uid"]);
664 unset($user_info["self"]);
666 return api_apply_template("user", $type, array('$user' => $user_info));
669 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
673 * get data from $_POST or $_GET
675 function requestdata($k){
676 if (isset($_POST[$k])){
679 if (isset($_GET[$k])){
685 /*Waitman Gobble Mod*/
686 function api_statuses_mediap(&$a, $type) {
687 if (api_user()===false) {
688 logger('api_statuses_update: no user');
691 $user_info = api_get_user($a);
693 $_REQUEST['type'] = 'wall';
694 $_REQUEST['profile_uid'] = api_user();
695 $_REQUEST['api_source'] = true;
696 $txt = requestdata('status');
697 //$txt = urldecode(requestdata('status'));
699 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
701 require_once('library/HTMLPurifier.auto.php');
703 $txt = html2bb_video($txt);
704 $config = HTMLPurifier_Config::createDefault();
705 $config->set('Cache.DefinitionImpl', null);
706 $purifier = new HTMLPurifier($config);
707 $txt = $purifier->purify($txt);
709 $txt = html2bbcode($txt);
711 $a->argv[1]=$user_info['screen_name']; //should be set to username?
713 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
714 $bebop = wall_upload_post($a);
716 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
717 $_REQUEST['body']=$txt."\n\n".$bebop;
720 // this should output the last post (the one we just posted).
721 return api_status_show($a,$type);
723 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
724 /*Waitman Gobble Mod*/
727 function api_statuses_update(&$a, $type) {
728 if (api_user()===false) {
729 logger('api_statuses_update: no user');
733 $user_info = api_get_user($a);
735 // convert $_POST array items to the form we use for web posts.
737 // logger('api_post: ' . print_r($_POST,true));
739 if(requestdata('htmlstatus')) {
740 $txt = requestdata('htmlstatus');
741 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
743 require_once('library/HTMLPurifier.auto.php');
745 $txt = html2bb_video($txt);
747 $config = HTMLPurifier_Config::createDefault();
748 $config->set('Cache.DefinitionImpl', null);
750 $purifier = new HTMLPurifier($config);
751 $txt = $purifier->purify($txt);
753 $_REQUEST['body'] = html2bbcode($txt);
757 $_REQUEST['body'] = requestdata('status');
759 $_REQUEST['title'] = requestdata('title');
761 $parent = requestdata('in_reply_to_status_id');
763 // Twidere sends "-1" if it is no reply ...
767 if(ctype_digit($parent))
768 $_REQUEST['parent'] = $parent;
770 $_REQUEST['parent_uri'] = $parent;
772 if(requestdata('lat') && requestdata('long'))
773 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
774 $_REQUEST['profile_uid'] = api_user();
777 $_REQUEST['type'] = 'net-comment';
779 // Check for throttling (maximum posts per day, week and month)
780 $throttle_day = get_config('system','throttle_limit_day');
781 if ($throttle_day > 0) {
782 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
784 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
785 AND `created` > '%s' AND `id` = `parent`",
786 intval(api_user()), dbesc($datefrom));
789 $posts_day = $r[0]["posts_day"];
793 if ($posts_day > $throttle_day) {
794 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
795 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
799 $throttle_week = get_config('system','throttle_limit_week');
800 if ($throttle_week > 0) {
801 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
803 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
804 AND `created` > '%s' AND `id` = `parent`",
805 intval(api_user()), dbesc($datefrom));
808 $posts_week = $r[0]["posts_week"];
812 if ($posts_week > $throttle_week) {
813 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
814 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
818 $throttle_month = get_config('system','throttle_limit_month');
819 if ($throttle_month > 0) {
820 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
822 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
823 AND `created` > '%s' AND `id` = `parent`",
824 intval(api_user()), dbesc($datefrom));
827 $posts_month = $r[0]["posts_month"];
831 if ($posts_month > $throttle_month) {
832 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
833 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
837 $_REQUEST['type'] = 'wall';
840 if(x($_FILES,'media')) {
841 // upload the image if we have one
842 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
843 $media = wall_upload_post($a);
845 $_REQUEST['body'] .= "\n\n".$media;
848 // To-Do: Multiple IDs
849 if (requestdata('media_ids')) {
850 $r = q("SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
851 intval(requestdata('media_ids')), api_user());
853 $phototypes = Photo::supportedTypes();
854 $ext = $phototypes[$r[0]['type']];
855 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
856 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
860 // set this so that the item_post() function is quiet and doesn't redirect or emit json
862 $_REQUEST['api_source'] = true;
864 if (!x($_REQUEST, "source"))
865 $_REQUEST["source"] = api_source();
867 // call out normal post function
871 // this should output the last post (the one we just posted).
872 return api_status_show($a,$type);
874 api_register_func('api/statuses/update','api_statuses_update', true);
875 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
878 function api_media_upload(&$a, $type) {
879 if (api_user()===false) {
884 $user_info = api_get_user($a);
886 if(!x($_FILES,'media')) {
891 $media = wall_upload_post($a, false);
897 $returndata = array();
898 $returndata["media_id"] = $media["id"];
899 $returndata["media_id_string"] = (string)$media["id"];
900 $returndata["size"] = $media["size"];
901 $returndata["image"] = array("w" => $media["width"],
902 "h" => $media["height"],
903 "image_type" => $media["type"]);
905 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
907 return array("media" => $returndata);
910 api_register_func('api/media/upload','api_media_upload', true);
912 function api_status_show(&$a, $type){
913 $user_info = api_get_user($a);
915 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
917 // get last public wall message
918 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
919 FROM `item`, `item` as `i`
920 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
921 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
922 AND `i`.`id` = `item`.`parent`
923 AND `item`.`type`!='activity'
924 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
925 ORDER BY `item`.`created` DESC
927 intval($user_info['cid']),
929 dbesc($user_info['url']),
930 dbesc(normalise_link($user_info['url'])),
931 dbesc($user_info['url']),
932 dbesc(normalise_link($user_info['url']))
935 if (count($lastwall)>0){
936 $lastwall = $lastwall[0];
938 $in_reply_to_status_id = NULL;
939 $in_reply_to_user_id = NULL;
940 $in_reply_to_status_id_str = NULL;
941 $in_reply_to_user_id_str = NULL;
942 $in_reply_to_screen_name = NULL;
943 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
944 $in_reply_to_status_id= intval($lastwall['parent']);
945 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
947 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
949 if ($r[0]['nick'] == "")
950 $r[0]['nick'] = api_get_nick($r[0]["url"]);
952 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
953 $in_reply_to_user_id = intval($r[0]['id']);
954 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
958 // There seems to be situation, where both fields are identical:
959 // https://github.com/friendica/friendica/issues/1010
960 // This is a bugfix for that.
961 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
962 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
963 $in_reply_to_status_id = NULL;
964 $in_reply_to_user_id = NULL;
965 $in_reply_to_status_id_str = NULL;
966 $in_reply_to_user_id_str = NULL;
967 $in_reply_to_screen_name = NULL;
970 $converted = api_convert_item($item);
972 $status_info = array(
973 'created_at' => api_date($lastwall['created']),
974 'id' => intval($lastwall['id']),
975 'id_str' => (string) $lastwall['id'],
976 'text' => $converted["text"],
977 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
978 'truncated' => false,
979 'in_reply_to_status_id' => $in_reply_to_status_id,
980 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
981 'in_reply_to_user_id' => $in_reply_to_user_id,
982 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
983 'in_reply_to_screen_name' => $in_reply_to_screen_name,
984 'user' => $user_info,
988 'contributors' => "",
989 'is_quote_status' => false,
990 'retweet_count' => 0,
991 'favorite_count' => 0,
992 'favorited' => $lastwall['starred'] ? true : false,
993 'retweeted' => false,
994 'possibly_sensitive' => false,
996 'statusnet_html' => $converted["html"],
997 'statusnet_conversation_id' => $lastwall['parent'],
1000 if (count($converted["attachments"]) > 0)
1001 $status_info["attachments"] = $converted["attachments"];
1003 if (count($converted["entities"]) > 0)
1004 $status_info["entities"] = $converted["entities"];
1006 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1007 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1008 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1009 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1011 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1012 unset($status_info["user"]["uid"]);
1013 unset($status_info["user"]["self"]);
1017 return($status_info);
1019 return api_apply_template("status", $type, array('$status' => $status_info));
1028 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1029 * The author's most recent status will be returned inline.
1030 * http://developer.twitter.com/doc/get/users/show
1032 function api_users_show(&$a, $type){
1033 $user_info = api_get_user($a);
1035 $lastwall = q("SELECT `item`.*
1036 FROM `item`, `contact`
1037 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1038 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1039 AND `contact`.`id`=`item`.`contact-id`
1040 AND `type`!='activity'
1041 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1042 ORDER BY `created` DESC
1045 dbesc(ACTIVITY_POST),
1046 intval($user_info['cid']),
1047 dbesc($user_info['url']),
1048 dbesc(normalise_link($user_info['url'])),
1049 dbesc($user_info['url']),
1050 dbesc(normalise_link($user_info['url']))
1052 if (count($lastwall)>0){
1053 $lastwall = $lastwall[0];
1055 $in_reply_to_status_id = NULL;
1056 $in_reply_to_user_id = NULL;
1057 $in_reply_to_status_id_str = NULL;
1058 $in_reply_to_user_id_str = NULL;
1059 $in_reply_to_screen_name = NULL;
1060 if ($lastwall['parent']!=$lastwall['id']) {
1061 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1062 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1063 if (count($reply)>0) {
1064 $in_reply_to_status_id = intval($lastwall['parent']);
1065 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1067 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1069 if ($r[0]['nick'] == "")
1070 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1072 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1073 $in_reply_to_user_id = intval($r[0]['id']);
1074 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1079 $converted = api_convert_item($item);
1081 $user_info['status'] = array(
1082 'text' => $converted["text"],
1083 'truncated' => false,
1084 'created_at' => api_date($lastwall['created']),
1085 'in_reply_to_status_id' => $in_reply_to_status_id,
1086 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1087 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1088 'id' => intval($lastwall['contact-id']),
1089 'id_str' => (string) $lastwall['contact-id'],
1090 'in_reply_to_user_id' => $in_reply_to_user_id,
1091 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1092 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1094 'favorited' => $lastwall['starred'] ? true : false,
1095 'statusnet_html' => $converted["html"],
1096 'statusnet_conversation_id' => $lastwall['parent'],
1099 if (count($converted["attachments"]) > 0)
1100 $user_info["status"]["attachments"] = $converted["attachments"];
1102 if (count($converted["entities"]) > 0)
1103 $user_info["status"]["entities"] = $converted["entities"];
1105 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1106 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1107 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1108 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1112 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1113 unset($user_info["uid"]);
1114 unset($user_info["self"]);
1116 return api_apply_template("user", $type, array('$user' => $user_info));
1119 api_register_func('api/users/show','api_users_show');
1122 function api_users_search(&$a, $type) {
1123 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1125 $userlist = array();
1127 if (isset($_GET["q"])) {
1128 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1130 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1133 foreach ($r AS $user) {
1134 $user_info = api_get_user($a, $user["id"]);
1135 //echo print_r($user_info, true)."\n";
1136 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1137 $userlist[] = $userdata["user"];
1139 $userlist = array("users" => $userlist);
1141 die(api_error($a, $type, t("User not found.")));
1143 die(api_error($a, $type, t("User not found.")));
1148 api_register_func('api/users/search','api_users_search');
1152 * http://developer.twitter.com/doc/get/statuses/home_timeline
1154 * TODO: Optional parameters
1155 * TODO: Add reply info
1157 function api_statuses_home_timeline(&$a, $type){
1158 if (api_user()===false) return false;
1160 unset($_REQUEST["user_id"]);
1161 unset($_GET["user_id"]);
1163 unset($_REQUEST["screen_name"]);
1164 unset($_GET["screen_name"]);
1166 $user_info = api_get_user($a);
1167 // get last newtork messages
1171 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1172 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1173 if ($page<0) $page=0;
1174 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1175 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1176 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1177 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1178 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1180 $start = $page*$count;
1184 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1185 if ($exclude_replies > 0)
1186 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1187 if ($conversation_id > 0)
1188 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1190 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1191 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1192 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1193 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1194 FROM `item`, `contact`
1195 WHERE `item`.`uid` = %d AND `verb` = '%s'
1196 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1197 AND `contact`.`id` = `item`.`contact-id`
1198 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1201 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1203 dbesc(ACTIVITY_POST),
1205 intval($start), intval($count)
1208 $ret = api_format_items($r,$user_info);
1210 // Set all posts from the query above to seen
1212 foreach ($r AS $item)
1213 $idarray[] = intval($item["id"]);
1215 $idlist = implode(",", $idarray);
1218 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1221 $data = array('$statuses' => $ret);
1225 $data = api_rss_extra($a, $data, $user_info);
1228 $as = api_format_as($a, $ret, $user_info);
1229 $as['title'] = $a->config['sitename']." Home Timeline";
1230 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1235 return api_apply_template("timeline", $type, $data);
1237 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1238 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1240 function api_statuses_public_timeline(&$a, $type){
1241 if (api_user()===false) return false;
1243 $user_info = api_get_user($a);
1244 // get last newtork messages
1248 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1249 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1250 if ($page<0) $page=0;
1251 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1252 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1253 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1254 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1255 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1257 $start = $page*$count;
1260 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1261 if ($exclude_replies > 0)
1262 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1263 if ($conversation_id > 0)
1264 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1266 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1267 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1268 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1269 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1270 `user`.`nickname`, `user`.`hidewall`
1271 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1272 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1273 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1274 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1275 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1276 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1277 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1280 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1281 dbesc(ACTIVITY_POST),
1286 $ret = api_format_items($r,$user_info);
1289 $data = array('$statuses' => $ret);
1293 $data = api_rss_extra($a, $data, $user_info);
1296 $as = api_format_as($a, $ret, $user_info);
1297 $as['title'] = $a->config['sitename']." Public Timeline";
1298 $as['link']['url'] = $a->get_baseurl()."/";
1303 return api_apply_template("timeline", $type, $data);
1305 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1310 function api_statuses_show(&$a, $type){
1311 if (api_user()===false) return false;
1313 $user_info = api_get_user($a);
1316 $id = intval($a->argv[3]);
1319 $id = intval($_REQUEST["id"]);
1323 $id = intval($a->argv[4]);
1325 logger('API: api_statuses_show: '.$id);
1327 $conversation = (x($_REQUEST,'conversation')?1:0);
1331 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1333 $sql_extra .= " AND `item`.`id` = %d";
1335 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1336 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1337 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1338 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1339 FROM `item`, `contact`
1340 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1341 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1342 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1345 dbesc(ACTIVITY_POST),
1350 die(api_error($a, $type, t("There is no status with this id.")));
1352 $ret = api_format_items($r,$user_info);
1354 if ($conversation) {
1355 $data = array('$statuses' => $ret);
1356 return api_apply_template("timeline", $type, $data);
1358 $data = array('$status' => $ret[0]);
1362 $data = api_rss_extra($a, $data, $user_info);
1364 return api_apply_template("status", $type, $data);
1367 api_register_func('api/statuses/show','api_statuses_show', true);
1373 function api_conversation_show(&$a, $type){
1374 if (api_user()===false) return false;
1376 $user_info = api_get_user($a);
1379 $id = intval($a->argv[3]);
1380 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1381 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1382 if ($page<0) $page=0;
1383 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1384 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1386 $start = $page*$count;
1389 $id = intval($_REQUEST["id"]);
1393 $id = intval($a->argv[4]);
1395 logger('API: api_conversation_show: '.$id);
1397 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1399 $id = $r[0]["parent"];
1404 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1406 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1407 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1408 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1409 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1410 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1411 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1412 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1413 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1414 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1415 AND `item`.`id`>%d $sql_extra
1416 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1417 intval($id), intval(api_user()),
1418 dbesc(ACTIVITY_POST),
1420 intval($start), intval($count)
1424 die(api_error($a, $type, t("There is no conversation with this id.")));
1426 $ret = api_format_items($r,$user_info);
1428 $data = array('$statuses' => $ret);
1429 return api_apply_template("timeline", $type, $data);
1431 api_register_func('api/conversation/show','api_conversation_show', true);
1437 function api_statuses_repeat(&$a, $type){
1440 if (api_user()===false) return false;
1442 $user_info = api_get_user($a);
1445 $id = intval($a->argv[3]);
1448 $id = intval($_REQUEST["id"]);
1452 $id = intval($a->argv[4]);
1454 logger('API: api_statuses_repeat: '.$id);
1456 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1457 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1458 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1459 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1460 FROM `item`, `contact`
1461 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1462 AND `contact`.`id` = `item`.`contact-id`
1463 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1465 AND `item`.`id`=%d",
1469 if ($r[0]['body'] != "") {
1470 if (!intval(get_config('system','old_share'))) {
1471 if (strpos($r[0]['body'], "[/share]") !== false) {
1472 $pos = strpos($r[0]['body'], "[share");
1473 $post = substr($r[0]['body'], $pos);
1475 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1477 $post .= $r[0]['body'];
1478 $post .= "[/share]";
1480 $_REQUEST['body'] = $post;
1482 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1484 $_REQUEST['profile_uid'] = api_user();
1485 $_REQUEST['type'] = 'wall';
1486 $_REQUEST['api_source'] = true;
1488 if (!x($_REQUEST, "source"))
1489 $_REQUEST["source"] = api_source();
1494 // this should output the last post (the one we just posted).
1496 return(api_status_show($a,$type));
1498 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1503 function api_statuses_destroy(&$a, $type){
1504 if (api_user()===false) return false;
1506 $user_info = api_get_user($a);
1509 $id = intval($a->argv[3]);
1512 $id = intval($_REQUEST["id"]);
1516 $id = intval($a->argv[4]);
1518 logger('API: api_statuses_destroy: '.$id);
1520 $ret = api_statuses_show($a, $type);
1522 drop_item($id, false);
1526 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1530 * http://developer.twitter.com/doc/get/statuses/mentions
1533 function api_statuses_mentions(&$a, $type){
1534 if (api_user()===false) return false;
1536 unset($_REQUEST["user_id"]);
1537 unset($_GET["user_id"]);
1539 unset($_REQUEST["screen_name"]);
1540 unset($_GET["screen_name"]);
1542 $user_info = api_get_user($a);
1543 // get last newtork messages
1547 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1548 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1549 if ($page<0) $page=0;
1550 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1551 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1552 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1554 $start = $page*$count;
1556 // Ugly code - should be changed
1557 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1558 $myurl = substr($myurl,strpos($myurl,'://')+3);
1559 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1560 $myurl = str_replace('www.','',$myurl);
1561 $diasp_url = str_replace('/profile/','/u/',$myurl);
1564 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1566 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1567 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1568 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1569 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1570 FROM `item`, `contact`
1571 WHERE `item`.`uid` = %d AND `verb` = '%s'
1572 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1573 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1574 AND `contact`.`id` = `item`.`contact-id`
1575 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1576 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1579 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1581 dbesc(ACTIVITY_POST),
1582 dbesc(protect_sprintf($myurl)),
1583 dbesc(protect_sprintf($myurl)),
1586 intval($start), intval($count)
1589 $ret = api_format_items($r,$user_info);
1592 $data = array('$statuses' => $ret);
1596 $data = api_rss_extra($a, $data, $user_info);
1599 $as = api_format_as($a, $ret, $user_info);
1600 $as["title"] = $a->config['sitename']." Mentions";
1601 $as['link']['url'] = $a->get_baseurl()."/";
1606 return api_apply_template("timeline", $type, $data);
1608 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1609 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1612 function api_statuses_user_timeline(&$a, $type){
1613 if (api_user()===false) return false;
1615 $user_info = api_get_user($a);
1616 // get last network messages
1618 logger("api_statuses_user_timeline: api_user: ". api_user() .
1619 "\nuser_info: ".print_r($user_info, true) .
1620 "\n_REQUEST: ".print_r($_REQUEST, true),
1624 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1625 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1626 if ($page<0) $page=0;
1627 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1628 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1629 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1630 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1632 $start = $page*$count;
1635 if ($user_info['self']==1)
1636 $sql_extra .= " AND `item`.`wall` = 1 ";
1638 if ($exclude_replies > 0)
1639 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1640 if ($conversation_id > 0)
1641 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1643 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1644 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1645 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1646 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1647 FROM `item`, `contact`
1648 WHERE `item`.`uid` = %d AND `verb` = '%s'
1649 AND `item`.`contact-id` = %d
1650 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1651 AND `contact`.`id` = `item`.`contact-id`
1652 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1655 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1657 dbesc(ACTIVITY_POST),
1658 intval($user_info['cid']),
1660 intval($start), intval($count)
1663 $ret = api_format_items($r,$user_info, true);
1665 $data = array('$statuses' => $ret);
1669 $data = api_rss_extra($a, $data, $user_info);
1672 return api_apply_template("timeline", $type, $data);
1675 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1679 * Star/unstar an item
1680 * param: id : id of the item
1682 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1684 function api_favorites_create_destroy(&$a, $type){
1685 if (api_user()===false) return false;
1687 # for versioned api.
1688 # TODO: we need a better global soluton
1690 if ($a->argv[1]=="1.1") $action_argv_id=3;
1692 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1693 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1694 if ($a->argc==$action_argv_id+2) {
1695 $itemid = intval($a->argv[$action_argv_id+1]);
1697 $itemid = intval($_REQUEST['id']);
1700 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1701 $itemid, api_user());
1703 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1707 $item[0]['starred']=1;
1710 $item[0]['starred']=0;
1713 die(api_error($a, $type, t("Invalid action. ".$action)));
1715 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1716 $item[0]['starred'], $itemid, api_user());
1718 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1719 $item[0]['starred'], $itemid, api_user());
1721 if ($r===false) die(api_error($a, $type, t("DB error")));
1724 $user_info = api_get_user($a);
1725 $rets = api_format_items($item,$user_info);
1728 $data = array('$status' => $ret);
1732 $data = api_rss_extra($a, $data, $user_info);
1735 return api_apply_template("status", $type, $data);
1738 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1739 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1741 function api_favorites(&$a, $type){
1744 if (api_user()===false) return false;
1746 $called_api= array();
1748 $user_info = api_get_user($a);
1750 // in friendica starred item are private
1751 // return favorites only for self
1752 logger('api_favorites: self:' . $user_info['self']);
1754 if ($user_info['self']==0) {
1760 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1761 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1762 $count = (x($_GET,'count')?$_GET['count']:20);
1763 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1764 if ($page<0) $page=0;
1766 $start = $page*$count;
1769 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1771 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1772 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1773 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1774 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1775 FROM `item`, `contact`
1776 WHERE `item`.`uid` = %d
1777 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1778 AND `item`.`starred` = 1
1779 AND `contact`.`id` = `item`.`contact-id`
1780 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1783 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1786 intval($start), intval($count)
1789 $ret = api_format_items($r,$user_info);
1793 $data = array('$statuses' => $ret);
1797 $data = api_rss_extra($a, $data, $user_info);
1800 return api_apply_template("timeline", $type, $data);
1803 api_register_func('api/favorites','api_favorites', true);
1808 function api_format_as($a, $ret, $user_info) {
1811 $as['title'] = $a->config['sitename']." Public Timeline";
1813 foreach ($ret as $item) {
1814 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1815 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1816 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1817 $avatar[0]["rel"] = "avatar";
1818 $avatar[0]["type"] = "";
1819 $avatar[0]["width"] = 96;
1820 $avatar[0]["height"] = 96;
1821 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1822 $avatar[1]["rel"] = "avatar";
1823 $avatar[1]["type"] = "";
1824 $avatar[1]["width"] = 48;
1825 $avatar[1]["height"] = 48;
1826 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1827 $avatar[2]["rel"] = "avatar";
1828 $avatar[2]["type"] = "";
1829 $avatar[2]["width"] = 24;
1830 $avatar[2]["height"] = 24;
1831 $singleitem["actor"]["avatarLinks"] = $avatar;
1833 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1834 $singleitem["actor"]["image"]["rel"] = "avatar";
1835 $singleitem["actor"]["image"]["type"] = "";
1836 $singleitem["actor"]["image"]["width"] = 96;
1837 $singleitem["actor"]["image"]["height"] = 96;
1838 $singleitem["actor"]["type"] = "person";
1839 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1840 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1841 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1842 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1843 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1844 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1845 $singleitem["actor"]["contact"]["addresses"] = "";
1847 $singleitem["body"] = $item["text"];
1848 $singleitem["object"]["displayName"] = $item["text"];
1849 $singleitem["object"]["id"] = $item["url"];
1850 $singleitem["object"]["type"] = "note";
1851 $singleitem["object"]["url"] = $item["url"];
1852 //$singleitem["context"] =;
1853 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1854 $singleitem["provider"]["objectType"] = "service";
1855 $singleitem["provider"]["displayName"] = "Test";
1856 $singleitem["provider"]["url"] = "http://test.tld";
1857 $singleitem["title"] = $item["text"];
1858 $singleitem["verb"] = "post";
1859 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1860 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1861 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1862 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1863 //$singleitem["original"] = $item;
1864 $items[] = $singleitem;
1866 $as['items'] = $items;
1867 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1868 $as['link']['rel'] = "alternate";
1869 $as['link']['type'] = "text/html";
1873 function api_format_messages($item, $recipient, $sender) {
1874 // standard meta information
1876 'id' => $item['id'],
1877 'sender_id' => $sender['id'] ,
1879 'recipient_id' => $recipient['id'],
1880 'created_at' => api_date($item['created']),
1881 'sender_screen_name' => $sender['screen_name'],
1882 'recipient_screen_name' => $recipient['screen_name'],
1883 'sender' => $sender,
1884 'recipient' => $recipient,
1887 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1888 unset($ret["sender"]["uid"]);
1889 unset($ret["sender"]["self"]);
1890 unset($ret["recipient"]["uid"]);
1891 unset($ret["recipient"]["self"]);
1893 //don't send title to regular StatusNET requests to avoid confusing these apps
1894 if (x($_GET, 'getText')) {
1895 $ret['title'] = $item['title'] ;
1896 if ($_GET["getText"] == "html") {
1897 $ret['text'] = bbcode($item['body'], false, false);
1899 elseif ($_GET["getText"] == "plain") {
1900 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1901 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1905 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1907 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1908 unset($ret['sender']);
1909 unset($ret['recipient']);
1915 function api_convert_item($item) {
1917 $body = $item['body'];
1918 $attachments = api_get_attachments($body);
1920 // Workaround for ostatus messages where the title is identically to the body
1921 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1922 $statusbody = trim(html2plain($html, 0));
1924 // handle data: images
1925 $statusbody = api_format_items_embeded_images($item,$statusbody);
1927 $statustitle = trim($item['title']);
1929 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1930 $statustext = trim($statusbody);
1932 $statustext = trim($statustitle."\n\n".$statusbody);
1934 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1935 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1937 $statushtml = trim(bbcode($body, false, false));
1939 if ($item['title'] != "")
1940 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1942 $entities = api_get_entitities($statustext, $body);
1944 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1947 function api_get_attachments(&$body) {
1950 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1952 $URLSearchString = "^\[\]";
1953 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1958 $attachments = array();
1960 foreach ($images[1] AS $image) {
1961 $imagedata = get_photo_info($image);
1964 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1967 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1968 foreach ($images[0] AS $orig)
1969 $body = str_replace($orig, "", $body);
1971 return $attachments;
1974 function api_get_entitities(&$text, $bbcode) {
1977 * Links at the first character of the post
1982 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1984 if ($include_entities != "true") {
1986 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1988 foreach ($images[1] AS $image) {
1989 $replace = proxy_url($image);
1990 $text = str_replace($image, $replace, $text);
1995 $bbcode = bb_CleanPictureLinks($bbcode);
1997 // Change pure links in text to bbcode uris
1998 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2000 $entities = array();
2001 $entities["hashtags"] = array();
2002 $entities["symbols"] = array();
2003 $entities["urls"] = array();
2004 $entities["user_mentions"] = array();
2006 $URLSearchString = "^\[\]";
2008 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2010 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2011 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2012 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2014 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2015 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2016 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2018 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2019 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2020 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2022 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2024 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2025 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2027 $ordered_urls = array();
2028 foreach ($urls[1] AS $id=>$url) {
2029 //$start = strpos($text, $url, $offset);
2030 $start = iconv_strpos($text, $url, 0, "UTF-8");
2031 if (!($start === false))
2032 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2035 ksort($ordered_urls);
2038 //foreach ($urls[1] AS $id=>$url) {
2039 foreach ($ordered_urls AS $url) {
2040 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2041 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2042 $display_url = $url["title"];
2044 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2045 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2047 if (strlen($display_url) > 26)
2048 $display_url = substr($display_url, 0, 25)."…";
2051 //$start = strpos($text, $url, $offset);
2052 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2053 if (!($start === false)) {
2054 $entities["urls"][] = array("url" => $url["url"],
2055 "expanded_url" => $url["url"],
2056 "display_url" => $display_url,
2057 "indices" => array($start, $start+strlen($url["url"])));
2058 $offset = $start + 1;
2062 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2063 $ordered_images = array();
2064 foreach ($images[1] AS $image) {
2065 //$start = strpos($text, $url, $offset);
2066 $start = iconv_strpos($text, $image, 0, "UTF-8");
2067 if (!($start === false))
2068 $ordered_images[$start] = $image;
2070 //$entities["media"] = array();
2073 foreach ($ordered_images AS $url) {
2074 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2075 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2077 if (strlen($display_url) > 26)
2078 $display_url = substr($display_url, 0, 25)."…";
2080 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2081 if (!($start === false)) {
2082 $image = get_photo_info($url);
2084 // If image cache is activated, then use the following sizes:
2085 // thumb (150), small (340), medium (600) and large (1024)
2086 if (!get_config("system", "proxy_disabled")) {
2087 $media_url = proxy_url($url);
2090 $scale = scale_image($image[0], $image[1], 150);
2091 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2093 if (($image[0] > 150) OR ($image[1] > 150)) {
2094 $scale = scale_image($image[0], $image[1], 340);
2095 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2098 $scale = scale_image($image[0], $image[1], 600);
2099 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2101 if (($image[0] > 600) OR ($image[1] > 600)) {
2102 $scale = scale_image($image[0], $image[1], 1024);
2103 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2107 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2110 $entities["media"][] = array(
2112 "id_str" => (string)$start+1,
2113 "indices" => array($start, $start+strlen($url)),
2114 "media_url" => normalise_link($media_url),
2115 "media_url_https" => $media_url,
2117 "display_url" => $display_url,
2118 "expanded_url" => $url,
2122 $offset = $start + 1;
2128 function api_format_items_embeded_images($item, $text){
2130 $text = preg_replace_callback(
2131 "|data:image/([^;]+)[^=]+=*|m",
2132 function($match) use ($a, $item) {
2133 return $a->get_baseurl()."/display/".$item['guid'];
2139 function api_format_items($r,$user_info, $filter_user = false) {
2144 foreach($r as $item) {
2145 api_share_as_retweet($item);
2147 localize_item($item);
2148 $status_user = api_item_get_user($a,$item);
2150 // Look if the posts are matching if they should be filtered by user id
2151 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2154 if ($item['thr-parent'] != $item['uri']) {
2155 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2157 dbesc($item['thr-parent']));
2159 $in_reply_to_status_id = intval($r[0]['id']);
2161 $in_reply_to_status_id = intval($item['parent']);
2163 $in_reply_to_status_id_str = (string) intval($item['parent']);
2165 $in_reply_to_screen_name = NULL;
2166 $in_reply_to_user_id = NULL;
2167 $in_reply_to_user_id_str = NULL;
2169 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2171 intval($in_reply_to_status_id));
2173 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2176 if ($r[0]['nick'] == "")
2177 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2179 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2180 $in_reply_to_user_id = intval($r[0]['id']);
2181 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2185 $in_reply_to_screen_name = NULL;
2186 $in_reply_to_user_id = NULL;
2187 $in_reply_to_status_id = NULL;
2188 $in_reply_to_user_id_str = NULL;
2189 $in_reply_to_status_id_str = NULL;
2192 $converted = api_convert_item($item);
2195 'text' => $converted["text"],
2196 'truncated' => False,
2197 'created_at'=> api_date($item['created']),
2198 'in_reply_to_status_id' => $in_reply_to_status_id,
2199 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2200 'source' => (($item['app']) ? $item['app'] : 'web'),
2201 'id' => intval($item['id']),
2202 'id_str' => (string) intval($item['id']),
2203 'in_reply_to_user_id' => $in_reply_to_user_id,
2204 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2205 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2207 'favorited' => $item['starred'] ? true : false,
2208 'user' => $status_user ,
2209 //'entities' => NULL,
2210 'statusnet_html' => $converted["html"],
2211 'statusnet_conversation_id' => $item['parent'],
2214 if (count($converted["attachments"]) > 0)
2215 $status["attachments"] = $converted["attachments"];
2217 if (count($converted["entities"]) > 0)
2218 $status["entities"] = $converted["entities"];
2220 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2221 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2222 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2223 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2226 // Retweets are only valid for top postings
2227 // It doesn't work reliable with the link if its a feed
2228 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2230 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2232 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2233 $retweeted_status = $status;
2234 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2236 $status["retweeted_status"] = $retweeted_status;
2239 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2240 unset($status["user"]["uid"]);
2241 unset($status["user"]["self"]);
2243 if ($item["coord"] != "") {
2244 $coords = explode(' ',$item["coord"]);
2245 if (count($coords) == 2) {
2246 $status["geo"] = array('type' => 'Point',
2247 'coordinates' => array((float) $coords[0],
2248 (float) $coords[1]));
2258 function api_account_rate_limit_status(&$a,$type) {
2261 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2262 'remaining_hits' => (string) 150,
2263 'hourly_limit' => (string) 150,
2264 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2267 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2269 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2272 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2274 function api_help_test(&$a,$type) {
2281 return api_apply_template('test', $type, array("$ok" => $ok));
2284 api_register_func('api/help/test','api_help_test',false);
2286 function api_lists(&$a,$type) {
2291 api_register_func('api/lists','api_lists',true);
2293 function api_lists_list(&$a,$type) {
2298 api_register_func('api/lists/list','api_lists_list',true);
2301 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2302 * This function is deprecated by Twitter
2303 * returns: json, xml
2305 function api_statuses_f(&$a, $type, $qtype) {
2306 if (api_user()===false) return false;
2307 $user_info = api_get_user($a);
2309 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2310 /* this is to stop Hotot to load friends multiple times
2311 * I'm not sure if I'm missing return something or
2312 * is a bug in hotot. Workaround, meantime
2316 return array('$users' => $ret);*/
2320 if($qtype == 'friends')
2321 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2322 if($qtype == 'followers')
2323 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2325 // friends and followers only for self
2326 if ($user_info['self'] == 0)
2327 $sql_extra = " AND false ";
2329 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2334 foreach($r as $cid){
2335 $user = api_get_user($a, $cid['nurl']);
2336 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2337 unset($user["uid"]);
2338 unset($user["self"]);
2344 return array('$users' => $ret);
2347 function api_statuses_friends(&$a, $type){
2348 $data = api_statuses_f($a,$type,"friends");
2349 if ($data===false) return false;
2350 return api_apply_template("friends", $type, $data);
2352 function api_statuses_followers(&$a, $type){
2353 $data = api_statuses_f($a,$type,"followers");
2354 if ($data===false) return false;
2355 return api_apply_template("friends", $type, $data);
2357 api_register_func('api/statuses/friends','api_statuses_friends',true);
2358 api_register_func('api/statuses/followers','api_statuses_followers',true);
2365 function api_statusnet_config(&$a,$type) {
2366 $name = $a->config['sitename'];
2367 $server = $a->get_hostname();
2368 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2369 $email = $a->config['admin_email'];
2370 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2371 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2372 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2373 if($a->config['api_import_size'])
2374 $texlimit = string($a->config['api_import_size']);
2375 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2376 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2379 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2380 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2381 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2382 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2383 'shorturllength' => '30',
2384 'friendica' => array(
2385 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2386 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2387 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2388 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2393 return api_apply_template('config', $type, array('$config' => $config));
2396 api_register_func('api/statusnet/config','api_statusnet_config',false);
2398 function api_statusnet_version(&$a,$type) {
2402 if($type === 'xml') {
2403 header("Content-type: application/xml");
2404 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2407 elseif($type === 'json') {
2408 header("Content-type: application/json");
2413 api_register_func('api/statusnet/version','api_statusnet_version',false);
2416 function api_ff_ids(&$a,$type,$qtype) {
2420 $user_info = api_get_user($a);
2422 if($qtype == 'friends')
2423 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2424 if($qtype == 'followers')
2425 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2427 if (!$user_info["self"])
2428 $sql_extra = " AND false ";
2430 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2432 $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",
2438 if($type === 'xml') {
2439 header("Content-type: application/xml");
2440 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2442 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2443 echo '</ids>' . "\r\n";
2446 elseif($type === 'json') {
2448 header("Content-type: application/json");
2453 $ret[] = intval($rr['id']);
2455 echo json_encode($ret);
2461 function api_friends_ids(&$a,$type) {
2462 api_ff_ids($a,$type,'friends');
2464 function api_followers_ids(&$a,$type) {
2465 api_ff_ids($a,$type,'followers');
2467 api_register_func('api/friends/ids','api_friends_ids',true);
2468 api_register_func('api/followers/ids','api_followers_ids',true);
2471 function api_direct_messages_new(&$a, $type) {
2472 if (api_user()===false) return false;
2474 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2476 $sender = api_get_user($a);
2478 if ($_POST['screen_name']) {
2479 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2481 dbesc($_POST['screen_name']));
2483 // Selecting the id by priority, friendica first
2484 api_best_nickname($r);
2486 $recipient = api_get_user($a, $r[0]['nurl']);
2488 $recipient = api_get_user($a, $_POST['user_id']);
2492 if (x($_REQUEST,'replyto')) {
2493 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2495 intval($_REQUEST['replyto']));
2496 $replyto = $r[0]['parent-uri'];
2497 $sub = $r[0]['title'];
2500 if (x($_REQUEST,'title')) {
2501 $sub = $_REQUEST['title'];
2504 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2508 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2511 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2512 $ret = api_format_messages($r[0], $recipient, $sender);
2515 $ret = array("error"=>$id);
2518 $data = Array('$messages'=>$ret);
2523 $data = api_rss_extra($a, $data, $user_info);
2526 return api_apply_template("direct_messages", $type, $data);
2529 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2531 function api_direct_messages_box(&$a, $type, $box) {
2532 if (api_user()===false) return false;
2536 $count = (x($_GET,'count')?$_GET['count']:20);
2537 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2538 if ($page<0) $page=0;
2540 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2541 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2543 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2544 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2547 unset($_REQUEST["user_id"]);
2548 unset($_GET["user_id"]);
2550 unset($_REQUEST["screen_name"]);
2551 unset($_GET["screen_name"]);
2553 $user_info = api_get_user($a);
2554 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2555 $profile_url = $user_info["url"];
2559 $start = $page*$count;
2562 if ($box=="sentbox") {
2563 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2565 elseif ($box=="conversation") {
2566 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2568 elseif ($box=="all") {
2569 $sql_extra = "true";
2571 elseif ($box=="inbox") {
2572 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2576 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2578 if ($user_id !="") {
2579 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2581 elseif($screen_name !=""){
2582 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2585 $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",
2588 intval($start), intval($count)
2593 foreach($r as $item) {
2594 if ($box == "inbox" || $item['from-url'] != $profile_url){
2595 $recipient = $user_info;
2596 $sender = api_get_user($a,normalise_link($item['contact-url']));
2598 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2599 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2600 $sender = $user_info;
2603 $ret[]=api_format_messages($item, $recipient, $sender);
2607 $data = array('$messages' => $ret);
2611 $data = api_rss_extra($a, $data, $user_info);
2614 return api_apply_template("direct_messages", $type, $data);
2618 function api_direct_messages_sentbox(&$a, $type){
2619 return api_direct_messages_box($a, $type, "sentbox");
2621 function api_direct_messages_inbox(&$a, $type){
2622 return api_direct_messages_box($a, $type, "inbox");
2624 function api_direct_messages_all(&$a, $type){
2625 return api_direct_messages_box($a, $type, "all");
2627 function api_direct_messages_conversation(&$a, $type){
2628 return api_direct_messages_box($a, $type, "conversation");
2630 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2631 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2632 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2633 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2637 function api_oauth_request_token(&$a, $type){
2639 $oauth = new FKOAuth1();
2640 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2641 }catch(Exception $e){
2642 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2647 function api_oauth_access_token(&$a, $type){
2649 $oauth = new FKOAuth1();
2650 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2651 }catch(Exception $e){
2652 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2658 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2659 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2662 function api_fr_photos_list(&$a,$type) {
2663 if (api_user()===false) return false;
2664 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2665 intval(local_user())
2670 $ret[] = $rr['resource-id'];
2671 header("Content-type: application/json");
2672 echo json_encode($ret);
2677 function api_fr_photo_detail(&$a,$type) {
2678 if (api_user()===false) return false;
2679 if(! $_REQUEST['photo_id']) return false;
2680 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2681 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2682 intval(local_user()),
2683 dbesc($_REQUEST['photo_id']),
2687 header("Content-type: application/json");
2688 $r[0]['data'] = base64_encode($r[0]['data']);
2689 echo json_encode($r[0]);
2695 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2696 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2701 * similar as /mod/redir.php
2702 * redirect to 'url' after dfrn auth
2704 * why this when there is mod/redir.php already?
2705 * This use api_user() and api_login()
2708 * c_url: url of remote contact to auth to
2709 * url: string, url to redirect after auth
2711 function api_friendica_remoteauth(&$a) {
2712 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2713 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2715 if ($url === '' || $c_url === '')
2716 die((api_error($a, 'json', "Wrong parameters")));
2718 $c_url = normalise_link($c_url);
2722 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2727 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2728 die((api_error($a, 'json', "Unknown contact")));
2732 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2734 if($r[0]['duplex'] && $r[0]['issued-id']) {
2735 $orig_id = $r[0]['issued-id'];
2736 $dfrn_id = '1:' . $orig_id;
2738 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2739 $orig_id = $r[0]['dfrn-id'];
2740 $dfrn_id = '0:' . $orig_id;
2743 $sec = random_string();
2745 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2746 VALUES( %d, %s, '%s', '%s', %d )",
2754 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2755 $dest = (($url) ? '&destination_url=' . $url : '');
2756 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2757 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2758 . '&type=profile&sec=' . $sec . $dest . $quiet );
2760 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2764 function api_share_as_retweet(&$item) {
2765 $body = trim($item["body"]);
2767 // Skip if it isn't a pure repeated messages
2768 // Does it start with a share?
2769 if (strpos($body, "[share") > 0)
2772 // Does it end with a share?
2773 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2776 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2777 // Skip if there is no shared message in there
2778 if ($body == $attributes)
2782 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2783 if ($matches[1] != "")
2784 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2786 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2787 if ($matches[1] != "")
2788 $author = $matches[1];
2791 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2792 if ($matches[1] != "")
2793 $profile = $matches[1];
2795 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2796 if ($matches[1] != "")
2797 $profile = $matches[1];
2800 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2801 if ($matches[1] != "")
2802 $avatar = $matches[1];
2804 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2805 if ($matches[1] != "")
2806 $avatar = $matches[1];
2809 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2810 if ($matches[1] != "")
2811 $link = $matches[1];
2813 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2814 if ($matches[1] != "")
2815 $link = $matches[1];
2817 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2819 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2822 $item["body"] = $shared_body;
2823 $item["author-name"] = $author;
2824 $item["author-link"] = $profile;
2825 $item["author-avatar"] = $avatar;
2826 $item["plink"] = $link;
2832 function api_get_nick($profile) {
2834 - remove trailing jung from profile url
2835 - pump.io check has to check the website
2840 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2841 if ($friendica != $profile)
2845 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2846 if ($diaspora != $profile)
2851 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2852 if ($twitter != $profile)
2858 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2859 if ($StatusnetHost != $profile) {
2860 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2861 if ($StatusnetUser != $profile) {
2862 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2863 $user = json_decode($UserData);
2865 $nick = $user->screen_name;
2870 // To-Do: look at the page if its really a pumpio site
2871 //if (!$nick == "") {
2872 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2873 // if ($pumpio != $profile)
2875 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2880 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2881 dbesc($nick), dbesc(normalise_link($profile)));
2888 function api_clean_plain_items($Text) {
2889 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2891 $Text = bb_CleanPictureLinks($Text);
2893 $URLSearchString = "^\[\]";
2895 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2897 if ($include_entities == "true") {
2898 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2901 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2905 function api_cleanup_share($shared) {
2906 if ($shared[2] != "type-link")
2909 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2915 if (isset($bookmark[2][0]))
2916 $title = $bookmark[2][0];
2918 if (isset($bookmark[1][0]))
2919 $link = $bookmark[1][0];
2921 if (strpos($shared[1],$title) !== false)
2924 if (strpos($shared[1],$link) !== false)
2927 $text = trim($shared[1]);
2929 //if (strlen($text) < strlen($title))
2930 if (($text == "") AND ($title != ""))
2931 $text .= "\n\n".trim($title);
2934 $text .= "\n".trim($link);
2936 return(trim($text));
2939 function api_best_nickname(&$contacts) {
2940 $best_contact = array();
2942 if (count($contact) == 0)
2945 foreach ($contacts AS $contact)
2946 if ($contact["network"] == "") {
2947 $contact["network"] = "dfrn";
2948 $best_contact = array($contact);
2951 if (sizeof($best_contact) == 0)
2952 foreach ($contacts AS $contact)
2953 if ($contact["network"] == "dfrn")
2954 $best_contact = array($contact);
2956 if (sizeof($best_contact) == 0)
2957 foreach ($contacts AS $contact)
2958 if ($contact["network"] == "dspr")
2959 $best_contact = array($contact);
2961 if (sizeof($best_contact) == 0)
2962 foreach ($contacts AS $contact)
2963 if ($contact["network"] == "stat")
2964 $best_contact = array($contact);
2966 if (sizeof($best_contact) == 0)
2967 foreach ($contacts AS $contact)
2968 if ($contact["network"] == "pump")
2969 $best_contact = array($contact);
2971 if (sizeof($best_contact) == 0)
2972 foreach ($contacts AS $contact)
2973 if ($contact["network"] == "twit")
2974 $best_contact = array($contact);
2976 if (sizeof($best_contact) == 1)
2977 $contacts = $best_contact;
2979 $contacts = array($contacts[0]);
2985 [pagename] => api/1.1/statuses/lookup.json
2986 [id] => 605138389168451584
2987 [include_cards] => true
2988 [cards_platform] => Android-12
2989 [include_entities] => true
2990 [include_my_retweet] => 1
2992 [include_reply_count] => true
2993 [include_descendent_reply_count] => true
2997 Not implemented by now:
2998 statuses/retweets_of_me
3003 account/update_location
3004 account/update_profile_background_image
3005 account/update_profile_image
3009 Not implemented in status.net:
3010 statuses/retweeted_to_me
3011 statuses/retweeted_by_me
3012 direct_messages/destroy
3014 account/update_delivery_device
3015 notifications/follow