3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
27 require_once('include/plaintext.php');
28 require_once('include/xml.php');
31 define('API_METHOD_ANY','*');
32 define('API_METHOD_GET','GET');
33 define('API_METHOD_POST','POST,PUT');
34 define('API_METHOD_DELETE','POST,DELETE');
42 * @brief Auth API user
44 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
45 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
46 * into a page, and visitors will post something without noticing it).
49 if ($_SESSION['allow_api'])
56 * @brief Get source name from API client
58 * Clients can send 'source' parameter to be show in post metadata
59 * as "sent via <source>".
60 * Some clients doesn't send a source param, we support ones we know
64 * Client source name, default to "api" if unset/unknown
66 function api_source() {
67 if (requestdata('source'))
68 return (requestdata('source'));
70 // Support for known clients that doesn't send a source name
71 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
74 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
80 * @brief Format date for API
82 * @param string $str Source date, as UTC
83 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
85 function api_date($str){
86 //Wed May 23 06:01:13 +0000 2007
87 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
91 * @brief Register API endpoint
93 * Register a function to be the endpont for defined API path.
95 * @param string $path API URL path, relative to $a->get_baseurl()
96 * @param string $func Function name to call on path request
97 * @param bool $auth API need logged user
98 * @param string $method
99 * HTTP method reqiured to call this endpoint.
100 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
101 * Default to API_METHOD_ANY
103 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
111 // Workaround for hotot
112 $path = str_replace("api/", "api/1.1/", $path);
121 * @brief Login API user
123 * Log in user via OAuth1 or Simple HTTP Auth.
124 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
127 * @hook 'authenticate'
129 * 'username' => username from login form
130 * 'password' => password from login form
131 * 'authenticated' => return status,
132 * 'user_record' => return authenticated user record
134 * array $user logged user record
136 function api_login(&$a){
139 $oauth = new FKOAuth1();
140 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
141 if (!is_null($token)){
142 $oauth->loginUser($token->uid);
143 call_hooks('logged_in', $a->user);
146 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
147 }catch(Exception $e){
153 // workaround for HTTP-auth in CGI mode
154 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
155 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
156 if(strlen($userpass)) {
157 list($name, $password) = explode(':', $userpass);
158 $_SERVER['PHP_AUTH_USER'] = $name;
159 $_SERVER['PHP_AUTH_PW'] = $password;
163 if (!isset($_SERVER['PHP_AUTH_USER'])) {
164 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
165 header('WWW-Authenticate: Basic realm="Friendica"');
166 throw new UnauthorizedException("This API requires login");
169 $user = $_SERVER['PHP_AUTH_USER'];
170 $password = $_SERVER['PHP_AUTH_PW'];
171 $encrypted = hash('whirlpool',trim($password));
173 // allow "user@server" login (but ignore 'server' part)
174 $at=strstr($user, "@", true);
175 if ( $at ) $user=$at;
178 * next code from mod/auth.php. needs better solution
183 'username' => trim($user),
184 'password' => trim($password),
185 'authenticated' => 0,
186 'user_record' => null
191 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
192 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
193 * and later plugins should not interfere with an earlier one that succeeded.
197 call_hooks('authenticate', $addon_auth);
199 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
200 $record = $addon_auth['user_record'];
203 // process normal login request
205 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
206 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
215 if((! $record) || (! count($record))) {
216 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
217 header('WWW-Authenticate: Basic realm="Friendica"');
218 #header('HTTP/1.0 401 Unauthorized');
219 #die('This api requires login');
220 throw new UnauthorizedException("This API requires login");
223 authenticate_success($record); $_SESSION["allow_api"] = true;
225 call_hooks('logged_in', $a->user);
230 * @brief Check HTTP method of called API
232 * API endpoints can define which HTTP method to accept when called.
233 * This function check the current HTTP method agains endpoint
236 * @param string $method Required methods, uppercase, separated by comma
239 function api_check_method($method) {
240 if ($method=="*") return True;
241 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
245 * @brief Main API entry point
247 * Authenticate user, call registered API function, set HTTP headers
250 * @return string API call result
252 function api_call(&$a){
253 GLOBAL $API, $called_api;
256 if (strpos($a->query_string, ".xml")>0) $type="xml";
257 if (strpos($a->query_string, ".json")>0) $type="json";
258 if (strpos($a->query_string, ".rss")>0) $type="rss";
259 if (strpos($a->query_string, ".atom")>0) $type="atom";
261 foreach ($API as $p=>$info){
262 if (strpos($a->query_string, $p)===0){
263 if (!api_check_method($info['method'])){
264 throw new MethodNotAllowedException();
267 $called_api= explode("/",$p);
268 //unset($_SERVER['PHP_AUTH_USER']);
269 if ($info['auth']===true && api_user()===false) {
273 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
274 logger('API parameters: ' . print_r($_REQUEST,true));
276 $stamp = microtime(true);
277 $r = call_user_func($info['func'], $a, $type);
278 $duration = (float)(microtime(true)-$stamp);
279 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
282 // api function returned false withour throw an
283 // exception. This should not happend, throw a 500
284 throw new InternalServerErrorException();
289 header ("Content-Type: text/xml");
293 header ("Content-Type: application/json");
295 $json = json_encode($rr);
296 if ($_GET['callback'])
297 $json = $_GET['callback']."(".$json.")";
301 header ("Content-Type: application/rss+xml");
302 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
305 header ("Content-Type: application/atom+xml");
306 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
312 throw new NotImplementedException();
313 } catch (HTTPException $e) {
314 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
315 return api_error($a, $type, $e);
320 * @brief Format API error string
323 * @param string $type Return type (xml, json, rss, as)
324 * @param HTTPException $error Error object
325 * @return strin error message formatted as $type
327 function api_error(&$a, $type, $e) {
328 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
329 # TODO: https://dev.twitter.com/overview/api/response-codes
331 $error = array("error" => $error,
332 "code" => $e->httpcode." ".$e->httpdesc,
333 "request" => $a->query_string);
335 $ret = api_format_data('status', $type, array('status' => $error));
339 header ("Content-Type: text/xml");
343 header ("Content-Type: application/json");
344 return json_encode($ret);
347 header ("Content-Type: application/rss+xml");
351 header ("Content-Type: application/atom+xml");
358 * @brief Set values for RSS template
361 * @param array $arr Array to be passed to template
362 * @param array $user_info
365 function api_rss_extra(&$a, $arr, $user_info){
366 if (is_null($user_info)) $user_info = api_get_user($a);
367 $arr['$user'] = $user_info;
368 $arr['$rss'] = array(
369 'alternate' => $user_info['url'],
370 'self' => $a->get_baseurl(). "/". $a->query_string,
371 'base' => $a->get_baseurl(),
372 'updated' => api_date(null),
373 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
374 'language' => $user_info['language'],
375 'logo' => $a->get_baseurl()."/images/friendica-32.png",
383 * @brief Unique contact to contact url.
385 * @param int $id Contact id
386 * @return bool|string
387 * Contact url or False if contact id is unknown
389 function api_unique_id_to_url($id){
390 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
393 return ($r[0]["url"]);
399 * @brief Get user info array.
402 * @param int|string $contact_id Contact ID or URL
403 * @param string $type Return type (for errors)
405 function api_get_user(&$a, $contact_id = Null, $type = "json"){
412 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
414 // Searching for contact URL
415 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
416 $user = dbesc(normalise_link($contact_id));
418 $extra_query = "AND `contact`.`nurl` = '%s' ";
419 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
422 // Searching for unique contact id
423 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
424 $user = dbesc(api_unique_id_to_url($contact_id));
427 throw new BadRequestException("User not found.");
430 $extra_query = "AND `contact`.`nurl` = '%s' ";
431 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
434 if(is_null($user) && x($_GET, 'user_id')) {
435 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
438 throw new BadRequestException("User not found.");
441 $extra_query = "AND `contact`.`nurl` = '%s' ";
442 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
444 if(is_null($user) && x($_GET, 'screen_name')) {
445 $user = dbesc($_GET['screen_name']);
447 $extra_query = "AND `contact`.`nick` = '%s' ";
448 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
451 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
452 $argid = count($called_api);
453 list($user, $null) = explode(".",$a->argv[$argid]);
454 if(is_numeric($user)){
455 $user = dbesc(api_unique_id_to_url($user));
461 $extra_query = "AND `contact`.`nurl` = '%s' ";
462 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
464 $user = dbesc($user);
466 $extra_query = "AND `contact`.`nick` = '%s' ";
467 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
471 logger("api_get_user: user ".$user, LOGGER_DEBUG);
474 if (api_user()===false) {
478 $user = $_SESSION['uid'];
479 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
484 logger('api_user: ' . $extra_query . ', user: ' . $user);
486 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
492 // Selecting the id by priority, friendica first
493 api_best_nickname($uinfo);
495 // if the contact wasn't found, fetch it from the unique contacts
496 if (count($uinfo)==0) {
500 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
503 // If no nick where given, extract it from the address
504 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
505 $r[0]['nick'] = api_get_nick($r[0]["url"]);
509 'id_str' => (string) $r[0]["id"],
510 'name' => $r[0]["name"],
511 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
512 'location' => $r[0]["location"],
513 'description' => $r[0]["about"],
514 'url' => $r[0]["url"],
515 'protected' => false,
516 'followers_count' => 0,
517 'friends_count' => 0,
519 'created_at' => api_date($r[0]["created"]),
520 'favourites_count' => 0,
522 'time_zone' => 'UTC',
523 'geo_enabled' => false,
525 'statuses_count' => 0,
527 'contributors_enabled' => false,
528 'is_translator' => false,
529 'is_translation_enabled' => false,
530 'profile_image_url' => $r[0]["photo"],
531 'profile_image_url_https' => $r[0]["photo"],
532 'following' => false,
533 'follow_request_sent' => false,
534 'notifications' => false,
535 'statusnet_blocking' => false,
536 'notifications' => false,
537 'statusnet_profile_url' => $r[0]["url"],
539 'cid' => get_contact($r[0]["url"], api_user()),
541 'network' => $r[0]["network"],
546 throw new BadRequestException("User not found.");
550 if($uinfo[0]['self']) {
551 $usr = q("select * from user where uid = %d limit 1",
554 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
558 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
559 // count public wall messages
560 $r = q("SELECT count(*) as `count` FROM `item`
563 intval($uinfo[0]['uid'])
565 $countitms = $r[0]['count'];
568 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
569 $r = q("SELECT count(*) as `count` FROM `item`
570 WHERE `contact-id` = %d",
571 intval($uinfo[0]['id'])
573 $countitms = $r[0]['count'];
577 $r = q("SELECT count(*) as `count` FROM `contact`
578 WHERE `uid` = %d AND `rel` IN ( %d, %d )
579 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
580 intval($uinfo[0]['uid']),
581 intval(CONTACT_IS_SHARING),
582 intval(CONTACT_IS_FRIEND)
584 $countfriends = $r[0]['count'];
586 $r = q("SELECT count(*) as `count` FROM `contact`
587 WHERE `uid` = %d AND `rel` IN ( %d, %d )
588 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
589 intval($uinfo[0]['uid']),
590 intval(CONTACT_IS_FOLLOWER),
591 intval(CONTACT_IS_FRIEND)
593 $countfollowers = $r[0]['count'];
595 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
596 intval($uinfo[0]['uid'])
598 $starred = $r[0]['count'];
601 if(! $uinfo[0]['self']) {
607 // Add a nick if it isn't present there
608 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
609 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
612 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
614 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
615 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
618 'id' => intval($gcontact_id),
619 'id_str' => (string) intval($gcontact_id),
620 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
621 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
622 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
623 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
624 'profile_image_url' => $uinfo[0]['micro'],
625 'profile_image_url_https' => $uinfo[0]['micro'],
626 'url' => $uinfo[0]['url'],
627 'protected' => false,
628 'followers_count' => intval($countfollowers),
629 'friends_count' => intval($countfriends),
630 'created_at' => api_date($uinfo[0]['created']),
631 'favourites_count' => intval($starred),
633 'time_zone' => 'UTC',
634 'statuses_count' => intval($countitms),
635 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
637 'statusnet_blocking' => false,
638 'notifications' => false,
639 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
640 'statusnet_profile_url' => $uinfo[0]['url'],
641 'uid' => intval($uinfo[0]['uid']),
642 'cid' => intval($uinfo[0]['cid']),
643 'self' => $uinfo[0]['self'],
644 'network' => $uinfo[0]['network'],
652 * @brief return api-formatted array for item's author and owner
655 * @param array $item : item from db
656 * @return array(array:author, array:owner)
658 function api_item_get_user(&$a, $item) {
660 // Make sure that there is an entry in the global contacts for author and owner
661 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
662 "photo" => $item['author-avatar'], "name" => $item['author-name']));
664 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
665 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
667 $status_user = api_get_user($a,$item["author-link"]);
668 $status_user["protected"] = (($item["allow_cid"] != "") OR
669 ($item["allow_gid"] != "") OR
670 ($item["deny_cid"] != "") OR
671 ($item["deny_gid"] != "") OR
674 $owner_user = api_get_user($a,$item["owner-link"]);
676 return (array($status_user, $owner_user));
680 * @brief walks recursively through an array with the possibility to change value and key
682 * @param array $array The array to walk through
683 * @param string $callback The callback function
685 * @return array the transformed array
687 function api_walk_recursive(array &$array, callable $callback) {
689 $new_array = array();
691 foreach ($array as $k => $v) {
693 if ($callback($v, $k))
694 $new_array[$k] = api_walk_recursive($v, $callback);
696 if ($callback($v, $k))
706 * @brief Callback function to transform the array in an array that can be transformed in a XML file
708 * @param variant $item Array item value
709 * @param string $key Array key
711 * @return boolean Should the array item be deleted?
713 function api_reformat_xml(&$item, &$key) {
715 $item = ($item ? "true" : "false");
717 if (substr($key, 0, 10) == "statusnet_")
718 $key = "statusnet:".substr($key, 10);
719 elseif (substr($key, 0, 10) == "friendica_")
720 $key = "friendica:".substr($key, 10);
722 // $key = "default:".$key;
728 * @brief Creates the XML from a JSON style array
730 * @param array $data JSON style array
731 * @param string $root_element Name of the root element
733 * @return string The XML data
735 function api_create_xml($data, $root_element) {
736 $childname = key($data);
737 $data2 = array_pop($data);
740 $namespaces = array("" => "http://api.twitter.com",
741 "statusnet" => "http://status.net/schema/api/1/",
742 "friendica" => "http://friendi.ca/schema/api/1/",
743 "georss" => "http://www.georss.org/georss");
745 /// @todo Auto detection of needed namespaces
746 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
747 $namespaces = array();
749 if (is_array($data2))
750 api_walk_recursive($data2, "api_reformat_xml");
756 foreach ($data2 AS $item)
757 $data4[$i++.":".$childname] = $item;
762 $data3 = array($root_element => $data2);
763 $ret = xml::from_array($data3, $xml, false, $namespaces);
768 * @brief Formats the data according to the data type
770 * @param string $root_element Name of the root element
771 * @param string $type Return type (atom, rss, xml, json)
772 * @param array $data JSON style array
774 * @return (string|object) XML data or JSON data
776 function api_format_data($root_element, $type, $data){
784 $ret = api_create_xml($data, $root_element);
799 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
800 * returns a 401 status code and an error message if not.
801 * http://developer.twitter.com/doc/get/account/verify_credentials
803 function api_account_verify_credentials(&$a, $type){
804 if (api_user()===false) throw new ForbiddenException();
806 unset($_REQUEST["user_id"]);
807 unset($_GET["user_id"]);
809 unset($_REQUEST["screen_name"]);
810 unset($_GET["screen_name"]);
812 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
814 $user_info = api_get_user($a);
816 // "verified" isn't used here in the standard
817 unset($user_info["verified"]);
819 // - Adding last status
821 $user_info["status"] = api_status_show($a,"raw");
822 if (!count($user_info["status"]))
823 unset($user_info["status"]);
825 unset($user_info["status"]["user"]);
828 // "uid" and "self" are only needed for some internal stuff, so remove it from here
829 unset($user_info["uid"]);
830 unset($user_info["self"]);
832 return api_format_data("user", $type, array('user' => $user_info));
835 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
839 * get data from $_POST or $_GET
841 function requestdata($k){
842 if (isset($_POST[$k])){
845 if (isset($_GET[$k])){
851 /*Waitman Gobble Mod*/
852 function api_statuses_mediap(&$a, $type) {
853 if (api_user()===false) {
854 logger('api_statuses_update: no user');
855 throw new ForbiddenException();
857 $user_info = api_get_user($a);
859 $_REQUEST['type'] = 'wall';
860 $_REQUEST['profile_uid'] = api_user();
861 $_REQUEST['api_source'] = true;
862 $txt = requestdata('status');
863 //$txt = urldecode(requestdata('status'));
865 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
867 $txt = html2bb_video($txt);
868 $config = HTMLPurifier_Config::createDefault();
869 $config->set('Cache.DefinitionImpl', null);
870 $purifier = new HTMLPurifier($config);
871 $txt = $purifier->purify($txt);
873 $txt = html2bbcode($txt);
875 $a->argv[1]=$user_info['screen_name']; //should be set to username?
877 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
878 $bebop = wall_upload_post($a);
880 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
881 $_REQUEST['body']=$txt."\n\n".$bebop;
884 // this should output the last post (the one we just posted).
885 return api_status_show($a,$type);
887 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
888 /*Waitman Gobble Mod*/
891 function api_statuses_update(&$a, $type) {
892 if (api_user()===false) {
893 logger('api_statuses_update: no user');
894 throw new ForbiddenException();
897 $user_info = api_get_user($a);
899 // convert $_POST array items to the form we use for web posts.
901 // logger('api_post: ' . print_r($_POST,true));
903 if(requestdata('htmlstatus')) {
904 $txt = requestdata('htmlstatus');
905 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
906 $txt = html2bb_video($txt);
908 $config = HTMLPurifier_Config::createDefault();
909 $config->set('Cache.DefinitionImpl', null);
911 $purifier = new HTMLPurifier($config);
912 $txt = $purifier->purify($txt);
914 $_REQUEST['body'] = html2bbcode($txt);
918 $_REQUEST['body'] = requestdata('status');
920 $_REQUEST['title'] = requestdata('title');
922 $parent = requestdata('in_reply_to_status_id');
924 // Twidere sends "-1" if it is no reply ...
928 if(ctype_digit($parent))
929 $_REQUEST['parent'] = $parent;
931 $_REQUEST['parent_uri'] = $parent;
933 if(requestdata('lat') && requestdata('long'))
934 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
935 $_REQUEST['profile_uid'] = api_user();
938 $_REQUEST['type'] = 'net-comment';
940 // Check for throttling (maximum posts per day, week and month)
941 $throttle_day = get_config('system','throttle_limit_day');
942 if ($throttle_day > 0) {
943 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
945 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
946 AND `created` > '%s' AND `id` = `parent`",
947 intval(api_user()), dbesc($datefrom));
950 $posts_day = $r[0]["posts_day"];
954 if ($posts_day > $throttle_day) {
955 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
956 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
957 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
961 $throttle_week = get_config('system','throttle_limit_week');
962 if ($throttle_week > 0) {
963 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
965 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
966 AND `created` > '%s' AND `id` = `parent`",
967 intval(api_user()), dbesc($datefrom));
970 $posts_week = $r[0]["posts_week"];
974 if ($posts_week > $throttle_week) {
975 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
976 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
977 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
982 $throttle_month = get_config('system','throttle_limit_month');
983 if ($throttle_month > 0) {
984 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
986 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
987 AND `created` > '%s' AND `id` = `parent`",
988 intval(api_user()), dbesc($datefrom));
991 $posts_month = $r[0]["posts_month"];
995 if ($posts_month > $throttle_month) {
996 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
997 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
998 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1002 $_REQUEST['type'] = 'wall';
1005 if(x($_FILES,'media')) {
1006 // upload the image if we have one
1007 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1008 $media = wall_upload_post($a);
1009 if(strlen($media)>0)
1010 $_REQUEST['body'] .= "\n\n".$media;
1013 // To-Do: Multiple IDs
1014 if (requestdata('media_ids')) {
1015 $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",
1016 intval(requestdata('media_ids')), api_user());
1018 $phototypes = Photo::supportedTypes();
1019 $ext = $phototypes[$r[0]['type']];
1020 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1021 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1025 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1027 $_REQUEST['api_source'] = true;
1029 if (!x($_REQUEST, "source"))
1030 $_REQUEST["source"] = api_source();
1032 // call out normal post function
1036 // this should output the last post (the one we just posted).
1037 return api_status_show($a,$type);
1039 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1040 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1043 function api_media_upload(&$a, $type) {
1044 if (api_user()===false) {
1046 throw new ForbiddenException();
1049 $user_info = api_get_user($a);
1051 if(!x($_FILES,'media')) {
1053 throw new BadRequestException("No media.");
1056 $media = wall_upload_post($a, false);
1059 throw new InternalServerErrorException();
1062 $returndata = array();
1063 $returndata["media_id"] = $media["id"];
1064 $returndata["media_id_string"] = (string)$media["id"];
1065 $returndata["size"] = $media["size"];
1066 $returndata["image"] = array("w" => $media["width"],
1067 "h" => $media["height"],
1068 "image_type" => $media["type"]);
1070 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1072 return array("media" => $returndata);
1074 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1076 function api_status_show(&$a, $type){
1077 $user_info = api_get_user($a);
1079 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1082 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1086 // get last public wall message
1087 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1088 FROM `item`, `item` as `i`
1089 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1090 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1091 AND `i`.`id` = `item`.`parent`
1092 AND `item`.`type`!='activity' $privacy_sql
1093 ORDER BY `item`.`created` DESC
1095 intval($user_info['cid']),
1097 dbesc($user_info['url']),
1098 dbesc(normalise_link($user_info['url'])),
1099 dbesc($user_info['url']),
1100 dbesc(normalise_link($user_info['url']))
1103 if (count($lastwall)>0){
1104 $lastwall = $lastwall[0];
1106 $in_reply_to_status_id = NULL;
1107 $in_reply_to_user_id = NULL;
1108 $in_reply_to_status_id_str = NULL;
1109 $in_reply_to_user_id_str = NULL;
1110 $in_reply_to_screen_name = NULL;
1111 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1112 $in_reply_to_status_id= intval($lastwall['parent']);
1113 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1115 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1117 if ($r[0]['nick'] == "")
1118 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1120 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1121 $in_reply_to_user_id = intval($r[0]['id']);
1122 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1126 // There seems to be situation, where both fields are identical:
1127 // https://github.com/friendica/friendica/issues/1010
1128 // This is a bugfix for that.
1129 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1130 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1131 $in_reply_to_status_id = NULL;
1132 $in_reply_to_user_id = NULL;
1133 $in_reply_to_status_id_str = NULL;
1134 $in_reply_to_user_id_str = NULL;
1135 $in_reply_to_screen_name = NULL;
1138 $converted = api_convert_item($lastwall);
1141 $geo = "georss:point";
1145 $status_info = array(
1146 'created_at' => api_date($lastwall['created']),
1147 'id' => intval($lastwall['id']),
1148 'id_str' => (string) $lastwall['id'],
1149 'text' => $converted["text"],
1150 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1151 'truncated' => false,
1152 'in_reply_to_status_id' => $in_reply_to_status_id,
1153 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1154 'in_reply_to_user_id' => $in_reply_to_user_id,
1155 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1156 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1157 'user' => $user_info,
1159 'coordinates' => "",
1161 'contributors' => "",
1162 'is_quote_status' => false,
1163 'retweet_count' => 0,
1164 'favorite_count' => 0,
1165 'favorited' => $lastwall['starred'] ? true : false,
1166 'retweeted' => false,
1167 'possibly_sensitive' => false,
1169 'statusnet_html' => $converted["html"],
1170 'statusnet_conversation_id' => $lastwall['parent'],
1173 if (count($converted["attachments"]) > 0)
1174 $status_info["attachments"] = $converted["attachments"];
1176 if (count($converted["entities"]) > 0)
1177 $status_info["entities"] = $converted["entities"];
1179 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1180 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1181 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1182 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1184 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1185 unset($status_info["user"]["uid"]);
1186 unset($status_info["user"]["self"]);
1189 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1192 return($status_info);
1194 return api_format_data("statuses", $type, array('status' => $status_info));
1203 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1204 * The author's most recent status will be returned inline.
1205 * http://developer.twitter.com/doc/get/users/show
1207 function api_users_show(&$a, $type){
1208 $user_info = api_get_user($a);
1210 $lastwall = q("SELECT `item`.*
1212 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1213 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1214 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1215 AND `type`!='activity'
1216 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1217 ORDER BY `created` DESC
1220 dbesc(ACTIVITY_POST),
1221 intval($user_info['cid']),
1222 dbesc($user_info['url']),
1223 dbesc(normalise_link($user_info['url'])),
1224 dbesc($user_info['url']),
1225 dbesc(normalise_link($user_info['url']))
1228 if (count($lastwall)>0){
1229 $lastwall = $lastwall[0];
1231 $in_reply_to_status_id = NULL;
1232 $in_reply_to_user_id = NULL;
1233 $in_reply_to_status_id_str = NULL;
1234 $in_reply_to_user_id_str = NULL;
1235 $in_reply_to_screen_name = NULL;
1236 if ($lastwall['parent']!=$lastwall['id']) {
1237 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1238 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1239 if (count($reply)>0) {
1240 $in_reply_to_status_id = intval($lastwall['parent']);
1241 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1243 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1245 if ($r[0]['nick'] == "")
1246 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1248 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1249 $in_reply_to_user_id = intval($r[0]['id']);
1250 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1255 $converted = api_convert_item($lastwall);
1258 $geo = "georss:point";
1262 $user_info['status'] = array(
1263 'text' => $converted["text"],
1264 'truncated' => false,
1265 'created_at' => api_date($lastwall['created']),
1266 'in_reply_to_status_id' => $in_reply_to_status_id,
1267 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1268 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1269 'id' => intval($lastwall['contact-id']),
1270 'id_str' => (string) $lastwall['contact-id'],
1271 'in_reply_to_user_id' => $in_reply_to_user_id,
1272 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1273 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1275 'favorited' => $lastwall['starred'] ? true : false,
1276 'statusnet_html' => $converted["html"],
1277 'statusnet_conversation_id' => $lastwall['parent'],
1280 if (count($converted["attachments"]) > 0)
1281 $user_info["status"]["attachments"] = $converted["attachments"];
1283 if (count($converted["entities"]) > 0)
1284 $user_info["status"]["entities"] = $converted["entities"];
1286 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1287 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1288 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1289 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1293 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1294 unset($user_info["uid"]);
1295 unset($user_info["self"]);
1297 return api_format_data("user", $type, array('user' => $user_info));
1300 api_register_func('api/users/show','api_users_show');
1303 function api_users_search(&$a, $type) {
1304 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1306 $userlist = array();
1308 if (isset($_GET["q"])) {
1309 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1311 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1315 foreach ($r AS $user) {
1316 $user_info = api_get_user($a, $user["id"], "json");
1319 $userlist[$k++.":user"] = $user_info;
1321 $userlist[] = $user_info;
1323 $userlist = array("users" => $userlist);
1325 throw new BadRequestException("User not found.");
1328 throw new BadRequestException("User not found.");
1330 return api_format_data("users", $type, $userlist);
1333 api_register_func('api/users/search','api_users_search');
1337 * http://developer.twitter.com/doc/get/statuses/home_timeline
1339 * TODO: Optional parameters
1340 * TODO: Add reply info
1342 function api_statuses_home_timeline(&$a, $type){
1343 if (api_user()===false) throw new ForbiddenException();
1345 unset($_REQUEST["user_id"]);
1346 unset($_GET["user_id"]);
1348 unset($_REQUEST["screen_name"]);
1349 unset($_GET["screen_name"]);
1351 $user_info = api_get_user($a);
1352 // get last newtork messages
1356 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1357 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1358 if ($page<0) $page=0;
1359 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1360 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1361 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1362 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1363 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1365 $start = $page*$count;
1369 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1370 if ($exclude_replies > 0)
1371 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1372 if ($conversation_id > 0)
1373 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1375 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1376 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1377 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1378 `contact`.`id` AS `cid`
1380 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1381 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1382 WHERE `item`.`uid` = %d AND `verb` = '%s'
1383 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1386 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1388 dbesc(ACTIVITY_POST),
1390 intval($start), intval($count)
1393 $ret = api_format_items($r,$user_info, false, $type);
1395 // Set all posts from the query above to seen
1397 foreach ($r AS $item)
1398 $idarray[] = intval($item["id"]);
1400 $idlist = implode(",", $idarray);
1402 if ($idlist != "") {
1403 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1406 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1409 $data = array('status' => $ret);
1413 $data = api_rss_extra($a, $data, $user_info);
1417 return api_format_data("statuses", $type, $data);
1419 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1420 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1422 function api_statuses_public_timeline(&$a, $type){
1423 if (api_user()===false) throw new ForbiddenException();
1425 $user_info = api_get_user($a);
1426 // get last newtork messages
1430 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1431 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1432 if ($page<0) $page=0;
1433 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1434 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1435 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1436 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1437 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1439 $start = $page*$count;
1442 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1443 if ($exclude_replies > 0)
1444 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1445 if ($conversation_id > 0)
1446 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1448 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1449 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1450 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1451 `contact`.`id` AS `cid`,
1452 `user`.`nickname`, `user`.`hidewall`
1454 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1455 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1456 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1457 AND NOT `user`.`hidewall`
1458 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1459 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1460 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1461 AND NOT `item`.`private` AND `item`.`wall`
1464 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1465 dbesc(ACTIVITY_POST),
1470 $ret = api_format_items($r,$user_info, false, $type);
1473 $data = array('status' => $ret);
1477 $data = api_rss_extra($a, $data, $user_info);
1481 return api_format_data("statuses", $type, $data);
1483 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1488 function api_statuses_show(&$a, $type){
1489 if (api_user()===false) throw new ForbiddenException();
1491 $user_info = api_get_user($a);
1494 $id = intval($a->argv[3]);
1497 $id = intval($_REQUEST["id"]);
1501 $id = intval($a->argv[4]);
1503 logger('API: api_statuses_show: '.$id);
1505 $conversation = (x($_REQUEST,'conversation')?1:0);
1509 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1511 $sql_extra .= " AND `item`.`id` = %d";
1513 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1514 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1515 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1516 `contact`.`id` AS `cid`
1518 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1519 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1520 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1521 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1524 dbesc(ACTIVITY_POST),
1529 throw new BadRequestException("There is no status with this id.");
1532 $ret = api_format_items($r,$user_info, false, $type);
1534 if ($conversation) {
1535 $data = array('status' => $ret);
1536 return api_format_data("statuses", $type, $data);
1538 $data = array('status' => $ret[0]);
1539 return api_format_data("status", $type, $data);
1542 api_register_func('api/statuses/show','api_statuses_show', true);
1548 function api_conversation_show(&$a, $type){
1549 if (api_user()===false) throw new ForbiddenException();
1551 $user_info = api_get_user($a);
1554 $id = intval($a->argv[3]);
1555 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1556 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1557 if ($page<0) $page=0;
1558 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1559 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1561 $start = $page*$count;
1564 $id = intval($_REQUEST["id"]);
1568 $id = intval($a->argv[4]);
1570 logger('API: api_conversation_show: '.$id);
1572 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1574 $id = $r[0]["parent"];
1579 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1581 // Not sure why this query was so complicated. We should keep it here for a while,
1582 // just to make sure that we really don't need it.
1583 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1584 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1586 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1587 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1588 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1589 `contact`.`id` AS `cid`
1591 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1592 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1593 WHERE `item`.`parent` = %d AND `item`.`visible`
1594 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1595 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1596 AND `item`.`id`>%d $sql_extra
1597 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1598 intval($id), intval(api_user()),
1599 dbesc(ACTIVITY_POST),
1601 intval($start), intval($count)
1605 throw new BadRequestException("There is no conversation with this id.");
1607 $ret = api_format_items($r,$user_info, false, $type);
1609 $data = array('status' => $ret);
1610 return api_format_data("statuses", $type, $data);
1612 api_register_func('api/conversation/show','api_conversation_show', true);
1613 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1619 function api_statuses_repeat(&$a, $type){
1622 if (api_user()===false) throw new ForbiddenException();
1624 $user_info = api_get_user($a);
1627 $id = intval($a->argv[3]);
1630 $id = intval($_REQUEST["id"]);
1634 $id = intval($a->argv[4]);
1636 logger('API: api_statuses_repeat: '.$id);
1638 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1639 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1640 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1641 `contact`.`id` AS `cid`
1643 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1644 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1645 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1646 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1647 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1649 AND `item`.`id`=%d",
1653 if ($r[0]['body'] != "") {
1654 if (!intval(get_config('system','old_share'))) {
1655 if (strpos($r[0]['body'], "[/share]") !== false) {
1656 $pos = strpos($r[0]['body'], "[share");
1657 $post = substr($r[0]['body'], $pos);
1659 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1661 $post .= $r[0]['body'];
1662 $post .= "[/share]";
1664 $_REQUEST['body'] = $post;
1666 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1668 $_REQUEST['profile_uid'] = api_user();
1669 $_REQUEST['type'] = 'wall';
1670 $_REQUEST['api_source'] = true;
1672 if (!x($_REQUEST, "source"))
1673 $_REQUEST["source"] = api_source();
1677 throw new ForbiddenException();
1679 // this should output the last post (the one we just posted).
1681 return(api_status_show($a,$type));
1683 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1688 function api_statuses_destroy(&$a, $type){
1689 if (api_user()===false) throw new ForbiddenException();
1691 $user_info = api_get_user($a);
1694 $id = intval($a->argv[3]);
1697 $id = intval($_REQUEST["id"]);
1701 $id = intval($a->argv[4]);
1703 logger('API: api_statuses_destroy: '.$id);
1705 $ret = api_statuses_show($a, $type);
1707 drop_item($id, false);
1711 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1715 * http://developer.twitter.com/doc/get/statuses/mentions
1718 function api_statuses_mentions(&$a, $type){
1719 if (api_user()===false) throw new ForbiddenException();
1721 unset($_REQUEST["user_id"]);
1722 unset($_GET["user_id"]);
1724 unset($_REQUEST["screen_name"]);
1725 unset($_GET["screen_name"]);
1727 $user_info = api_get_user($a);
1728 // get last newtork messages
1732 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1733 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1734 if ($page<0) $page=0;
1735 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1736 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1737 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1739 $start = $page*$count;
1741 // Ugly code - should be changed
1742 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1743 $myurl = substr($myurl,strpos($myurl,'://')+3);
1744 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1745 $myurl = str_replace('www.','',$myurl);
1746 $diasp_url = str_replace('/profile/','/u/',$myurl);
1749 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1751 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1752 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1753 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1754 `contact`.`id` AS `cid`
1755 FROM `item` FORCE INDEX (`uid_id`)
1756 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1757 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1758 WHERE `item`.`uid` = %d AND `verb` = '%s'
1759 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1760 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1761 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1764 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1766 dbesc(ACTIVITY_POST),
1767 dbesc(protect_sprintf($myurl)),
1768 dbesc(protect_sprintf($myurl)),
1771 intval($start), intval($count)
1774 $ret = api_format_items($r,$user_info, false, $type);
1777 $data = array('status' => $ret);
1781 $data = api_rss_extra($a, $data, $user_info);
1785 return api_format_data("statuses", $type, $data);
1787 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1788 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1791 function api_statuses_user_timeline(&$a, $type){
1792 if (api_user()===false) throw new ForbiddenException();
1794 $user_info = api_get_user($a);
1795 // get last network messages
1797 logger("api_statuses_user_timeline: api_user: ". api_user() .
1798 "\nuser_info: ".print_r($user_info, true) .
1799 "\n_REQUEST: ".print_r($_REQUEST, true),
1803 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1804 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1805 if ($page<0) $page=0;
1806 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1807 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1808 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1809 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1811 $start = $page*$count;
1814 if ($user_info['self']==1)
1815 $sql_extra .= " AND `item`.`wall` = 1 ";
1817 if ($exclude_replies > 0)
1818 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1819 if ($conversation_id > 0)
1820 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1822 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1823 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1824 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1825 `contact`.`id` AS `cid`
1826 FROM `item` FORCE INDEX (`uid_contactid_id`)
1827 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1828 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1829 WHERE `item`.`uid` = %d AND `verb` = '%s'
1830 AND `item`.`contact-id` = %d
1831 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1834 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1836 dbesc(ACTIVITY_POST),
1837 intval($user_info['cid']),
1839 intval($start), intval($count)
1842 $ret = api_format_items($r,$user_info, true, $type);
1844 $data = array('status' => $ret);
1848 $data = api_rss_extra($a, $data, $user_info);
1851 return api_format_data("statuses", $type, $data);
1853 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1857 * Star/unstar an item
1858 * param: id : id of the item
1860 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1862 function api_favorites_create_destroy(&$a, $type){
1863 if (api_user()===false) throw new ForbiddenException();
1865 // for versioned api.
1866 /// @TODO We need a better global soluton
1868 if ($a->argv[1]=="1.1") $action_argv_id=3;
1870 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1871 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1872 if ($a->argc==$action_argv_id+2) {
1873 $itemid = intval($a->argv[$action_argv_id+1]);
1875 $itemid = intval($_REQUEST['id']);
1878 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1879 $itemid, api_user());
1881 if ($item===false || count($item)==0)
1882 throw new BadRequestException("Invalid item.");
1886 $item[0]['starred']=1;
1889 $item[0]['starred']=0;
1892 throw new BadRequestException("Invalid action ".$action);
1894 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1895 $item[0]['starred'], $itemid, api_user());
1897 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1898 $item[0]['starred'], $itemid, api_user());
1901 throw InternalServerErrorException("DB error");
1904 $user_info = api_get_user($a);
1905 $rets = api_format_items($item,$user_info, false, $type);
1908 $data = array('status' => $ret);
1912 $data = api_rss_extra($a, $data, $user_info);
1915 return api_format_data("status", $type, $data);
1917 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1918 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1920 function api_favorites(&$a, $type){
1923 if (api_user()===false) throw new ForbiddenException();
1925 $called_api= array();
1927 $user_info = api_get_user($a);
1929 // in friendica starred item are private
1930 // return favorites only for self
1931 logger('api_favorites: self:' . $user_info['self']);
1933 if ($user_info['self']==0) {
1939 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1940 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1941 $count = (x($_GET,'count')?$_GET['count']:20);
1942 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1943 if ($page<0) $page=0;
1945 $start = $page*$count;
1948 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1950 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1951 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1952 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1953 `contact`.`id` AS `cid`
1954 FROM `item`, `contact`
1955 WHERE `item`.`uid` = %d
1956 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1957 AND `item`.`starred` = 1
1958 AND `contact`.`id` = `item`.`contact-id`
1959 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1962 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1965 intval($start), intval($count)
1968 $ret = api_format_items($r,$user_info, false, $type);
1972 $data = array('status' => $ret);
1976 $data = api_rss_extra($a, $data, $user_info);
1979 return api_format_data("statuses", $type, $data);
1981 api_register_func('api/favorites','api_favorites', true);
1983 function api_format_messages($item, $recipient, $sender) {
1984 // standard meta information
1986 'id' => $item['id'],
1987 'sender_id' => $sender['id'] ,
1989 'recipient_id' => $recipient['id'],
1990 'created_at' => api_date($item['created']),
1991 'sender_screen_name' => $sender['screen_name'],
1992 'recipient_screen_name' => $recipient['screen_name'],
1993 'sender' => $sender,
1994 'recipient' => $recipient,
1997 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1998 unset($ret["sender"]["uid"]);
1999 unset($ret["sender"]["self"]);
2000 unset($ret["recipient"]["uid"]);
2001 unset($ret["recipient"]["self"]);
2003 //don't send title to regular StatusNET requests to avoid confusing these apps
2004 if (x($_GET, 'getText')) {
2005 $ret['title'] = $item['title'] ;
2006 if ($_GET["getText"] == "html") {
2007 $ret['text'] = bbcode($item['body'], false, false);
2009 elseif ($_GET["getText"] == "plain") {
2010 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2011 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2015 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2017 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2018 unset($ret['sender']);
2019 unset($ret['recipient']);
2025 function api_convert_item($item) {
2026 $body = $item['body'];
2027 $attachments = api_get_attachments($body);
2029 // Workaround for ostatus messages where the title is identically to the body
2030 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2031 $statusbody = trim(html2plain($html, 0));
2033 // handle data: images
2034 $statusbody = api_format_items_embeded_images($item,$statusbody);
2036 $statustitle = trim($item['title']);
2038 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2039 $statustext = trim($statusbody);
2041 $statustext = trim($statustitle."\n\n".$statusbody);
2043 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2044 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2046 $statushtml = trim(bbcode($body, false, false));
2048 $search = array("<br>", "<blockquote>", "</blockquote>",
2049 "<h1>", "</h1>", "<h2>", "</h2>",
2050 "<h3>", "</h3>", "<h4>", "</h4>",
2051 "<h5>", "</h5>", "<h6>", "</h6>");
2052 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2053 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2054 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2055 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2056 $statushtml = str_replace($search, $replace, $statushtml);
2058 if ($item['title'] != "")
2059 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2061 $entities = api_get_entitities($statustext, $body);
2064 "text" => $statustext,
2065 "html" => $statushtml,
2066 "attachments" => $attachments,
2067 "entities" => $entities
2071 function api_get_attachments(&$body) {
2074 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2076 $URLSearchString = "^\[\]";
2077 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2082 $attachments = array();
2084 foreach ($images[1] AS $image) {
2085 $imagedata = get_photo_info($image);
2088 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2091 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2092 foreach ($images[0] AS $orig)
2093 $body = str_replace($orig, "", $body);
2095 return $attachments;
2098 function api_get_entitities(&$text, $bbcode) {
2101 * Links at the first character of the post
2106 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2108 if ($include_entities != "true") {
2110 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2112 foreach ($images[1] AS $image) {
2113 $replace = proxy_url($image);
2114 $text = str_replace($image, $replace, $text);
2119 $bbcode = bb_CleanPictureLinks($bbcode);
2121 // Change pure links in text to bbcode uris
2122 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2124 $entities = array();
2125 $entities["hashtags"] = array();
2126 $entities["symbols"] = array();
2127 $entities["urls"] = array();
2128 $entities["user_mentions"] = array();
2130 $URLSearchString = "^\[\]";
2132 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2134 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2135 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2136 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2138 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2139 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2140 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2142 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2143 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2144 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2146 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2148 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2149 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2151 $ordered_urls = array();
2152 foreach ($urls[1] AS $id=>$url) {
2153 //$start = strpos($text, $url, $offset);
2154 $start = iconv_strpos($text, $url, 0, "UTF-8");
2155 if (!($start === false))
2156 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2159 ksort($ordered_urls);
2162 //foreach ($urls[1] AS $id=>$url) {
2163 foreach ($ordered_urls AS $url) {
2164 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2165 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2166 $display_url = $url["title"];
2168 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2169 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2171 if (strlen($display_url) > 26)
2172 $display_url = substr($display_url, 0, 25)."…";
2175 //$start = strpos($text, $url, $offset);
2176 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2177 if (!($start === false)) {
2178 $entities["urls"][] = array("url" => $url["url"],
2179 "expanded_url" => $url["url"],
2180 "display_url" => $display_url,
2181 "indices" => array($start, $start+strlen($url["url"])));
2182 $offset = $start + 1;
2186 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2187 $ordered_images = array();
2188 foreach ($images[1] AS $image) {
2189 //$start = strpos($text, $url, $offset);
2190 $start = iconv_strpos($text, $image, 0, "UTF-8");
2191 if (!($start === false))
2192 $ordered_images[$start] = $image;
2194 //$entities["media"] = array();
2197 foreach ($ordered_images AS $url) {
2198 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2199 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2201 if (strlen($display_url) > 26)
2202 $display_url = substr($display_url, 0, 25)."…";
2204 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2205 if (!($start === false)) {
2206 $image = get_photo_info($url);
2208 // If image cache is activated, then use the following sizes:
2209 // thumb (150), small (340), medium (600) and large (1024)
2210 if (!get_config("system", "proxy_disabled")) {
2211 $media_url = proxy_url($url);
2214 $scale = scale_image($image[0], $image[1], 150);
2215 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2217 if (($image[0] > 150) OR ($image[1] > 150)) {
2218 $scale = scale_image($image[0], $image[1], 340);
2219 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2222 $scale = scale_image($image[0], $image[1], 600);
2223 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2225 if (($image[0] > 600) OR ($image[1] > 600)) {
2226 $scale = scale_image($image[0], $image[1], 1024);
2227 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2231 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2234 $entities["media"][] = array(
2236 "id_str" => (string)$start+1,
2237 "indices" => array($start, $start+strlen($url)),
2238 "media_url" => normalise_link($media_url),
2239 "media_url_https" => $media_url,
2241 "display_url" => $display_url,
2242 "expanded_url" => $url,
2246 $offset = $start + 1;
2252 function api_format_items_embeded_images(&$item, $text){
2254 $text = preg_replace_callback(
2255 "|data:image/([^;]+)[^=]+=*|m",
2256 function($match) use ($a, $item) {
2257 return $a->get_baseurl()."/display/".$item['guid'];
2265 * @brief return <a href='url'>name</a> as array
2267 * @param string $txt
2272 function api_contactlink_to_array($txt) {
2274 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2275 if ($r && count($match)==3) {
2277 'name' => $match[2],
2291 * @brief return likes, dislikes and attend status for item
2293 * @param array $item
2295 * likes => int count
2296 * dislikes => int count
2298 function api_format_items_activities(&$item, $type = "json") {
2299 $activities = array(
2301 'dislike' => array(),
2302 'attendyes' => array(),
2303 'attendno' => array(),
2304 'attendmaybe' => array()
2306 $items = q('SELECT * FROM item
2307 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2308 intval($item['uid']),
2309 dbesc($item['uri']));
2310 foreach ($items as $i){
2311 builtin_activity_puller($i, $activities);
2314 if ($type == "xml") {
2315 $xml_activities = array();
2316 foreach ($activities as $k => $v)
2317 $xml_activities["friendica:".$k] = $v;
2319 $activities = $xml_activities;
2323 $uri = $item['uri']."-l";
2324 foreach($activities as $k => $v) {
2325 $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2332 * @brief format items to be returned by api
2334 * @param array $r array of items
2335 * @param array $user_info
2336 * @param bool $filter_user filter items by $user_info
2338 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2343 foreach($r as $item) {
2345 localize_item($item);
2346 list($status_user, $owner_user) = api_item_get_user($a,$item);
2348 // Look if the posts are matching if they should be filtered by user id
2349 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2352 if ($item['thr-parent'] != $item['uri']) {
2353 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2355 dbesc($item['thr-parent']));
2357 $in_reply_to_status_id = intval($r[0]['id']);
2359 $in_reply_to_status_id = intval($item['parent']);
2361 $in_reply_to_status_id_str = (string) intval($item['parent']);
2363 $in_reply_to_screen_name = NULL;
2364 $in_reply_to_user_id = NULL;
2365 $in_reply_to_user_id_str = NULL;
2367 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2369 intval($in_reply_to_status_id));
2371 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2374 if ($r[0]['nick'] == "")
2375 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2377 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2378 $in_reply_to_user_id = intval($r[0]['id']);
2379 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2383 $in_reply_to_screen_name = NULL;
2384 $in_reply_to_user_id = NULL;
2385 $in_reply_to_status_id = NULL;
2386 $in_reply_to_user_id_str = NULL;
2387 $in_reply_to_status_id_str = NULL;
2390 $converted = api_convert_item($item);
2393 $geo = "georss:point";
2398 'text' => $converted["text"],
2399 'truncated' => False,
2400 'created_at'=> api_date($item['created']),
2401 'in_reply_to_status_id' => $in_reply_to_status_id,
2402 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2403 'source' => (($item['app']) ? $item['app'] : 'web'),
2404 'id' => intval($item['id']),
2405 'id_str' => (string) intval($item['id']),
2406 'in_reply_to_user_id' => $in_reply_to_user_id,
2407 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2408 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2410 'favorited' => $item['starred'] ? true : false,
2411 'user' => $status_user ,
2412 'friendica_owner' => $owner_user,
2413 //'entities' => NULL,
2414 'statusnet_html' => $converted["html"],
2415 'statusnet_conversation_id' => $item['parent'],
2416 'friendica_activities' => api_format_items_activities($item, $type),
2419 if (count($converted["attachments"]) > 0)
2420 $status["attachments"] = $converted["attachments"];
2422 if (count($converted["entities"]) > 0)
2423 $status["entities"] = $converted["entities"];
2425 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2426 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2427 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2428 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2431 // Retweets are only valid for top postings
2432 // It doesn't work reliable with the link if its a feed
2433 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2435 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2438 if ($item["id"] == $item["parent"]) {
2439 $retweeted_item = api_share_as_retweet($item);
2440 if ($retweeted_item !== false) {
2441 $retweeted_status = $status;
2443 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2444 } catch( BadRequestException $e ) {
2445 // user not found. should be found?
2446 /// @todo check if the user should be always found
2447 $retweeted_status["user"] = array();
2450 $rt_converted = api_convert_item($retweeted_item);
2452 $retweeted_status['text'] = $rt_converted["text"];
2453 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2454 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2455 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2456 $status['retweeted_status'] = $retweeted_status;
2460 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2461 unset($status["user"]["uid"]);
2462 unset($status["user"]["self"]);
2464 if ($item["coord"] != "") {
2465 $coords = explode(' ',$item["coord"]);
2466 if (count($coords) == 2) {
2467 if ($type == "json")
2468 $status["geo"] = array('type' => 'Point',
2469 'coordinates' => array((float) $coords[0],
2470 (float) $coords[1]));
2471 else // Not sure if this is the official format - if someone founds a documentation we can check
2472 $status["georss:point"] = $item["coord"];
2481 function api_account_rate_limit_status(&$a,$type) {
2485 'remaining-hits' => (string) 150,
2486 '@attributes' => array("type" => "integer"),
2487 'hourly-limit' => (string) 150,
2488 '@attributes2' => array("type" => "integer"),
2489 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2490 '@attributes3' => array("type" => "datetime"),
2491 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2492 '@attributes4' => array("type" => "integer"),
2496 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2497 'remaining_hits' => (string) 150,
2498 'hourly_limit' => (string) 150,
2499 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2502 return api_format_data('hash', $type, array('hash' => $hash));
2504 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2506 function api_help_test(&$a,$type) {
2512 return api_format_data('ok', $type, array("ok" => $ok));
2514 api_register_func('api/help/test','api_help_test',false);
2516 function api_lists(&$a,$type) {
2518 return api_format_data('lists', $type, array("lists_list" => $ret));
2520 api_register_func('api/lists','api_lists',true);
2522 function api_lists_list(&$a,$type) {
2524 return api_format_data('lists', $type, array("lists_list" => $ret));
2526 api_register_func('api/lists/list','api_lists_list',true);
2529 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2530 * This function is deprecated by Twitter
2531 * returns: json, xml
2533 function api_statuses_f(&$a, $type, $qtype) {
2534 if (api_user()===false) throw new ForbiddenException();
2535 $user_info = api_get_user($a);
2537 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2538 /* this is to stop Hotot to load friends multiple times
2539 * I'm not sure if I'm missing return something or
2540 * is a bug in hotot. Workaround, meantime
2544 return array('$users' => $ret);*/
2548 if($qtype == 'friends')
2549 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2550 if($qtype == 'followers')
2551 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2553 // friends and followers only for self
2554 if ($user_info['self'] == 0)
2555 $sql_extra = " AND false ";
2557 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2562 foreach($r as $cid){
2563 $user = api_get_user($a, $cid['nurl']);
2564 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2565 unset($user["uid"]);
2566 unset($user["self"]);
2572 return array('user' => $ret);
2575 function api_statuses_friends(&$a, $type){
2576 $data = api_statuses_f($a,$type,"friends");
2577 if ($data===false) return false;
2578 return api_format_data("users", $type, $data);
2580 function api_statuses_followers(&$a, $type){
2581 $data = api_statuses_f($a,$type,"followers");
2582 if ($data===false) return false;
2583 return api_format_data("users", $type, $data);
2585 api_register_func('api/statuses/friends','api_statuses_friends',true);
2586 api_register_func('api/statuses/followers','api_statuses_followers',true);
2593 function api_statusnet_config(&$a,$type) {
2594 $name = $a->config['sitename'];
2595 $server = $a->get_hostname();
2596 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2597 $email = $a->config['admin_email'];
2598 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2599 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2600 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2601 if($a->config['api_import_size'])
2602 $texlimit = string($a->config['api_import_size']);
2603 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2604 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2607 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2608 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2609 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2610 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2611 'shorturllength' => '30',
2612 'friendica' => array(
2613 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2614 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2615 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2616 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2621 return api_format_data('config', $type, array('config' => $config));
2624 api_register_func('api/statusnet/config','api_statusnet_config',false);
2626 function api_statusnet_version(&$a,$type) {
2628 $fake_statusnet_version = "0.9.7";
2630 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2632 api_register_func('api/statusnet/version','api_statusnet_version',false);
2635 * @todo use api_format_data() to return data
2637 function api_ff_ids(&$a,$type,$qtype) {
2638 if(! api_user()) throw new ForbiddenException();
2640 $user_info = api_get_user($a);
2642 if($qtype == 'friends')
2643 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2644 if($qtype == 'followers')
2645 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2647 if (!$user_info["self"])
2648 $sql_extra = " AND false ";
2650 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2652 $r = q("SELECT `gcontact`.`id` FROM `contact`, `gcontact` WHERE `contact`.`nurl` = `gcontact`.`nurl` AND `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` $sql_extra",
2656 if(!dbm::is_result($r))
2664 $ids[] = intval($rr['id']);
2666 return api_format_data("ids", $type, array('id' => $ids));
2669 function api_friends_ids(&$a,$type) {
2670 return api_ff_ids($a,$type,'friends');
2672 function api_followers_ids(&$a,$type) {
2673 return api_ff_ids($a,$type,'followers');
2675 api_register_func('api/friends/ids','api_friends_ids',true);
2676 api_register_func('api/followers/ids','api_followers_ids',true);
2679 function api_direct_messages_new(&$a, $type) {
2680 if (api_user()===false) throw new ForbiddenException();
2682 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2684 $sender = api_get_user($a);
2686 if ($_POST['screen_name']) {
2687 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2689 dbesc($_POST['screen_name']));
2691 // Selecting the id by priority, friendica first
2692 api_best_nickname($r);
2694 $recipient = api_get_user($a, $r[0]['nurl']);
2696 $recipient = api_get_user($a, $_POST['user_id']);
2700 if (x($_REQUEST,'replyto')) {
2701 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2703 intval($_REQUEST['replyto']));
2704 $replyto = $r[0]['parent-uri'];
2705 $sub = $r[0]['title'];
2708 if (x($_REQUEST,'title')) {
2709 $sub = $_REQUEST['title'];
2712 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2716 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2719 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2720 $ret = api_format_messages($r[0], $recipient, $sender);
2723 $ret = array("error"=>$id);
2726 $data = Array('direct_message'=>$ret);
2731 $data = api_rss_extra($a, $data, $user_info);
2734 return api_format_data("direct-messages", $type, $data);
2737 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2739 function api_direct_messages_box(&$a, $type, $box) {
2740 if (api_user()===false) throw new ForbiddenException();
2743 $count = (x($_GET,'count')?$_GET['count']:20);
2744 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2745 if ($page<0) $page=0;
2747 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2748 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2750 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2751 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2754 unset($_REQUEST["user_id"]);
2755 unset($_GET["user_id"]);
2757 unset($_REQUEST["screen_name"]);
2758 unset($_GET["screen_name"]);
2760 $user_info = api_get_user($a);
2761 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2762 $profile_url = $user_info["url"];
2766 $start = $page*$count;
2769 if ($box=="sentbox") {
2770 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2772 elseif ($box=="conversation") {
2773 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2775 elseif ($box=="all") {
2776 $sql_extra = "true";
2778 elseif ($box=="inbox") {
2779 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2783 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2785 if ($user_id !="") {
2786 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2788 elseif($screen_name !=""){
2789 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2792 $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",
2795 intval($start), intval($count)
2800 foreach($r as $item) {
2801 if ($box == "inbox" || $item['from-url'] != $profile_url){
2802 $recipient = $user_info;
2803 $sender = api_get_user($a,normalise_link($item['contact-url']));
2805 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2806 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2807 $sender = $user_info;
2810 $ret[]=api_format_messages($item, $recipient, $sender);
2814 $data = array('direct_message' => $ret);
2818 $data = api_rss_extra($a, $data, $user_info);
2821 return api_format_data("direct-messages", $type, $data);
2825 function api_direct_messages_sentbox(&$a, $type){
2826 return api_direct_messages_box($a, $type, "sentbox");
2828 function api_direct_messages_inbox(&$a, $type){
2829 return api_direct_messages_box($a, $type, "inbox");
2831 function api_direct_messages_all(&$a, $type){
2832 return api_direct_messages_box($a, $type, "all");
2834 function api_direct_messages_conversation(&$a, $type){
2835 return api_direct_messages_box($a, $type, "conversation");
2837 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2838 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2839 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2840 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2844 function api_oauth_request_token(&$a, $type){
2846 $oauth = new FKOAuth1();
2847 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2848 }catch(Exception $e){
2849 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2854 function api_oauth_access_token(&$a, $type){
2856 $oauth = new FKOAuth1();
2857 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2858 }catch(Exception $e){
2859 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2865 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2866 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2869 function api_fr_photos_list(&$a,$type) {
2870 if (api_user()===false) throw new ForbiddenException();
2871 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2872 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2873 intval(local_user())
2876 'image/jpeg' => 'jpg',
2877 'image/png' => 'png',
2878 'image/gif' => 'gif'
2880 $data = array('photo'=>array());
2882 foreach($r as $rr) {
2884 $photo['id'] = $rr['resource-id'];
2885 $photo['album'] = $rr['album'];
2886 $photo['filename'] = $rr['filename'];
2887 $photo['type'] = $rr['type'];
2888 $thumb = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2891 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
2893 $photo['thumb'] = $thumb;
2894 $data['photo'][] = $photo;
2898 return api_format_data("photos", $type, $data);
2901 function api_fr_photo_detail(&$a,$type) {
2902 if (api_user()===false) throw new ForbiddenException();
2903 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2905 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2906 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2907 $data_sql = ($scale === false ? "" : "data, ");
2909 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2910 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2911 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2913 intval(local_user()),
2914 dbesc($_REQUEST['photo_id']),
2919 'image/jpeg' => 'jpg',
2920 'image/png' => 'png',
2921 'image/gif' => 'gif'
2925 $data = array('photo' => $r[0]);
2926 $data['photo']['id'] = $data['photo']['resource-id'];
2927 if ($scale !== false) {
2928 $data['photo']['data'] = base64_encode($data['photo']['data']);
2930 unset($data['photo']['datasize']); //needed only with scale param
2932 if ($type == "xml") {
2933 $data['photo']['links'] = array();
2934 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
2935 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
2937 "href" => $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
2939 $data['photo']['link'] = array();
2940 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2941 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2944 unset($data['photo']['resource-id']);
2945 unset($data['photo']['minscale']);
2946 unset($data['photo']['maxscale']);
2949 throw new NotFoundException();
2952 return api_format_data("photo_detail", $type, $data);
2955 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2956 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2961 * similar as /mod/redir.php
2962 * redirect to 'url' after dfrn auth
2964 * why this when there is mod/redir.php already?
2965 * This use api_user() and api_login()
2968 * c_url: url of remote contact to auth to
2969 * url: string, url to redirect after auth
2971 function api_friendica_remoteauth(&$a) {
2972 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2973 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2975 if ($url === '' || $c_url === '')
2976 throw new BadRequestException("Wrong parameters.");
2978 $c_url = normalise_link($c_url);
2982 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2987 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2988 throw new BadRequestException("Unknown contact");
2992 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2994 if($r[0]['duplex'] && $r[0]['issued-id']) {
2995 $orig_id = $r[0]['issued-id'];
2996 $dfrn_id = '1:' . $orig_id;
2998 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2999 $orig_id = $r[0]['dfrn-id'];
3000 $dfrn_id = '0:' . $orig_id;
3003 $sec = random_string();
3005 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3006 VALUES( %d, %s, '%s', '%s', %d )",
3014 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3015 $dest = (($url) ? '&destination_url=' . $url : '');
3016 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3017 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3018 . '&type=profile&sec=' . $sec . $dest . $quiet );
3020 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3023 * @brief Return the item shared, if the item contains only the [share] tag
3025 * @param array $item Sharer item
3026 * @return array Shared item or false if not a reshare
3028 function api_share_as_retweet(&$item) {
3029 $body = trim($item["body"]);
3031 if (diaspora::is_reshare($body, false)===false) {
3035 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3036 // Skip if there is no shared message in there
3037 // we already checked this in diaspora::is_reshare()
3038 // but better one more than one less...
3039 if ($body == $attributes)
3043 // build the fake reshared item
3044 $reshared_item = $item;
3047 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3048 if ($matches[1] != "")
3049 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3051 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3052 if ($matches[1] != "")
3053 $author = $matches[1];
3056 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3057 if ($matches[1] != "")
3058 $profile = $matches[1];
3060 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3061 if ($matches[1] != "")
3062 $profile = $matches[1];
3065 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3066 if ($matches[1] != "")
3067 $avatar = $matches[1];
3069 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3070 if ($matches[1] != "")
3071 $avatar = $matches[1];
3074 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3075 if ($matches[1] != "")
3076 $link = $matches[1];
3078 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3079 if ($matches[1] != "")
3080 $link = $matches[1];
3083 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3084 if ($matches[1] != "")
3085 $posted= $matches[1];
3087 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3088 if ($matches[1] != "")
3089 $posted = $matches[1];
3091 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3093 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3098 $reshared_item["body"] = $shared_body;
3099 $reshared_item["author-name"] = $author;
3100 $reshared_item["author-link"] = $profile;
3101 $reshared_item["author-avatar"] = $avatar;
3102 $reshared_item["plink"] = $link;
3103 $reshared_item["created"] = $posted;
3104 $reshared_item["edited"] = $posted;
3106 return $reshared_item;
3110 function api_get_nick($profile) {
3112 - remove trailing junk from profile url
3113 - pump.io check has to check the website
3118 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3119 dbesc(normalise_link($profile)));
3121 $nick = $r[0]["nick"];
3124 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3125 dbesc(normalise_link($profile)));
3127 $nick = $r[0]["nick"];
3131 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3132 if ($friendica != $profile)
3137 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3138 if ($diaspora != $profile)
3143 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3144 if ($twitter != $profile)
3150 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3151 if ($StatusnetHost != $profile) {
3152 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3153 if ($StatusnetUser != $profile) {
3154 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3155 $user = json_decode($UserData);
3157 $nick = $user->screen_name;
3162 // To-Do: look at the page if its really a pumpio site
3163 //if (!$nick == "") {
3164 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3165 // if ($pumpio != $profile)
3167 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3177 function api_clean_plain_items($Text) {
3178 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3180 $Text = bb_CleanPictureLinks($Text);
3181 $URLSearchString = "^\[\]";
3183 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3185 if ($include_entities == "true") {
3186 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3189 // Simplify "attachment" element
3190 $Text = api_clean_attachments($Text);
3196 * @brief Removes most sharing information for API text export
3198 * @param string $body The original body
3200 * @return string Cleaned body
3202 function api_clean_attachments($body) {
3203 $data = get_attachment_data($body);
3210 if (isset($data["text"]))
3211 $body = $data["text"];
3213 if (($body == "") AND (isset($data["title"])))
3214 $body = $data["title"];
3216 if (isset($data["url"]))
3217 $body .= "\n".$data["url"];
3219 $body .= $data["after"];
3224 function api_best_nickname(&$contacts) {
3225 $best_contact = array();
3227 if (count($contact) == 0)
3230 foreach ($contacts AS $contact)
3231 if ($contact["network"] == "") {
3232 $contact["network"] = "dfrn";
3233 $best_contact = array($contact);
3236 if (sizeof($best_contact) == 0)
3237 foreach ($contacts AS $contact)
3238 if ($contact["network"] == "dfrn")
3239 $best_contact = array($contact);
3241 if (sizeof($best_contact) == 0)
3242 foreach ($contacts AS $contact)
3243 if ($contact["network"] == "dspr")
3244 $best_contact = array($contact);
3246 if (sizeof($best_contact) == 0)
3247 foreach ($contacts AS $contact)
3248 if ($contact["network"] == "stat")
3249 $best_contact = array($contact);
3251 if (sizeof($best_contact) == 0)
3252 foreach ($contacts AS $contact)
3253 if ($contact["network"] == "pump")
3254 $best_contact = array($contact);
3256 if (sizeof($best_contact) == 0)
3257 foreach ($contacts AS $contact)
3258 if ($contact["network"] == "twit")
3259 $best_contact = array($contact);
3261 if (sizeof($best_contact) == 1)
3262 $contacts = $best_contact;
3264 $contacts = array($contacts[0]);
3267 // return all or a specified group of the user with the containing contacts
3268 function api_friendica_group_show(&$a, $type) {
3269 if (api_user()===false) throw new ForbiddenException();
3272 $user_info = api_get_user($a);
3273 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3274 $uid = $user_info['uid'];
3276 // get data of the specified group id or all groups if not specified
3278 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3281 // error message if specified gid is not in database
3283 throw new BadRequestException("gid not available");
3286 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3289 // loop through all groups and retrieve all members for adding data in the user array
3290 foreach ($r as $rr) {
3291 $members = group_get_members($rr['id']);
3294 if ($type == "xml") {
3295 $user_element = "users";
3297 foreach ($members as $member) {
3298 $user = api_get_user($a, $member['nurl']);
3299 $users[$k++.":user"] = $user;
3302 $user_element = "user";
3303 foreach ($members as $member) {
3304 $user = api_get_user($a, $member['nurl']);
3308 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3310 return api_format_data("groups", $type, array('group' => $grps));
3312 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3315 // delete the specified group of the user
3316 function api_friendica_group_delete(&$a, $type) {
3317 if (api_user()===false) throw new ForbiddenException();
3320 $user_info = api_get_user($a);
3321 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3322 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3323 $uid = $user_info['uid'];
3325 // error if no gid specified
3326 if ($gid == 0 || $name == "")
3327 throw new BadRequestException('gid or name not specified');
3329 // get data of the specified group id
3330 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3333 // error message if specified gid is not in database
3335 throw new BadRequestException('gid not available');
3337 // get data of the specified group id and group name
3338 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3342 // error message if specified gid is not in database
3343 if (count($rname) == 0)
3344 throw new BadRequestException('wrong group name');
3347 $ret = group_rmv($uid, $name);
3350 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3351 return api_format_data("group_delete", $type, array('result' => $success));
3354 throw new BadRequestException('other API error');
3356 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3359 // create the specified group with the posted array of contacts
3360 function api_friendica_group_create(&$a, $type) {
3361 if (api_user()===false) throw new ForbiddenException();
3364 $user_info = api_get_user($a);
3365 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3366 $uid = $user_info['uid'];
3367 $json = json_decode($_POST['json'], true);
3368 $users = $json['user'];
3370 // error if no name specified
3372 throw new BadRequestException('group name not specified');
3374 // get data of the specified group name
3375 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3378 // error message if specified group name already exists
3379 if (count($rname) != 0)
3380 throw new BadRequestException('group name already exists');
3382 // check if specified group name is a deleted group
3383 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3386 // error message if specified group name already exists
3387 if (count($rname) != 0)
3388 $reactivate_group = true;
3391 $ret = group_add($uid, $name);
3393 $gid = group_byname($uid, $name);
3395 throw new BadRequestException('other API error');
3398 $erroraddinguser = false;
3399 $errorusers = array();
3400 foreach ($users as $user) {
3401 $cid = $user['cid'];
3402 // check if user really exists as contact
3403 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3406 if (count($contact))
3407 $result = group_add_member($uid, $name, $cid, $gid);
3409 $erroraddinguser = true;
3410 $errorusers[] = $cid;
3414 // return success message incl. missing users in array
3415 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3416 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3417 return api_format_data("group_create", $type, array('result' => $success));
3419 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3422 // update the specified group with the posted array of contacts
3423 function api_friendica_group_update(&$a, $type) {
3424 if (api_user()===false) throw new ForbiddenException();
3427 $user_info = api_get_user($a);
3428 $uid = $user_info['uid'];
3429 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3430 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3431 $json = json_decode($_POST['json'], true);
3432 $users = $json['user'];
3434 // error if no name specified
3436 throw new BadRequestException('group name not specified');
3438 // error if no gid specified
3440 throw new BadRequestException('gid not specified');
3443 $members = group_get_members($gid);
3444 foreach ($members as $member) {
3445 $cid = $member['id'];
3446 foreach ($users as $user) {
3447 $found = ($user['cid'] == $cid ? true : false);
3450 $ret = group_rmv_member($uid, $name, $cid);
3455 $erroraddinguser = false;
3456 $errorusers = array();
3457 foreach ($users as $user) {
3458 $cid = $user['cid'];
3459 // check if user really exists as contact
3460 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3463 if (count($contact))
3464 $result = group_add_member($uid, $name, $cid, $gid);
3466 $erroraddinguser = true;
3467 $errorusers[] = $cid;
3471 // return success message incl. missing users in array
3472 $status = ($erroraddinguser ? "missing user" : "ok");
3473 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3474 return api_format_data("group_update", $type, array('result' => $success));
3476 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3479 function api_friendica_activity(&$a, $type) {
3480 if (api_user()===false) throw new ForbiddenException();
3481 $verb = strtolower($a->argv[3]);
3482 $verb = preg_replace("|\..*$|", "", $verb);
3484 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3486 $res = do_like($id, $verb);
3493 return api_format_data('ok', $type, array('ok' => $ok));
3495 throw new BadRequestException('Error adding activity');
3499 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3500 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3501 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3502 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3503 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3504 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3505 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3506 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3507 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3508 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3511 * @brief Returns notifications
3514 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3517 function api_friendica_notification(&$a, $type) {
3518 if (api_user()===false) throw new ForbiddenException();
3519 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3520 $nm = new NotificationsManager();
3522 $notes = $nm->getAll(array(), "+seen -date", 50);
3524 if ($type == "xml") {
3525 $xmlnotes = array();
3526 foreach ($notes AS $note)
3527 $xmlnotes[] = array("@attributes" => $note);
3532 return api_format_data("notes", $type, array('note' => $notes));
3536 * @brief Set notification as seen and returns associated item (if possible)
3538 * POST request with 'id' param as notification id
3541 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3544 function api_friendica_notification_seen(&$a, $type){
3545 if (api_user()===false) throw new ForbiddenException();
3546 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3548 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3550 $nm = new NotificationsManager();
3551 $note = $nm->getByID($id);
3552 if (is_null($note)) throw new BadRequestException("Invalid argument");
3554 $nm->setSeen($note);
3555 if ($note['otype']=='item') {
3556 // would be really better with an ItemsManager and $im->getByID() :-P
3557 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3558 intval($note['iid']),
3559 intval(local_user())
3562 // we found the item, return it to the user
3563 $user_info = api_get_user($a);
3564 $ret = api_format_items($r,$user_info, false, $type);
3565 $data = array('status' => $ret);
3566 return api_format_data("status", $type, $data);
3568 // the item can't be found, but we set the note as seen, so we count this as a success
3570 return api_format_data('result', $type, array('result' => "success"));
3573 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3574 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3579 [pagename] => api/1.1/statuses/lookup.json
3580 [id] => 605138389168451584
3581 [include_cards] => true
3582 [cards_platform] => Android-12
3583 [include_entities] => true
3584 [include_my_retweet] => 1
3586 [include_reply_count] => true
3587 [include_descendent_reply_count] => true
3591 Not implemented by now:
3592 statuses/retweets_of_me
3597 account/update_location
3598 account/update_profile_background_image
3599 account/update_profile_image
3603 Not implemented in status.net:
3604 statuses/retweeted_to_me
3605 statuses/retweeted_by_me
3606 direct_messages/destroy
3608 account/update_delivery_device
3609 notifications/follow