3 - Automatically detect if incoming data is HTML or BBCode
7 Gerhard Seeber Mail: gerhard@seeber.at Friendica: http://mozartweg.dyndns.org/friendica/gerhard
14 Gerhard Seeber 2015-NOV-25 Add API call /friendica/group_show to return all or a single group
15 with the containing contacts (necessary for Windows 10 Universal app)
16 Gerhard Seeber 2015-NOV-27 Add API call /friendica/group_delete to delete the specified group id
17 (necessary for Windows 10 Universal app)
18 Gerhard Seeber 2015-DEC-01 Add API call /friendica/group_create to create a group with the specified
19 name and the given list of contacts (necessary for Windows 10 Universal
21 Gerhard Seeber 2015-DEC-07 Add API call /friendica/group_update to update a group with the given
22 list of contacts (necessary for Windows 10 Universal app)
26 require_once("include/bbcode.php");
27 require_once("include/datetime.php");
28 require_once("include/conversation.php");
29 require_once("include/oauth.php");
30 require_once("include/html2plain.php");
31 require_once("mod/share.php");
32 require_once("include/Photo.php");
33 require_once("mod/item.php");
34 require_once('include/security.php');
35 require_once('include/contact_selectors.php');
36 require_once('include/html2bbcode.php');
37 require_once('mod/wall_upload.php');
38 require_once("mod/proxy.php");
39 require_once("include/message.php");
40 require_once("include/group.php");
52 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
53 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
54 // into a page, and visitors will post something without noticing it).
55 // Instead, use this function.
56 if ($_SESSION["allow_api"])
62 function api_source() {
63 if (requestdata('source'))
64 return (requestdata('source'));
66 // Support for known clients that doesn't send a source name
67 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
70 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
75 function api_date($str){
76 //Wed May 23 06:01:13 +0000 2007
77 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
81 function api_register_func($path, $func, $auth=false){
83 $API[$path] = array('func'=>$func, 'auth'=>$auth);
85 // Workaround for hotot
86 $path = str_replace("api/", "api/1.1/", $path);
87 $API[$path] = array('func'=>$func, 'auth'=>$auth);
94 function api_login(&$a){
97 $oauth = new FKOAuth1();
98 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
99 if (!is_null($token)){
100 $oauth->loginUser($token->uid);
101 call_hooks('logged_in', $a->user);
104 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
105 }catch(Exception $e){
106 logger(__file__.__line__.__function__."\n".$e);
107 //die(__file__.__line__.__function__."<pre>".$e); die();
112 // workaround for HTTP-auth in CGI mode
113 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
114 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
115 if(strlen($userpass)) {
116 list($name, $password) = explode(':', $userpass);
117 $_SERVER['PHP_AUTH_USER'] = $name;
118 $_SERVER['PHP_AUTH_PW'] = $password;
122 if (!isset($_SERVER['PHP_AUTH_USER'])) {
123 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
124 header('WWW-Authenticate: Basic realm="Friendica"');
125 header('HTTP/1.0 401 Unauthorized');
126 die((api_error($a, 'json', "This api requires login")));
128 //die('This api requires login');
131 $user = $_SERVER['PHP_AUTH_USER'];
132 $password = $_SERVER['PHP_AUTH_PW'];
133 $encrypted = hash('whirlpool',trim($password));
135 // allow "user@server" login (but ignore 'server' part)
136 $at=strstr($user, "@", true);
137 if ( $at ) $user=$at;
140 * next code from mod/auth.php. needs better solution
145 'username' => trim($user),
146 'password' => trim($password),
147 'authenticated' => 0,
148 'user_record' => null
153 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
154 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
155 * and later plugins should not interfere with an earlier one that succeeded.
159 call_hooks('authenticate', $addon_auth);
161 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
162 $record = $addon_auth['user_record'];
165 // process normal login request
167 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
168 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
177 if((! $record) || (! count($record))) {
178 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
179 header('WWW-Authenticate: Basic realm="Friendica"');
180 header('HTTP/1.0 401 Unauthorized');
181 die('This api requires login');
184 authenticate_success($record); $_SESSION["allow_api"] = true;
186 call_hooks('logged_in', $a->user);
190 /**************************
191 * MAIN API ENTRY POINT *
192 **************************/
193 function api_call(&$a){
194 GLOBAL $API, $called_api;
198 foreach ($API as $p=>$info){
199 if (strpos($a->query_string, $p)===0){
200 $called_api= explode("/",$p);
201 //unset($_SERVER['PHP_AUTH_USER']);
202 if ($info['auth']===true && api_user()===false) {
206 load_contact_links(api_user());
208 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
209 logger('API parameters: ' . print_r($_REQUEST,true));
211 if (strpos($a->query_string, ".xml")>0) $type="xml";
212 if (strpos($a->query_string, ".json")>0) $type="json";
213 if (strpos($a->query_string, ".rss")>0) $type="rss";
214 if (strpos($a->query_string, ".atom")>0) $type="atom";
215 if (strpos($a->query_string, ".as")>0) $type="as";
217 $stamp = microtime(true);
218 $r = call_user_func($info['func'], $a, $type);
219 $duration = (float)(microtime(true)-$stamp);
220 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
222 if ($r===false) return;
226 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
227 header ("Content-Type: text/xml");
228 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
231 header ("Content-Type: application/json");
233 $json = json_encode($rr);
234 if ($_GET['callback'])
235 $json = $_GET['callback']."(".$json.")";
239 header ("Content-Type: application/rss+xml");
240 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
243 header ("Content-Type: application/atom+xml");
244 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
247 //header ("Content-Type: application/json");
249 // return json_encode($rr);
250 return json_encode($r);
254 //echo "<pre>"; var_dump($r); die();
257 header("HTTP/1.1 404 Not Found");
258 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
259 return(api_error($a, $type, "not implemented"));
263 function api_error(&$a, $type, $error) {
264 # TODO: https://dev.twitter.com/overview/api/response-codes
265 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
268 header ("Content-Type: text/xml");
269 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
272 header ("Content-Type: application/json");
273 return json_encode(array('error' => $error, 'request' => $a->query_string));
276 header ("Content-Type: application/rss+xml");
277 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
280 header ("Content-Type: application/atom+xml");
281 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
289 function api_rss_extra(&$a, $arr, $user_info){
290 if (is_null($user_info)) $user_info = api_get_user($a);
291 $arr['$user'] = $user_info;
292 $arr['$rss'] = array(
293 'alternate' => $user_info['url'],
294 'self' => $a->get_baseurl(). "/". $a->query_string,
295 'base' => $a->get_baseurl(),
296 'updated' => api_date(null),
297 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
298 'language' => $user_info['language'],
299 'logo' => $a->get_baseurl()."/images/friendica-32.png",
307 * Unique contact to contact url.
309 function api_unique_id_to_url($id){
310 $r = q("SELECT `url` FROM `unique_contacts` WHERE `id`=%d LIMIT 1",
313 return ($r[0]["url"]);
319 * Returns user info array.
321 function api_get_user(&$a, $contact_id = Null, $type = "json"){
328 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
330 // Searching for contact URL
331 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
332 $user = dbesc(normalise_link($contact_id));
334 $extra_query = "AND `contact`.`nurl` = '%s' ";
335 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
338 // Searching for unique contact id
339 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
340 $user = dbesc(api_unique_id_to_url($contact_id));
343 die(api_error($a, $type, t("User not found.")));
346 $extra_query = "AND `contact`.`nurl` = '%s' ";
347 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
350 if(is_null($user) && x($_GET, 'user_id')) {
351 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
354 die(api_error($a, $type, t("User not found.")));
357 $extra_query = "AND `contact`.`nurl` = '%s' ";
358 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
360 if(is_null($user) && x($_GET, 'screen_name')) {
361 $user = dbesc($_GET['screen_name']);
363 $extra_query = "AND `contact`.`nick` = '%s' ";
364 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
367 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
368 $argid = count($called_api);
369 list($user, $null) = explode(".",$a->argv[$argid]);
370 if(is_numeric($user)){
371 $user = dbesc(api_unique_id_to_url($user));
377 $extra_query = "AND `contact`.`nurl` = '%s' ";
378 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
380 $user = dbesc($user);
382 $extra_query = "AND `contact`.`nick` = '%s' ";
383 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
387 logger("api_get_user: user ".$user, LOGGER_DEBUG);
390 if (api_user()===false) {
391 api_login($a); return False;
393 $user = $_SESSION['uid'];
394 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
399 logger('api_user: ' . $extra_query . ', user: ' . $user);
401 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
407 // Selecting the id by priority, friendica first
408 api_best_nickname($uinfo);
410 // if the contact wasn't found, fetch it from the unique contacts
411 if (count($uinfo)==0) {
415 $r = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", $url);
417 $r = q("SELECT * FROM `unique_contacts` WHERE `nick`='%s' LIMIT 1", $nick);
420 // If no nick where given, extract it from the address
421 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
422 $r[0]['nick'] = api_get_nick($r[0]["url"]);
426 'id_str' => (string) $r[0]["id"],
427 'name' => $r[0]["name"],
428 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
430 'description' => NULL,
431 'url' => $r[0]["url"],
432 'protected' => false,
433 'followers_count' => 0,
434 'friends_count' => 0,
436 'created_at' => api_date(0),
437 'favourites_count' => 0,
439 'time_zone' => 'UTC',
440 'geo_enabled' => false,
442 'statuses_count' => 0,
444 'contributors_enabled' => false,
445 'is_translator' => false,
446 'is_translation_enabled' => false,
447 'profile_image_url' => $r[0]["avatar"],
448 'profile_image_url_https' => $r[0]["avatar"],
449 'following' => false,
450 'follow_request_sent' => false,
451 'notifications' => false,
452 'statusnet_blocking' => false,
453 'notifications' => false,
454 'statusnet_profile_url' => $r[0]["url"],
463 die(api_error($a, $type, t("User not found.")));
467 if($uinfo[0]['self']) {
468 $usr = q("select * from user where uid = %d limit 1",
471 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
475 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
476 // count public wall messages
477 $r = q("SELECT count(*) as `count` FROM `item`
480 intval($uinfo[0]['uid'])
482 $countitms = $r[0]['count'];
485 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
486 $r = q("SELECT count(*) as `count` FROM `item`
487 WHERE `contact-id` = %d",
488 intval($uinfo[0]['id'])
490 $countitms = $r[0]['count'];
494 $r = q("SELECT count(*) as `count` FROM `contact`
495 WHERE `uid` = %d AND `rel` IN ( %d, %d )
496 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
497 intval($uinfo[0]['uid']),
498 intval(CONTACT_IS_SHARING),
499 intval(CONTACT_IS_FRIEND)
501 $countfriends = $r[0]['count'];
503 $r = q("SELECT count(*) as `count` FROM `contact`
504 WHERE `uid` = %d AND `rel` IN ( %d, %d )
505 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
506 intval($uinfo[0]['uid']),
507 intval(CONTACT_IS_FOLLOWER),
508 intval(CONTACT_IS_FRIEND)
510 $countfollowers = $r[0]['count'];
512 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
513 intval($uinfo[0]['uid'])
515 $starred = $r[0]['count'];
518 if(! $uinfo[0]['self']) {
524 // Add a nick if it isn't present there
525 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
526 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
529 // Fetching unique id
530 $r = q("SELECT id FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
532 // If not there, then add it
533 if (count($r) == 0) {
534 q("INSERT INTO `unique_contacts` (`url`, `name`, `nick`, `avatar`) VALUES ('%s', '%s', '%s', '%s')",
535 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
537 $r = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
540 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
543 'id' => intval($r[0]['id']),
544 'id_str' => (string) intval($r[0]['id']),
545 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
546 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
547 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
548 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
549 'profile_image_url' => $uinfo[0]['micro'],
550 'profile_image_url_https' => $uinfo[0]['micro'],
551 'url' => $uinfo[0]['url'],
552 'protected' => false,
553 'followers_count' => intval($countfollowers),
554 'friends_count' => intval($countfriends),
555 'created_at' => api_date($uinfo[0]['created']),
556 'favourites_count' => intval($starred),
558 'time_zone' => 'UTC',
559 'statuses_count' => intval($countitms),
560 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
562 'statusnet_blocking' => false,
563 'notifications' => false,
564 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
565 'statusnet_profile_url' => $uinfo[0]['url'],
566 'uid' => intval($uinfo[0]['uid']),
567 'cid' => intval($uinfo[0]['cid']),
568 'self' => $uinfo[0]['self'],
569 'network' => $uinfo[0]['network'],
576 function api_item_get_user(&$a, $item) {
578 $author = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
579 dbesc(normalise_link($item['author-link'])));
581 if (count($author) == 0) {
582 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
583 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
585 $author = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
586 dbesc(normalise_link($item['author-link'])));
587 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
588 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
589 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
590 dbesc(normalise_link($item["author-link"])));
593 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
594 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
595 dbesc(normalise_link($item["author-link"])));
598 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
599 dbesc(normalise_link($item['owner-link'])));
601 if (count($owner) == 0) {
602 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
603 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
605 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
606 dbesc(normalise_link($item['owner-link'])));
607 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
608 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
609 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
610 dbesc(normalise_link($item["owner-link"])));
613 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
614 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
615 dbesc(normalise_link($item["owner-link"])));
618 // Comments in threads may appear as wall-to-wall postings.
619 // So only take the owner at the top posting.
620 if ($item["id"] == $item["parent"])
621 $status_user = api_get_user($a,$item["owner-link"]);
623 $status_user = api_get_user($a,$item["author-link"]);
625 $status_user["protected"] = (($item["allow_cid"] != "") OR
626 ($item["allow_gid"] != "") OR
627 ($item["deny_cid"] != "") OR
628 ($item["deny_gid"] != "") OR
631 return ($status_user);
636 * load api $templatename for $type and replace $data array
638 function api_apply_template($templatename, $type, $data){
646 $data = array_xmlify($data);
647 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
649 header ("Content-Type: text/xml");
650 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
653 $ret = replace_macros($tpl, $data);
668 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
669 * returns a 401 status code and an error message if not.
670 * http://developer.twitter.com/doc/get/account/verify_credentials
672 function api_account_verify_credentials(&$a, $type){
673 if (api_user()===false) return false;
675 unset($_REQUEST["user_id"]);
676 unset($_GET["user_id"]);
678 unset($_REQUEST["screen_name"]);
679 unset($_GET["screen_name"]);
681 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
683 $user_info = api_get_user($a);
685 // "verified" isn't used here in the standard
686 unset($user_info["verified"]);
688 // - Adding last status
690 $user_info["status"] = api_status_show($a,"raw");
691 if (!count($user_info["status"]))
692 unset($user_info["status"]);
694 unset($user_info["status"]["user"]);
697 // "uid" and "self" are only needed for some internal stuff, so remove it from here
698 unset($user_info["uid"]);
699 unset($user_info["self"]);
701 return api_apply_template("user", $type, array('$user' => $user_info));
704 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
708 * get data from $_POST or $_GET
710 function requestdata($k){
711 if (isset($_POST[$k])){
714 if (isset($_GET[$k])){
720 /*Waitman Gobble Mod*/
721 function api_statuses_mediap(&$a, $type) {
722 if (api_user()===false) {
723 logger('api_statuses_update: no user');
726 $user_info = api_get_user($a);
728 $_REQUEST['type'] = 'wall';
729 $_REQUEST['profile_uid'] = api_user();
730 $_REQUEST['api_source'] = true;
731 $txt = requestdata('status');
732 //$txt = urldecode(requestdata('status'));
734 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
736 require_once('library/HTMLPurifier.auto.php');
738 $txt = html2bb_video($txt);
739 $config = HTMLPurifier_Config::createDefault();
740 $config->set('Cache.DefinitionImpl', null);
741 $purifier = new HTMLPurifier($config);
742 $txt = $purifier->purify($txt);
744 $txt = html2bbcode($txt);
746 $a->argv[1]=$user_info['screen_name']; //should be set to username?
748 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
749 $bebop = wall_upload_post($a);
751 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
752 $_REQUEST['body']=$txt."\n\n".$bebop;
755 // this should output the last post (the one we just posted).
756 return api_status_show($a,$type);
758 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
759 /*Waitman Gobble Mod*/
762 function api_statuses_update(&$a, $type) {
763 if (api_user()===false) {
764 logger('api_statuses_update: no user');
768 $user_info = api_get_user($a);
770 // convert $_POST array items to the form we use for web posts.
772 // logger('api_post: ' . print_r($_POST,true));
774 if(requestdata('htmlstatus')) {
775 $txt = requestdata('htmlstatus');
776 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
778 require_once('library/HTMLPurifier.auto.php');
780 $txt = html2bb_video($txt);
782 $config = HTMLPurifier_Config::createDefault();
783 $config->set('Cache.DefinitionImpl', null);
785 $purifier = new HTMLPurifier($config);
786 $txt = $purifier->purify($txt);
788 $_REQUEST['body'] = html2bbcode($txt);
792 $_REQUEST['body'] = requestdata('status');
794 $_REQUEST['title'] = requestdata('title');
796 $parent = requestdata('in_reply_to_status_id');
798 // Twidere sends "-1" if it is no reply ...
802 if(ctype_digit($parent))
803 $_REQUEST['parent'] = $parent;
805 $_REQUEST['parent_uri'] = $parent;
807 if(requestdata('lat') && requestdata('long'))
808 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
809 $_REQUEST['profile_uid'] = api_user();
812 $_REQUEST['type'] = 'net-comment';
814 // Check for throttling (maximum posts per day, week and month)
815 $throttle_day = get_config('system','throttle_limit_day');
816 if ($throttle_day > 0) {
817 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
819 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
820 AND `created` > '%s' AND `id` = `parent`",
821 intval(api_user()), dbesc($datefrom));
824 $posts_day = $r[0]["posts_day"];
828 if ($posts_day > $throttle_day) {
829 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
830 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
834 $throttle_week = get_config('system','throttle_limit_week');
835 if ($throttle_week > 0) {
836 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
838 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
839 AND `created` > '%s' AND `id` = `parent`",
840 intval(api_user()), dbesc($datefrom));
843 $posts_week = $r[0]["posts_week"];
847 if ($posts_week > $throttle_week) {
848 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
849 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
853 $throttle_month = get_config('system','throttle_limit_month');
854 if ($throttle_month > 0) {
855 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
857 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
858 AND `created` > '%s' AND `id` = `parent`",
859 intval(api_user()), dbesc($datefrom));
862 $posts_month = $r[0]["posts_month"];
866 if ($posts_month > $throttle_month) {
867 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
868 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
872 $_REQUEST['type'] = 'wall';
875 if(x($_FILES,'media')) {
876 // upload the image if we have one
877 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
878 $media = wall_upload_post($a);
880 $_REQUEST['body'] .= "\n\n".$media;
883 // To-Do: Multiple IDs
884 if (requestdata('media_ids')) {
885 $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",
886 intval(requestdata('media_ids')), api_user());
888 $phototypes = Photo::supportedTypes();
889 $ext = $phototypes[$r[0]['type']];
890 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
891 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
895 // set this so that the item_post() function is quiet and doesn't redirect or emit json
897 $_REQUEST['api_source'] = true;
899 if (!x($_REQUEST, "source"))
900 $_REQUEST["source"] = api_source();
902 // call out normal post function
906 // this should output the last post (the one we just posted).
907 return api_status_show($a,$type);
909 api_register_func('api/statuses/update','api_statuses_update', true);
910 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
913 function api_media_upload(&$a, $type) {
914 if (api_user()===false) {
919 $user_info = api_get_user($a);
921 if(!x($_FILES,'media')) {
926 $media = wall_upload_post($a, false);
932 $returndata = array();
933 $returndata["media_id"] = $media["id"];
934 $returndata["media_id_string"] = (string)$media["id"];
935 $returndata["size"] = $media["size"];
936 $returndata["image"] = array("w" => $media["width"],
937 "h" => $media["height"],
938 "image_type" => $media["type"]);
940 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
942 return array("media" => $returndata);
945 api_register_func('api/media/upload','api_media_upload', true);
947 function api_status_show(&$a, $type){
948 $user_info = api_get_user($a);
950 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
953 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
957 // get last public wall message
958 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
959 FROM `item`, `item` as `i`
960 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
961 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
962 AND `i`.`id` = `item`.`parent`
963 AND `item`.`type`!='activity' $privacy_sql
964 ORDER BY `item`.`created` DESC
966 intval($user_info['cid']),
968 dbesc($user_info['url']),
969 dbesc(normalise_link($user_info['url'])),
970 dbesc($user_info['url']),
971 dbesc(normalise_link($user_info['url']))
974 if (count($lastwall)>0){
975 $lastwall = $lastwall[0];
977 $in_reply_to_status_id = NULL;
978 $in_reply_to_user_id = NULL;
979 $in_reply_to_status_id_str = NULL;
980 $in_reply_to_user_id_str = NULL;
981 $in_reply_to_screen_name = NULL;
982 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
983 $in_reply_to_status_id= intval($lastwall['parent']);
984 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
986 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
988 if ($r[0]['nick'] == "")
989 $r[0]['nick'] = api_get_nick($r[0]["url"]);
991 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
992 $in_reply_to_user_id = intval($r[0]['id']);
993 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
997 // There seems to be situation, where both fields are identical:
998 // https://github.com/friendica/friendica/issues/1010
999 // This is a bugfix for that.
1000 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1001 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1002 $in_reply_to_status_id = NULL;
1003 $in_reply_to_user_id = NULL;
1004 $in_reply_to_status_id_str = NULL;
1005 $in_reply_to_user_id_str = NULL;
1006 $in_reply_to_screen_name = NULL;
1009 $converted = api_convert_item($lastwall);
1011 $status_info = array(
1012 'created_at' => api_date($lastwall['created']),
1013 'id' => intval($lastwall['id']),
1014 'id_str' => (string) $lastwall['id'],
1015 'text' => $converted["text"],
1016 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1017 'truncated' => false,
1018 'in_reply_to_status_id' => $in_reply_to_status_id,
1019 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1020 'in_reply_to_user_id' => $in_reply_to_user_id,
1021 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1022 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1023 'user' => $user_info,
1025 'coordinates' => "",
1027 'contributors' => "",
1028 'is_quote_status' => false,
1029 'retweet_count' => 0,
1030 'favorite_count' => 0,
1031 'favorited' => $lastwall['starred'] ? true : false,
1032 'retweeted' => false,
1033 'possibly_sensitive' => false,
1035 'statusnet_html' => $converted["html"],
1036 'statusnet_conversation_id' => $lastwall['parent'],
1039 if (count($converted["attachments"]) > 0)
1040 $status_info["attachments"] = $converted["attachments"];
1042 if (count($converted["entities"]) > 0)
1043 $status_info["entities"] = $converted["entities"];
1045 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1046 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1047 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1048 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1050 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1051 unset($status_info["user"]["uid"]);
1052 unset($status_info["user"]["self"]);
1055 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1058 return($status_info);
1060 return api_apply_template("status", $type, array('$status' => $status_info));
1069 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1070 * The author's most recent status will be returned inline.
1071 * http://developer.twitter.com/doc/get/users/show
1073 function api_users_show(&$a, $type){
1074 $user_info = api_get_user($a);
1076 $lastwall = q("SELECT `item`.*
1077 FROM `item`, `contact`
1078 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1079 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1080 AND `contact`.`id`=`item`.`contact-id`
1081 AND `type`!='activity'
1082 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1083 ORDER BY `created` DESC
1086 dbesc(ACTIVITY_POST),
1087 intval($user_info['cid']),
1088 dbesc($user_info['url']),
1089 dbesc(normalise_link($user_info['url'])),
1090 dbesc($user_info['url']),
1091 dbesc(normalise_link($user_info['url']))
1093 if (count($lastwall)>0){
1094 $lastwall = $lastwall[0];
1096 $in_reply_to_status_id = NULL;
1097 $in_reply_to_user_id = NULL;
1098 $in_reply_to_status_id_str = NULL;
1099 $in_reply_to_user_id_str = NULL;
1100 $in_reply_to_screen_name = NULL;
1101 if ($lastwall['parent']!=$lastwall['id']) {
1102 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1103 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1104 if (count($reply)>0) {
1105 $in_reply_to_status_id = intval($lastwall['parent']);
1106 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1108 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1110 if ($r[0]['nick'] == "")
1111 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1113 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1114 $in_reply_to_user_id = intval($r[0]['id']);
1115 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1120 $converted = api_convert_item($lastwall);
1122 $user_info['status'] = array(
1123 'text' => $converted["text"],
1124 'truncated' => false,
1125 'created_at' => api_date($lastwall['created']),
1126 'in_reply_to_status_id' => $in_reply_to_status_id,
1127 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1128 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1129 'id' => intval($lastwall['contact-id']),
1130 'id_str' => (string) $lastwall['contact-id'],
1131 'in_reply_to_user_id' => $in_reply_to_user_id,
1132 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1133 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1135 'favorited' => $lastwall['starred'] ? true : false,
1136 'statusnet_html' => $converted["html"],
1137 'statusnet_conversation_id' => $lastwall['parent'],
1140 if (count($converted["attachments"]) > 0)
1141 $user_info["status"]["attachments"] = $converted["attachments"];
1143 if (count($converted["entities"]) > 0)
1144 $user_info["status"]["entities"] = $converted["entities"];
1146 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1147 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1148 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1149 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1153 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1154 unset($user_info["uid"]);
1155 unset($user_info["self"]);
1157 return api_apply_template("user", $type, array('$user' => $user_info));
1160 api_register_func('api/users/show','api_users_show');
1163 function api_users_search(&$a, $type) {
1164 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1166 $userlist = array();
1168 if (isset($_GET["q"])) {
1169 $r = q("SELECT id FROM `unique_contacts` WHERE `name`='%s'", dbesc($_GET["q"]));
1171 $r = q("SELECT `id` FROM `unique_contacts` WHERE `nick`='%s'", dbesc($_GET["q"]));
1174 foreach ($r AS $user) {
1175 $user_info = api_get_user($a, $user["id"]);
1176 //echo print_r($user_info, true)."\n";
1177 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1178 $userlist[] = $userdata["user"];
1180 $userlist = array("users" => $userlist);
1182 die(api_error($a, $type, t("User not found.")));
1184 die(api_error($a, $type, t("User not found.")));
1189 api_register_func('api/users/search','api_users_search');
1193 * http://developer.twitter.com/doc/get/statuses/home_timeline
1195 * TODO: Optional parameters
1196 * TODO: Add reply info
1198 function api_statuses_home_timeline(&$a, $type){
1199 if (api_user()===false) return false;
1201 unset($_REQUEST["user_id"]);
1202 unset($_GET["user_id"]);
1204 unset($_REQUEST["screen_name"]);
1205 unset($_GET["screen_name"]);
1207 $user_info = api_get_user($a);
1208 // get last newtork messages
1212 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1213 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1214 if ($page<0) $page=0;
1215 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1216 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1217 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1218 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1219 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1221 $start = $page*$count;
1225 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1226 if ($exclude_replies > 0)
1227 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1228 if ($conversation_id > 0)
1229 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1231 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1232 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1233 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1234 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1235 FROM `item`, `contact`
1236 WHERE `item`.`uid` = %d AND `verb` = '%s'
1237 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1238 AND `contact`.`id` = `item`.`contact-id`
1239 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1242 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1244 dbesc(ACTIVITY_POST),
1246 intval($start), intval($count)
1249 $ret = api_format_items($r,$user_info);
1251 // Set all posts from the query above to seen
1253 foreach ($r AS $item)
1254 $idarray[] = intval($item["id"]);
1256 $idlist = implode(",", $idarray);
1259 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1262 $data = array('$statuses' => $ret);
1266 $data = api_rss_extra($a, $data, $user_info);
1269 $as = api_format_as($a, $ret, $user_info);
1270 $as['title'] = $a->config['sitename']." Home Timeline";
1271 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1276 return api_apply_template("timeline", $type, $data);
1278 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1279 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1281 function api_statuses_public_timeline(&$a, $type){
1282 if (api_user()===false) return false;
1284 $user_info = api_get_user($a);
1285 // get last newtork messages
1289 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1290 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1291 if ($page<0) $page=0;
1292 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1293 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1294 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1295 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1296 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1298 $start = $page*$count;
1301 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1302 if ($exclude_replies > 0)
1303 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1304 if ($conversation_id > 0)
1305 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1307 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1308 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1309 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1310 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1311 `user`.`nickname`, `user`.`hidewall`
1312 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1313 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1314 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1315 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1316 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1317 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1318 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1321 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1322 dbesc(ACTIVITY_POST),
1327 $ret = api_format_items($r,$user_info);
1330 $data = array('$statuses' => $ret);
1334 $data = api_rss_extra($a, $data, $user_info);
1337 $as = api_format_as($a, $ret, $user_info);
1338 $as['title'] = $a->config['sitename']." Public Timeline";
1339 $as['link']['url'] = $a->get_baseurl()."/";
1344 return api_apply_template("timeline", $type, $data);
1346 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1351 function api_statuses_show(&$a, $type){
1352 if (api_user()===false) return false;
1354 $user_info = api_get_user($a);
1357 $id = intval($a->argv[3]);
1360 $id = intval($_REQUEST["id"]);
1364 $id = intval($a->argv[4]);
1366 logger('API: api_statuses_show: '.$id);
1368 $conversation = (x($_REQUEST,'conversation')?1:0);
1372 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1374 $sql_extra .= " AND `item`.`id` = %d";
1376 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1377 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1378 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1379 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1380 FROM `item`, `contact`
1381 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1382 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1383 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1386 dbesc(ACTIVITY_POST),
1391 die(api_error($a, $type, t("There is no status with this id.")));
1393 $ret = api_format_items($r,$user_info);
1395 if ($conversation) {
1396 $data = array('$statuses' => $ret);
1397 return api_apply_template("timeline", $type, $data);
1399 $data = array('$status' => $ret[0]);
1403 $data = api_rss_extra($a, $data, $user_info);
1405 return api_apply_template("status", $type, $data);
1408 api_register_func('api/statuses/show','api_statuses_show', true);
1414 function api_conversation_show(&$a, $type){
1415 if (api_user()===false) return false;
1417 $user_info = api_get_user($a);
1420 $id = intval($a->argv[3]);
1421 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1422 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1423 if ($page<0) $page=0;
1424 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1425 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1427 $start = $page*$count;
1430 $id = intval($_REQUEST["id"]);
1434 $id = intval($a->argv[4]);
1436 logger('API: api_conversation_show: '.$id);
1438 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1440 $id = $r[0]["parent"];
1445 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1447 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1448 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1449 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1450 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1451 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1452 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1453 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1454 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1455 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1456 AND `item`.`id`>%d $sql_extra
1457 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1458 intval($id), intval(api_user()),
1459 dbesc(ACTIVITY_POST),
1461 intval($start), intval($count)
1465 die(api_error($a, $type, t("There is no conversation with this id.")));
1467 $ret = api_format_items($r,$user_info);
1469 $data = array('$statuses' => $ret);
1470 return api_apply_template("timeline", $type, $data);
1472 api_register_func('api/conversation/show','api_conversation_show', true);
1478 function api_statuses_repeat(&$a, $type){
1481 if (api_user()===false) return false;
1483 $user_info = api_get_user($a);
1486 $id = intval($a->argv[3]);
1489 $id = intval($_REQUEST["id"]);
1493 $id = intval($a->argv[4]);
1495 logger('API: api_statuses_repeat: '.$id);
1497 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1498 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1499 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1500 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1501 FROM `item`, `contact`
1502 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1503 AND `contact`.`id` = `item`.`contact-id`
1504 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1506 AND `item`.`id`=%d",
1510 if ($r[0]['body'] != "") {
1511 if (!intval(get_config('system','old_share'))) {
1512 if (strpos($r[0]['body'], "[/share]") !== false) {
1513 $pos = strpos($r[0]['body'], "[share");
1514 $post = substr($r[0]['body'], $pos);
1516 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1518 $post .= $r[0]['body'];
1519 $post .= "[/share]";
1521 $_REQUEST['body'] = $post;
1523 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1525 $_REQUEST['profile_uid'] = api_user();
1526 $_REQUEST['type'] = 'wall';
1527 $_REQUEST['api_source'] = true;
1529 if (!x($_REQUEST, "source"))
1530 $_REQUEST["source"] = api_source();
1535 // this should output the last post (the one we just posted).
1537 return(api_status_show($a,$type));
1539 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1544 function api_statuses_destroy(&$a, $type){
1545 if (api_user()===false) return false;
1547 $user_info = api_get_user($a);
1550 $id = intval($a->argv[3]);
1553 $id = intval($_REQUEST["id"]);
1557 $id = intval($a->argv[4]);
1559 logger('API: api_statuses_destroy: '.$id);
1561 $ret = api_statuses_show($a, $type);
1563 drop_item($id, false);
1567 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1571 * http://developer.twitter.com/doc/get/statuses/mentions
1574 function api_statuses_mentions(&$a, $type){
1575 if (api_user()===false) return false;
1577 unset($_REQUEST["user_id"]);
1578 unset($_GET["user_id"]);
1580 unset($_REQUEST["screen_name"]);
1581 unset($_GET["screen_name"]);
1583 $user_info = api_get_user($a);
1584 // get last newtork messages
1588 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1589 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1590 if ($page<0) $page=0;
1591 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1592 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1593 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1595 $start = $page*$count;
1597 // Ugly code - should be changed
1598 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1599 $myurl = substr($myurl,strpos($myurl,'://')+3);
1600 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1601 $myurl = str_replace('www.','',$myurl);
1602 $diasp_url = str_replace('/profile/','/u/',$myurl);
1605 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1607 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1608 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1609 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1610 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1611 FROM `item`, `contact`
1612 WHERE `item`.`uid` = %d AND `verb` = '%s'
1613 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1614 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1615 AND `contact`.`id` = `item`.`contact-id`
1616 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1617 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1620 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1622 dbesc(ACTIVITY_POST),
1623 dbesc(protect_sprintf($myurl)),
1624 dbesc(protect_sprintf($myurl)),
1627 intval($start), intval($count)
1630 $ret = api_format_items($r,$user_info);
1633 $data = array('$statuses' => $ret);
1637 $data = api_rss_extra($a, $data, $user_info);
1640 $as = api_format_as($a, $ret, $user_info);
1641 $as["title"] = $a->config['sitename']." Mentions";
1642 $as['link']['url'] = $a->get_baseurl()."/";
1647 return api_apply_template("timeline", $type, $data);
1649 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1650 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1653 function api_statuses_user_timeline(&$a, $type){
1654 if (api_user()===false) return false;
1656 $user_info = api_get_user($a);
1657 // get last network messages
1659 logger("api_statuses_user_timeline: api_user: ". api_user() .
1660 "\nuser_info: ".print_r($user_info, true) .
1661 "\n_REQUEST: ".print_r($_REQUEST, true),
1665 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1666 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1667 if ($page<0) $page=0;
1668 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1669 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1670 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1671 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1673 $start = $page*$count;
1676 if ($user_info['self']==1)
1677 $sql_extra .= " AND `item`.`wall` = 1 ";
1679 if ($exclude_replies > 0)
1680 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1681 if ($conversation_id > 0)
1682 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1684 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1685 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1686 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1687 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1688 FROM `item`, `contact`
1689 WHERE `item`.`uid` = %d AND `verb` = '%s'
1690 AND `item`.`contact-id` = %d
1691 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1692 AND `contact`.`id` = `item`.`contact-id`
1693 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1696 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1698 dbesc(ACTIVITY_POST),
1699 intval($user_info['cid']),
1701 intval($start), intval($count)
1704 $ret = api_format_items($r,$user_info, true);
1706 $data = array('$statuses' => $ret);
1710 $data = api_rss_extra($a, $data, $user_info);
1713 return api_apply_template("timeline", $type, $data);
1716 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1720 * Star/unstar an item
1721 * param: id : id of the item
1723 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1725 function api_favorites_create_destroy(&$a, $type){
1726 if (api_user()===false) return false;
1728 # for versioned api.
1729 # TODO: we need a better global soluton
1731 if ($a->argv[1]=="1.1") $action_argv_id=3;
1733 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1734 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1735 if ($a->argc==$action_argv_id+2) {
1736 $itemid = intval($a->argv[$action_argv_id+1]);
1738 $itemid = intval($_REQUEST['id']);
1741 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1742 $itemid, api_user());
1744 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1748 $item[0]['starred']=1;
1751 $item[0]['starred']=0;
1754 die(api_error($a, $type, t("Invalid action. ".$action)));
1756 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1757 $item[0]['starred'], $itemid, api_user());
1759 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1760 $item[0]['starred'], $itemid, api_user());
1762 if ($r===false) die(api_error($a, $type, t("DB error")));
1765 $user_info = api_get_user($a);
1766 $rets = api_format_items($item,$user_info);
1769 $data = array('$status' => $ret);
1773 $data = api_rss_extra($a, $data, $user_info);
1776 return api_apply_template("status", $type, $data);
1779 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1780 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1782 function api_favorites(&$a, $type){
1785 if (api_user()===false) return false;
1787 $called_api= array();
1789 $user_info = api_get_user($a);
1791 // in friendica starred item are private
1792 // return favorites only for self
1793 logger('api_favorites: self:' . $user_info['self']);
1795 if ($user_info['self']==0) {
1801 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1802 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1803 $count = (x($_GET,'count')?$_GET['count']:20);
1804 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1805 if ($page<0) $page=0;
1807 $start = $page*$count;
1810 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1812 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1813 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1814 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1815 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1816 FROM `item`, `contact`
1817 WHERE `item`.`uid` = %d
1818 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1819 AND `item`.`starred` = 1
1820 AND `contact`.`id` = `item`.`contact-id`
1821 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1824 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1827 intval($start), intval($count)
1830 $ret = api_format_items($r,$user_info);
1834 $data = array('$statuses' => $ret);
1838 $data = api_rss_extra($a, $data, $user_info);
1841 return api_apply_template("timeline", $type, $data);
1844 api_register_func('api/favorites','api_favorites', true);
1849 function api_format_as($a, $ret, $user_info) {
1852 $as['title'] = $a->config['sitename']." Public Timeline";
1854 foreach ($ret as $item) {
1855 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1856 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1857 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1858 $avatar[0]["rel"] = "avatar";
1859 $avatar[0]["type"] = "";
1860 $avatar[0]["width"] = 96;
1861 $avatar[0]["height"] = 96;
1862 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1863 $avatar[1]["rel"] = "avatar";
1864 $avatar[1]["type"] = "";
1865 $avatar[1]["width"] = 48;
1866 $avatar[1]["height"] = 48;
1867 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1868 $avatar[2]["rel"] = "avatar";
1869 $avatar[2]["type"] = "";
1870 $avatar[2]["width"] = 24;
1871 $avatar[2]["height"] = 24;
1872 $singleitem["actor"]["avatarLinks"] = $avatar;
1874 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1875 $singleitem["actor"]["image"]["rel"] = "avatar";
1876 $singleitem["actor"]["image"]["type"] = "";
1877 $singleitem["actor"]["image"]["width"] = 96;
1878 $singleitem["actor"]["image"]["height"] = 96;
1879 $singleitem["actor"]["type"] = "person";
1880 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1881 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1882 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1883 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1884 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1885 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1886 $singleitem["actor"]["contact"]["addresses"] = "";
1888 $singleitem["body"] = $item["text"];
1889 $singleitem["object"]["displayName"] = $item["text"];
1890 $singleitem["object"]["id"] = $item["url"];
1891 $singleitem["object"]["type"] = "note";
1892 $singleitem["object"]["url"] = $item["url"];
1893 //$singleitem["context"] =;
1894 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1895 $singleitem["provider"]["objectType"] = "service";
1896 $singleitem["provider"]["displayName"] = "Test";
1897 $singleitem["provider"]["url"] = "http://test.tld";
1898 $singleitem["title"] = $item["text"];
1899 $singleitem["verb"] = "post";
1900 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1901 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1902 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1903 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1904 //$singleitem["original"] = $item;
1905 $items[] = $singleitem;
1907 $as['items'] = $items;
1908 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1909 $as['link']['rel'] = "alternate";
1910 $as['link']['type'] = "text/html";
1914 function api_format_messages($item, $recipient, $sender) {
1915 // standard meta information
1917 'id' => $item['id'],
1918 'sender_id' => $sender['id'] ,
1920 'recipient_id' => $recipient['id'],
1921 'created_at' => api_date($item['created']),
1922 'sender_screen_name' => $sender['screen_name'],
1923 'recipient_screen_name' => $recipient['screen_name'],
1924 'sender' => $sender,
1925 'recipient' => $recipient,
1928 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1929 unset($ret["sender"]["uid"]);
1930 unset($ret["sender"]["self"]);
1931 unset($ret["recipient"]["uid"]);
1932 unset($ret["recipient"]["self"]);
1934 //don't send title to regular StatusNET requests to avoid confusing these apps
1935 if (x($_GET, 'getText')) {
1936 $ret['title'] = $item['title'] ;
1937 if ($_GET["getText"] == "html") {
1938 $ret['text'] = bbcode($item['body'], false, false);
1940 elseif ($_GET["getText"] == "plain") {
1941 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1942 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1946 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1948 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1949 unset($ret['sender']);
1950 unset($ret['recipient']);
1956 function api_convert_item($item) {
1958 $body = $item['body'];
1959 $attachments = api_get_attachments($body);
1961 // Workaround for ostatus messages where the title is identically to the body
1962 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1963 $statusbody = trim(html2plain($html, 0));
1965 // handle data: images
1966 $statusbody = api_format_items_embeded_images($item,$statusbody);
1968 $statustitle = trim($item['title']);
1970 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1971 $statustext = trim($statusbody);
1973 $statustext = trim($statustitle."\n\n".$statusbody);
1975 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1976 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1978 $statushtml = trim(bbcode($body, false, false));
1980 if ($item['title'] != "")
1981 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1983 $entities = api_get_entitities($statustext, $body);
1985 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1988 function api_get_attachments(&$body) {
1991 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1993 $URLSearchString = "^\[\]";
1994 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1999 $attachments = array();
2001 foreach ($images[1] AS $image) {
2002 $imagedata = get_photo_info($image);
2005 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2008 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2009 foreach ($images[0] AS $orig)
2010 $body = str_replace($orig, "", $body);
2012 return $attachments;
2015 function api_get_entitities(&$text, $bbcode) {
2018 * 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) {
2875 - remove trailing junk from profile url
2876 - pump.io check has to check the website
2881 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
2882 dbesc(normalise_link($profile)));
2884 $nick = $r[0]["nick"];
2887 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
2888 dbesc(normalise_link($profile)));
2890 $nick = $r[0]["nick"];
2894 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2895 if ($friendica != $profile)
2900 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2901 if ($diaspora != $profile)
2906 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2907 if ($twitter != $profile)
2913 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2914 if ($StatusnetHost != $profile) {
2915 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2916 if ($StatusnetUser != $profile) {
2917 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2918 $user = json_decode($UserData);
2920 $nick = $user->screen_name;
2925 // To-Do: look at the page if its really a pumpio site
2926 //if (!$nick == "") {
2927 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2928 // if ($pumpio != $profile)
2930 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2935 q("UPDATE `unique_contacts` SET `nick` = '%s' WHERE `nick` != '%s' AND url = '%s'",
2936 dbesc($nick), dbesc($nick), dbesc(normalise_link($profile)));
2943 function api_clean_plain_items($Text) {
2944 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2946 $Text = bb_CleanPictureLinks($Text);
2948 $URLSearchString = "^\[\]";
2950 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2952 if ($include_entities == "true") {
2953 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2956 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2960 function api_cleanup_share($shared) {
2961 if ($shared[2] != "type-link")
2964 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2970 if (isset($bookmark[2][0]))
2971 $title = $bookmark[2][0];
2973 if (isset($bookmark[1][0]))
2974 $link = $bookmark[1][0];
2976 if (strpos($shared[1],$title) !== false)
2979 if (strpos($shared[1],$link) !== false)
2982 $text = trim($shared[1]);
2984 //if (strlen($text) < strlen($title))
2985 if (($text == "") AND ($title != ""))
2986 $text .= "\n\n".trim($title);
2989 $text .= "\n".trim($link);
2991 return(trim($text));
2994 function api_best_nickname(&$contacts) {
2995 $best_contact = array();
2997 if (count($contact) == 0)
3000 foreach ($contacts AS $contact)
3001 if ($contact["network"] == "") {
3002 $contact["network"] = "dfrn";
3003 $best_contact = array($contact);
3006 if (sizeof($best_contact) == 0)
3007 foreach ($contacts AS $contact)
3008 if ($contact["network"] == "dfrn")
3009 $best_contact = array($contact);
3011 if (sizeof($best_contact) == 0)
3012 foreach ($contacts AS $contact)
3013 if ($contact["network"] == "dspr")
3014 $best_contact = array($contact);
3016 if (sizeof($best_contact) == 0)
3017 foreach ($contacts AS $contact)
3018 if ($contact["network"] == "stat")
3019 $best_contact = array($contact);
3021 if (sizeof($best_contact) == 0)
3022 foreach ($contacts AS $contact)
3023 if ($contact["network"] == "pump")
3024 $best_contact = array($contact);
3026 if (sizeof($best_contact) == 0)
3027 foreach ($contacts AS $contact)
3028 if ($contact["network"] == "twit")
3029 $best_contact = array($contact);
3031 if (sizeof($best_contact) == 1)
3032 $contacts = $best_contact;
3034 $contacts = array($contacts[0]);
3037 // return all or a specified group of the user with the containing contacts
3038 function api_friendica_group_show(&$a, $type) {
3039 if (api_user()===false) return false;
3042 $user_info = api_get_user($a);
3043 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3044 $uid = $user_info['uid'];
3046 // get data of the specified group id or all groups if not specified
3048 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3051 // error message if specified gid is not in database
3053 die(api_error($a, $type, 'gid not available'));
3056 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3059 // loop through all groups and retrieve all members for adding data in the user array
3060 foreach ($r as $rr) {
3061 $members = group_get_members($rr['id']);
3063 foreach ($members as $member) {
3064 $user = api_get_user($a, $member['nurl']);
3067 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3069 return api_apply_template("group_show", $type, array('$groups' => $grps));
3071 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3074 // delete the specified group of the user
3075 function api_friendica_group_delete(&$a, $type) {
3076 if (api_user()===false) return false;
3079 $user_info = api_get_user($a);
3080 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3081 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3082 $uid = $user_info['uid'];
3084 // error if no gid specified
3085 if ($gid == 0 || $name == "")
3086 die(api_error($a, $type, 'gid or name not specified'));
3088 // get data of the specified group id
3089 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3092 // error message if specified gid is not in database
3094 die(api_error($a, $type, 'gid not available'));
3096 // get data of the specified group id and group name
3097 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3101 // error message if specified gid is not in database
3102 if (count($rname) == 0)
3103 die(api_error($a, $type, 'wrong group name'));
3106 $ret = group_rmv($uid, $name);
3109 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3110 return api_apply_template("group_delete", $type, array('$result' => $success));
3113 die(api_error($a, $type, 'other API error'));
3115 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true);
3118 // create the specified group with the posted array of contacts
3119 function api_friendica_group_create(&$a, $type) {
3120 if (api_user()===false) return false;
3123 $user_info = api_get_user($a);
3124 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3125 $uid = $user_info['uid'];
3126 $json = json_decode($_POST['json'], true);
3127 $users = $json['user'];
3129 // error if no name specified
3131 die(api_error($a, $type, 'group name not specified'));
3133 // get data of the specified group name
3134 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3137 // error message if specified group name already exists
3138 if (count($rname) != 0)
3139 die(api_error($a, $type, 'group name already exists'));
3141 // check if specified group name is a deleted group
3142 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3145 // error message if specified group name already exists
3146 if (count($rname) != 0)
3147 $reactivate_group = true;
3150 $ret = group_add($uid, $name);
3152 $gid = group_byname($uid, $name);
3154 die(api_error($a, $type, 'other API error'));
3157 $erroraddinguser = false;
3158 $errorusers = array();
3159 foreach ($users as $user) {
3160 $cid = $user['cid'];
3161 // check if user really exists as contact
3162 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3165 if (count($contact))
3166 $result = group_add_member($uid, $name, $cid, $gid);
3168 $erroraddinguser = true;
3169 $errorusers[] = $cid;
3173 // return success message incl. missing users in array
3174 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3175 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3176 return api_apply_template("group_create", $type, array('result' => $success));
3178 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true);
3181 // update the specified group with the posted array of contacts
3182 function api_friendica_group_update(&$a, $type) {
3183 if (api_user()===false) return false;
3186 $user_info = api_get_user($a);
3187 $uid = $user_info['uid'];
3188 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3189 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3190 $json = json_decode($_POST['json'], true);
3191 $users = $json['user'];
3193 // error if no name specified
3195 die(api_error($a, $type, 'group name not specified'));
3197 // error if no gid specified
3199 die(api_error($a, $type, 'gid not specified'));
3202 $members = group_get_members($gid);
3203 foreach ($members as $member) {
3204 $cid = $member['id'];
3205 foreach ($users as $user) {
3206 $found = ($user['cid'] == $cid ? true : false);
3209 $ret = group_rmv_member($uid, $name, $cid);
3214 $erroraddinguser = false;
3215 $errorusers = array();
3216 foreach ($users as $user) {
3217 $cid = $user['cid'];
3218 // check if user really exists as contact
3219 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3222 if (count($contact))
3223 $result = group_add_member($uid, $name, $cid, $gid);
3225 $erroraddinguser = true;
3226 $errorusers[] = $cid;
3230 // return success message incl. missing users in array
3231 $status = ($erroraddinguser ? "missing user" : "ok");
3232 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3233 return api_apply_template("group_update", $type, array('result' => $success));
3235 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true);
3239 [pagename] => api/1.1/statuses/lookup.json
3240 [id] => 605138389168451584
3241 [include_cards] => true
3242 [cards_platform] => Android-12
3243 [include_entities] => true
3244 [include_my_retweet] => 1
3246 [include_reply_count] => true
3247 [include_descendent_reply_count] => true
3251 Not implemented by now:
3252 statuses/retweets_of_me
3257 account/update_location
3258 account/update_profile_background_image
3259 account/update_profile_image
3263 Not implemented in status.net:
3264 statuses/retweeted_to_me
3265 statuses/retweeted_by_me
3266 direct_messages/destroy
3268 account/update_delivery_device
3269 notifications/follow