3 * @file include/api.php
5 * @todo Automatically detect if incoming data is HTML or BBCode
9 Gerhard Seeber Mail: gerhard@seeber.at Friendica: http://mozartweg.dyndns.org/friendica/gerhard
16 Gerhard Seeber 2015-NOV-25 Add API call /friendica/group_show to return all or a single group
17 with the containing contacts (necessary for Windows 10 Universal app)
18 Gerhard Seeber 2015-NOV-27 Add API call /friendica/group_delete to delete the specified group id
19 (necessary for Windows 10 Universal app)
20 Gerhard Seeber 2015-DEC-01 Add API call /friendica/group_create to create a group with the specified
21 name and the given list of contacts (necessary for Windows 10 Universal
23 Gerhard Seeber 2015-DEC-07 Add API call /friendica/group_update to update a group with the given
24 list of contacts (necessary for Windows 10 Universal app)
28 require_once("include/bbcode.php");
29 require_once("include/datetime.php");
30 require_once("include/conversation.php");
31 require_once("include/oauth.php");
32 require_once("include/html2plain.php");
33 require_once("mod/share.php");
34 require_once("include/Photo.php");
35 require_once("mod/item.php");
36 require_once('include/security.php');
37 require_once('include/contact_selectors.php');
38 require_once('include/html2bbcode.php');
39 require_once('mod/wall_upload.php');
40 require_once("mod/proxy.php");
41 require_once("include/message.php");
42 require_once("include/group.php");
54 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
55 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
56 // into a page, and visitors will post something without noticing it).
57 // Instead, use this function.
58 if ($_SESSION["allow_api"])
64 function api_source() {
65 if (requestdata('source'))
66 return (requestdata('source'));
68 // Support for known clients that doesn't send a source name
69 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
72 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
77 function api_date($str){
78 //Wed May 23 06:01:13 +0000 2007
79 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
83 function api_register_func($path, $func, $auth=false){
85 $API[$path] = array('func'=>$func, 'auth'=>$auth);
87 // Workaround for hotot
88 $path = str_replace("api/", "api/1.1/", $path);
89 $API[$path] = array('func'=>$func, 'auth'=>$auth);
96 function api_login(&$a){
99 $oauth = new FKOAuth1();
100 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
101 if (!is_null($token)){
102 $oauth->loginUser($token->uid);
103 call_hooks('logged_in', $a->user);
106 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
107 }catch(Exception $e){
108 logger(__file__.__line__.__function__."\n".$e);
109 //die(__file__.__line__.__function__."<pre>".$e); die();
114 // workaround for HTTP-auth in CGI mode
115 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
116 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
117 if(strlen($userpass)) {
118 list($name, $password) = explode(':', $userpass);
119 $_SERVER['PHP_AUTH_USER'] = $name;
120 $_SERVER['PHP_AUTH_PW'] = $password;
124 if (!isset($_SERVER['PHP_AUTH_USER'])) {
125 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
126 header('WWW-Authenticate: Basic realm="Friendica"');
127 header('HTTP/1.0 401 Unauthorized');
128 die((api_error($a, 'json', "This api requires login")));
130 //die('This api requires login');
133 $user = $_SERVER['PHP_AUTH_USER'];
134 $password = $_SERVER['PHP_AUTH_PW'];
135 $encrypted = hash('whirlpool',trim($password));
137 // allow "user@server" login (but ignore 'server' part)
138 $at=strstr($user, "@", true);
139 if ( $at ) $user=$at;
142 * next code from mod/auth.php. needs better solution
147 'username' => trim($user),
148 'password' => trim($password),
149 'authenticated' => 0,
150 'user_record' => null
155 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
156 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
157 * and later plugins should not interfere with an earlier one that succeeded.
161 call_hooks('authenticate', $addon_auth);
163 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
164 $record = $addon_auth['user_record'];
167 // process normal login request
169 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
170 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
179 if((! $record) || (! count($record))) {
180 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
181 header('WWW-Authenticate: Basic realm="Friendica"');
182 header('HTTP/1.0 401 Unauthorized');
183 die('This api requires login');
186 authenticate_success($record); $_SESSION["allow_api"] = true;
188 call_hooks('logged_in', $a->user);
192 /**************************
193 * MAIN API ENTRY POINT *
194 **************************/
195 function api_call(&$a){
196 GLOBAL $API, $called_api;
200 foreach ($API as $p=>$info){
201 if (strpos($a->query_string, $p)===0){
202 $called_api= explode("/",$p);
203 //unset($_SERVER['PHP_AUTH_USER']);
204 if ($info['auth']===true && api_user()===false) {
208 load_contact_links(api_user());
210 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
211 logger('API parameters: ' . print_r($_REQUEST,true));
213 if (strpos($a->query_string, ".xml")>0) $type="xml";
214 if (strpos($a->query_string, ".json")>0) $type="json";
215 if (strpos($a->query_string, ".rss")>0) $type="rss";
216 if (strpos($a->query_string, ".atom")>0) $type="atom";
217 if (strpos($a->query_string, ".as")>0) $type="as";
219 $stamp = microtime(true);
220 $r = call_user_func($info['func'], $a, $type);
221 $duration = (float)(microtime(true)-$stamp);
222 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
224 if ($r===false) return;
228 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
229 header ("Content-Type: text/xml");
230 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
233 header ("Content-Type: application/json");
235 $json = json_encode($rr);
236 if ($_GET['callback'])
237 $json = $_GET['callback']."(".$json.")";
241 header ("Content-Type: application/rss+xml");
242 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
245 header ("Content-Type: application/atom+xml");
246 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
249 //header ("Content-Type: application/json");
251 // return json_encode($rr);
252 return json_encode($r);
256 //echo "<pre>"; var_dump($r); die();
259 header("HTTP/1.1 404 Not Found");
260 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
261 return(api_error($a, $type, "not implemented"));
265 function api_error(&$a, $type, $error) {
266 /// @TODO https://dev.twitter.com/overview/api/response-codes
267 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
270 header ("Content-Type: text/xml");
271 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
274 header ("Content-Type: application/json");
275 return json_encode(array('error' => $error, 'request' => $a->query_string));
278 header ("Content-Type: application/rss+xml");
279 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
282 header ("Content-Type: application/atom+xml");
283 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
291 function api_rss_extra(&$a, $arr, $user_info){
292 if (is_null($user_info)) $user_info = api_get_user($a);
293 $arr['$user'] = $user_info;
294 $arr['$rss'] = array(
295 'alternate' => $user_info['url'],
296 'self' => $a->get_baseurl(). "/". $a->query_string,
297 'base' => $a->get_baseurl(),
298 'updated' => api_date(null),
299 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
300 'language' => $user_info['language'],
301 'logo' => $a->get_baseurl()."/images/friendica-32.png",
309 * Unique contact to contact url.
311 function api_unique_id_to_url($id){
312 $r = q("SELECT `url` FROM `unique_contacts` WHERE `id`=%d LIMIT 1",
315 return ($r[0]["url"]);
321 * Returns user info array.
323 function api_get_user(&$a, $contact_id = Null, $type = "json"){
330 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
332 // Searching for contact URL
333 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
334 $user = dbesc(normalise_link($contact_id));
336 $extra_query = "AND `contact`.`nurl` = '%s' ";
337 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
340 // Searching for unique contact id
341 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
342 $user = dbesc(api_unique_id_to_url($contact_id));
345 die(api_error($a, $type, t("User not found.")));
348 $extra_query = "AND `contact`.`nurl` = '%s' ";
349 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
352 if(is_null($user) && x($_GET, 'user_id')) {
353 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
356 die(api_error($a, $type, t("User not found.")));
359 $extra_query = "AND `contact`.`nurl` = '%s' ";
360 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
362 if(is_null($user) && x($_GET, 'screen_name')) {
363 $user = dbesc($_GET['screen_name']);
365 $extra_query = "AND `contact`.`nick` = '%s' ";
366 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
369 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
370 $argid = count($called_api);
371 list($user, $null) = explode(".",$a->argv[$argid]);
372 if(is_numeric($user)){
373 $user = dbesc(api_unique_id_to_url($user));
379 $extra_query = "AND `contact`.`nurl` = '%s' ";
380 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
382 $user = dbesc($user);
384 $extra_query = "AND `contact`.`nick` = '%s' ";
385 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
389 logger("api_get_user: user ".$user, LOGGER_DEBUG);
392 if (api_user()===false) {
393 api_login($a); return False;
395 $user = $_SESSION['uid'];
396 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
401 logger('api_user: ' . $extra_query . ', user: ' . $user);
403 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
409 // Selecting the id by priority, friendica first
410 api_best_nickname($uinfo);
412 // if the contact wasn't found, fetch it from the unique contacts
413 if (count($uinfo)==0) {
417 $r = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", $url);
419 $r = q("SELECT * FROM `unique_contacts` WHERE `nick`='%s' LIMIT 1", $nick);
422 // If no nick where given, extract it from the address
423 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
424 $r[0]['nick'] = api_get_nick($r[0]["url"]);
428 'id_str' => (string) $r[0]["id"],
429 'name' => $r[0]["name"],
430 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
432 'description' => NULL,
433 'url' => $r[0]["url"],
434 'protected' => false,
435 'followers_count' => 0,
436 'friends_count' => 0,
438 'created_at' => api_date(0),
439 'favourites_count' => 0,
441 'time_zone' => 'UTC',
442 'geo_enabled' => false,
444 'statuses_count' => 0,
446 'contributors_enabled' => false,
447 'is_translator' => false,
448 'is_translation_enabled' => false,
449 'profile_image_url' => $r[0]["avatar"],
450 'profile_image_url_https' => $r[0]["avatar"],
451 'following' => false,
452 'follow_request_sent' => false,
453 'notifications' => false,
454 'statusnet_blocking' => false,
455 'notifications' => false,
456 'statusnet_profile_url' => $r[0]["url"],
465 die(api_error($a, $type, t("User not found.")));
469 if($uinfo[0]['self']) {
470 $usr = q("select * from user where uid = %d limit 1",
473 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
477 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
478 // count public wall messages
479 $r = q("SELECT count(*) as `count` FROM `item`
482 intval($uinfo[0]['uid'])
484 $countitms = $r[0]['count'];
487 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
488 $r = q("SELECT count(*) as `count` FROM `item`
489 WHERE `contact-id` = %d",
490 intval($uinfo[0]['id'])
492 $countitms = $r[0]['count'];
496 $r = q("SELECT count(*) as `count` FROM `contact`
497 WHERE `uid` = %d AND `rel` IN ( %d, %d )
498 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
499 intval($uinfo[0]['uid']),
500 intval(CONTACT_IS_SHARING),
501 intval(CONTACT_IS_FRIEND)
503 $countfriends = $r[0]['count'];
505 $r = q("SELECT count(*) as `count` FROM `contact`
506 WHERE `uid` = %d AND `rel` IN ( %d, %d )
507 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
508 intval($uinfo[0]['uid']),
509 intval(CONTACT_IS_FOLLOWER),
510 intval(CONTACT_IS_FRIEND)
512 $countfollowers = $r[0]['count'];
514 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
515 intval($uinfo[0]['uid'])
517 $starred = $r[0]['count'];
520 if(! $uinfo[0]['self']) {
526 // Add a nick if it isn't present there
527 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
528 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
531 // Fetching unique id
532 $r = q("SELECT id FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
534 // If not there, then add it
535 if (count($r) == 0) {
536 q("INSERT INTO `unique_contacts` (`url`, `name`, `nick`, `avatar`) VALUES ('%s', '%s', '%s', '%s')",
537 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
539 $r = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
542 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
545 'id' => intval($r[0]['id']),
546 'id_str' => (string) intval($r[0]['id']),
547 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
548 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
549 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
550 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
551 'profile_image_url' => $uinfo[0]['micro'],
552 'profile_image_url_https' => $uinfo[0]['micro'],
553 'url' => $uinfo[0]['url'],
554 'protected' => false,
555 'followers_count' => intval($countfollowers),
556 'friends_count' => intval($countfriends),
557 'created_at' => api_date($uinfo[0]['created']),
558 'favourites_count' => intval($starred),
560 'time_zone' => 'UTC',
561 'statuses_count' => intval($countitms),
562 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
564 'statusnet_blocking' => false,
565 'notifications' => false,
566 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
567 'statusnet_profile_url' => $uinfo[0]['url'],
568 'uid' => intval($uinfo[0]['uid']),
569 'cid' => intval($uinfo[0]['cid']),
570 'self' => $uinfo[0]['self'],
571 'network' => $uinfo[0]['network'],
578 function api_item_get_user(&$a, $item) {
580 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
581 dbesc(normalise_link($item['author-link'])));
583 if (count($author) == 0) {
584 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
585 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
587 $author = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
588 dbesc(normalise_link($item['author-link'])));
589 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
590 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
591 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
592 dbesc(normalise_link($item["author-link"])));
595 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
596 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
597 dbesc(normalise_link($item["author-link"])));
600 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
601 dbesc(normalise_link($item['owner-link'])));
603 if (count($owner) == 0) {
604 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
605 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
607 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
608 dbesc(normalise_link($item['owner-link'])));
609 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
610 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
611 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
612 dbesc(normalise_link($item["owner-link"])));
615 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
616 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
617 dbesc(normalise_link($item["owner-link"])));
620 // Comments in threads may appear as wall-to-wall postings.
621 // So only take the owner at the top posting.
622 if ($item["id"] == $item["parent"])
623 $status_user = api_get_user($a,$item["owner-link"]);
625 $status_user = api_get_user($a,$item["author-link"]);
627 $status_user["protected"] = (($item["allow_cid"] != "") OR
628 ($item["allow_gid"] != "") OR
629 ($item["deny_cid"] != "") OR
630 ($item["deny_gid"] != "") OR
633 return ($status_user);
638 * load api $templatename for $type and replace $data array
640 function api_apply_template($templatename, $type, $data){
648 $data = array_xmlify($data);
649 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
651 header ("Content-Type: text/xml");
652 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
655 $ret = replace_macros($tpl, $data);
670 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
671 * returns a 401 status code and an error message if not.
672 * http://developer.twitter.com/doc/get/account/verify_credentials
674 function api_account_verify_credentials(&$a, $type){
675 if (api_user()===false) return false;
677 unset($_REQUEST["user_id"]);
678 unset($_GET["user_id"]);
680 unset($_REQUEST["screen_name"]);
681 unset($_GET["screen_name"]);
683 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
685 $user_info = api_get_user($a);
687 // "verified" isn't used here in the standard
688 unset($user_info["verified"]);
690 // - Adding last status
692 $user_info["status"] = api_status_show($a,"raw");
693 if (!count($user_info["status"]))
694 unset($user_info["status"]);
696 unset($user_info["status"]["user"]);
699 // "uid" and "self" are only needed for some internal stuff, so remove it from here
700 unset($user_info["uid"]);
701 unset($user_info["self"]);
703 return api_apply_template("user", $type, array('$user' => $user_info));
706 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
710 * get data from $_POST or $_GET
712 function requestdata($k){
713 if (isset($_POST[$k])){
716 if (isset($_GET[$k])){
722 /*Waitman Gobble Mod*/
723 function api_statuses_mediap(&$a, $type) {
724 if (api_user()===false) {
725 logger('api_statuses_update: no user');
728 $user_info = api_get_user($a);
730 $_REQUEST['type'] = 'wall';
731 $_REQUEST['profile_uid'] = api_user();
732 $_REQUEST['api_source'] = true;
733 $txt = requestdata('status');
734 //$txt = urldecode(requestdata('status'));
736 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
738 require_once('library/HTMLPurifier.auto.php');
740 $txt = html2bb_video($txt);
741 $config = HTMLPurifier_Config::createDefault();
742 $config->set('Cache.DefinitionImpl', null);
743 $purifier = new HTMLPurifier($config);
744 $txt = $purifier->purify($txt);
746 $txt = html2bbcode($txt);
748 $a->argv[1]=$user_info['screen_name']; //should be set to username?
750 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
751 $bebop = wall_upload_post($a);
753 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
754 $_REQUEST['body']=$txt."\n\n".$bebop;
757 // this should output the last post (the one we just posted).
758 return api_status_show($a,$type);
760 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
761 /*Waitman Gobble Mod*/
764 function api_statuses_update(&$a, $type) {
765 if (api_user()===false) {
766 logger('api_statuses_update: no user');
770 $user_info = api_get_user($a);
772 // convert $_POST array items to the form we use for web posts.
774 // logger('api_post: ' . print_r($_POST,true));
776 if(requestdata('htmlstatus')) {
777 $txt = requestdata('htmlstatus');
778 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
780 require_once('library/HTMLPurifier.auto.php');
782 $txt = html2bb_video($txt);
784 $config = HTMLPurifier_Config::createDefault();
785 $config->set('Cache.DefinitionImpl', null);
787 $purifier = new HTMLPurifier($config);
788 $txt = $purifier->purify($txt);
790 $_REQUEST['body'] = html2bbcode($txt);
794 $_REQUEST['body'] = requestdata('status');
796 $_REQUEST['title'] = requestdata('title');
798 $parent = requestdata('in_reply_to_status_id');
800 // Twidere sends "-1" if it is no reply ...
804 if(ctype_digit($parent))
805 $_REQUEST['parent'] = $parent;
807 $_REQUEST['parent_uri'] = $parent;
809 if(requestdata('lat') && requestdata('long'))
810 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
811 $_REQUEST['profile_uid'] = api_user();
814 $_REQUEST['type'] = 'net-comment';
816 // Check for throttling (maximum posts per day, week and month)
817 $throttle_day = get_config('system','throttle_limit_day');
818 if ($throttle_day > 0) {
819 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
821 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
822 AND `created` > '%s' AND `id` = `parent`",
823 intval(api_user()), dbesc($datefrom));
826 $posts_day = $r[0]["posts_day"];
830 if ($posts_day > $throttle_day) {
831 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
832 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
836 $throttle_week = get_config('system','throttle_limit_week');
837 if ($throttle_week > 0) {
838 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
840 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
841 AND `created` > '%s' AND `id` = `parent`",
842 intval(api_user()), dbesc($datefrom));
845 $posts_week = $r[0]["posts_week"];
849 if ($posts_week > $throttle_week) {
850 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
851 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
855 $throttle_month = get_config('system','throttle_limit_month');
856 if ($throttle_month > 0) {
857 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
859 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
860 AND `created` > '%s' AND `id` = `parent`",
861 intval(api_user()), dbesc($datefrom));
864 $posts_month = $r[0]["posts_month"];
868 if ($posts_month > $throttle_month) {
869 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
870 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
874 $_REQUEST['type'] = 'wall';
877 if(x($_FILES,'media')) {
878 // upload the image if we have one
879 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
880 $media = wall_upload_post($a);
882 $_REQUEST['body'] .= "\n\n".$media;
885 /// @TODO Multiple IDs
886 if (requestdata('media_ids')) {
887 $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",
888 intval(requestdata('media_ids')), api_user());
890 $phototypes = Photo::supportedTypes();
891 $ext = $phototypes[$r[0]['type']];
892 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
893 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
897 // set this so that the item_post() function is quiet and doesn't redirect or emit json
899 $_REQUEST['api_source'] = true;
901 if (!x($_REQUEST, "source"))
902 $_REQUEST["source"] = api_source();
904 // call out normal post function
908 // this should output the last post (the one we just posted).
909 return api_status_show($a,$type);
911 api_register_func('api/statuses/update','api_statuses_update', true);
912 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
915 function api_media_upload(&$a, $type) {
916 if (api_user()===false) {
921 $user_info = api_get_user($a);
923 if(!x($_FILES,'media')) {
928 $media = wall_upload_post($a, false);
934 $returndata = array();
935 $returndata["media_id"] = $media["id"];
936 $returndata["media_id_string"] = (string)$media["id"];
937 $returndata["size"] = $media["size"];
938 $returndata["image"] = array("w" => $media["width"],
939 "h" => $media["height"],
940 "image_type" => $media["type"]);
942 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
944 return array("media" => $returndata);
947 api_register_func('api/media/upload','api_media_upload', true);
949 function api_status_show(&$a, $type){
950 $user_info = api_get_user($a);
952 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
955 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
959 // get last public wall message
960 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
961 FROM `item`, `item` as `i`
962 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
963 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
964 AND `i`.`id` = `item`.`parent`
965 AND `item`.`type`!='activity' $privacy_sql
966 ORDER BY `item`.`created` DESC
968 intval($user_info['cid']),
970 dbesc($user_info['url']),
971 dbesc(normalise_link($user_info['url'])),
972 dbesc($user_info['url']),
973 dbesc(normalise_link($user_info['url']))
976 if (count($lastwall)>0){
977 $lastwall = $lastwall[0];
979 $in_reply_to_status_id = NULL;
980 $in_reply_to_user_id = NULL;
981 $in_reply_to_status_id_str = NULL;
982 $in_reply_to_user_id_str = NULL;
983 $in_reply_to_screen_name = NULL;
984 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
985 $in_reply_to_status_id= intval($lastwall['parent']);
986 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
988 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
990 if ($r[0]['nick'] == "")
991 $r[0]['nick'] = api_get_nick($r[0]["url"]);
993 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
994 $in_reply_to_user_id = intval($r[0]['id']);
995 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
999 // There seems to be situation, where both fields are identical:
1000 // https://github.com/friendica/friendica/issues/1010
1001 // This is a bugfix for that.
1002 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1003 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1004 $in_reply_to_status_id = NULL;
1005 $in_reply_to_user_id = NULL;
1006 $in_reply_to_status_id_str = NULL;
1007 $in_reply_to_user_id_str = NULL;
1008 $in_reply_to_screen_name = NULL;
1011 $converted = api_convert_item($lastwall);
1013 $status_info = array(
1014 'created_at' => api_date($lastwall['created']),
1015 'id' => intval($lastwall['id']),
1016 'id_str' => (string) $lastwall['id'],
1017 'text' => $converted["text"],
1018 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1019 'truncated' => false,
1020 'in_reply_to_status_id' => $in_reply_to_status_id,
1021 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1022 'in_reply_to_user_id' => $in_reply_to_user_id,
1023 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1024 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1025 'user' => $user_info,
1027 'coordinates' => "",
1029 'contributors' => "",
1030 'is_quote_status' => false,
1031 'retweet_count' => 0,
1032 'favorite_count' => 0,
1033 'favorited' => $lastwall['starred'] ? true : false,
1034 'retweeted' => false,
1035 'possibly_sensitive' => false,
1037 'statusnet_html' => $converted["html"],
1038 'statusnet_conversation_id' => $lastwall['parent'],
1041 if (count($converted["attachments"]) > 0)
1042 $status_info["attachments"] = $converted["attachments"];
1044 if (count($converted["entities"]) > 0)
1045 $status_info["entities"] = $converted["entities"];
1047 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1048 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1049 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1050 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1052 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1053 unset($status_info["user"]["uid"]);
1054 unset($status_info["user"]["self"]);
1057 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1060 return($status_info);
1062 return api_apply_template("status", $type, array('$status' => $status_info));
1071 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1072 * The author's most recent status will be returned inline.
1073 * http://developer.twitter.com/doc/get/users/show
1075 function api_users_show(&$a, $type){
1076 $user_info = api_get_user($a);
1078 $lastwall = q("SELECT `item`.*
1079 FROM `item`, `contact`
1080 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1081 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1082 AND `contact`.`id`=`item`.`contact-id`
1083 AND `type`!='activity'
1084 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1085 ORDER BY `created` DESC
1088 dbesc(ACTIVITY_POST),
1089 intval($user_info['cid']),
1090 dbesc($user_info['url']),
1091 dbesc(normalise_link($user_info['url'])),
1092 dbesc($user_info['url']),
1093 dbesc(normalise_link($user_info['url']))
1095 if (count($lastwall)>0){
1096 $lastwall = $lastwall[0];
1098 $in_reply_to_status_id = NULL;
1099 $in_reply_to_user_id = NULL;
1100 $in_reply_to_status_id_str = NULL;
1101 $in_reply_to_user_id_str = NULL;
1102 $in_reply_to_screen_name = NULL;
1103 if ($lastwall['parent']!=$lastwall['id']) {
1104 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1105 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1106 if (count($reply)>0) {
1107 $in_reply_to_status_id = intval($lastwall['parent']);
1108 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1110 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1112 if ($r[0]['nick'] == "")
1113 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1115 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1116 $in_reply_to_user_id = intval($r[0]['id']);
1117 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1122 $converted = api_convert_item($lastwall);
1124 $user_info['status'] = array(
1125 'text' => $converted["text"],
1126 'truncated' => false,
1127 'created_at' => api_date($lastwall['created']),
1128 'in_reply_to_status_id' => $in_reply_to_status_id,
1129 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1130 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1131 'id' => intval($lastwall['contact-id']),
1132 'id_str' => (string) $lastwall['contact-id'],
1133 'in_reply_to_user_id' => $in_reply_to_user_id,
1134 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1135 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1137 'favorited' => $lastwall['starred'] ? true : false,
1138 'statusnet_html' => $converted["html"],
1139 'statusnet_conversation_id' => $lastwall['parent'],
1142 if (count($converted["attachments"]) > 0)
1143 $user_info["status"]["attachments"] = $converted["attachments"];
1145 if (count($converted["entities"]) > 0)
1146 $user_info["status"]["entities"] = $converted["entities"];
1148 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1149 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1150 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1151 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1155 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1156 unset($user_info["uid"]);
1157 unset($user_info["self"]);
1159 return api_apply_template("user", $type, array('$user' => $user_info));
1162 api_register_func('api/users/show','api_users_show');
1165 function api_users_search(&$a, $type) {
1166 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1168 $userlist = array();
1170 if (isset($_GET["q"])) {
1171 $r = q("SELECT id FROM `unique_contacts` WHERE `name`='%s'", dbesc($_GET["q"]));
1173 $r = q("SELECT `id` FROM `unique_contacts` WHERE `nick`='%s'", dbesc($_GET["q"]));
1176 foreach ($r AS $user) {
1177 $user_info = api_get_user($a, $user["id"]);
1178 //echo print_r($user_info, true)."\n";
1179 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1180 $userlist[] = $userdata["user"];
1182 $userlist = array("users" => $userlist);
1184 die(api_error($a, $type, t("User not found.")));
1186 die(api_error($a, $type, t("User not found.")));
1191 api_register_func('api/users/search','api_users_search');
1195 * http://developer.twitter.com/doc/get/statuses/home_timeline
1197 * @TODO Optional parameters
1198 * @TODO Add reply info
1200 function api_statuses_home_timeline(&$a, $type){
1201 if (api_user()===false) return false;
1203 unset($_REQUEST["user_id"]);
1204 unset($_GET["user_id"]);
1206 unset($_REQUEST["screen_name"]);
1207 unset($_GET["screen_name"]);
1209 $user_info = api_get_user($a);
1210 // get last newtork messages
1214 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1215 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1216 if ($page<0) $page=0;
1217 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1218 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1219 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1220 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1221 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1223 $start = $page*$count;
1227 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1228 if ($exclude_replies > 0)
1229 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1230 if ($conversation_id > 0)
1231 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1233 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1234 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1235 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1236 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1237 FROM `item`, `contact`
1238 WHERE `item`.`uid` = %d AND `verb` = '%s'
1239 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1240 AND `contact`.`id` = `item`.`contact-id`
1241 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1244 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1246 dbesc(ACTIVITY_POST),
1248 intval($start), intval($count)
1251 $ret = api_format_items($r,$user_info);
1253 // Set all posts from the query above to seen
1255 foreach ($r AS $item)
1256 $idarray[] = intval($item["id"]);
1258 $idlist = implode(",", $idarray);
1261 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1264 $data = array('$statuses' => $ret);
1268 $data = api_rss_extra($a, $data, $user_info);
1271 $as = api_format_as($a, $ret, $user_info);
1272 $as['title'] = $a->config['sitename']." Home Timeline";
1273 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1278 return api_apply_template("timeline", $type, $data);
1280 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1281 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1283 function api_statuses_public_timeline(&$a, $type){
1284 if (api_user()===false) return false;
1286 $user_info = api_get_user($a);
1287 // get last newtork messages
1291 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1292 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1293 if ($page<0) $page=0;
1294 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1295 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1296 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1297 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1298 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1300 $start = $page*$count;
1303 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1304 if ($exclude_replies > 0)
1305 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1306 if ($conversation_id > 0)
1307 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1309 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1310 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1311 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1312 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1313 `user`.`nickname`, `user`.`hidewall`
1314 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1315 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1316 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1317 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1318 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1319 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1320 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1323 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1324 dbesc(ACTIVITY_POST),
1329 $ret = api_format_items($r,$user_info);
1332 $data = array('$statuses' => $ret);
1336 $data = api_rss_extra($a, $data, $user_info);
1339 $as = api_format_as($a, $ret, $user_info);
1340 $as['title'] = $a->config['sitename']." Public Timeline";
1341 $as['link']['url'] = $a->get_baseurl()."/";
1346 return api_apply_template("timeline", $type, $data);
1348 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1353 function api_statuses_show(&$a, $type){
1354 if (api_user()===false) return false;
1356 $user_info = api_get_user($a);
1359 $id = intval($a->argv[3]);
1362 $id = intval($_REQUEST["id"]);
1366 $id = intval($a->argv[4]);
1368 logger('API: api_statuses_show: '.$id);
1370 $conversation = (x($_REQUEST,'conversation')?1:0);
1374 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1376 $sql_extra .= " AND `item`.`id` = %d";
1378 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1379 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1380 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1381 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1382 FROM `item`, `contact`
1383 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1384 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1385 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1388 dbesc(ACTIVITY_POST),
1393 die(api_error($a, $type, t("There is no status with this id.")));
1395 $ret = api_format_items($r,$user_info);
1397 if ($conversation) {
1398 $data = array('$statuses' => $ret);
1399 return api_apply_template("timeline", $type, $data);
1401 $data = array('$status' => $ret[0]);
1405 $data = api_rss_extra($a, $data, $user_info);
1407 return api_apply_template("status", $type, $data);
1410 api_register_func('api/statuses/show','api_statuses_show', true);
1416 function api_conversation_show(&$a, $type){
1417 if (api_user()===false) return false;
1419 $user_info = api_get_user($a);
1422 $id = intval($a->argv[3]);
1423 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1424 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1425 if ($page<0) $page=0;
1426 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1427 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1429 $start = $page*$count;
1432 $id = intval($_REQUEST["id"]);
1436 $id = intval($a->argv[4]);
1438 logger('API: api_conversation_show: '.$id);
1440 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1442 $id = $r[0]["parent"];
1447 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1449 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1450 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1451 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1452 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1453 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1454 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1455 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1456 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1457 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1458 AND `item`.`id`>%d $sql_extra
1459 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1460 intval($id), intval(api_user()),
1461 dbesc(ACTIVITY_POST),
1463 intval($start), intval($count)
1467 die(api_error($a, $type, t("There is no conversation with this id.")));
1469 $ret = api_format_items($r,$user_info);
1471 $data = array('$statuses' => $ret);
1472 return api_apply_template("timeline", $type, $data);
1474 api_register_func('api/conversation/show','api_conversation_show', true);
1480 function api_statuses_repeat(&$a, $type){
1483 if (api_user()===false) return false;
1485 $user_info = api_get_user($a);
1488 $id = intval($a->argv[3]);
1491 $id = intval($_REQUEST["id"]);
1495 $id = intval($a->argv[4]);
1497 logger('API: api_statuses_repeat: '.$id);
1499 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1500 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1501 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1502 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1503 FROM `item`, `contact`
1504 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1505 AND `contact`.`id` = `item`.`contact-id`
1506 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1508 AND `item`.`id`=%d",
1512 if ($r[0]['body'] != "") {
1513 if (!intval(get_config('system','old_share'))) {
1514 if (strpos($r[0]['body'], "[/share]") !== false) {
1515 $pos = strpos($r[0]['body'], "[share");
1516 $post = substr($r[0]['body'], $pos);
1518 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1520 $post .= $r[0]['body'];
1521 $post .= "[/share]";
1523 $_REQUEST['body'] = $post;
1525 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1527 $_REQUEST['profile_uid'] = api_user();
1528 $_REQUEST['type'] = 'wall';
1529 $_REQUEST['api_source'] = true;
1531 if (!x($_REQUEST, "source"))
1532 $_REQUEST["source"] = api_source();
1537 // this should output the last post (the one we just posted).
1539 return(api_status_show($a,$type));
1541 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1546 function api_statuses_destroy(&$a, $type){
1547 if (api_user()===false) return false;
1549 $user_info = api_get_user($a);
1552 $id = intval($a->argv[3]);
1555 $id = intval($_REQUEST["id"]);
1559 $id = intval($a->argv[4]);
1561 logger('API: api_statuses_destroy: '.$id);
1563 $ret = api_statuses_show($a, $type);
1565 drop_item($id, false);
1569 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1573 * http://developer.twitter.com/doc/get/statuses/mentions
1576 function api_statuses_mentions(&$a, $type){
1577 if (api_user()===false) return false;
1579 unset($_REQUEST["user_id"]);
1580 unset($_GET["user_id"]);
1582 unset($_REQUEST["screen_name"]);
1583 unset($_GET["screen_name"]);
1585 $user_info = api_get_user($a);
1586 // get last newtork messages
1590 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1591 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1592 if ($page<0) $page=0;
1593 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1594 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1595 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1597 $start = $page*$count;
1599 // Ugly code - should be changed
1600 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1601 $myurl = substr($myurl,strpos($myurl,'://')+3);
1602 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1603 $myurl = str_replace('www.','',$myurl);
1604 $diasp_url = str_replace('/profile/','/u/',$myurl);
1607 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1609 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1610 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1611 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1612 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1613 FROM `item`, `contact`
1614 WHERE `item`.`uid` = %d AND `verb` = '%s'
1615 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1616 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1617 AND `contact`.`id` = `item`.`contact-id`
1618 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1619 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1622 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1624 dbesc(ACTIVITY_POST),
1625 dbesc(protect_sprintf($myurl)),
1626 dbesc(protect_sprintf($myurl)),
1629 intval($start), intval($count)
1632 $ret = api_format_items($r,$user_info);
1635 $data = array('$statuses' => $ret);
1639 $data = api_rss_extra($a, $data, $user_info);
1642 $as = api_format_as($a, $ret, $user_info);
1643 $as["title"] = $a->config['sitename']." Mentions";
1644 $as['link']['url'] = $a->get_baseurl()."/";
1649 return api_apply_template("timeline", $type, $data);
1651 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1652 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1655 function api_statuses_user_timeline(&$a, $type){
1656 if (api_user()===false) return false;
1658 $user_info = api_get_user($a);
1659 // get last network messages
1661 logger("api_statuses_user_timeline: api_user: ". api_user() .
1662 "\nuser_info: ".print_r($user_info, true) .
1663 "\n_REQUEST: ".print_r($_REQUEST, true),
1667 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1668 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1669 if ($page<0) $page=0;
1670 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1671 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1672 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1673 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1675 $start = $page*$count;
1678 if ($user_info['self']==1)
1679 $sql_extra .= " AND `item`.`wall` = 1 ";
1681 if ($exclude_replies > 0)
1682 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1683 if ($conversation_id > 0)
1684 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1686 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1687 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1688 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1689 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1690 FROM `item`, `contact`
1691 WHERE `item`.`uid` = %d AND `verb` = '%s'
1692 AND `item`.`contact-id` = %d
1693 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1694 AND `contact`.`id` = `item`.`contact-id`
1695 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1698 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1700 dbesc(ACTIVITY_POST),
1701 intval($user_info['cid']),
1703 intval($start), intval($count)
1706 $ret = api_format_items($r,$user_info, true);
1708 $data = array('$statuses' => $ret);
1712 $data = api_rss_extra($a, $data, $user_info);
1715 return api_apply_template("timeline", $type, $data);
1718 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1722 * Star/unstar an item
1723 * param: id : id of the item
1725 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1727 function api_favorites_create_destroy(&$a, $type){
1728 if (api_user()===false) return false;
1730 // for versioned api.
1731 /// @TODO We need a better global soluton
1733 if ($a->argv[1]=="1.1") $action_argv_id=3;
1735 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1736 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1737 if ($a->argc==$action_argv_id+2) {
1738 $itemid = intval($a->argv[$action_argv_id+1]);
1740 $itemid = intval($_REQUEST['id']);
1743 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1744 $itemid, api_user());
1746 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1750 $item[0]['starred']=1;
1753 $item[0]['starred']=0;
1756 die(api_error($a, $type, t("Invalid action. ".$action)));
1758 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1759 $item[0]['starred'], $itemid, api_user());
1761 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1762 $item[0]['starred'], $itemid, api_user());
1764 if ($r===false) die(api_error($a, $type, t("DB error")));
1767 $user_info = api_get_user($a);
1768 $rets = api_format_items($item,$user_info);
1771 $data = array('$status' => $ret);
1775 $data = api_rss_extra($a, $data, $user_info);
1778 return api_apply_template("status", $type, $data);
1781 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1782 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1784 function api_favorites(&$a, $type){
1787 if (api_user()===false) return false;
1789 $called_api= array();
1791 $user_info = api_get_user($a);
1793 // in friendica starred item are private
1794 // return favorites only for self
1795 logger('api_favorites: self:' . $user_info['self']);
1797 if ($user_info['self']==0) {
1803 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1804 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1805 $count = (x($_GET,'count')?$_GET['count']:20);
1806 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1807 if ($page<0) $page=0;
1809 $start = $page*$count;
1812 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1814 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1815 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1816 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1817 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1818 FROM `item`, `contact`
1819 WHERE `item`.`uid` = %d
1820 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1821 AND `item`.`starred` = 1
1822 AND `contact`.`id` = `item`.`contact-id`
1823 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1826 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1829 intval($start), intval($count)
1832 $ret = api_format_items($r,$user_info);
1836 $data = array('$statuses' => $ret);
1840 $data = api_rss_extra($a, $data, $user_info);
1843 return api_apply_template("timeline", $type, $data);
1846 api_register_func('api/favorites','api_favorites', true);
1851 function api_format_as($a, $ret, $user_info) {
1854 $as['title'] = $a->config['sitename']." Public Timeline";
1856 foreach ($ret as $item) {
1857 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1858 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1859 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1860 $avatar[0]["rel"] = "avatar";
1861 $avatar[0]["type"] = "";
1862 $avatar[0]["width"] = 96;
1863 $avatar[0]["height"] = 96;
1864 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1865 $avatar[1]["rel"] = "avatar";
1866 $avatar[1]["type"] = "";
1867 $avatar[1]["width"] = 48;
1868 $avatar[1]["height"] = 48;
1869 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1870 $avatar[2]["rel"] = "avatar";
1871 $avatar[2]["type"] = "";
1872 $avatar[2]["width"] = 24;
1873 $avatar[2]["height"] = 24;
1874 $singleitem["actor"]["avatarLinks"] = $avatar;
1876 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1877 $singleitem["actor"]["image"]["rel"] = "avatar";
1878 $singleitem["actor"]["image"]["type"] = "";
1879 $singleitem["actor"]["image"]["width"] = 96;
1880 $singleitem["actor"]["image"]["height"] = 96;
1881 $singleitem["actor"]["type"] = "person";
1882 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1883 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1884 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1885 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1886 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1887 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1888 $singleitem["actor"]["contact"]["addresses"] = "";
1890 $singleitem["body"] = $item["text"];
1891 $singleitem["object"]["displayName"] = $item["text"];
1892 $singleitem["object"]["id"] = $item["url"];
1893 $singleitem["object"]["type"] = "note";
1894 $singleitem["object"]["url"] = $item["url"];
1895 //$singleitem["context"] =;
1896 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1897 $singleitem["provider"]["objectType"] = "service";
1898 $singleitem["provider"]["displayName"] = "Test";
1899 $singleitem["provider"]["url"] = "http://test.tld";
1900 $singleitem["title"] = $item["text"];
1901 $singleitem["verb"] = "post";
1902 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1903 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1904 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1905 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1906 //$singleitem["original"] = $item;
1907 $items[] = $singleitem;
1909 $as['items'] = $items;
1910 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1911 $as['link']['rel'] = "alternate";
1912 $as['link']['type'] = "text/html";
1916 function api_format_messages($item, $recipient, $sender) {
1917 // standard meta information
1919 'id' => $item['id'],
1920 'sender_id' => $sender['id'] ,
1922 'recipient_id' => $recipient['id'],
1923 'created_at' => api_date($item['created']),
1924 'sender_screen_name' => $sender['screen_name'],
1925 'recipient_screen_name' => $recipient['screen_name'],
1926 'sender' => $sender,
1927 'recipient' => $recipient,
1930 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1931 unset($ret["sender"]["uid"]);
1932 unset($ret["sender"]["self"]);
1933 unset($ret["recipient"]["uid"]);
1934 unset($ret["recipient"]["self"]);
1936 //don't send title to regular StatusNET requests to avoid confusing these apps
1937 if (x($_GET, 'getText')) {
1938 $ret['title'] = $item['title'] ;
1939 if ($_GET["getText"] == "html") {
1940 $ret['text'] = bbcode($item['body'], false, false);
1942 elseif ($_GET["getText"] == "plain") {
1943 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1944 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1948 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1950 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1951 unset($ret['sender']);
1952 unset($ret['recipient']);
1958 function api_convert_item($item) {
1960 $body = $item['body'];
1961 $attachments = api_get_attachments($body);
1963 // Workaround for ostatus messages where the title is identically to the body
1964 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1965 $statusbody = trim(html2plain($html, 0));
1967 // handle data: images
1968 $statusbody = api_format_items_embeded_images($item,$statusbody);
1970 $statustitle = trim($item['title']);
1972 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1973 $statustext = trim($statusbody);
1975 $statustext = trim($statustitle."\n\n".$statusbody);
1977 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1978 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1980 $statushtml = trim(bbcode($body, false, false));
1982 if ($item['title'] != "")
1983 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1985 $entities = api_get_entitities($statustext, $body);
1987 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1990 function api_get_attachments(&$body) {
1993 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1995 $URLSearchString = "^\[\]";
1996 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2001 $attachments = array();
2003 foreach ($images[1] AS $image) {
2004 $imagedata = get_photo_info($image);
2007 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2010 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2011 foreach ($images[0] AS $orig)
2012 $body = str_replace($orig, "", $body);
2014 return $attachments;
2017 function api_get_entitities(&$text, $bbcode) {
2019 /// Links at the first character of the post
2023 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2025 if ($include_entities != "true") {
2027 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2029 foreach ($images[1] AS $image) {
2030 $replace = proxy_url($image);
2031 $text = str_replace($image, $replace, $text);
2036 $bbcode = bb_CleanPictureLinks($bbcode);
2038 // Change pure links in text to bbcode uris
2039 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2041 $entities = array();
2042 $entities["hashtags"] = array();
2043 $entities["symbols"] = array();
2044 $entities["urls"] = array();
2045 $entities["user_mentions"] = array();
2047 $URLSearchString = "^\[\]";
2049 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2051 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2052 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2053 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2055 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2056 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2057 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2059 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2060 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2061 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2063 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2065 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2066 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2068 $ordered_urls = array();
2069 foreach ($urls[1] AS $id=>$url) {
2070 //$start = strpos($text, $url, $offset);
2071 $start = iconv_strpos($text, $url, 0, "UTF-8");
2072 if (!($start === false))
2073 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2076 ksort($ordered_urls);
2079 //foreach ($urls[1] AS $id=>$url) {
2080 foreach ($ordered_urls AS $url) {
2081 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2082 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2083 $display_url = $url["title"];
2085 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2086 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2088 if (strlen($display_url) > 26)
2089 $display_url = substr($display_url, 0, 25)."…";
2092 //$start = strpos($text, $url, $offset);
2093 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2094 if (!($start === false)) {
2095 $entities["urls"][] = array("url" => $url["url"],
2096 "expanded_url" => $url["url"],
2097 "display_url" => $display_url,
2098 "indices" => array($start, $start+strlen($url["url"])));
2099 $offset = $start + 1;
2103 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2104 $ordered_images = array();
2105 foreach ($images[1] AS $image) {
2106 //$start = strpos($text, $url, $offset);
2107 $start = iconv_strpos($text, $image, 0, "UTF-8");
2108 if (!($start === false))
2109 $ordered_images[$start] = $image;
2111 //$entities["media"] = array();
2114 foreach ($ordered_images AS $url) {
2115 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2116 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2118 if (strlen($display_url) > 26)
2119 $display_url = substr($display_url, 0, 25)."…";
2121 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2122 if (!($start === false)) {
2123 $image = get_photo_info($url);
2125 // If image cache is activated, then use the following sizes:
2126 // thumb (150), small (340), medium (600) and large (1024)
2127 if (!get_config("system", "proxy_disabled")) {
2128 $media_url = proxy_url($url);
2131 $scale = scale_image($image[0], $image[1], 150);
2132 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2134 if (($image[0] > 150) OR ($image[1] > 150)) {
2135 $scale = scale_image($image[0], $image[1], 340);
2136 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2139 $scale = scale_image($image[0], $image[1], 600);
2140 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2142 if (($image[0] > 600) OR ($image[1] > 600)) {
2143 $scale = scale_image($image[0], $image[1], 1024);
2144 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2148 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2151 $entities["media"][] = array(
2153 "id_str" => (string)$start+1,
2154 "indices" => array($start, $start+strlen($url)),
2155 "media_url" => normalise_link($media_url),
2156 "media_url_https" => $media_url,
2158 "display_url" => $display_url,
2159 "expanded_url" => $url,
2163 $offset = $start + 1;
2169 function api_format_items_embeded_images($item, $text){
2171 $text = preg_replace_callback(
2172 "|data:image/([^;]+)[^=]+=*|m",
2173 function($match) use ($a, $item) {
2174 return $a->get_baseurl()."/display/".$item['guid'];
2180 function api_format_items($r,$user_info, $filter_user = false) {
2185 foreach($r as $item) {
2186 api_share_as_retweet($item);
2188 localize_item($item);
2189 $status_user = api_item_get_user($a,$item);
2191 // Look if the posts are matching if they should be filtered by user id
2192 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2195 if ($item['thr-parent'] != $item['uri']) {
2196 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2198 dbesc($item['thr-parent']));
2200 $in_reply_to_status_id = intval($r[0]['id']);
2202 $in_reply_to_status_id = intval($item['parent']);
2204 $in_reply_to_status_id_str = (string) intval($item['parent']);
2206 $in_reply_to_screen_name = NULL;
2207 $in_reply_to_user_id = NULL;
2208 $in_reply_to_user_id_str = NULL;
2210 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2212 intval($in_reply_to_status_id));
2214 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2217 if ($r[0]['nick'] == "")
2218 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2220 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2221 $in_reply_to_user_id = intval($r[0]['id']);
2222 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2226 $in_reply_to_screen_name = NULL;
2227 $in_reply_to_user_id = NULL;
2228 $in_reply_to_status_id = NULL;
2229 $in_reply_to_user_id_str = NULL;
2230 $in_reply_to_status_id_str = NULL;
2233 $converted = api_convert_item($item);
2236 'text' => $converted["text"],
2237 'truncated' => False,
2238 'created_at'=> api_date($item['created']),
2239 'in_reply_to_status_id' => $in_reply_to_status_id,
2240 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2241 'source' => (($item['app']) ? $item['app'] : 'web'),
2242 'id' => intval($item['id']),
2243 'id_str' => (string) intval($item['id']),
2244 'in_reply_to_user_id' => $in_reply_to_user_id,
2245 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2246 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2248 'favorited' => $item['starred'] ? true : false,
2249 'user' => $status_user ,
2250 //'entities' => NULL,
2251 'statusnet_html' => $converted["html"],
2252 'statusnet_conversation_id' => $item['parent'],
2255 if (count($converted["attachments"]) > 0)
2256 $status["attachments"] = $converted["attachments"];
2258 if (count($converted["entities"]) > 0)
2259 $status["entities"] = $converted["entities"];
2261 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2262 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2263 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2264 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2267 // Retweets are only valid for top postings
2268 // It doesn't work reliable with the link if its a feed
2269 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2271 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2273 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2274 $retweeted_status = $status;
2275 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2277 $status["retweeted_status"] = $retweeted_status;
2280 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2281 unset($status["user"]["uid"]);
2282 unset($status["user"]["self"]);
2284 if ($item["coord"] != "") {
2285 $coords = explode(' ',$item["coord"]);
2286 if (count($coords) == 2) {
2287 $status["geo"] = array('type' => 'Point',
2288 'coordinates' => array((float) $coords[0],
2289 (float) $coords[1]));
2299 function api_account_rate_limit_status(&$a,$type) {
2302 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2303 'remaining_hits' => (string) 150,
2304 'hourly_limit' => (string) 150,
2305 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2308 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2310 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2313 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2315 function api_help_test(&$a,$type) {
2322 return api_apply_template('test', $type, array("$ok" => $ok));
2325 api_register_func('api/help/test','api_help_test',false);
2327 function api_lists(&$a,$type) {
2332 api_register_func('api/lists','api_lists',true);
2334 function api_lists_list(&$a,$type) {
2339 api_register_func('api/lists/list','api_lists_list',true);
2342 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2343 * This function is deprecated by Twitter
2344 * returns: json, xml
2346 function api_statuses_f(&$a, $type, $qtype) {
2347 if (api_user()===false) return false;
2348 $user_info = api_get_user($a);
2350 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2351 /* this is to stop Hotot to load friends multiple times
2352 * I'm not sure if I'm missing return something or
2353 * is a bug in hotot. Workaround, meantime
2357 return array('$users' => $ret);*/
2361 if($qtype == 'friends')
2362 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2363 if($qtype == 'followers')
2364 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2366 // friends and followers only for self
2367 if ($user_info['self'] == 0)
2368 $sql_extra = " AND false ";
2370 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2375 foreach($r as $cid){
2376 $user = api_get_user($a, $cid['nurl']);
2377 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2378 unset($user["uid"]);
2379 unset($user["self"]);
2385 return array('$users' => $ret);
2388 function api_statuses_friends(&$a, $type){
2389 $data = api_statuses_f($a,$type,"friends");
2390 if ($data===false) return false;
2391 return api_apply_template("friends", $type, $data);
2393 function api_statuses_followers(&$a, $type){
2394 $data = api_statuses_f($a,$type,"followers");
2395 if ($data===false) return false;
2396 return api_apply_template("friends", $type, $data);
2398 api_register_func('api/statuses/friends','api_statuses_friends',true);
2399 api_register_func('api/statuses/followers','api_statuses_followers',true);
2406 function api_statusnet_config(&$a,$type) {
2407 $name = $a->config['sitename'];
2408 $server = $a->get_hostname();
2409 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2410 $email = $a->config['admin_email'];
2411 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2412 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2413 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2414 if($a->config['api_import_size'])
2415 $texlimit = string($a->config['api_import_size']);
2416 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2417 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2420 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2421 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2422 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2423 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2424 'shorturllength' => '30',
2425 'friendica' => array(
2426 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2427 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2428 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2429 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2434 return api_apply_template('config', $type, array('$config' => $config));
2437 api_register_func('api/statusnet/config','api_statusnet_config',false);
2439 function api_statusnet_version(&$a,$type) {
2443 if($type === 'xml') {
2444 header("Content-type: application/xml");
2445 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2448 elseif($type === 'json') {
2449 header("Content-type: application/json");
2454 api_register_func('api/statusnet/version','api_statusnet_version',false);
2457 function api_ff_ids(&$a,$type,$qtype) {
2461 $user_info = api_get_user($a);
2463 if($qtype == 'friends')
2464 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2465 if($qtype == 'followers')
2466 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2468 if (!$user_info["self"])
2469 $sql_extra = " AND false ";
2471 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2473 $r = q("SELECT `unique_contact`.`id` FROM contact, `unique_contacts` WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2479 if($type === 'xml') {
2480 header("Content-type: application/xml");
2481 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2483 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2484 echo '</ids>' . "\r\n";
2487 elseif($type === 'json') {
2489 header("Content-type: application/json");
2494 $ret[] = intval($rr['id']);
2496 echo json_encode($ret);
2502 function api_friends_ids(&$a,$type) {
2503 api_ff_ids($a,$type,'friends');
2505 function api_followers_ids(&$a,$type) {
2506 api_ff_ids($a,$type,'followers');
2508 api_register_func('api/friends/ids','api_friends_ids',true);
2509 api_register_func('api/followers/ids','api_followers_ids',true);
2512 function api_direct_messages_new(&$a, $type) {
2513 if (api_user()===false) return false;
2515 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2517 $sender = api_get_user($a);
2519 if ($_POST['screen_name']) {
2520 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2522 dbesc($_POST['screen_name']));
2524 // Selecting the id by priority, friendica first
2525 api_best_nickname($r);
2527 $recipient = api_get_user($a, $r[0]['nurl']);
2529 $recipient = api_get_user($a, $_POST['user_id']);
2533 if (x($_REQUEST,'replyto')) {
2534 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2536 intval($_REQUEST['replyto']));
2537 $replyto = $r[0]['parent-uri'];
2538 $sub = $r[0]['title'];
2541 if (x($_REQUEST,'title')) {
2542 $sub = $_REQUEST['title'];
2545 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2549 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2552 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2553 $ret = api_format_messages($r[0], $recipient, $sender);
2556 $ret = array("error"=>$id);
2559 $data = Array('$messages'=>$ret);
2564 $data = api_rss_extra($a, $data, $user_info);
2567 return api_apply_template("direct_messages", $type, $data);
2570 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2572 function api_direct_messages_box(&$a, $type, $box) {
2573 if (api_user()===false) return false;
2577 $count = (x($_GET,'count')?$_GET['count']:20);
2578 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2579 if ($page<0) $page=0;
2581 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2582 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2584 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2585 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2588 unset($_REQUEST["user_id"]);
2589 unset($_GET["user_id"]);
2591 unset($_REQUEST["screen_name"]);
2592 unset($_GET["screen_name"]);
2594 $user_info = api_get_user($a);
2595 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2596 $profile_url = $user_info["url"];
2600 $start = $page*$count;
2603 if ($box=="sentbox") {
2604 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2606 elseif ($box=="conversation") {
2607 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2609 elseif ($box=="all") {
2610 $sql_extra = "true";
2612 elseif ($box=="inbox") {
2613 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2617 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2619 if ($user_id !="") {
2620 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2622 elseif($screen_name !=""){
2623 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2626 $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",
2629 intval($start), intval($count)
2634 foreach($r as $item) {
2635 if ($box == "inbox" || $item['from-url'] != $profile_url){
2636 $recipient = $user_info;
2637 $sender = api_get_user($a,normalise_link($item['contact-url']));
2639 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2640 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2641 $sender = $user_info;
2644 $ret[]=api_format_messages($item, $recipient, $sender);
2648 $data = array('$messages' => $ret);
2652 $data = api_rss_extra($a, $data, $user_info);
2655 return api_apply_template("direct_messages", $type, $data);
2659 function api_direct_messages_sentbox(&$a, $type){
2660 return api_direct_messages_box($a, $type, "sentbox");
2662 function api_direct_messages_inbox(&$a, $type){
2663 return api_direct_messages_box($a, $type, "inbox");
2665 function api_direct_messages_all(&$a, $type){
2666 return api_direct_messages_box($a, $type, "all");
2668 function api_direct_messages_conversation(&$a, $type){
2669 return api_direct_messages_box($a, $type, "conversation");
2671 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2672 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2673 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2674 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2678 function api_oauth_request_token(&$a, $type){
2680 $oauth = new FKOAuth1();
2681 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2682 }catch(Exception $e){
2683 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2688 function api_oauth_access_token(&$a, $type){
2690 $oauth = new FKOAuth1();
2691 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2692 }catch(Exception $e){
2693 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2699 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2700 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2703 function api_fr_photos_list(&$a,$type) {
2704 if (api_user()===false) return false;
2705 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2706 intval(local_user())
2711 $ret[] = $rr['resource-id'];
2712 header("Content-type: application/json");
2713 echo json_encode($ret);
2718 function api_fr_photo_detail(&$a,$type) {
2719 if (api_user()===false) return false;
2720 if(! $_REQUEST['photo_id']) return false;
2721 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2722 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2723 intval(local_user()),
2724 dbesc($_REQUEST['photo_id']),
2728 header("Content-type: application/json");
2729 $r[0]['data'] = base64_encode($r[0]['data']);
2730 echo json_encode($r[0]);
2736 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2737 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2742 * similar as /mod/redir.php
2743 * redirect to 'url' after dfrn auth
2745 * why this when there is mod/redir.php already?
2746 * This use api_user() and api_login()
2749 * c_url: url of remote contact to auth to
2750 * url: string, url to redirect after auth
2752 function api_friendica_remoteauth(&$a) {
2753 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2754 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2756 if ($url === '' || $c_url === '')
2757 die((api_error($a, 'json', "Wrong parameters")));
2759 $c_url = normalise_link($c_url);
2763 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2768 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2769 die((api_error($a, 'json', "Unknown contact")));
2773 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2775 if($r[0]['duplex'] && $r[0]['issued-id']) {
2776 $orig_id = $r[0]['issued-id'];
2777 $dfrn_id = '1:' . $orig_id;
2779 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2780 $orig_id = $r[0]['dfrn-id'];
2781 $dfrn_id = '0:' . $orig_id;
2784 $sec = random_string();
2786 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2787 VALUES( %d, %s, '%s', '%s', %d )",
2795 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2796 $dest = (($url) ? '&destination_url=' . $url : '');
2797 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2798 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2799 . '&type=profile&sec=' . $sec . $dest . $quiet );
2801 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2805 function api_share_as_retweet(&$item) {
2806 $body = trim($item["body"]);
2808 // Skip if it isn't a pure repeated messages
2809 // Does it start with a share?
2810 if (strpos($body, "[share") > 0)
2813 // Does it end with a share?
2814 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2817 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2818 // Skip if there is no shared message in there
2819 if ($body == $attributes)
2823 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2824 if ($matches[1] != "")
2825 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2827 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2828 if ($matches[1] != "")
2829 $author = $matches[1];
2832 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2833 if ($matches[1] != "")
2834 $profile = $matches[1];
2836 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2837 if ($matches[1] != "")
2838 $profile = $matches[1];
2841 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2842 if ($matches[1] != "")
2843 $avatar = $matches[1];
2845 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2846 if ($matches[1] != "")
2847 $avatar = $matches[1];
2850 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2851 if ($matches[1] != "")
2852 $link = $matches[1];
2854 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2855 if ($matches[1] != "")
2856 $link = $matches[1];
2858 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2860 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2863 $item["body"] = $shared_body;
2864 $item["author-name"] = $author;
2865 $item["author-link"] = $profile;
2866 $item["author-avatar"] = $avatar;
2867 $item["plink"] = $link;
2873 function api_get_nick($profile) {
2874 /// @TODO Remove trailing junk from profile url
2875 /// @TODO pump.io check has to check the website
2879 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
2880 dbesc(normalise_link($profile)));
2882 $nick = $r[0]["nick"];
2885 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
2886 dbesc(normalise_link($profile)));
2888 $nick = $r[0]["nick"];
2892 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2893 if ($friendica != $profile)
2898 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2899 if ($diaspora != $profile)
2904 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2905 if ($twitter != $profile)
2911 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2912 if ($StatusnetHost != $profile) {
2913 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2914 if ($StatusnetUser != $profile) {
2915 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2916 $user = json_decode($UserData);
2918 $nick = $user->screen_name;
2923 /// @TODO Look at the page if its really a pumpio site
2924 //if (!$nick == "") {
2925 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2926 // if ($pumpio != $profile)
2928 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2933 q("UPDATE `unique_contacts` SET `nick` = '%s' WHERE `nick` != '%s' AND url = '%s'",
2934 dbesc($nick), dbesc($nick), dbesc(normalise_link($profile)));
2941 function api_clean_plain_items($Text) {
2942 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2944 $Text = bb_CleanPictureLinks($Text);
2946 $URLSearchString = "^\[\]";
2948 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2950 if ($include_entities == "true") {
2951 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2954 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2958 function api_cleanup_share($shared) {
2959 if ($shared[2] != "type-link")
2962 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2968 if (isset($bookmark[2][0]))
2969 $title = $bookmark[2][0];
2971 if (isset($bookmark[1][0]))
2972 $link = $bookmark[1][0];
2974 if (strpos($shared[1],$title) !== false)
2977 if (strpos($shared[1],$link) !== false)
2980 $text = trim($shared[1]);
2982 //if (strlen($text) < strlen($title))
2983 if (($text == "") AND ($title != ""))
2984 $text .= "\n\n".trim($title);
2987 $text .= "\n".trim($link);
2989 return(trim($text));
2992 function api_best_nickname(&$contacts) {
2993 $best_contact = array();
2995 if (count($contact) == 0)
2998 foreach ($contacts AS $contact)
2999 if ($contact["network"] == "") {
3000 $contact["network"] = "dfrn";
3001 $best_contact = array($contact);
3004 if (sizeof($best_contact) == 0)
3005 foreach ($contacts AS $contact)
3006 if ($contact["network"] == "dfrn")
3007 $best_contact = array($contact);
3009 if (sizeof($best_contact) == 0)
3010 foreach ($contacts AS $contact)
3011 if ($contact["network"] == "dspr")
3012 $best_contact = array($contact);
3014 if (sizeof($best_contact) == 0)
3015 foreach ($contacts AS $contact)
3016 if ($contact["network"] == "stat")
3017 $best_contact = array($contact);
3019 if (sizeof($best_contact) == 0)
3020 foreach ($contacts AS $contact)
3021 if ($contact["network"] == "pump")
3022 $best_contact = array($contact);
3024 if (sizeof($best_contact) == 0)
3025 foreach ($contacts AS $contact)
3026 if ($contact["network"] == "twit")
3027 $best_contact = array($contact);
3029 if (sizeof($best_contact) == 1)
3030 $contacts = $best_contact;
3032 $contacts = array($contacts[0]);
3035 // return all or a specified group of the user with the containing contacts
3036 function api_friendica_group_show(&$a, $type) {
3037 if (api_user()===false) return false;
3040 $user_info = api_get_user($a);
3041 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3042 $uid = $user_info['uid'];
3044 // get data of the specified group id or all groups if not specified
3046 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3049 // error message if specified gid is not in database
3051 die(api_error($a, $type, 'gid not available'));
3054 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3057 // loop through all groups and retrieve all members for adding data in the user array
3058 foreach ($r as $rr) {
3059 $members = group_get_members($rr['id']);
3061 foreach ($members as $member) {
3062 $user = api_get_user($a, $member['nurl']);
3065 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3067 return api_apply_template("group_show", $type, array('$groups' => $grps));
3069 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3072 // delete the specified group of the user
3073 function api_friendica_group_delete(&$a, $type) {
3074 if (api_user()===false) return false;
3077 $user_info = api_get_user($a);
3078 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3079 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3080 $uid = $user_info['uid'];
3082 // error if no gid specified
3083 if ($gid == 0 || $name == "")
3084 die(api_error($a, $type, 'gid or name not specified'));
3086 // get data of the specified group id
3087 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3090 // error message if specified gid is not in database
3092 die(api_error($a, $type, 'gid not available'));
3094 // get data of the specified group id and group name
3095 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3099 // error message if specified gid is not in database
3100 if (count($rname) == 0)
3101 die(api_error($a, $type, 'wrong group name'));
3104 $ret = group_rmv($uid, $name);
3107 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3108 return api_apply_template("group_delete", $type, array('$result' => $success));
3111 die(api_error($a, $type, 'other API error'));
3113 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true);
3116 // create the specified group with the posted array of contacts
3117 function api_friendica_group_create(&$a, $type) {
3118 if (api_user()===false) return false;
3121 $user_info = api_get_user($a);
3122 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3123 $uid = $user_info['uid'];
3124 $json = json_decode($_POST['json'], true);
3125 $users = $json['user'];
3127 // error if no name specified
3129 die(api_error($a, $type, 'group name not specified'));
3131 // get data of the specified group name
3132 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3135 // error message if specified group name already exists
3136 if (count($rname) != 0)
3137 die(api_error($a, $type, 'group name already exists'));
3139 // check if specified group name is a deleted group
3140 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3143 // error message if specified group name already exists
3144 if (count($rname) != 0)
3145 $reactivate_group = true;
3148 $ret = group_add($uid, $name);
3150 $gid = group_byname($uid, $name);
3152 die(api_error($a, $type, 'other API error'));
3155 $erroraddinguser = false;
3156 $errorusers = array();
3157 foreach ($users as $user) {
3158 $cid = $user['cid'];
3159 // check if user really exists as contact
3160 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3163 if (count($contact))
3164 $result = group_add_member($uid, $name, $cid, $gid);
3166 $erroraddinguser = true;
3167 $errorusers[] = $cid;
3171 // return success message incl. missing users in array
3172 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3173 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3174 return api_apply_template("group_create", $type, array('result' => $success));
3176 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
3179 // update the specified group with the posted array of contacts
3180 function api_friendica_group_update(&$a, $type) {
3181 if (api_user()===false) return false;
3184 $user_info = api_get_user($a);
3185 $uid = $user_info['uid'];
3186 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3187 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3188 $json = json_decode($_POST['json'], true);
3189 $users = $json['user'];
3191 // error if no name specified
3193 die(api_error($a, $type, 'group name not specified'));
3195 // error if no gid specified
3197 die(api_error($a, $type, 'gid not specified'));
3200 $members = group_get_members($gid);
3201 foreach ($members as $member) {
3202 $cid = $member['id'];
3203 foreach ($users as $user) {
3204 $found = ($user['cid'] == $cid ? true : false);
3207 $ret = group_rmv_member($uid, $name, $cid);
3212 $erroraddinguser = false;
3213 $errorusers = array();
3214 foreach ($users as $user) {
3215 $cid = $user['cid'];
3216 // check if user really exists as contact
3217 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3220 if (count($contact))
3221 $result = group_add_member($uid, $name, $cid, $gid);
3223 $erroraddinguser = true;
3224 $errorusers[] = $cid;
3228 // return success message incl. missing users in array
3229 $status = ($erroraddinguser ? "missing user" : "ok");
3230 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3231 return api_apply_template("group_update", $type, array('result' => $success));
3233 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true);
3237 [pagename] => api/1.1/statuses/lookup.json
3238 [id] => 605138389168451584
3239 [include_cards] => true
3240 [cards_platform] => Android-12
3241 [include_entities] => true
3242 [include_my_retweet] => 1
3244 [include_reply_count] => true
3245 [include_descendent_reply_count] => true
3249 Not implemented by now:
3250 statuses/retweets_of_me
3255 account/update_location
3256 account/update_profile_background_image
3257 account/update_profile_image
3261 Not implemented in status.net:
3262 statuses/retweeted_to_me
3263 statuses/retweeted_by_me
3264 direct_messages/destroy
3266 account/update_delivery_device
3267 notifications/follow