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"],
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`.*
1211 FROM `item`, `contact`
1212 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1213 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1214 AND `contact`.`id`=`item`.`contact-id`
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']))
1227 if (count($lastwall)>0){
1228 $lastwall = $lastwall[0];
1230 $in_reply_to_status_id = NULL;
1231 $in_reply_to_user_id = NULL;
1232 $in_reply_to_status_id_str = NULL;
1233 $in_reply_to_user_id_str = NULL;
1234 $in_reply_to_screen_name = NULL;
1235 if ($lastwall['parent']!=$lastwall['id']) {
1236 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1237 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1238 if (count($reply)>0) {
1239 $in_reply_to_status_id = intval($lastwall['parent']);
1240 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1242 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1244 if ($r[0]['nick'] == "")
1245 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1247 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1248 $in_reply_to_user_id = intval($r[0]['id']);
1249 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1254 $converted = api_convert_item($lastwall);
1257 $geo = "georss:point";
1261 $user_info['status'] = array(
1262 'text' => $converted["text"],
1263 'truncated' => false,
1264 'created_at' => api_date($lastwall['created']),
1265 'in_reply_to_status_id' => $in_reply_to_status_id,
1266 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1267 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1268 'id' => intval($lastwall['contact-id']),
1269 'id_str' => (string) $lastwall['contact-id'],
1270 'in_reply_to_user_id' => $in_reply_to_user_id,
1271 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1272 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1274 'favorited' => $lastwall['starred'] ? true : false,
1275 'statusnet_html' => $converted["html"],
1276 'statusnet_conversation_id' => $lastwall['parent'],
1279 if (count($converted["attachments"]) > 0)
1280 $user_info["status"]["attachments"] = $converted["attachments"];
1282 if (count($converted["entities"]) > 0)
1283 $user_info["status"]["entities"] = $converted["entities"];
1285 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1286 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1287 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1288 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1292 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1293 unset($user_info["uid"]);
1294 unset($user_info["self"]);
1296 return api_format_data("user", $type, array('user' => $user_info));
1299 api_register_func('api/users/show','api_users_show');
1302 function api_users_search(&$a, $type) {
1303 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1305 $userlist = array();
1307 if (isset($_GET["q"])) {
1308 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1310 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1314 foreach ($r AS $user) {
1315 $user_info = api_get_user($a, $user["id"], "json");
1318 $userlist[$k++.":user"] = $user_info;
1320 $userlist[] = $user_info;
1322 $userlist = array("users" => $userlist);
1324 throw new BadRequestException("User not found.");
1327 throw new BadRequestException("User not found.");
1329 return api_format_data("users", $type, $userlist);
1332 api_register_func('api/users/search','api_users_search');
1336 * http://developer.twitter.com/doc/get/statuses/home_timeline
1338 * TODO: Optional parameters
1339 * TODO: Add reply info
1341 function api_statuses_home_timeline(&$a, $type){
1342 if (api_user()===false) throw new ForbiddenException();
1344 unset($_REQUEST["user_id"]);
1345 unset($_GET["user_id"]);
1347 unset($_REQUEST["screen_name"]);
1348 unset($_GET["screen_name"]);
1350 $user_info = api_get_user($a);
1351 // get last newtork messages
1355 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1356 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1357 if ($page<0) $page=0;
1358 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1359 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1360 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1361 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1362 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1364 $start = $page*$count;
1368 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1369 if ($exclude_replies > 0)
1370 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1371 if ($conversation_id > 0)
1372 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1374 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1375 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1376 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1377 `contact`.`id` AS `cid`
1378 FROM `item`, `contact`
1379 WHERE `item`.`uid` = %d AND `verb` = '%s'
1380 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1381 AND `contact`.`id` = `item`.`contact-id`
1382 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1385 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1387 dbesc(ACTIVITY_POST),
1389 intval($start), intval($count)
1392 $ret = api_format_items($r,$user_info, false, $type);
1394 // Set all posts from the query above to seen
1396 foreach ($r AS $item)
1397 $idarray[] = intval($item["id"]);
1399 $idlist = implode(",", $idarray);
1401 if ($idlist != "") {
1402 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1405 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1408 $data = array('status' => $ret);
1412 $data = api_rss_extra($a, $data, $user_info);
1416 return api_format_data("statuses", $type, $data);
1418 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1419 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1421 function api_statuses_public_timeline(&$a, $type){
1422 if (api_user()===false) throw new ForbiddenException();
1424 $user_info = api_get_user($a);
1425 // get last newtork messages
1429 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1430 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1431 if ($page<0) $page=0;
1432 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1433 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1434 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1435 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1436 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1438 $start = $page*$count;
1441 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1442 if ($exclude_replies > 0)
1443 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1444 if ($conversation_id > 0)
1445 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1447 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1448 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1449 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1450 `contact`.`id` AS `cid`,
1451 `user`.`nickname`, `user`.`hidewall`
1452 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1453 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1454 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1455 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1456 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1457 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1458 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1461 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1462 dbesc(ACTIVITY_POST),
1467 $ret = api_format_items($r,$user_info, false, $type);
1470 $data = array('status' => $ret);
1474 $data = api_rss_extra($a, $data, $user_info);
1478 return api_format_data("statuses", $type, $data);
1480 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1485 function api_statuses_show(&$a, $type){
1486 if (api_user()===false) throw new ForbiddenException();
1488 $user_info = api_get_user($a);
1491 $id = intval($a->argv[3]);
1494 $id = intval($_REQUEST["id"]);
1498 $id = intval($a->argv[4]);
1500 logger('API: api_statuses_show: '.$id);
1502 $conversation = (x($_REQUEST,'conversation')?1:0);
1506 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1508 $sql_extra .= " AND `item`.`id` = %d";
1510 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1511 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1512 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1513 `contact`.`id` AS `cid`
1514 FROM `item`, `contact`
1515 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1516 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1517 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1520 dbesc(ACTIVITY_POST),
1525 throw new BadRequestException("There is no status with this id.");
1528 $ret = api_format_items($r,$user_info, false, $type);
1530 if ($conversation) {
1531 $data = array('status' => $ret);
1532 return api_format_data("statuses", $type, $data);
1534 $data = array('status' => $ret[0]);
1535 return api_format_data("status", $type, $data);
1538 api_register_func('api/statuses/show','api_statuses_show', true);
1544 function api_conversation_show(&$a, $type){
1545 if (api_user()===false) throw new ForbiddenException();
1547 $user_info = api_get_user($a);
1550 $id = intval($a->argv[3]);
1551 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1552 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1553 if ($page<0) $page=0;
1554 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1555 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1557 $start = $page*$count;
1560 $id = intval($_REQUEST["id"]);
1564 $id = intval($a->argv[4]);
1566 logger('API: api_conversation_show: '.$id);
1568 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1570 $id = $r[0]["parent"];
1575 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1577 // Not sure why this query was so complicated. We should keep it here for a while,
1578 // just to make sure that we really don't need it.
1579 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1580 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1582 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1583 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1584 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1585 `contact`.`id` AS `cid`
1587 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1588 WHERE `item`.`parent` = %d AND `item`.`visible`
1589 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1590 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1591 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1592 AND `item`.`id`>%d $sql_extra
1593 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1594 intval($id), intval(api_user()),
1595 dbesc(ACTIVITY_POST),
1597 intval($start), intval($count)
1601 throw new BadRequestException("There is no conversation with this id.");
1603 $ret = api_format_items($r,$user_info, false, $type);
1605 $data = array('status' => $ret);
1606 return api_format_data("statuses", $type, $data);
1608 api_register_func('api/conversation/show','api_conversation_show', true);
1609 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1615 function api_statuses_repeat(&$a, $type){
1618 if (api_user()===false) throw new ForbiddenException();
1620 $user_info = api_get_user($a);
1623 $id = intval($a->argv[3]);
1626 $id = intval($_REQUEST["id"]);
1630 $id = intval($a->argv[4]);
1632 logger('API: api_statuses_repeat: '.$id);
1634 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1635 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1636 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1637 `contact`.`id` AS `cid`
1638 FROM `item`, `contact`
1639 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1640 AND `contact`.`id` = `item`.`contact-id`
1641 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1642 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1643 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1645 AND `item`.`id`=%d",
1649 if ($r[0]['body'] != "") {
1650 if (!intval(get_config('system','old_share'))) {
1651 if (strpos($r[0]['body'], "[/share]") !== false) {
1652 $pos = strpos($r[0]['body'], "[share");
1653 $post = substr($r[0]['body'], $pos);
1655 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1657 $post .= $r[0]['body'];
1658 $post .= "[/share]";
1660 $_REQUEST['body'] = $post;
1662 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1664 $_REQUEST['profile_uid'] = api_user();
1665 $_REQUEST['type'] = 'wall';
1666 $_REQUEST['api_source'] = true;
1668 if (!x($_REQUEST, "source"))
1669 $_REQUEST["source"] = api_source();
1673 throw new ForbiddenException();
1675 // this should output the last post (the one we just posted).
1677 return(api_status_show($a,$type));
1679 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1684 function api_statuses_destroy(&$a, $type){
1685 if (api_user()===false) throw new ForbiddenException();
1687 $user_info = api_get_user($a);
1690 $id = intval($a->argv[3]);
1693 $id = intval($_REQUEST["id"]);
1697 $id = intval($a->argv[4]);
1699 logger('API: api_statuses_destroy: '.$id);
1701 $ret = api_statuses_show($a, $type);
1703 drop_item($id, false);
1707 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1711 * http://developer.twitter.com/doc/get/statuses/mentions
1714 function api_statuses_mentions(&$a, $type){
1715 if (api_user()===false) throw new ForbiddenException();
1717 unset($_REQUEST["user_id"]);
1718 unset($_GET["user_id"]);
1720 unset($_REQUEST["screen_name"]);
1721 unset($_GET["screen_name"]);
1723 $user_info = api_get_user($a);
1724 // get last newtork messages
1728 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1729 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1730 if ($page<0) $page=0;
1731 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1732 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1733 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1735 $start = $page*$count;
1737 // Ugly code - should be changed
1738 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1739 $myurl = substr($myurl,strpos($myurl,'://')+3);
1740 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1741 $myurl = str_replace('www.','',$myurl);
1742 $diasp_url = str_replace('/profile/','/u/',$myurl);
1745 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1747 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1748 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1749 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1750 `contact`.`id` AS `cid`
1751 FROM `item` FORCE INDEX (`uid_id`), `contact`
1752 WHERE `item`.`uid` = %d AND `verb` = '%s'
1753 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1754 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1755 AND `contact`.`id` = `item`.`contact-id`
1756 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1757 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1760 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1762 dbesc(ACTIVITY_POST),
1763 dbesc(protect_sprintf($myurl)),
1764 dbesc(protect_sprintf($myurl)),
1767 intval($start), intval($count)
1770 $ret = api_format_items($r,$user_info, false, $type);
1773 $data = array('status' => $ret);
1777 $data = api_rss_extra($a, $data, $user_info);
1781 return api_format_data("statuses", $type, $data);
1783 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1784 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1787 function api_statuses_user_timeline(&$a, $type){
1788 if (api_user()===false) throw new ForbiddenException();
1790 $user_info = api_get_user($a);
1791 // get last network messages
1793 logger("api_statuses_user_timeline: api_user: ". api_user() .
1794 "\nuser_info: ".print_r($user_info, true) .
1795 "\n_REQUEST: ".print_r($_REQUEST, true),
1799 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1800 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1801 if ($page<0) $page=0;
1802 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1803 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1804 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1805 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1807 $start = $page*$count;
1810 if ($user_info['self']==1)
1811 $sql_extra .= " AND `item`.`wall` = 1 ";
1813 if ($exclude_replies > 0)
1814 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1815 if ($conversation_id > 0)
1816 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1818 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1819 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1820 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1821 `contact`.`id` AS `cid`
1823 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1824 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1825 WHERE `item`.`uid` = %d AND `verb` = '%s'
1826 AND `item`.`contact-id` = %d
1827 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1830 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1832 dbesc(ACTIVITY_POST),
1833 intval($user_info['cid']),
1835 intval($start), intval($count)
1838 $ret = api_format_items($r,$user_info, true, $type);
1840 $data = array('status' => $ret);
1844 $data = api_rss_extra($a, $data, $user_info);
1847 return api_format_data("statuses", $type, $data);
1849 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1853 * Star/unstar an item
1854 * param: id : id of the item
1856 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1858 function api_favorites_create_destroy(&$a, $type){
1859 if (api_user()===false) throw new ForbiddenException();
1861 // for versioned api.
1862 /// @TODO We need a better global soluton
1864 if ($a->argv[1]=="1.1") $action_argv_id=3;
1866 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1867 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1868 if ($a->argc==$action_argv_id+2) {
1869 $itemid = intval($a->argv[$action_argv_id+1]);
1871 $itemid = intval($_REQUEST['id']);
1874 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1875 $itemid, api_user());
1877 if ($item===false || count($item)==0)
1878 throw new BadRequestException("Invalid item.");
1882 $item[0]['starred']=1;
1885 $item[0]['starred']=0;
1888 throw new BadRequestException("Invalid action ".$action);
1890 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1891 $item[0]['starred'], $itemid, api_user());
1893 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1894 $item[0]['starred'], $itemid, api_user());
1897 throw InternalServerErrorException("DB error");
1900 $user_info = api_get_user($a);
1901 $rets = api_format_items($item,$user_info, false, $type);
1904 $data = array('status' => $ret);
1908 $data = api_rss_extra($a, $data, $user_info);
1911 return api_format_data("status", $type, $data);
1913 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1914 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1916 function api_favorites(&$a, $type){
1919 if (api_user()===false) throw new ForbiddenException();
1921 $called_api= array();
1923 $user_info = api_get_user($a);
1925 // in friendica starred item are private
1926 // return favorites only for self
1927 logger('api_favorites: self:' . $user_info['self']);
1929 if ($user_info['self']==0) {
1935 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1936 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1937 $count = (x($_GET,'count')?$_GET['count']:20);
1938 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1939 if ($page<0) $page=0;
1941 $start = $page*$count;
1944 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1946 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1947 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1948 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1949 `contact`.`id` AS `cid`
1950 FROM `item`, `contact`
1951 WHERE `item`.`uid` = %d
1952 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1953 AND `item`.`starred` = 1
1954 AND `contact`.`id` = `item`.`contact-id`
1955 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1958 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1961 intval($start), intval($count)
1964 $ret = api_format_items($r,$user_info, false, $type);
1968 $data = array('status' => $ret);
1972 $data = api_rss_extra($a, $data, $user_info);
1975 return api_format_data("statuses", $type, $data);
1977 api_register_func('api/favorites','api_favorites', true);
1979 function api_format_messages($item, $recipient, $sender) {
1980 // standard meta information
1982 'id' => $item['id'],
1983 'sender_id' => $sender['id'] ,
1985 'recipient_id' => $recipient['id'],
1986 'created_at' => api_date($item['created']),
1987 'sender_screen_name' => $sender['screen_name'],
1988 'recipient_screen_name' => $recipient['screen_name'],
1989 'sender' => $sender,
1990 'recipient' => $recipient,
1993 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1994 unset($ret["sender"]["uid"]);
1995 unset($ret["sender"]["self"]);
1996 unset($ret["recipient"]["uid"]);
1997 unset($ret["recipient"]["self"]);
1999 //don't send title to regular StatusNET requests to avoid confusing these apps
2000 if (x($_GET, 'getText')) {
2001 $ret['title'] = $item['title'] ;
2002 if ($_GET["getText"] == "html") {
2003 $ret['text'] = bbcode($item['body'], false, false);
2005 elseif ($_GET["getText"] == "plain") {
2006 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2007 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2011 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2013 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2014 unset($ret['sender']);
2015 unset($ret['recipient']);
2021 function api_convert_item($item) {
2022 $body = $item['body'];
2023 $attachments = api_get_attachments($body);
2025 // Workaround for ostatus messages where the title is identically to the body
2026 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2027 $statusbody = trim(html2plain($html, 0));
2029 // handle data: images
2030 $statusbody = api_format_items_embeded_images($item,$statusbody);
2032 $statustitle = trim($item['title']);
2034 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2035 $statustext = trim($statusbody);
2037 $statustext = trim($statustitle."\n\n".$statusbody);
2039 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2040 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2042 $statushtml = trim(bbcode($body, false, false));
2044 $search = array("<br>", "<blockquote>", "</blockquote>",
2045 "<h1>", "</h1>", "<h2>", "</h2>",
2046 "<h3>", "</h3>", "<h4>", "</h4>",
2047 "<h5>", "</h5>", "<h6>", "</h6>");
2048 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2049 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2050 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2051 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2052 $statushtml = str_replace($search, $replace, $statushtml);
2054 if ($item['title'] != "")
2055 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2057 $entities = api_get_entitities($statustext, $body);
2060 "text" => $statustext,
2061 "html" => $statushtml,
2062 "attachments" => $attachments,
2063 "entities" => $entities
2067 function api_get_attachments(&$body) {
2070 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2072 $URLSearchString = "^\[\]";
2073 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2078 $attachments = array();
2080 foreach ($images[1] AS $image) {
2081 $imagedata = get_photo_info($image);
2084 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2087 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2088 foreach ($images[0] AS $orig)
2089 $body = str_replace($orig, "", $body);
2091 return $attachments;
2094 function api_get_entitities(&$text, $bbcode) {
2097 * Links at the first character of the post
2102 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2104 if ($include_entities != "true") {
2106 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2108 foreach ($images[1] AS $image) {
2109 $replace = proxy_url($image);
2110 $text = str_replace($image, $replace, $text);
2115 $bbcode = bb_CleanPictureLinks($bbcode);
2117 // Change pure links in text to bbcode uris
2118 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2120 $entities = array();
2121 $entities["hashtags"] = array();
2122 $entities["symbols"] = array();
2123 $entities["urls"] = array();
2124 $entities["user_mentions"] = array();
2126 $URLSearchString = "^\[\]";
2128 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2130 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2131 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2132 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2134 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2135 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2136 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2138 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2139 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2140 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2142 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2144 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2145 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2147 $ordered_urls = array();
2148 foreach ($urls[1] AS $id=>$url) {
2149 //$start = strpos($text, $url, $offset);
2150 $start = iconv_strpos($text, $url, 0, "UTF-8");
2151 if (!($start === false))
2152 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2155 ksort($ordered_urls);
2158 //foreach ($urls[1] AS $id=>$url) {
2159 foreach ($ordered_urls AS $url) {
2160 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2161 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2162 $display_url = $url["title"];
2164 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2165 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2167 if (strlen($display_url) > 26)
2168 $display_url = substr($display_url, 0, 25)."…";
2171 //$start = strpos($text, $url, $offset);
2172 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2173 if (!($start === false)) {
2174 $entities["urls"][] = array("url" => $url["url"],
2175 "expanded_url" => $url["url"],
2176 "display_url" => $display_url,
2177 "indices" => array($start, $start+strlen($url["url"])));
2178 $offset = $start + 1;
2182 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2183 $ordered_images = array();
2184 foreach ($images[1] AS $image) {
2185 //$start = strpos($text, $url, $offset);
2186 $start = iconv_strpos($text, $image, 0, "UTF-8");
2187 if (!($start === false))
2188 $ordered_images[$start] = $image;
2190 //$entities["media"] = array();
2193 foreach ($ordered_images AS $url) {
2194 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2195 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2197 if (strlen($display_url) > 26)
2198 $display_url = substr($display_url, 0, 25)."…";
2200 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2201 if (!($start === false)) {
2202 $image = get_photo_info($url);
2204 // If image cache is activated, then use the following sizes:
2205 // thumb (150), small (340), medium (600) and large (1024)
2206 if (!get_config("system", "proxy_disabled")) {
2207 $media_url = proxy_url($url);
2210 $scale = scale_image($image[0], $image[1], 150);
2211 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2213 if (($image[0] > 150) OR ($image[1] > 150)) {
2214 $scale = scale_image($image[0], $image[1], 340);
2215 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2218 $scale = scale_image($image[0], $image[1], 600);
2219 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2221 if (($image[0] > 600) OR ($image[1] > 600)) {
2222 $scale = scale_image($image[0], $image[1], 1024);
2223 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2227 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2230 $entities["media"][] = array(
2232 "id_str" => (string)$start+1,
2233 "indices" => array($start, $start+strlen($url)),
2234 "media_url" => normalise_link($media_url),
2235 "media_url_https" => $media_url,
2237 "display_url" => $display_url,
2238 "expanded_url" => $url,
2242 $offset = $start + 1;
2248 function api_format_items_embeded_images(&$item, $text){
2250 $text = preg_replace_callback(
2251 "|data:image/([^;]+)[^=]+=*|m",
2252 function($match) use ($a, $item) {
2253 return $a->get_baseurl()."/display/".$item['guid'];
2261 * @brief return <a href='url'>name</a> as array
2263 * @param string $txt
2268 function api_contactlink_to_array($txt) {
2270 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2271 if ($r && count($match)==3) {
2273 'name' => $match[2],
2287 * @brief return likes, dislikes and attend status for item
2289 * @param array $item
2291 * likes => int count
2292 * dislikes => int count
2294 function api_format_items_activities(&$item, $type = "json") {
2295 $activities = array(
2297 'dislike' => array(),
2298 'attendyes' => array(),
2299 'attendno' => array(),
2300 'attendmaybe' => array()
2302 $items = q('SELECT * FROM item
2303 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2304 intval($item['uid']),
2305 dbesc($item['uri']));
2306 foreach ($items as $i){
2307 builtin_activity_puller($i, $activities);
2310 if ($type == "xml") {
2311 $xml_activities = array();
2312 foreach ($activities as $k => $v)
2313 $xml_activities["friendica:".$k] = $v;
2315 $activities = $xml_activities;
2319 $uri = $item['uri']."-l";
2320 foreach($activities as $k => $v) {
2321 $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2328 * @brief format items to be returned by api
2330 * @param array $r array of items
2331 * @param array $user_info
2332 * @param bool $filter_user filter items by $user_info
2334 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2339 foreach($r as $item) {
2341 localize_item($item);
2342 list($status_user, $owner_user) = api_item_get_user($a,$item);
2344 // Look if the posts are matching if they should be filtered by user id
2345 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2348 if ($item['thr-parent'] != $item['uri']) {
2349 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2351 dbesc($item['thr-parent']));
2353 $in_reply_to_status_id = intval($r[0]['id']);
2355 $in_reply_to_status_id = intval($item['parent']);
2357 $in_reply_to_status_id_str = (string) intval($item['parent']);
2359 $in_reply_to_screen_name = NULL;
2360 $in_reply_to_user_id = NULL;
2361 $in_reply_to_user_id_str = NULL;
2363 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2365 intval($in_reply_to_status_id));
2367 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2370 if ($r[0]['nick'] == "")
2371 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2373 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2374 $in_reply_to_user_id = intval($r[0]['id']);
2375 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2379 $in_reply_to_screen_name = NULL;
2380 $in_reply_to_user_id = NULL;
2381 $in_reply_to_status_id = NULL;
2382 $in_reply_to_user_id_str = NULL;
2383 $in_reply_to_status_id_str = NULL;
2386 $converted = api_convert_item($item);
2389 $geo = "georss:point";
2394 'text' => $converted["text"],
2395 'truncated' => False,
2396 'created_at'=> api_date($item['created']),
2397 'in_reply_to_status_id' => $in_reply_to_status_id,
2398 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2399 'source' => (($item['app']) ? $item['app'] : 'web'),
2400 'id' => intval($item['id']),
2401 'id_str' => (string) intval($item['id']),
2402 'in_reply_to_user_id' => $in_reply_to_user_id,
2403 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2404 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2406 'favorited' => $item['starred'] ? true : false,
2407 'user' => $status_user ,
2408 'friendica_owner' => $owner_user,
2409 //'entities' => NULL,
2410 'statusnet_html' => $converted["html"],
2411 'statusnet_conversation_id' => $item['parent'],
2412 'friendica_activities' => api_format_items_activities($item, $type),
2415 if (count($converted["attachments"]) > 0)
2416 $status["attachments"] = $converted["attachments"];
2418 if (count($converted["entities"]) > 0)
2419 $status["entities"] = $converted["entities"];
2421 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2422 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2423 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2424 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2427 // Retweets are only valid for top postings
2428 // It doesn't work reliable with the link if its a feed
2429 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2431 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2434 if ($item["id"] == $item["parent"]) {
2435 $retweeted_item = api_share_as_retweet($item);
2436 if ($retweeted_item !== false) {
2437 $retweeted_status = $status;
2439 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2440 } catch( BadRequestException $e ) {
2441 // user not found. should be found?
2442 /// @todo check if the user should be always found
2443 $retweeted_status["user"] = array();
2446 $rt_converted = api_convert_item($retweeted_item);
2448 $retweeted_status['text'] = $rt_converted["text"];
2449 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2450 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2451 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2452 $status['retweeted_status'] = $retweeted_status;
2456 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2457 unset($status["user"]["uid"]);
2458 unset($status["user"]["self"]);
2460 if ($item["coord"] != "") {
2461 $coords = explode(' ',$item["coord"]);
2462 if (count($coords) == 2) {
2463 if ($type == "json")
2464 $status["geo"] = array('type' => 'Point',
2465 'coordinates' => array((float) $coords[0],
2466 (float) $coords[1]));
2467 else // Not sure if this is the official format - if someone founds a documentation we can check
2468 $status["georss:point"] = $item["coord"];
2477 function api_account_rate_limit_status(&$a,$type) {
2481 'remaining-hits' => (string) 150,
2482 '@attributes' => array("type" => "integer"),
2483 'hourly-limit' => (string) 150,
2484 '@attributes2' => array("type" => "integer"),
2485 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2486 '@attributes3' => array("type" => "datetime"),
2487 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2488 '@attributes4' => array("type" => "integer"),
2492 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2493 'remaining_hits' => (string) 150,
2494 'hourly_limit' => (string) 150,
2495 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2498 return api_format_data('hash', $type, array('hash' => $hash));
2500 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2502 function api_help_test(&$a,$type) {
2508 return api_format_data('ok', $type, array("ok" => $ok));
2510 api_register_func('api/help/test','api_help_test',false);
2512 function api_lists(&$a,$type) {
2514 return api_format_data('lists', $type, array("lists_list" => $ret));
2516 api_register_func('api/lists','api_lists',true);
2518 function api_lists_list(&$a,$type) {
2520 return api_format_data('lists', $type, array("lists_list" => $ret));
2522 api_register_func('api/lists/list','api_lists_list',true);
2525 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2526 * This function is deprecated by Twitter
2527 * returns: json, xml
2529 function api_statuses_f(&$a, $type, $qtype) {
2530 if (api_user()===false) throw new ForbiddenException();
2531 $user_info = api_get_user($a);
2533 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2534 /* this is to stop Hotot to load friends multiple times
2535 * I'm not sure if I'm missing return something or
2536 * is a bug in hotot. Workaround, meantime
2540 return array('$users' => $ret);*/
2544 if($qtype == 'friends')
2545 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2546 if($qtype == 'followers')
2547 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2549 // friends and followers only for self
2550 if ($user_info['self'] == 0)
2551 $sql_extra = " AND false ";
2553 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2558 foreach($r as $cid){
2559 $user = api_get_user($a, $cid['nurl']);
2560 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2561 unset($user["uid"]);
2562 unset($user["self"]);
2568 return array('user' => $ret);
2571 function api_statuses_friends(&$a, $type){
2572 $data = api_statuses_f($a,$type,"friends");
2573 if ($data===false) return false;
2574 return api_format_data("users", $type, $data);
2576 function api_statuses_followers(&$a, $type){
2577 $data = api_statuses_f($a,$type,"followers");
2578 if ($data===false) return false;
2579 return api_format_data("users", $type, $data);
2581 api_register_func('api/statuses/friends','api_statuses_friends',true);
2582 api_register_func('api/statuses/followers','api_statuses_followers',true);
2589 function api_statusnet_config(&$a,$type) {
2590 $name = $a->config['sitename'];
2591 $server = $a->get_hostname();
2592 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2593 $email = $a->config['admin_email'];
2594 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2595 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2596 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2597 if($a->config['api_import_size'])
2598 $texlimit = string($a->config['api_import_size']);
2599 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2600 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2603 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2604 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2605 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2606 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2607 'shorturllength' => '30',
2608 'friendica' => array(
2609 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2610 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2611 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2612 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2617 return api_format_data('config', $type, array('config' => $config));
2620 api_register_func('api/statusnet/config','api_statusnet_config',false);
2622 function api_statusnet_version(&$a,$type) {
2624 $fake_statusnet_version = "0.9.7";
2626 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2628 api_register_func('api/statusnet/version','api_statusnet_version',false);
2631 * @todo use api_format_data() to return data
2633 function api_ff_ids(&$a,$type,$qtype) {
2634 if(! api_user()) throw new ForbiddenException();
2636 $user_info = api_get_user($a);
2638 if($qtype == 'friends')
2639 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2640 if($qtype == 'followers')
2641 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2643 if (!$user_info["self"])
2644 $sql_extra = " AND false ";
2646 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2648 $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",
2652 if(!dbm::is_result($r))
2660 $ids[] = intval($rr['id']);
2662 return api_format_data("ids", $type, array('id' => $ids));
2665 function api_friends_ids(&$a,$type) {
2666 return api_ff_ids($a,$type,'friends');
2668 function api_followers_ids(&$a,$type) {
2669 return api_ff_ids($a,$type,'followers');
2671 api_register_func('api/friends/ids','api_friends_ids',true);
2672 api_register_func('api/followers/ids','api_followers_ids',true);
2675 function api_direct_messages_new(&$a, $type) {
2676 if (api_user()===false) throw new ForbiddenException();
2678 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2680 $sender = api_get_user($a);
2682 if ($_POST['screen_name']) {
2683 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2685 dbesc($_POST['screen_name']));
2687 // Selecting the id by priority, friendica first
2688 api_best_nickname($r);
2690 $recipient = api_get_user($a, $r[0]['nurl']);
2692 $recipient = api_get_user($a, $_POST['user_id']);
2696 if (x($_REQUEST,'replyto')) {
2697 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2699 intval($_REQUEST['replyto']));
2700 $replyto = $r[0]['parent-uri'];
2701 $sub = $r[0]['title'];
2704 if (x($_REQUEST,'title')) {
2705 $sub = $_REQUEST['title'];
2708 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2712 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2715 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2716 $ret = api_format_messages($r[0], $recipient, $sender);
2719 $ret = array("error"=>$id);
2722 $data = Array('direct_message'=>$ret);
2727 $data = api_rss_extra($a, $data, $user_info);
2730 return api_format_data("direct-messages", $type, $data);
2733 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2735 function api_direct_messages_box(&$a, $type, $box) {
2736 if (api_user()===false) throw new ForbiddenException();
2739 $count = (x($_GET,'count')?$_GET['count']:20);
2740 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2741 if ($page<0) $page=0;
2743 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2744 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2746 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2747 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2750 unset($_REQUEST["user_id"]);
2751 unset($_GET["user_id"]);
2753 unset($_REQUEST["screen_name"]);
2754 unset($_GET["screen_name"]);
2756 $user_info = api_get_user($a);
2757 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2758 $profile_url = $user_info["url"];
2762 $start = $page*$count;
2765 if ($box=="sentbox") {
2766 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2768 elseif ($box=="conversation") {
2769 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2771 elseif ($box=="all") {
2772 $sql_extra = "true";
2774 elseif ($box=="inbox") {
2775 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2779 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2781 if ($user_id !="") {
2782 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2784 elseif($screen_name !=""){
2785 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2788 $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",
2791 intval($start), intval($count)
2796 foreach($r as $item) {
2797 if ($box == "inbox" || $item['from-url'] != $profile_url){
2798 $recipient = $user_info;
2799 $sender = api_get_user($a,normalise_link($item['contact-url']));
2801 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2802 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2803 $sender = $user_info;
2806 $ret[]=api_format_messages($item, $recipient, $sender);
2810 $data = array('direct_message' => $ret);
2814 $data = api_rss_extra($a, $data, $user_info);
2817 return api_format_data("direct-messages", $type, $data);
2821 function api_direct_messages_sentbox(&$a, $type){
2822 return api_direct_messages_box($a, $type, "sentbox");
2824 function api_direct_messages_inbox(&$a, $type){
2825 return api_direct_messages_box($a, $type, "inbox");
2827 function api_direct_messages_all(&$a, $type){
2828 return api_direct_messages_box($a, $type, "all");
2830 function api_direct_messages_conversation(&$a, $type){
2831 return api_direct_messages_box($a, $type, "conversation");
2833 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2834 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2835 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2836 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2840 function api_oauth_request_token(&$a, $type){
2842 $oauth = new FKOAuth1();
2843 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2844 }catch(Exception $e){
2845 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2850 function api_oauth_access_token(&$a, $type){
2852 $oauth = new FKOAuth1();
2853 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2854 }catch(Exception $e){
2855 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2861 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2862 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2865 function api_fr_photos_list(&$a,$type) {
2866 if (api_user()===false) throw new ForbiddenException();
2867 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2868 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2869 intval(local_user())
2872 'image/jpeg' => 'jpg',
2873 'image/png' => 'png',
2874 'image/gif' => 'gif'
2876 $data = array('photo'=>array());
2878 foreach($r as $rr) {
2880 $photo['id'] = $rr['resource-id'];
2881 $photo['album'] = $rr['album'];
2882 $photo['filename'] = $rr['filename'];
2883 $photo['type'] = $rr['type'];
2884 $thumb = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2887 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
2889 $photo['thumb'] = $thumb;
2890 $data['photo'][] = $photo;
2894 return api_format_data("photos", $type, $data);
2897 function api_fr_photo_detail(&$a,$type) {
2898 if (api_user()===false) throw new ForbiddenException();
2899 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2901 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2902 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2903 $data_sql = ($scale === false ? "" : "data, ");
2905 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2906 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2907 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2909 intval(local_user()),
2910 dbesc($_REQUEST['photo_id']),
2915 'image/jpeg' => 'jpg',
2916 'image/png' => 'png',
2917 'image/gif' => 'gif'
2921 $data = array('photo' => $r[0]);
2922 $data['photo']['id'] = $data['photo']['resource-id'];
2923 if ($scale !== false) {
2924 $data['photo']['data'] = base64_encode($data['photo']['data']);
2926 unset($data['photo']['datasize']); //needed only with scale param
2928 if ($type == "xml") {
2929 $data['photo']['links'] = array();
2930 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
2931 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
2933 "href" => $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
2935 $data['photo']['link'] = array();
2936 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2937 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2940 unset($data['photo']['resource-id']);
2941 unset($data['photo']['minscale']);
2942 unset($data['photo']['maxscale']);
2945 throw new NotFoundException();
2948 return api_format_data("photo_detail", $type, $data);
2951 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2952 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2957 * similar as /mod/redir.php
2958 * redirect to 'url' after dfrn auth
2960 * why this when there is mod/redir.php already?
2961 * This use api_user() and api_login()
2964 * c_url: url of remote contact to auth to
2965 * url: string, url to redirect after auth
2967 function api_friendica_remoteauth(&$a) {
2968 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2969 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2971 if ($url === '' || $c_url === '')
2972 throw new BadRequestException("Wrong parameters.");
2974 $c_url = normalise_link($c_url);
2978 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2983 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2984 throw new BadRequestException("Unknown contact");
2988 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2990 if($r[0]['duplex'] && $r[0]['issued-id']) {
2991 $orig_id = $r[0]['issued-id'];
2992 $dfrn_id = '1:' . $orig_id;
2994 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2995 $orig_id = $r[0]['dfrn-id'];
2996 $dfrn_id = '0:' . $orig_id;
2999 $sec = random_string();
3001 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3002 VALUES( %d, %s, '%s', '%s', %d )",
3010 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3011 $dest = (($url) ? '&destination_url=' . $url : '');
3012 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3013 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3014 . '&type=profile&sec=' . $sec . $dest . $quiet );
3016 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3019 * @brief Return the item shared, if the item contains only the [share] tag
3021 * @param array $item Sharer item
3022 * @return array Shared item or false if not a reshare
3024 function api_share_as_retweet(&$item) {
3025 $body = trim($item["body"]);
3027 if (diaspora::is_reshare($body, false)===false) {
3031 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3032 // Skip if there is no shared message in there
3033 // we already checked this in diaspora::is_reshare()
3034 // but better one more than one less...
3035 if ($body == $attributes)
3039 // build the fake reshared item
3040 $reshared_item = $item;
3043 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3044 if ($matches[1] != "")
3045 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3047 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3048 if ($matches[1] != "")
3049 $author = $matches[1];
3052 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3053 if ($matches[1] != "")
3054 $profile = $matches[1];
3056 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3057 if ($matches[1] != "")
3058 $profile = $matches[1];
3061 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3062 if ($matches[1] != "")
3063 $avatar = $matches[1];
3065 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3066 if ($matches[1] != "")
3067 $avatar = $matches[1];
3070 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3071 if ($matches[1] != "")
3072 $link = $matches[1];
3074 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3075 if ($matches[1] != "")
3076 $link = $matches[1];
3079 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3080 if ($matches[1] != "")
3081 $posted= $matches[1];
3083 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3084 if ($matches[1] != "")
3085 $posted = $matches[1];
3087 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3089 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3094 $reshared_item["body"] = $shared_body;
3095 $reshared_item["author-name"] = $author;
3096 $reshared_item["author-link"] = $profile;
3097 $reshared_item["author-avatar"] = $avatar;
3098 $reshared_item["plink"] = $link;
3099 $reshared_item["created"] = $posted;
3100 $reshared_item["edited"] = $posted;
3102 return $reshared_item;
3106 function api_get_nick($profile) {
3108 - remove trailing junk from profile url
3109 - pump.io check has to check the website
3114 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3115 dbesc(normalise_link($profile)));
3117 $nick = $r[0]["nick"];
3120 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3121 dbesc(normalise_link($profile)));
3123 $nick = $r[0]["nick"];
3127 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3128 if ($friendica != $profile)
3133 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3134 if ($diaspora != $profile)
3139 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3140 if ($twitter != $profile)
3146 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3147 if ($StatusnetHost != $profile) {
3148 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3149 if ($StatusnetUser != $profile) {
3150 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3151 $user = json_decode($UserData);
3153 $nick = $user->screen_name;
3158 // To-Do: look at the page if its really a pumpio site
3159 //if (!$nick == "") {
3160 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3161 // if ($pumpio != $profile)
3163 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3173 function api_clean_plain_items($Text) {
3174 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3176 $Text = bb_CleanPictureLinks($Text);
3177 $URLSearchString = "^\[\]";
3179 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3181 if ($include_entities == "true") {
3182 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3185 // Simplify "attachment" element
3186 $Text = api_clean_attachments($Text);
3192 * @brief Removes most sharing information for API text export
3194 * @param string $body The original body
3196 * @return string Cleaned body
3198 function api_clean_attachments($body) {
3199 $data = get_attachment_data($body);
3206 if (isset($data["text"]))
3207 $body = $data["text"];
3209 if (($body == "") AND (isset($data["title"])))
3210 $body = $data["title"];
3212 if (isset($data["url"]))
3213 $body .= "\n".$data["url"];
3215 $body .= $data["after"];
3220 function api_best_nickname(&$contacts) {
3221 $best_contact = array();
3223 if (count($contact) == 0)
3226 foreach ($contacts AS $contact)
3227 if ($contact["network"] == "") {
3228 $contact["network"] = "dfrn";
3229 $best_contact = array($contact);
3232 if (sizeof($best_contact) == 0)
3233 foreach ($contacts AS $contact)
3234 if ($contact["network"] == "dfrn")
3235 $best_contact = array($contact);
3237 if (sizeof($best_contact) == 0)
3238 foreach ($contacts AS $contact)
3239 if ($contact["network"] == "dspr")
3240 $best_contact = array($contact);
3242 if (sizeof($best_contact) == 0)
3243 foreach ($contacts AS $contact)
3244 if ($contact["network"] == "stat")
3245 $best_contact = array($contact);
3247 if (sizeof($best_contact) == 0)
3248 foreach ($contacts AS $contact)
3249 if ($contact["network"] == "pump")
3250 $best_contact = array($contact);
3252 if (sizeof($best_contact) == 0)
3253 foreach ($contacts AS $contact)
3254 if ($contact["network"] == "twit")
3255 $best_contact = array($contact);
3257 if (sizeof($best_contact) == 1)
3258 $contacts = $best_contact;
3260 $contacts = array($contacts[0]);
3263 // return all or a specified group of the user with the containing contacts
3264 function api_friendica_group_show(&$a, $type) {
3265 if (api_user()===false) throw new ForbiddenException();
3268 $user_info = api_get_user($a);
3269 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3270 $uid = $user_info['uid'];
3272 // get data of the specified group id or all groups if not specified
3274 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3277 // error message if specified gid is not in database
3279 throw new BadRequestException("gid not available");
3282 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3285 // loop through all groups and retrieve all members for adding data in the user array
3286 foreach ($r as $rr) {
3287 $members = group_get_members($rr['id']);
3290 if ($type == "xml") {
3291 $user_element = "users";
3293 foreach ($members as $member) {
3294 $user = api_get_user($a, $member['nurl']);
3295 $users[$k++.":user"] = $user;
3298 $user_element = "user";
3299 foreach ($members as $member) {
3300 $user = api_get_user($a, $member['nurl']);
3304 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3306 return api_format_data("groups", $type, array('group' => $grps));
3308 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3311 // delete the specified group of the user
3312 function api_friendica_group_delete(&$a, $type) {
3313 if (api_user()===false) throw new ForbiddenException();
3316 $user_info = api_get_user($a);
3317 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3318 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3319 $uid = $user_info['uid'];
3321 // error if no gid specified
3322 if ($gid == 0 || $name == "")
3323 throw new BadRequestException('gid or name not specified');
3325 // get data of the specified group id
3326 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3329 // error message if specified gid is not in database
3331 throw new BadRequestException('gid not available');
3333 // get data of the specified group id and group name
3334 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3338 // error message if specified gid is not in database
3339 if (count($rname) == 0)
3340 throw new BadRequestException('wrong group name');
3343 $ret = group_rmv($uid, $name);
3346 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3347 return api_format_data("group_delete", $type, array('result' => $success));
3350 throw new BadRequestException('other API error');
3352 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3355 // create the specified group with the posted array of contacts
3356 function api_friendica_group_create(&$a, $type) {
3357 if (api_user()===false) throw new ForbiddenException();
3360 $user_info = api_get_user($a);
3361 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3362 $uid = $user_info['uid'];
3363 $json = json_decode($_POST['json'], true);
3364 $users = $json['user'];
3366 // error if no name specified
3368 throw new BadRequestException('group name not specified');
3370 // get data of the specified group name
3371 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3374 // error message if specified group name already exists
3375 if (count($rname) != 0)
3376 throw new BadRequestException('group name already exists');
3378 // check if specified group name is a deleted group
3379 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3382 // error message if specified group name already exists
3383 if (count($rname) != 0)
3384 $reactivate_group = true;
3387 $ret = group_add($uid, $name);
3389 $gid = group_byname($uid, $name);
3391 throw new BadRequestException('other API error');
3394 $erroraddinguser = false;
3395 $errorusers = array();
3396 foreach ($users as $user) {
3397 $cid = $user['cid'];
3398 // check if user really exists as contact
3399 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3402 if (count($contact))
3403 $result = group_add_member($uid, $name, $cid, $gid);
3405 $erroraddinguser = true;
3406 $errorusers[] = $cid;
3410 // return success message incl. missing users in array
3411 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3412 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3413 return api_format_data("group_create", $type, array('result' => $success));
3415 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3418 // update the specified group with the posted array of contacts
3419 function api_friendica_group_update(&$a, $type) {
3420 if (api_user()===false) throw new ForbiddenException();
3423 $user_info = api_get_user($a);
3424 $uid = $user_info['uid'];
3425 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3426 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3427 $json = json_decode($_POST['json'], true);
3428 $users = $json['user'];
3430 // error if no name specified
3432 throw new BadRequestException('group name not specified');
3434 // error if no gid specified
3436 throw new BadRequestException('gid not specified');
3439 $members = group_get_members($gid);
3440 foreach ($members as $member) {
3441 $cid = $member['id'];
3442 foreach ($users as $user) {
3443 $found = ($user['cid'] == $cid ? true : false);
3446 $ret = group_rmv_member($uid, $name, $cid);
3451 $erroraddinguser = false;
3452 $errorusers = array();
3453 foreach ($users as $user) {
3454 $cid = $user['cid'];
3455 // check if user really exists as contact
3456 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3459 if (count($contact))
3460 $result = group_add_member($uid, $name, $cid, $gid);
3462 $erroraddinguser = true;
3463 $errorusers[] = $cid;
3467 // return success message incl. missing users in array
3468 $status = ($erroraddinguser ? "missing user" : "ok");
3469 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3470 return api_format_data("group_update", $type, array('result' => $success));
3472 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3475 function api_friendica_activity(&$a, $type) {
3476 if (api_user()===false) throw new ForbiddenException();
3477 $verb = strtolower($a->argv[3]);
3478 $verb = preg_replace("|\..*$|", "", $verb);
3480 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3482 $res = do_like($id, $verb);
3489 return api_format_data('ok', $type, array('ok' => $ok));
3491 throw new BadRequestException('Error adding activity');
3495 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3496 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3497 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3498 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3499 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3500 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3501 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3502 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3503 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3504 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3507 * @brief Returns notifications
3510 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3513 function api_friendica_notification(&$a, $type) {
3514 if (api_user()===false) throw new ForbiddenException();
3515 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3516 $nm = new NotificationsManager();
3518 $notes = $nm->getAll(array(), "+seen -date", 50);
3520 if ($type == "xml") {
3521 $xmlnotes = array();
3522 foreach ($notes AS $note)
3523 $xmlnotes[] = array("@attributes" => $note);
3528 return api_format_data("notes", $type, array('note' => $notes));
3532 * @brief Set notification as seen and returns associated item (if possible)
3534 * POST request with 'id' param as notification id
3537 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3540 function api_friendica_notification_seen(&$a, $type){
3541 if (api_user()===false) throw new ForbiddenException();
3542 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3544 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3546 $nm = new NotificationsManager();
3547 $note = $nm->getByID($id);
3548 if (is_null($note)) throw new BadRequestException("Invalid argument");
3550 $nm->setSeen($note);
3551 if ($note['otype']=='item') {
3552 // would be really better with an ItemsManager and $im->getByID() :-P
3553 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3554 intval($note['iid']),
3555 intval(local_user())
3558 // we found the item, return it to the user
3559 $user_info = api_get_user($a);
3560 $ret = api_format_items($r,$user_info, false, $type);
3561 $data = array('status' => $ret);
3562 return api_format_data("status", $type, $data);
3564 // the item can't be found, but we set the note as seen, so we count this as a success
3566 return api_format_data('result', $type, array('result' => "success"));
3569 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3570 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3575 [pagename] => api/1.1/statuses/lookup.json
3576 [id] => 605138389168451584
3577 [include_cards] => true
3578 [cards_platform] => Android-12
3579 [include_entities] => true
3580 [include_my_retweet] => 1
3582 [include_reply_count] => true
3583 [include_descendent_reply_count] => true
3587 Not implemented by now:
3588 statuses/retweets_of_me
3593 account/update_location
3594 account/update_profile_background_image
3595 account/update_profile_image
3599 Not implemented in status.net:
3600 statuses/retweeted_to_me
3601 statuses/retweeted_by_me
3602 direct_messages/destroy
3604 account/update_delivery_device
3605 notifications/follow