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 (`name` != '%s' OR `avatar` != '%s') AND url = '%s'",
566 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
567 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
568 dbesc(normalise_link($item["author-link"])));
571 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
572 dbesc(normalise_link($item['owner-link'])));
574 if (count($owner) == 0) {
575 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
576 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
578 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
579 dbesc(normalise_link($item['owner-link'])));
580 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
581 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE (`name` != '%s' OR `avatar` != '%s') AND url = '%s'",
582 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
583 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
584 dbesc(normalise_link($item["owner-link"])));
587 // Comments in threads may appear as wall-to-wall postings.
588 // So only take the owner at the top posting.
589 if ($item["id"] == $item["parent"])
590 $status_user = api_get_user($a,$item["owner-link"]);
592 $status_user = api_get_user($a,$item["author-link"]);
594 $status_user["protected"] = (($item["allow_cid"] != "") OR
595 ($item["allow_gid"] != "") OR
596 ($item["deny_cid"] != "") OR
597 ($item["deny_gid"] != "") OR
600 return ($status_user);
605 * load api $templatename for $type and replace $data array
607 function api_apply_template($templatename, $type, $data){
615 $data = array_xmlify($data);
616 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
618 header ("Content-Type: text/xml");
619 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
622 $ret = replace_macros($tpl, $data);
637 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
638 * returns a 401 status code and an error message if not.
639 * http://developer.twitter.com/doc/get/account/verify_credentials
641 function api_account_verify_credentials(&$a, $type){
642 if (api_user()===false) return false;
644 unset($_REQUEST["user_id"]);
645 unset($_GET["user_id"]);
647 unset($_REQUEST["screen_name"]);
648 unset($_GET["screen_name"]);
650 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
652 $user_info = api_get_user($a);
654 // "verified" isn't used here in the standard
655 unset($user_info["verified"]);
657 // - Adding last status
659 $user_info["status"] = api_status_show($a,"raw");
660 if (!count($user_info["status"]))
661 unset($user_info["status"]);
663 unset($user_info["status"]["user"]);
666 // "uid" and "self" are only needed for some internal stuff, so remove it from here
667 unset($user_info["uid"]);
668 unset($user_info["self"]);
670 return api_apply_template("user", $type, array('$user' => $user_info));
673 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
677 * get data from $_POST or $_GET
679 function requestdata($k){
680 if (isset($_POST[$k])){
683 if (isset($_GET[$k])){
689 /*Waitman Gobble Mod*/
690 function api_statuses_mediap(&$a, $type) {
691 if (api_user()===false) {
692 logger('api_statuses_update: no user');
695 $user_info = api_get_user($a);
697 $_REQUEST['type'] = 'wall';
698 $_REQUEST['profile_uid'] = api_user();
699 $_REQUEST['api_source'] = true;
700 $txt = requestdata('status');
701 //$txt = urldecode(requestdata('status'));
703 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
705 require_once('library/HTMLPurifier.auto.php');
707 $txt = html2bb_video($txt);
708 $config = HTMLPurifier_Config::createDefault();
709 $config->set('Cache.DefinitionImpl', null);
710 $purifier = new HTMLPurifier($config);
711 $txt = $purifier->purify($txt);
713 $txt = html2bbcode($txt);
715 $a->argv[1]=$user_info['screen_name']; //should be set to username?
717 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
718 $bebop = wall_upload_post($a);
720 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
721 $_REQUEST['body']=$txt."\n\n".$bebop;
724 // this should output the last post (the one we just posted).
725 return api_status_show($a,$type);
727 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
728 /*Waitman Gobble Mod*/
731 function api_statuses_update(&$a, $type) {
732 if (api_user()===false) {
733 logger('api_statuses_update: no user');
737 $user_info = api_get_user($a);
739 // convert $_POST array items to the form we use for web posts.
741 // logger('api_post: ' . print_r($_POST,true));
743 if(requestdata('htmlstatus')) {
744 $txt = requestdata('htmlstatus');
745 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
747 require_once('library/HTMLPurifier.auto.php');
749 $txt = html2bb_video($txt);
751 $config = HTMLPurifier_Config::createDefault();
752 $config->set('Cache.DefinitionImpl', null);
754 $purifier = new HTMLPurifier($config);
755 $txt = $purifier->purify($txt);
757 $_REQUEST['body'] = html2bbcode($txt);
761 $_REQUEST['body'] = requestdata('status');
763 $_REQUEST['title'] = requestdata('title');
765 $parent = requestdata('in_reply_to_status_id');
767 // Twidere sends "-1" if it is no reply ...
771 if(ctype_digit($parent))
772 $_REQUEST['parent'] = $parent;
774 $_REQUEST['parent_uri'] = $parent;
776 if(requestdata('lat') && requestdata('long'))
777 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
778 $_REQUEST['profile_uid'] = api_user();
781 $_REQUEST['type'] = 'net-comment';
783 // Check for throttling (maximum posts per day, week and month)
784 $throttle_day = get_config('system','throttle_limit_day');
785 if ($throttle_day > 0) {
786 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
788 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
789 AND `created` > '%s' AND `id` = `parent`",
790 intval(api_user()), dbesc($datefrom));
793 $posts_day = $r[0]["posts_day"];
797 if ($posts_day > $throttle_day) {
798 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
799 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
803 $throttle_week = get_config('system','throttle_limit_week');
804 if ($throttle_week > 0) {
805 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
807 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
808 AND `created` > '%s' AND `id` = `parent`",
809 intval(api_user()), dbesc($datefrom));
812 $posts_week = $r[0]["posts_week"];
816 if ($posts_week > $throttle_week) {
817 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
818 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
822 $throttle_month = get_config('system','throttle_limit_month');
823 if ($throttle_month > 0) {
824 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
826 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
827 AND `created` > '%s' AND `id` = `parent`",
828 intval(api_user()), dbesc($datefrom));
831 $posts_month = $r[0]["posts_month"];
835 if ($posts_month > $throttle_month) {
836 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
837 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
841 $_REQUEST['type'] = 'wall';
844 if(x($_FILES,'media')) {
845 // upload the image if we have one
846 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
847 $media = wall_upload_post($a);
849 $_REQUEST['body'] .= "\n\n".$media;
852 // To-Do: Multiple IDs
853 if (requestdata('media_ids')) {
854 $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",
855 intval(requestdata('media_ids')), api_user());
857 $phototypes = Photo::supportedTypes();
858 $ext = $phototypes[$r[0]['type']];
859 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
860 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
864 // set this so that the item_post() function is quiet and doesn't redirect or emit json
866 $_REQUEST['api_source'] = true;
868 if (!x($_REQUEST, "source"))
869 $_REQUEST["source"] = api_source();
871 // call out normal post function
875 // this should output the last post (the one we just posted).
876 return api_status_show($a,$type);
878 api_register_func('api/statuses/update','api_statuses_update', true);
879 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
882 function api_media_upload(&$a, $type) {
883 if (api_user()===false) {
888 $user_info = api_get_user($a);
890 if(!x($_FILES,'media')) {
895 $media = wall_upload_post($a, false);
901 $returndata = array();
902 $returndata["media_id"] = $media["id"];
903 $returndata["media_id_string"] = (string)$media["id"];
904 $returndata["size"] = $media["size"];
905 $returndata["image"] = array("w" => $media["width"],
906 "h" => $media["height"],
907 "image_type" => $media["type"]);
909 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
911 return array("media" => $returndata);
914 api_register_func('api/media/upload','api_media_upload', true);
916 function api_status_show(&$a, $type){
917 $user_info = api_get_user($a);
919 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
922 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
926 // get last public wall message
927 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
928 FROM `item`, `item` as `i`
929 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
930 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
931 AND `i`.`id` = `item`.`parent`
932 AND `item`.`type`!='activity' $privacy_sql
933 ORDER BY `item`.`created` DESC
935 intval($user_info['cid']),
937 dbesc($user_info['url']),
938 dbesc(normalise_link($user_info['url'])),
939 dbesc($user_info['url']),
940 dbesc(normalise_link($user_info['url']))
943 if (count($lastwall)>0){
944 $lastwall = $lastwall[0];
946 $in_reply_to_status_id = NULL;
947 $in_reply_to_user_id = NULL;
948 $in_reply_to_status_id_str = NULL;
949 $in_reply_to_user_id_str = NULL;
950 $in_reply_to_screen_name = NULL;
951 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
952 $in_reply_to_status_id= intval($lastwall['parent']);
953 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
955 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
957 if ($r[0]['nick'] == "")
958 $r[0]['nick'] = api_get_nick($r[0]["url"]);
960 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
961 $in_reply_to_user_id = intval($r[0]['id']);
962 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
966 // There seems to be situation, where both fields are identical:
967 // https://github.com/friendica/friendica/issues/1010
968 // This is a bugfix for that.
969 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
970 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
971 $in_reply_to_status_id = NULL;
972 $in_reply_to_user_id = NULL;
973 $in_reply_to_status_id_str = NULL;
974 $in_reply_to_user_id_str = NULL;
975 $in_reply_to_screen_name = NULL;
978 $converted = api_convert_item($lastwall);
980 $status_info = array(
981 'created_at' => api_date($lastwall['created']),
982 'id' => intval($lastwall['id']),
983 'id_str' => (string) $lastwall['id'],
984 'text' => $converted["text"],
985 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
986 'truncated' => false,
987 'in_reply_to_status_id' => $in_reply_to_status_id,
988 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
989 'in_reply_to_user_id' => $in_reply_to_user_id,
990 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
991 'in_reply_to_screen_name' => $in_reply_to_screen_name,
992 'user' => $user_info,
996 'contributors' => "",
997 'is_quote_status' => false,
998 'retweet_count' => 0,
999 'favorite_count' => 0,
1000 'favorited' => $lastwall['starred'] ? true : false,
1001 'retweeted' => false,
1002 'possibly_sensitive' => false,
1004 'statusnet_html' => $converted["html"],
1005 'statusnet_conversation_id' => $lastwall['parent'],
1008 if (count($converted["attachments"]) > 0)
1009 $status_info["attachments"] = $converted["attachments"];
1011 if (count($converted["entities"]) > 0)
1012 $status_info["entities"] = $converted["entities"];
1014 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1015 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1016 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1017 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1019 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1020 unset($status_info["user"]["uid"]);
1021 unset($status_info["user"]["self"]);
1024 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1027 return($status_info);
1029 return api_apply_template("status", $type, array('$status' => $status_info));
1038 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1039 * The author's most recent status will be returned inline.
1040 * http://developer.twitter.com/doc/get/users/show
1042 function api_users_show(&$a, $type){
1043 $user_info = api_get_user($a);
1045 $lastwall = q("SELECT `item`.*
1046 FROM `item`, `contact`
1047 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1048 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1049 AND `contact`.`id`=`item`.`contact-id`
1050 AND `type`!='activity'
1051 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1052 ORDER BY `created` DESC
1055 dbesc(ACTIVITY_POST),
1056 intval($user_info['cid']),
1057 dbesc($user_info['url']),
1058 dbesc(normalise_link($user_info['url'])),
1059 dbesc($user_info['url']),
1060 dbesc(normalise_link($user_info['url']))
1062 if (count($lastwall)>0){
1063 $lastwall = $lastwall[0];
1065 $in_reply_to_status_id = NULL;
1066 $in_reply_to_user_id = NULL;
1067 $in_reply_to_status_id_str = NULL;
1068 $in_reply_to_user_id_str = NULL;
1069 $in_reply_to_screen_name = NULL;
1070 if ($lastwall['parent']!=$lastwall['id']) {
1071 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1072 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1073 if (count($reply)>0) {
1074 $in_reply_to_status_id = intval($lastwall['parent']);
1075 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1077 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1079 if ($r[0]['nick'] == "")
1080 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1082 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1083 $in_reply_to_user_id = intval($r[0]['id']);
1084 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1089 $converted = api_convert_item($lastwall);
1091 $user_info['status'] = array(
1092 'text' => $converted["text"],
1093 'truncated' => false,
1094 'created_at' => api_date($lastwall['created']),
1095 'in_reply_to_status_id' => $in_reply_to_status_id,
1096 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1097 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1098 'id' => intval($lastwall['contact-id']),
1099 'id_str' => (string) $lastwall['contact-id'],
1100 'in_reply_to_user_id' => $in_reply_to_user_id,
1101 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1102 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1104 'favorited' => $lastwall['starred'] ? true : false,
1105 'statusnet_html' => $converted["html"],
1106 'statusnet_conversation_id' => $lastwall['parent'],
1109 if (count($converted["attachments"]) > 0)
1110 $user_info["status"]["attachments"] = $converted["attachments"];
1112 if (count($converted["entities"]) > 0)
1113 $user_info["status"]["entities"] = $converted["entities"];
1115 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1116 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1117 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1118 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1122 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1123 unset($user_info["uid"]);
1124 unset($user_info["self"]);
1126 return api_apply_template("user", $type, array('$user' => $user_info));
1129 api_register_func('api/users/show','api_users_show');
1132 function api_users_search(&$a, $type) {
1133 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1135 $userlist = array();
1137 if (isset($_GET["q"])) {
1138 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1140 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1143 foreach ($r AS $user) {
1144 $user_info = api_get_user($a, $user["id"]);
1145 //echo print_r($user_info, true)."\n";
1146 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1147 $userlist[] = $userdata["user"];
1149 $userlist = array("users" => $userlist);
1151 die(api_error($a, $type, t("User not found.")));
1153 die(api_error($a, $type, t("User not found.")));
1158 api_register_func('api/users/search','api_users_search');
1162 * http://developer.twitter.com/doc/get/statuses/home_timeline
1164 * TODO: Optional parameters
1165 * TODO: Add reply info
1167 function api_statuses_home_timeline(&$a, $type){
1168 if (api_user()===false) return false;
1170 unset($_REQUEST["user_id"]);
1171 unset($_GET["user_id"]);
1173 unset($_REQUEST["screen_name"]);
1174 unset($_GET["screen_name"]);
1176 $user_info = api_get_user($a);
1177 // get last newtork messages
1181 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1182 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1183 if ($page<0) $page=0;
1184 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1185 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1186 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1187 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1188 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1190 $start = $page*$count;
1194 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1195 if ($exclude_replies > 0)
1196 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1197 if ($conversation_id > 0)
1198 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1200 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1201 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1202 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1203 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1204 FROM `item`, `contact`
1205 WHERE `item`.`uid` = %d AND `verb` = '%s'
1206 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1207 AND `contact`.`id` = `item`.`contact-id`
1208 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1211 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1213 dbesc(ACTIVITY_POST),
1215 intval($start), intval($count)
1218 $ret = api_format_items($r,$user_info);
1220 // Set all posts from the query above to seen
1222 foreach ($r AS $item)
1223 $idarray[] = intval($item["id"]);
1225 $idlist = implode(",", $idarray);
1228 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1231 $data = array('$statuses' => $ret);
1235 $data = api_rss_extra($a, $data, $user_info);
1238 $as = api_format_as($a, $ret, $user_info);
1239 $as['title'] = $a->config['sitename']." Home Timeline";
1240 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1245 return api_apply_template("timeline", $type, $data);
1247 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1248 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1250 function api_statuses_public_timeline(&$a, $type){
1251 if (api_user()===false) return false;
1253 $user_info = api_get_user($a);
1254 // get last newtork messages
1258 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1259 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1260 if ($page<0) $page=0;
1261 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1262 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1263 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1264 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1265 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1267 $start = $page*$count;
1270 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1271 if ($exclude_replies > 0)
1272 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1273 if ($conversation_id > 0)
1274 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1276 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1277 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1278 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1279 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1280 `user`.`nickname`, `user`.`hidewall`
1281 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1282 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1283 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1284 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1285 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1286 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1287 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1290 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1291 dbesc(ACTIVITY_POST),
1296 $ret = api_format_items($r,$user_info);
1299 $data = array('$statuses' => $ret);
1303 $data = api_rss_extra($a, $data, $user_info);
1306 $as = api_format_as($a, $ret, $user_info);
1307 $as['title'] = $a->config['sitename']." Public Timeline";
1308 $as['link']['url'] = $a->get_baseurl()."/";
1313 return api_apply_template("timeline", $type, $data);
1315 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1320 function api_statuses_show(&$a, $type){
1321 if (api_user()===false) return false;
1323 $user_info = api_get_user($a);
1326 $id = intval($a->argv[3]);
1329 $id = intval($_REQUEST["id"]);
1333 $id = intval($a->argv[4]);
1335 logger('API: api_statuses_show: '.$id);
1337 $conversation = (x($_REQUEST,'conversation')?1:0);
1341 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1343 $sql_extra .= " AND `item`.`id` = %d";
1345 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1346 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1347 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1348 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1349 FROM `item`, `contact`
1350 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1351 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1352 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1355 dbesc(ACTIVITY_POST),
1360 die(api_error($a, $type, t("There is no status with this id.")));
1362 $ret = api_format_items($r,$user_info);
1364 if ($conversation) {
1365 $data = array('$statuses' => $ret);
1366 return api_apply_template("timeline", $type, $data);
1368 $data = array('$status' => $ret[0]);
1372 $data = api_rss_extra($a, $data, $user_info);
1374 return api_apply_template("status", $type, $data);
1377 api_register_func('api/statuses/show','api_statuses_show', true);
1383 function api_conversation_show(&$a, $type){
1384 if (api_user()===false) return false;
1386 $user_info = api_get_user($a);
1389 $id = intval($a->argv[3]);
1390 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1391 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1392 if ($page<0) $page=0;
1393 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1394 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1396 $start = $page*$count;
1399 $id = intval($_REQUEST["id"]);
1403 $id = intval($a->argv[4]);
1405 logger('API: api_conversation_show: '.$id);
1407 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1409 $id = $r[0]["parent"];
1414 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1416 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1417 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1418 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1419 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1420 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1421 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1422 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1423 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1424 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1425 AND `item`.`id`>%d $sql_extra
1426 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1427 intval($id), intval(api_user()),
1428 dbesc(ACTIVITY_POST),
1430 intval($start), intval($count)
1434 die(api_error($a, $type, t("There is no conversation with this id.")));
1436 $ret = api_format_items($r,$user_info);
1438 $data = array('$statuses' => $ret);
1439 return api_apply_template("timeline", $type, $data);
1441 api_register_func('api/conversation/show','api_conversation_show', true);
1447 function api_statuses_repeat(&$a, $type){
1450 if (api_user()===false) return false;
1452 $user_info = api_get_user($a);
1455 $id = intval($a->argv[3]);
1458 $id = intval($_REQUEST["id"]);
1462 $id = intval($a->argv[4]);
1464 logger('API: api_statuses_repeat: '.$id);
1466 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1467 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1468 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1469 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1470 FROM `item`, `contact`
1471 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1472 AND `contact`.`id` = `item`.`contact-id`
1473 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1475 AND `item`.`id`=%d",
1479 if ($r[0]['body'] != "") {
1480 if (!intval(get_config('system','old_share'))) {
1481 if (strpos($r[0]['body'], "[/share]") !== false) {
1482 $pos = strpos($r[0]['body'], "[share");
1483 $post = substr($r[0]['body'], $pos);
1485 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1487 $post .= $r[0]['body'];
1488 $post .= "[/share]";
1490 $_REQUEST['body'] = $post;
1492 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1494 $_REQUEST['profile_uid'] = api_user();
1495 $_REQUEST['type'] = 'wall';
1496 $_REQUEST['api_source'] = true;
1498 if (!x($_REQUEST, "source"))
1499 $_REQUEST["source"] = api_source();
1504 // this should output the last post (the one we just posted).
1506 return(api_status_show($a,$type));
1508 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1513 function api_statuses_destroy(&$a, $type){
1514 if (api_user()===false) return false;
1516 $user_info = api_get_user($a);
1519 $id = intval($a->argv[3]);
1522 $id = intval($_REQUEST["id"]);
1526 $id = intval($a->argv[4]);
1528 logger('API: api_statuses_destroy: '.$id);
1530 $ret = api_statuses_show($a, $type);
1532 drop_item($id, false);
1536 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1540 * http://developer.twitter.com/doc/get/statuses/mentions
1543 function api_statuses_mentions(&$a, $type){
1544 if (api_user()===false) return false;
1546 unset($_REQUEST["user_id"]);
1547 unset($_GET["user_id"]);
1549 unset($_REQUEST["screen_name"]);
1550 unset($_GET["screen_name"]);
1552 $user_info = api_get_user($a);
1553 // get last newtork messages
1557 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1558 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1559 if ($page<0) $page=0;
1560 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1561 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1562 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1564 $start = $page*$count;
1566 // Ugly code - should be changed
1567 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1568 $myurl = substr($myurl,strpos($myurl,'://')+3);
1569 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1570 $myurl = str_replace('www.','',$myurl);
1571 $diasp_url = str_replace('/profile/','/u/',$myurl);
1574 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1576 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1577 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1578 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1579 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1580 FROM `item`, `contact`
1581 WHERE `item`.`uid` = %d AND `verb` = '%s'
1582 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1583 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1584 AND `contact`.`id` = `item`.`contact-id`
1585 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1586 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1589 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1591 dbesc(ACTIVITY_POST),
1592 dbesc(protect_sprintf($myurl)),
1593 dbesc(protect_sprintf($myurl)),
1596 intval($start), intval($count)
1599 $ret = api_format_items($r,$user_info);
1602 $data = array('$statuses' => $ret);
1606 $data = api_rss_extra($a, $data, $user_info);
1609 $as = api_format_as($a, $ret, $user_info);
1610 $as["title"] = $a->config['sitename']." Mentions";
1611 $as['link']['url'] = $a->get_baseurl()."/";
1616 return api_apply_template("timeline", $type, $data);
1618 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1619 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1622 function api_statuses_user_timeline(&$a, $type){
1623 if (api_user()===false) return false;
1625 $user_info = api_get_user($a);
1626 // get last network messages
1628 logger("api_statuses_user_timeline: api_user: ". api_user() .
1629 "\nuser_info: ".print_r($user_info, true) .
1630 "\n_REQUEST: ".print_r($_REQUEST, true),
1634 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1635 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1636 if ($page<0) $page=0;
1637 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1638 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1639 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1640 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1642 $start = $page*$count;
1645 if ($user_info['self']==1)
1646 $sql_extra .= " AND `item`.`wall` = 1 ";
1648 if ($exclude_replies > 0)
1649 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1650 if ($conversation_id > 0)
1651 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1653 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1654 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1655 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1656 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1657 FROM `item`, `contact`
1658 WHERE `item`.`uid` = %d AND `verb` = '%s'
1659 AND `item`.`contact-id` = %d
1660 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1661 AND `contact`.`id` = `item`.`contact-id`
1662 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1665 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1667 dbesc(ACTIVITY_POST),
1668 intval($user_info['cid']),
1670 intval($start), intval($count)
1673 $ret = api_format_items($r,$user_info, true);
1675 $data = array('$statuses' => $ret);
1679 $data = api_rss_extra($a, $data, $user_info);
1682 return api_apply_template("timeline", $type, $data);
1685 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1689 * Star/unstar an item
1690 * param: id : id of the item
1692 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1694 function api_favorites_create_destroy(&$a, $type){
1695 if (api_user()===false) return false;
1697 # for versioned api.
1698 # TODO: we need a better global soluton
1700 if ($a->argv[1]=="1.1") $action_argv_id=3;
1702 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1703 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1704 if ($a->argc==$action_argv_id+2) {
1705 $itemid = intval($a->argv[$action_argv_id+1]);
1707 $itemid = intval($_REQUEST['id']);
1710 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1711 $itemid, api_user());
1713 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1717 $item[0]['starred']=1;
1720 $item[0]['starred']=0;
1723 die(api_error($a, $type, t("Invalid action. ".$action)));
1725 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1726 $item[0]['starred'], $itemid, api_user());
1728 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1729 $item[0]['starred'], $itemid, api_user());
1731 if ($r===false) die(api_error($a, $type, t("DB error")));
1734 $user_info = api_get_user($a);
1735 $rets = api_format_items($item,$user_info);
1738 $data = array('$status' => $ret);
1742 $data = api_rss_extra($a, $data, $user_info);
1745 return api_apply_template("status", $type, $data);
1748 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1749 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1751 function api_favorites(&$a, $type){
1754 if (api_user()===false) return false;
1756 $called_api= array();
1758 $user_info = api_get_user($a);
1760 // in friendica starred item are private
1761 // return favorites only for self
1762 logger('api_favorites: self:' . $user_info['self']);
1764 if ($user_info['self']==0) {
1770 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1771 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1772 $count = (x($_GET,'count')?$_GET['count']:20);
1773 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1774 if ($page<0) $page=0;
1776 $start = $page*$count;
1779 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1781 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1782 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1783 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1784 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1785 FROM `item`, `contact`
1786 WHERE `item`.`uid` = %d
1787 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1788 AND `item`.`starred` = 1
1789 AND `contact`.`id` = `item`.`contact-id`
1790 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1793 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1796 intval($start), intval($count)
1799 $ret = api_format_items($r,$user_info);
1803 $data = array('$statuses' => $ret);
1807 $data = api_rss_extra($a, $data, $user_info);
1810 return api_apply_template("timeline", $type, $data);
1813 api_register_func('api/favorites','api_favorites', true);
1818 function api_format_as($a, $ret, $user_info) {
1821 $as['title'] = $a->config['sitename']." Public Timeline";
1823 foreach ($ret as $item) {
1824 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1825 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1826 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1827 $avatar[0]["rel"] = "avatar";
1828 $avatar[0]["type"] = "";
1829 $avatar[0]["width"] = 96;
1830 $avatar[0]["height"] = 96;
1831 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1832 $avatar[1]["rel"] = "avatar";
1833 $avatar[1]["type"] = "";
1834 $avatar[1]["width"] = 48;
1835 $avatar[1]["height"] = 48;
1836 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1837 $avatar[2]["rel"] = "avatar";
1838 $avatar[2]["type"] = "";
1839 $avatar[2]["width"] = 24;
1840 $avatar[2]["height"] = 24;
1841 $singleitem["actor"]["avatarLinks"] = $avatar;
1843 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1844 $singleitem["actor"]["image"]["rel"] = "avatar";
1845 $singleitem["actor"]["image"]["type"] = "";
1846 $singleitem["actor"]["image"]["width"] = 96;
1847 $singleitem["actor"]["image"]["height"] = 96;
1848 $singleitem["actor"]["type"] = "person";
1849 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1850 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1851 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1852 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1853 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1854 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1855 $singleitem["actor"]["contact"]["addresses"] = "";
1857 $singleitem["body"] = $item["text"];
1858 $singleitem["object"]["displayName"] = $item["text"];
1859 $singleitem["object"]["id"] = $item["url"];
1860 $singleitem["object"]["type"] = "note";
1861 $singleitem["object"]["url"] = $item["url"];
1862 //$singleitem["context"] =;
1863 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1864 $singleitem["provider"]["objectType"] = "service";
1865 $singleitem["provider"]["displayName"] = "Test";
1866 $singleitem["provider"]["url"] = "http://test.tld";
1867 $singleitem["title"] = $item["text"];
1868 $singleitem["verb"] = "post";
1869 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1870 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1871 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1872 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1873 //$singleitem["original"] = $item;
1874 $items[] = $singleitem;
1876 $as['items'] = $items;
1877 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1878 $as['link']['rel'] = "alternate";
1879 $as['link']['type'] = "text/html";
1883 function api_format_messages($item, $recipient, $sender) {
1884 // standard meta information
1886 'id' => $item['id'],
1887 'sender_id' => $sender['id'] ,
1889 'recipient_id' => $recipient['id'],
1890 'created_at' => api_date($item['created']),
1891 'sender_screen_name' => $sender['screen_name'],
1892 'recipient_screen_name' => $recipient['screen_name'],
1893 'sender' => $sender,
1894 'recipient' => $recipient,
1897 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1898 unset($ret["sender"]["uid"]);
1899 unset($ret["sender"]["self"]);
1900 unset($ret["recipient"]["uid"]);
1901 unset($ret["recipient"]["self"]);
1903 //don't send title to regular StatusNET requests to avoid confusing these apps
1904 if (x($_GET, 'getText')) {
1905 $ret['title'] = $item['title'] ;
1906 if ($_GET["getText"] == "html") {
1907 $ret['text'] = bbcode($item['body'], false, false);
1909 elseif ($_GET["getText"] == "plain") {
1910 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1911 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1915 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1917 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1918 unset($ret['sender']);
1919 unset($ret['recipient']);
1925 function api_convert_item($item) {
1927 $body = $item['body'];
1928 $attachments = api_get_attachments($body);
1930 // Workaround for ostatus messages where the title is identically to the body
1931 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1932 $statusbody = trim(html2plain($html, 0));
1934 // handle data: images
1935 $statusbody = api_format_items_embeded_images($item,$statusbody);
1937 $statustitle = trim($item['title']);
1939 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1940 $statustext = trim($statusbody);
1942 $statustext = trim($statustitle."\n\n".$statusbody);
1944 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1945 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1947 $statushtml = trim(bbcode($body, false, false));
1949 if ($item['title'] != "")
1950 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1952 $entities = api_get_entitities($statustext, $body);
1954 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1957 function api_get_attachments(&$body) {
1960 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1962 $URLSearchString = "^\[\]";
1963 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1968 $attachments = array();
1970 foreach ($images[1] AS $image) {
1971 $imagedata = get_photo_info($image);
1974 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1977 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1978 foreach ($images[0] AS $orig)
1979 $body = str_replace($orig, "", $body);
1981 return $attachments;
1984 function api_get_entitities(&$text, $bbcode) {
1987 * Links at the first character of the post
1992 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1994 if ($include_entities != "true") {
1996 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1998 foreach ($images[1] AS $image) {
1999 $replace = proxy_url($image);
2000 $text = str_replace($image, $replace, $text);
2005 $bbcode = bb_CleanPictureLinks($bbcode);
2007 // Change pure links in text to bbcode uris
2008 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2010 $entities = array();
2011 $entities["hashtags"] = array();
2012 $entities["symbols"] = array();
2013 $entities["urls"] = array();
2014 $entities["user_mentions"] = array();
2016 $URLSearchString = "^\[\]";
2018 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2020 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2021 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2022 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2024 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2025 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2026 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2028 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2029 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2030 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2032 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2034 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2035 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2037 $ordered_urls = array();
2038 foreach ($urls[1] AS $id=>$url) {
2039 //$start = strpos($text, $url, $offset);
2040 $start = iconv_strpos($text, $url, 0, "UTF-8");
2041 if (!($start === false))
2042 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2045 ksort($ordered_urls);
2048 //foreach ($urls[1] AS $id=>$url) {
2049 foreach ($ordered_urls AS $url) {
2050 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2051 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2052 $display_url = $url["title"];
2054 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2055 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2057 if (strlen($display_url) > 26)
2058 $display_url = substr($display_url, 0, 25)."…";
2061 //$start = strpos($text, $url, $offset);
2062 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2063 if (!($start === false)) {
2064 $entities["urls"][] = array("url" => $url["url"],
2065 "expanded_url" => $url["url"],
2066 "display_url" => $display_url,
2067 "indices" => array($start, $start+strlen($url["url"])));
2068 $offset = $start + 1;
2072 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2073 $ordered_images = array();
2074 foreach ($images[1] AS $image) {
2075 //$start = strpos($text, $url, $offset);
2076 $start = iconv_strpos($text, $image, 0, "UTF-8");
2077 if (!($start === false))
2078 $ordered_images[$start] = $image;
2080 //$entities["media"] = array();
2083 foreach ($ordered_images AS $url) {
2084 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2085 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2087 if (strlen($display_url) > 26)
2088 $display_url = substr($display_url, 0, 25)."…";
2090 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2091 if (!($start === false)) {
2092 $image = get_photo_info($url);
2094 // If image cache is activated, then use the following sizes:
2095 // thumb (150), small (340), medium (600) and large (1024)
2096 if (!get_config("system", "proxy_disabled")) {
2097 $media_url = proxy_url($url);
2100 $scale = scale_image($image[0], $image[1], 150);
2101 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2103 if (($image[0] > 150) OR ($image[1] > 150)) {
2104 $scale = scale_image($image[0], $image[1], 340);
2105 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2108 $scale = scale_image($image[0], $image[1], 600);
2109 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2111 if (($image[0] > 600) OR ($image[1] > 600)) {
2112 $scale = scale_image($image[0], $image[1], 1024);
2113 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2117 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2120 $entities["media"][] = array(
2122 "id_str" => (string)$start+1,
2123 "indices" => array($start, $start+strlen($url)),
2124 "media_url" => normalise_link($media_url),
2125 "media_url_https" => $media_url,
2127 "display_url" => $display_url,
2128 "expanded_url" => $url,
2132 $offset = $start + 1;
2138 function api_format_items_embeded_images($item, $text){
2140 $text = preg_replace_callback(
2141 "|data:image/([^;]+)[^=]+=*|m",
2142 function($match) use ($a, $item) {
2143 return $a->get_baseurl()."/display/".$item['guid'];
2149 function api_format_items($r,$user_info, $filter_user = false) {
2154 foreach($r as $item) {
2155 api_share_as_retweet($item);
2157 localize_item($item);
2158 $status_user = api_item_get_user($a,$item);
2160 // Look if the posts are matching if they should be filtered by user id
2161 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2164 if ($item['thr-parent'] != $item['uri']) {
2165 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2167 dbesc($item['thr-parent']));
2169 $in_reply_to_status_id = intval($r[0]['id']);
2171 $in_reply_to_status_id = intval($item['parent']);
2173 $in_reply_to_status_id_str = (string) intval($item['parent']);
2175 $in_reply_to_screen_name = NULL;
2176 $in_reply_to_user_id = NULL;
2177 $in_reply_to_user_id_str = NULL;
2179 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2181 intval($in_reply_to_status_id));
2183 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2186 if ($r[0]['nick'] == "")
2187 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2189 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2190 $in_reply_to_user_id = intval($r[0]['id']);
2191 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2195 $in_reply_to_screen_name = NULL;
2196 $in_reply_to_user_id = NULL;
2197 $in_reply_to_status_id = NULL;
2198 $in_reply_to_user_id_str = NULL;
2199 $in_reply_to_status_id_str = NULL;
2202 $converted = api_convert_item($item);
2205 'text' => $converted["text"],
2206 'truncated' => False,
2207 'created_at'=> api_date($item['created']),
2208 'in_reply_to_status_id' => $in_reply_to_status_id,
2209 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2210 'source' => (($item['app']) ? $item['app'] : 'web'),
2211 'id' => intval($item['id']),
2212 'id_str' => (string) intval($item['id']),
2213 'in_reply_to_user_id' => $in_reply_to_user_id,
2214 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2215 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2217 'favorited' => $item['starred'] ? true : false,
2218 'user' => $status_user ,
2219 //'entities' => NULL,
2220 'statusnet_html' => $converted["html"],
2221 'statusnet_conversation_id' => $item['parent'],
2224 if (count($converted["attachments"]) > 0)
2225 $status["attachments"] = $converted["attachments"];
2227 if (count($converted["entities"]) > 0)
2228 $status["entities"] = $converted["entities"];
2230 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2231 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2232 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2233 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2236 // Retweets are only valid for top postings
2237 // It doesn't work reliable with the link if its a feed
2238 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2240 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2242 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2243 $retweeted_status = $status;
2244 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2246 $status["retweeted_status"] = $retweeted_status;
2249 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2250 unset($status["user"]["uid"]);
2251 unset($status["user"]["self"]);
2253 if ($item["coord"] != "") {
2254 $coords = explode(' ',$item["coord"]);
2255 if (count($coords) == 2) {
2256 $status["geo"] = array('type' => 'Point',
2257 'coordinates' => array((float) $coords[0],
2258 (float) $coords[1]));
2268 function api_account_rate_limit_status(&$a,$type) {
2271 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2272 'remaining_hits' => (string) 150,
2273 'hourly_limit' => (string) 150,
2274 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2277 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2279 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2282 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2284 function api_help_test(&$a,$type) {
2291 return api_apply_template('test', $type, array("$ok" => $ok));
2294 api_register_func('api/help/test','api_help_test',false);
2296 function api_lists(&$a,$type) {
2301 api_register_func('api/lists','api_lists',true);
2303 function api_lists_list(&$a,$type) {
2308 api_register_func('api/lists/list','api_lists_list',true);
2311 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2312 * This function is deprecated by Twitter
2313 * returns: json, xml
2315 function api_statuses_f(&$a, $type, $qtype) {
2316 if (api_user()===false) return false;
2317 $user_info = api_get_user($a);
2319 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2320 /* this is to stop Hotot to load friends multiple times
2321 * I'm not sure if I'm missing return something or
2322 * is a bug in hotot. Workaround, meantime
2326 return array('$users' => $ret);*/
2330 if($qtype == 'friends')
2331 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2332 if($qtype == 'followers')
2333 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2335 // friends and followers only for self
2336 if ($user_info['self'] == 0)
2337 $sql_extra = " AND false ";
2339 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2344 foreach($r as $cid){
2345 $user = api_get_user($a, $cid['nurl']);
2346 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2347 unset($user["uid"]);
2348 unset($user["self"]);
2354 return array('$users' => $ret);
2357 function api_statuses_friends(&$a, $type){
2358 $data = api_statuses_f($a,$type,"friends");
2359 if ($data===false) return false;
2360 return api_apply_template("friends", $type, $data);
2362 function api_statuses_followers(&$a, $type){
2363 $data = api_statuses_f($a,$type,"followers");
2364 if ($data===false) return false;
2365 return api_apply_template("friends", $type, $data);
2367 api_register_func('api/statuses/friends','api_statuses_friends',true);
2368 api_register_func('api/statuses/followers','api_statuses_followers',true);
2375 function api_statusnet_config(&$a,$type) {
2376 $name = $a->config['sitename'];
2377 $server = $a->get_hostname();
2378 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2379 $email = $a->config['admin_email'];
2380 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2381 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2382 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2383 if($a->config['api_import_size'])
2384 $texlimit = string($a->config['api_import_size']);
2385 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2386 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2389 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2390 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2391 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2392 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2393 'shorturllength' => '30',
2394 'friendica' => array(
2395 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2396 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2397 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2398 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2403 return api_apply_template('config', $type, array('$config' => $config));
2406 api_register_func('api/statusnet/config','api_statusnet_config',false);
2408 function api_statusnet_version(&$a,$type) {
2412 if($type === 'xml') {
2413 header("Content-type: application/xml");
2414 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2417 elseif($type === 'json') {
2418 header("Content-type: application/json");
2423 api_register_func('api/statusnet/version','api_statusnet_version',false);
2426 function api_ff_ids(&$a,$type,$qtype) {
2430 $user_info = api_get_user($a);
2432 if($qtype == 'friends')
2433 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2434 if($qtype == 'followers')
2435 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2437 if (!$user_info["self"])
2438 $sql_extra = " AND false ";
2440 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2442 $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",
2448 if($type === 'xml') {
2449 header("Content-type: application/xml");
2450 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2452 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2453 echo '</ids>' . "\r\n";
2456 elseif($type === 'json') {
2458 header("Content-type: application/json");
2463 $ret[] = intval($rr['id']);
2465 echo json_encode($ret);
2471 function api_friends_ids(&$a,$type) {
2472 api_ff_ids($a,$type,'friends');
2474 function api_followers_ids(&$a,$type) {
2475 api_ff_ids($a,$type,'followers');
2477 api_register_func('api/friends/ids','api_friends_ids',true);
2478 api_register_func('api/followers/ids','api_followers_ids',true);
2481 function api_direct_messages_new(&$a, $type) {
2482 if (api_user()===false) return false;
2484 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2486 $sender = api_get_user($a);
2488 if ($_POST['screen_name']) {
2489 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2491 dbesc($_POST['screen_name']));
2493 // Selecting the id by priority, friendica first
2494 api_best_nickname($r);
2496 $recipient = api_get_user($a, $r[0]['nurl']);
2498 $recipient = api_get_user($a, $_POST['user_id']);
2502 if (x($_REQUEST,'replyto')) {
2503 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2505 intval($_REQUEST['replyto']));
2506 $replyto = $r[0]['parent-uri'];
2507 $sub = $r[0]['title'];
2510 if (x($_REQUEST,'title')) {
2511 $sub = $_REQUEST['title'];
2514 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2518 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2521 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2522 $ret = api_format_messages($r[0], $recipient, $sender);
2525 $ret = array("error"=>$id);
2528 $data = Array('$messages'=>$ret);
2533 $data = api_rss_extra($a, $data, $user_info);
2536 return api_apply_template("direct_messages", $type, $data);
2539 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2541 function api_direct_messages_box(&$a, $type, $box) {
2542 if (api_user()===false) return false;
2546 $count = (x($_GET,'count')?$_GET['count']:20);
2547 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2548 if ($page<0) $page=0;
2550 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2551 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2553 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2554 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2557 unset($_REQUEST["user_id"]);
2558 unset($_GET["user_id"]);
2560 unset($_REQUEST["screen_name"]);
2561 unset($_GET["screen_name"]);
2563 $user_info = api_get_user($a);
2564 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2565 $profile_url = $user_info["url"];
2569 $start = $page*$count;
2572 if ($box=="sentbox") {
2573 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2575 elseif ($box=="conversation") {
2576 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2578 elseif ($box=="all") {
2579 $sql_extra = "true";
2581 elseif ($box=="inbox") {
2582 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2586 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2588 if ($user_id !="") {
2589 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2591 elseif($screen_name !=""){
2592 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2595 $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",
2598 intval($start), intval($count)
2603 foreach($r as $item) {
2604 if ($box == "inbox" || $item['from-url'] != $profile_url){
2605 $recipient = $user_info;
2606 $sender = api_get_user($a,normalise_link($item['contact-url']));
2608 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2609 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2610 $sender = $user_info;
2613 $ret[]=api_format_messages($item, $recipient, $sender);
2617 $data = array('$messages' => $ret);
2621 $data = api_rss_extra($a, $data, $user_info);
2624 return api_apply_template("direct_messages", $type, $data);
2628 function api_direct_messages_sentbox(&$a, $type){
2629 return api_direct_messages_box($a, $type, "sentbox");
2631 function api_direct_messages_inbox(&$a, $type){
2632 return api_direct_messages_box($a, $type, "inbox");
2634 function api_direct_messages_all(&$a, $type){
2635 return api_direct_messages_box($a, $type, "all");
2637 function api_direct_messages_conversation(&$a, $type){
2638 return api_direct_messages_box($a, $type, "conversation");
2640 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2641 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2642 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2643 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2647 function api_oauth_request_token(&$a, $type){
2649 $oauth = new FKOAuth1();
2650 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2651 }catch(Exception $e){
2652 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2657 function api_oauth_access_token(&$a, $type){
2659 $oauth = new FKOAuth1();
2660 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2661 }catch(Exception $e){
2662 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2668 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2669 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2672 function api_fr_photos_list(&$a,$type) {
2673 if (api_user()===false) return false;
2674 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2675 intval(local_user())
2680 $ret[] = $rr['resource-id'];
2681 header("Content-type: application/json");
2682 echo json_encode($ret);
2687 function api_fr_photo_detail(&$a,$type) {
2688 if (api_user()===false) return false;
2689 if(! $_REQUEST['photo_id']) return false;
2690 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2691 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2692 intval(local_user()),
2693 dbesc($_REQUEST['photo_id']),
2697 header("Content-type: application/json");
2698 $r[0]['data'] = base64_encode($r[0]['data']);
2699 echo json_encode($r[0]);
2705 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2706 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2711 * similar as /mod/redir.php
2712 * redirect to 'url' after dfrn auth
2714 * why this when there is mod/redir.php already?
2715 * This use api_user() and api_login()
2718 * c_url: url of remote contact to auth to
2719 * url: string, url to redirect after auth
2721 function api_friendica_remoteauth(&$a) {
2722 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2723 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2725 if ($url === '' || $c_url === '')
2726 die((api_error($a, 'json', "Wrong parameters")));
2728 $c_url = normalise_link($c_url);
2732 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2737 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2738 die((api_error($a, 'json', "Unknown contact")));
2742 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2744 if($r[0]['duplex'] && $r[0]['issued-id']) {
2745 $orig_id = $r[0]['issued-id'];
2746 $dfrn_id = '1:' . $orig_id;
2748 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2749 $orig_id = $r[0]['dfrn-id'];
2750 $dfrn_id = '0:' . $orig_id;
2753 $sec = random_string();
2755 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2756 VALUES( %d, %s, '%s', '%s', %d )",
2764 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2765 $dest = (($url) ? '&destination_url=' . $url : '');
2766 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2767 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2768 . '&type=profile&sec=' . $sec . $dest . $quiet );
2770 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2774 function api_share_as_retweet(&$item) {
2775 $body = trim($item["body"]);
2777 // Skip if it isn't a pure repeated messages
2778 // Does it start with a share?
2779 if (strpos($body, "[share") > 0)
2782 // Does it end with a share?
2783 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2786 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2787 // Skip if there is no shared message in there
2788 if ($body == $attributes)
2792 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2793 if ($matches[1] != "")
2794 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2796 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2797 if ($matches[1] != "")
2798 $author = $matches[1];
2801 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2802 if ($matches[1] != "")
2803 $profile = $matches[1];
2805 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2806 if ($matches[1] != "")
2807 $profile = $matches[1];
2810 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2811 if ($matches[1] != "")
2812 $avatar = $matches[1];
2814 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2815 if ($matches[1] != "")
2816 $avatar = $matches[1];
2819 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2820 if ($matches[1] != "")
2821 $link = $matches[1];
2823 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2824 if ($matches[1] != "")
2825 $link = $matches[1];
2827 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2829 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2832 $item["body"] = $shared_body;
2833 $item["author-name"] = $author;
2834 $item["author-link"] = $profile;
2835 $item["author-avatar"] = $avatar;
2836 $item["plink"] = $link;
2842 function api_get_nick($profile) {
2844 - remove trailing jung from profile url
2845 - pump.io check has to check the website
2850 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2851 if ($friendica != $profile)
2855 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2856 if ($diaspora != $profile)
2861 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2862 if ($twitter != $profile)
2868 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2869 if ($StatusnetHost != $profile) {
2870 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2871 if ($StatusnetUser != $profile) {
2872 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2873 $user = json_decode($UserData);
2875 $nick = $user->screen_name;
2880 // To-Do: look at the page if its really a pumpio site
2881 //if (!$nick == "") {
2882 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2883 // if ($pumpio != $profile)
2885 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2890 q("UPDATE unique_contacts SET nick = '%s' WHERE `nick` != '%s' AND url = '%s'",
2891 dbesc($nick), dbesc($nick), dbesc(normalise_link($profile)));
2898 function api_clean_plain_items($Text) {
2899 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2901 $Text = bb_CleanPictureLinks($Text);
2903 $URLSearchString = "^\[\]";
2905 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2907 if ($include_entities == "true") {
2908 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2911 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2915 function api_cleanup_share($shared) {
2916 if ($shared[2] != "type-link")
2919 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2925 if (isset($bookmark[2][0]))
2926 $title = $bookmark[2][0];
2928 if (isset($bookmark[1][0]))
2929 $link = $bookmark[1][0];
2931 if (strpos($shared[1],$title) !== false)
2934 if (strpos($shared[1],$link) !== false)
2937 $text = trim($shared[1]);
2939 //if (strlen($text) < strlen($title))
2940 if (($text == "") AND ($title != ""))
2941 $text .= "\n\n".trim($title);
2944 $text .= "\n".trim($link);
2946 return(trim($text));
2949 function api_best_nickname(&$contacts) {
2950 $best_contact = array();
2952 if (count($contact) == 0)
2955 foreach ($contacts AS $contact)
2956 if ($contact["network"] == "") {
2957 $contact["network"] = "dfrn";
2958 $best_contact = array($contact);
2961 if (sizeof($best_contact) == 0)
2962 foreach ($contacts AS $contact)
2963 if ($contact["network"] == "dfrn")
2964 $best_contact = array($contact);
2966 if (sizeof($best_contact) == 0)
2967 foreach ($contacts AS $contact)
2968 if ($contact["network"] == "dspr")
2969 $best_contact = array($contact);
2971 if (sizeof($best_contact) == 0)
2972 foreach ($contacts AS $contact)
2973 if ($contact["network"] == "stat")
2974 $best_contact = array($contact);
2976 if (sizeof($best_contact) == 0)
2977 foreach ($contacts AS $contact)
2978 if ($contact["network"] == "pump")
2979 $best_contact = array($contact);
2981 if (sizeof($best_contact) == 0)
2982 foreach ($contacts AS $contact)
2983 if ($contact["network"] == "twit")
2984 $best_contact = array($contact);
2986 if (sizeof($best_contact) == 1)
2987 $contacts = $best_contact;
2989 $contacts = array($contacts[0]);
2995 [pagename] => api/1.1/statuses/lookup.json
2996 [id] => 605138389168451584
2997 [include_cards] => true
2998 [cards_platform] => Android-12
2999 [include_entities] => true
3000 [include_my_retweet] => 1
3002 [include_reply_count] => true
3003 [include_descendent_reply_count] => true
3007 Not implemented by now:
3008 statuses/retweets_of_me
3013 account/update_location
3014 account/update_profile_background_image
3015 account/update_profile_image
3019 Not implemented in status.net:
3020 statuses/retweeted_to_me
3021 statuses/retweeted_by_me
3022 direct_messages/destroy
3024 account/update_delivery_device
3025 notifications/follow