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 NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` 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);
225 $_SESSION["allow_api"] = true;
227 call_hooks('logged_in', $a->user);
232 * @brief Check HTTP method of called API
234 * API endpoints can define which HTTP method to accept when called.
235 * This function check the current HTTP method agains endpoint
238 * @param string $method Required methods, uppercase, separated by comma
241 function api_check_method($method) {
242 if ($method=="*") return True;
243 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
247 * @brief Main API entry point
249 * Authenticate user, call registered API function, set HTTP headers
252 * @return string API call result
254 function api_call(&$a){
255 GLOBAL $API, $called_api;
258 if (strpos($a->query_string, ".xml")>0) $type="xml";
259 if (strpos($a->query_string, ".json")>0) $type="json";
260 if (strpos($a->query_string, ".rss")>0) $type="rss";
261 if (strpos($a->query_string, ".atom")>0) $type="atom";
263 foreach ($API as $p=>$info){
264 if (strpos($a->query_string, $p)===0){
265 if (!api_check_method($info['method'])){
266 throw new MethodNotAllowedException();
269 $called_api= explode("/",$p);
270 //unset($_SERVER['PHP_AUTH_USER']);
271 if ($info['auth']===true && api_user()===false) {
275 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
276 logger('API parameters: ' . print_r($_REQUEST,true));
278 $stamp = microtime(true);
279 $r = call_user_func($info['func'], $a, $type);
280 $duration = (float)(microtime(true)-$stamp);
281 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
284 // api function returned false withour throw an
285 // exception. This should not happend, throw a 500
286 throw new InternalServerErrorException();
291 header ("Content-Type: text/xml");
295 header ("Content-Type: application/json");
297 $json = json_encode($rr);
298 if ($_GET['callback'])
299 $json = $_GET['callback']."(".$json.")";
303 header ("Content-Type: application/rss+xml");
304 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
307 header ("Content-Type: application/atom+xml");
308 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
314 throw new NotImplementedException();
315 } catch (HTTPException $e) {
316 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
317 return api_error($a, $type, $e);
322 * @brief Format API error string
325 * @param string $type Return type (xml, json, rss, as)
326 * @param HTTPException $error Error object
327 * @return strin error message formatted as $type
329 function api_error(&$a, $type, $e) {
330 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
331 # TODO: https://dev.twitter.com/overview/api/response-codes
333 $error = array("error" => $error,
334 "code" => $e->httpcode." ".$e->httpdesc,
335 "request" => $a->query_string);
337 $ret = api_format_data('status', $type, array('status' => $error));
341 header ("Content-Type: text/xml");
345 header ("Content-Type: application/json");
346 return json_encode($ret);
349 header ("Content-Type: application/rss+xml");
353 header ("Content-Type: application/atom+xml");
360 * @brief Set values for RSS template
363 * @param array $arr Array to be passed to template
364 * @param array $user_info
367 function api_rss_extra(&$a, $arr, $user_info){
368 if (is_null($user_info)) $user_info = api_get_user($a);
369 $arr['$user'] = $user_info;
370 $arr['$rss'] = array(
371 'alternate' => $user_info['url'],
372 'self' => $a->get_baseurl(). "/". $a->query_string,
373 'base' => $a->get_baseurl(),
374 'updated' => api_date(null),
375 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
376 'language' => $user_info['language'],
377 'logo' => $a->get_baseurl()."/images/friendica-32.png",
385 * @brief Unique contact to contact url.
387 * @param int $id Contact id
388 * @return bool|string
389 * Contact url or False if contact id is unknown
391 function api_unique_id_to_url($id){
392 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
395 return ($r[0]["url"]);
401 * @brief Get user info array.
404 * @param int|string $contact_id Contact ID or URL
405 * @param string $type Return type (for errors)
407 function api_get_user(&$a, $contact_id = Null, $type = "json"){
414 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
416 // Searching for contact URL
417 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
418 $user = dbesc(normalise_link($contact_id));
420 $extra_query = "AND `contact`.`nurl` = '%s' ";
421 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
424 // Searching for unique contact id
425 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
426 $user = dbesc(api_unique_id_to_url($contact_id));
429 throw new BadRequestException("User not found.");
432 $extra_query = "AND `contact`.`nurl` = '%s' ";
433 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
436 if(is_null($user) && x($_GET, 'user_id')) {
437 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
440 throw new BadRequestException("User not found.");
443 $extra_query = "AND `contact`.`nurl` = '%s' ";
444 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
446 if(is_null($user) && x($_GET, 'screen_name')) {
447 $user = dbesc($_GET['screen_name']);
449 $extra_query = "AND `contact`.`nick` = '%s' ";
450 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
453 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
454 $argid = count($called_api);
455 list($user, $null) = explode(".",$a->argv[$argid]);
456 if(is_numeric($user)){
457 $user = dbesc(api_unique_id_to_url($user));
463 $extra_query = "AND `contact`.`nurl` = '%s' ";
464 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
466 $user = dbesc($user);
468 $extra_query = "AND `contact`.`nick` = '%s' ";
469 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
473 logger("api_get_user: user ".$user, LOGGER_DEBUG);
476 if (api_user()===false) {
480 $user = $_SESSION['uid'];
481 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
486 logger('api_user: ' . $extra_query . ', user: ' . $user);
488 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
494 // Selecting the id by priority, friendica first
495 api_best_nickname($uinfo);
497 // if the contact wasn't found, fetch it from the unique contacts
498 if (count($uinfo)==0) {
502 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
505 // If no nick where given, extract it from the address
506 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
507 $r[0]['nick'] = api_get_nick($r[0]["url"]);
511 'id_str' => (string) $r[0]["id"],
512 'name' => $r[0]["name"],
513 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
514 'location' => $r[0]["location"],
515 'description' => $r[0]["about"],
516 'url' => $r[0]["url"],
517 'protected' => false,
518 'followers_count' => 0,
519 'friends_count' => 0,
521 'created_at' => api_date($r[0]["created"]),
522 'favourites_count' => 0,
524 'time_zone' => 'UTC',
525 'geo_enabled' => false,
527 'statuses_count' => 0,
529 'contributors_enabled' => false,
530 'is_translator' => false,
531 'is_translation_enabled' => false,
532 'profile_image_url' => $r[0]["photo"],
533 'profile_image_url_https' => $r[0]["photo"],
534 'following' => false,
535 'follow_request_sent' => false,
536 'notifications' => false,
537 'statusnet_blocking' => false,
538 'notifications' => false,
539 'statusnet_profile_url' => $r[0]["url"],
541 'cid' => get_contact($r[0]["url"], api_user()),
543 'network' => $r[0]["network"],
548 throw new BadRequestException("User not found.");
552 if($uinfo[0]['self']) {
554 if ($uinfo[0]['network'] == "")
555 $uinfo[0]['network'] = NETWORK_DFRN;
557 $usr = q("select * from user where uid = %d limit 1",
560 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
564 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
565 // count public wall messages
566 $r = q("SELECT count(*) as `count` FROM `item`
569 intval($uinfo[0]['uid'])
571 $countitms = $r[0]['count'];
574 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
575 $r = q("SELECT count(*) as `count` FROM `item`
576 WHERE `contact-id` = %d",
577 intval($uinfo[0]['id'])
579 $countitms = $r[0]['count'];
583 $r = q("SELECT count(*) as `count` FROM `contact`
584 WHERE `uid` = %d AND `rel` IN ( %d, %d )
585 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
586 intval($uinfo[0]['uid']),
587 intval(CONTACT_IS_SHARING),
588 intval(CONTACT_IS_FRIEND)
590 $countfriends = $r[0]['count'];
592 $r = q("SELECT count(*) as `count` FROM `contact`
593 WHERE `uid` = %d AND `rel` IN ( %d, %d )
594 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
595 intval($uinfo[0]['uid']),
596 intval(CONTACT_IS_FOLLOWER),
597 intval(CONTACT_IS_FRIEND)
599 $countfollowers = $r[0]['count'];
601 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
602 intval($uinfo[0]['uid'])
604 $starred = $r[0]['count'];
607 if(! $uinfo[0]['self']) {
613 // Add a nick if it isn't present there
614 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
615 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
618 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
620 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
621 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
624 'id' => intval($gcontact_id),
625 'id_str' => (string) intval($gcontact_id),
626 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
627 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
628 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
629 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
630 'profile_image_url' => $uinfo[0]['micro'],
631 'profile_image_url_https' => $uinfo[0]['micro'],
632 'url' => $uinfo[0]['url'],
633 'protected' => false,
634 'followers_count' => intval($countfollowers),
635 'friends_count' => intval($countfriends),
636 'created_at' => api_date($uinfo[0]['created']),
637 'favourites_count' => intval($starred),
639 'time_zone' => 'UTC',
640 'statuses_count' => intval($countitms),
641 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
643 'statusnet_blocking' => false,
644 'notifications' => false,
645 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
646 'statusnet_profile_url' => $uinfo[0]['url'],
647 'uid' => intval($uinfo[0]['uid']),
648 'cid' => intval($uinfo[0]['cid']),
649 'self' => $uinfo[0]['self'],
650 'network' => $uinfo[0]['network'],
658 * @brief return api-formatted array for item's author and owner
661 * @param array $item : item from db
662 * @return array(array:author, array:owner)
664 function api_item_get_user(&$a, $item) {
666 // Make sure that there is an entry in the global contacts for author and owner
667 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
668 "photo" => $item['author-avatar'], "name" => $item['author-name']));
670 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
671 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
673 $status_user = api_get_user($a,$item["author-link"]);
674 $status_user["protected"] = (($item["allow_cid"] != "") OR
675 ($item["allow_gid"] != "") OR
676 ($item["deny_cid"] != "") OR
677 ($item["deny_gid"] != "") OR
680 $owner_user = api_get_user($a,$item["owner-link"]);
682 return (array($status_user, $owner_user));
686 * @brief walks recursively through an array with the possibility to change value and key
688 * @param array $array The array to walk through
689 * @param string $callback The callback function
691 * @return array the transformed array
693 function api_walk_recursive(array &$array, callable $callback) {
695 $new_array = array();
697 foreach ($array as $k => $v) {
699 if ($callback($v, $k))
700 $new_array[$k] = api_walk_recursive($v, $callback);
702 if ($callback($v, $k))
712 * @brief Callback function to transform the array in an array that can be transformed in a XML file
714 * @param variant $item Array item value
715 * @param string $key Array key
717 * @return boolean Should the array item be deleted?
719 function api_reformat_xml(&$item, &$key) {
721 $item = ($item ? "true" : "false");
723 if (substr($key, 0, 10) == "statusnet_")
724 $key = "statusnet:".substr($key, 10);
725 elseif (substr($key, 0, 10) == "friendica_")
726 $key = "friendica:".substr($key, 10);
728 // $key = "default:".$key;
734 * @brief Creates the XML from a JSON style array
736 * @param array $data JSON style array
737 * @param string $root_element Name of the root element
739 * @return string The XML data
741 function api_create_xml($data, $root_element) {
742 $childname = key($data);
743 $data2 = array_pop($data);
746 $namespaces = array("" => "http://api.twitter.com",
747 "statusnet" => "http://status.net/schema/api/1/",
748 "friendica" => "http://friendi.ca/schema/api/1/",
749 "georss" => "http://www.georss.org/georss");
751 /// @todo Auto detection of needed namespaces
752 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
753 $namespaces = array();
755 if (is_array($data2))
756 api_walk_recursive($data2, "api_reformat_xml");
762 foreach ($data2 AS $item)
763 $data4[$i++.":".$childname] = $item;
768 $data3 = array($root_element => $data2);
769 $ret = xml::from_array($data3, $xml, false, $namespaces);
774 * @brief Formats the data according to the data type
776 * @param string $root_element Name of the root element
777 * @param string $type Return type (atom, rss, xml, json)
778 * @param array $data JSON style array
780 * @return (string|object) XML data or JSON data
782 function api_format_data($root_element, $type, $data){
790 $ret = api_create_xml($data, $root_element);
805 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
806 * returns a 401 status code and an error message if not.
807 * http://developer.twitter.com/doc/get/account/verify_credentials
809 function api_account_verify_credentials(&$a, $type){
810 if (api_user()===false) throw new ForbiddenException();
812 unset($_REQUEST["user_id"]);
813 unset($_GET["user_id"]);
815 unset($_REQUEST["screen_name"]);
816 unset($_GET["screen_name"]);
818 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
820 $user_info = api_get_user($a);
822 // "verified" isn't used here in the standard
823 unset($user_info["verified"]);
825 // - Adding last status
827 $user_info["status"] = api_status_show($a,"raw");
828 if (!count($user_info["status"]))
829 unset($user_info["status"]);
831 unset($user_info["status"]["user"]);
834 // "uid" and "self" are only needed for some internal stuff, so remove it from here
835 unset($user_info["uid"]);
836 unset($user_info["self"]);
838 return api_format_data("user", $type, array('user' => $user_info));
841 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
845 * get data from $_POST or $_GET
847 function requestdata($k){
848 if (isset($_POST[$k])){
851 if (isset($_GET[$k])){
857 /*Waitman Gobble Mod*/
858 function api_statuses_mediap(&$a, $type) {
859 if (api_user()===false) {
860 logger('api_statuses_update: no user');
861 throw new ForbiddenException();
863 $user_info = api_get_user($a);
865 $_REQUEST['type'] = 'wall';
866 $_REQUEST['profile_uid'] = api_user();
867 $_REQUEST['api_source'] = true;
868 $txt = requestdata('status');
869 //$txt = urldecode(requestdata('status'));
871 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
873 $txt = html2bb_video($txt);
874 $config = HTMLPurifier_Config::createDefault();
875 $config->set('Cache.DefinitionImpl', null);
876 $purifier = new HTMLPurifier($config);
877 $txt = $purifier->purify($txt);
879 $txt = html2bbcode($txt);
881 $a->argv[1]=$user_info['screen_name']; //should be set to username?
883 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
884 $bebop = wall_upload_post($a);
886 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
887 $_REQUEST['body']=$txt."\n\n".$bebop;
890 // this should output the last post (the one we just posted).
891 return api_status_show($a,$type);
893 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
894 /*Waitman Gobble Mod*/
897 function api_statuses_update(&$a, $type) {
898 if (api_user()===false) {
899 logger('api_statuses_update: no user');
900 throw new ForbiddenException();
903 $user_info = api_get_user($a);
905 // convert $_POST array items to the form we use for web posts.
907 // logger('api_post: ' . print_r($_POST,true));
909 if(requestdata('htmlstatus')) {
910 $txt = requestdata('htmlstatus');
911 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
912 $txt = html2bb_video($txt);
914 $config = HTMLPurifier_Config::createDefault();
915 $config->set('Cache.DefinitionImpl', null);
917 $purifier = new HTMLPurifier($config);
918 $txt = $purifier->purify($txt);
920 $_REQUEST['body'] = html2bbcode($txt);
924 $_REQUEST['body'] = requestdata('status');
926 $_REQUEST['title'] = requestdata('title');
928 $parent = requestdata('in_reply_to_status_id');
930 // Twidere sends "-1" if it is no reply ...
934 if(ctype_digit($parent))
935 $_REQUEST['parent'] = $parent;
937 $_REQUEST['parent_uri'] = $parent;
939 if(requestdata('lat') && requestdata('long'))
940 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
941 $_REQUEST['profile_uid'] = api_user();
944 $_REQUEST['type'] = 'net-comment';
946 // Check for throttling (maximum posts per day, week and month)
947 $throttle_day = get_config('system','throttle_limit_day');
948 if ($throttle_day > 0) {
949 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
951 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
952 AND `created` > '%s' AND `id` = `parent`",
953 intval(api_user()), dbesc($datefrom));
956 $posts_day = $r[0]["posts_day"];
960 if ($posts_day > $throttle_day) {
961 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
962 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
963 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
967 $throttle_week = get_config('system','throttle_limit_week');
968 if ($throttle_week > 0) {
969 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
971 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
972 AND `created` > '%s' AND `id` = `parent`",
973 intval(api_user()), dbesc($datefrom));
976 $posts_week = $r[0]["posts_week"];
980 if ($posts_week > $throttle_week) {
981 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
982 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
983 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
988 $throttle_month = get_config('system','throttle_limit_month');
989 if ($throttle_month > 0) {
990 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
992 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
993 AND `created` > '%s' AND `id` = `parent`",
994 intval(api_user()), dbesc($datefrom));
997 $posts_month = $r[0]["posts_month"];
1001 if ($posts_month > $throttle_month) {
1002 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1003 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1004 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1008 $_REQUEST['type'] = 'wall';
1011 if(x($_FILES,'media')) {
1012 // upload the image if we have one
1013 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1014 $media = wall_upload_post($a);
1015 if(strlen($media)>0)
1016 $_REQUEST['body'] .= "\n\n".$media;
1019 // To-Do: Multiple IDs
1020 if (requestdata('media_ids')) {
1021 $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",
1022 intval(requestdata('media_ids')), api_user());
1024 $phototypes = Photo::supportedTypes();
1025 $ext = $phototypes[$r[0]['type']];
1026 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1027 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1031 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1033 $_REQUEST['api_source'] = true;
1035 if (!x($_REQUEST, "source"))
1036 $_REQUEST["source"] = api_source();
1038 // call out normal post function
1042 // this should output the last post (the one we just posted).
1043 return api_status_show($a,$type);
1045 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1046 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1049 function api_media_upload(&$a, $type) {
1050 if (api_user()===false) {
1052 throw new ForbiddenException();
1055 $user_info = api_get_user($a);
1057 if(!x($_FILES,'media')) {
1059 throw new BadRequestException("No media.");
1062 $media = wall_upload_post($a, false);
1065 throw new InternalServerErrorException();
1068 $returndata = array();
1069 $returndata["media_id"] = $media["id"];
1070 $returndata["media_id_string"] = (string)$media["id"];
1071 $returndata["size"] = $media["size"];
1072 $returndata["image"] = array("w" => $media["width"],
1073 "h" => $media["height"],
1074 "image_type" => $media["type"]);
1076 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1078 return array("media" => $returndata);
1080 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1082 function api_status_show(&$a, $type){
1083 $user_info = api_get_user($a);
1085 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1088 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1092 // get last public wall message
1093 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1094 FROM `item`, `item` as `i`
1095 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1096 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1097 AND `i`.`id` = `item`.`parent`
1098 AND `item`.`type`!='activity' $privacy_sql
1099 ORDER BY `item`.`id` DESC
1101 intval($user_info['cid']),
1103 dbesc($user_info['url']),
1104 dbesc(normalise_link($user_info['url'])),
1105 dbesc($user_info['url']),
1106 dbesc(normalise_link($user_info['url']))
1109 if (count($lastwall)>0){
1110 $lastwall = $lastwall[0];
1112 $in_reply_to_status_id = NULL;
1113 $in_reply_to_user_id = NULL;
1114 $in_reply_to_status_id_str = NULL;
1115 $in_reply_to_user_id_str = NULL;
1116 $in_reply_to_screen_name = NULL;
1117 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1118 $in_reply_to_status_id= intval($lastwall['parent']);
1119 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1121 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1123 if ($r[0]['nick'] == "")
1124 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1126 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1127 $in_reply_to_user_id = intval($r[0]['id']);
1128 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1132 // There seems to be situation, where both fields are identical:
1133 // https://github.com/friendica/friendica/issues/1010
1134 // This is a bugfix for that.
1135 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1136 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1137 $in_reply_to_status_id = NULL;
1138 $in_reply_to_user_id = NULL;
1139 $in_reply_to_status_id_str = NULL;
1140 $in_reply_to_user_id_str = NULL;
1141 $in_reply_to_screen_name = NULL;
1144 $converted = api_convert_item($lastwall);
1147 $geo = "georss:point";
1151 $status_info = array(
1152 'created_at' => api_date($lastwall['created']),
1153 'id' => intval($lastwall['id']),
1154 'id_str' => (string) $lastwall['id'],
1155 'text' => $converted["text"],
1156 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1157 'truncated' => false,
1158 'in_reply_to_status_id' => $in_reply_to_status_id,
1159 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1160 'in_reply_to_user_id' => $in_reply_to_user_id,
1161 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1162 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1163 'user' => $user_info,
1165 'coordinates' => "",
1167 'contributors' => "",
1168 'is_quote_status' => false,
1169 'retweet_count' => 0,
1170 'favorite_count' => 0,
1171 'favorited' => $lastwall['starred'] ? true : false,
1172 'retweeted' => false,
1173 'possibly_sensitive' => false,
1175 'statusnet_html' => $converted["html"],
1176 'statusnet_conversation_id' => $lastwall['parent'],
1179 if (count($converted["attachments"]) > 0)
1180 $status_info["attachments"] = $converted["attachments"];
1182 if (count($converted["entities"]) > 0)
1183 $status_info["entities"] = $converted["entities"];
1185 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1186 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1187 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1188 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1190 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1191 unset($status_info["user"]["uid"]);
1192 unset($status_info["user"]["self"]);
1195 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1198 return($status_info);
1200 return api_format_data("statuses", $type, array('status' => $status_info));
1209 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1210 * The author's most recent status will be returned inline.
1211 * http://developer.twitter.com/doc/get/users/show
1213 function api_users_show(&$a, $type){
1214 $user_info = api_get_user($a);
1215 $lastwall = q("SELECT `item`.*
1217 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1218 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1219 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1220 AND `type`!='activity'
1221 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1225 dbesc(ACTIVITY_POST),
1226 intval($user_info['cid']),
1227 dbesc($user_info['url']),
1228 dbesc(normalise_link($user_info['url'])),
1229 dbesc($user_info['url']),
1230 dbesc(normalise_link($user_info['url']))
1233 if (count($lastwall)>0){
1234 $lastwall = $lastwall[0];
1236 $in_reply_to_status_id = NULL;
1237 $in_reply_to_user_id = NULL;
1238 $in_reply_to_status_id_str = NULL;
1239 $in_reply_to_user_id_str = NULL;
1240 $in_reply_to_screen_name = NULL;
1241 if ($lastwall['parent']!=$lastwall['id']) {
1242 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1243 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1244 if (count($reply)>0) {
1245 $in_reply_to_status_id = intval($lastwall['parent']);
1246 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1248 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1250 if ($r[0]['nick'] == "")
1251 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1253 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1254 $in_reply_to_user_id = intval($r[0]['id']);
1255 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1260 $converted = api_convert_item($lastwall);
1263 $geo = "georss:point";
1267 $user_info['status'] = array(
1268 'text' => $converted["text"],
1269 'truncated' => false,
1270 'created_at' => api_date($lastwall['created']),
1271 'in_reply_to_status_id' => $in_reply_to_status_id,
1272 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1273 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1274 'id' => intval($lastwall['contact-id']),
1275 'id_str' => (string) $lastwall['contact-id'],
1276 'in_reply_to_user_id' => $in_reply_to_user_id,
1277 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1278 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1280 'favorited' => $lastwall['starred'] ? true : false,
1281 'statusnet_html' => $converted["html"],
1282 'statusnet_conversation_id' => $lastwall['parent'],
1285 if (count($converted["attachments"]) > 0)
1286 $user_info["status"]["attachments"] = $converted["attachments"];
1288 if (count($converted["entities"]) > 0)
1289 $user_info["status"]["entities"] = $converted["entities"];
1291 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1292 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1293 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1294 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1298 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1299 unset($user_info["uid"]);
1300 unset($user_info["self"]);
1302 return api_format_data("user", $type, array('user' => $user_info));
1305 api_register_func('api/users/show','api_users_show');
1308 function api_users_search(&$a, $type) {
1309 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1311 $userlist = array();
1313 if (isset($_GET["q"])) {
1314 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1316 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1320 foreach ($r AS $user) {
1321 $user_info = api_get_user($a, $user["id"], "json");
1324 $userlist[$k++.":user"] = $user_info;
1326 $userlist[] = $user_info;
1328 $userlist = array("users" => $userlist);
1330 throw new BadRequestException("User not found.");
1333 throw new BadRequestException("User not found.");
1335 return api_format_data("users", $type, $userlist);
1338 api_register_func('api/users/search','api_users_search');
1342 * http://developer.twitter.com/doc/get/statuses/home_timeline
1344 * TODO: Optional parameters
1345 * TODO: Add reply info
1347 function api_statuses_home_timeline(&$a, $type){
1348 if (api_user()===false) throw new ForbiddenException();
1350 unset($_REQUEST["user_id"]);
1351 unset($_GET["user_id"]);
1353 unset($_REQUEST["screen_name"]);
1354 unset($_GET["screen_name"]);
1356 $user_info = api_get_user($a);
1357 // get last newtork messages
1361 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1362 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1363 if ($page<0) $page=0;
1364 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1365 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1366 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1367 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1368 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1370 $start = $page*$count;
1374 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1375 if ($exclude_replies > 0)
1376 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1377 if ($conversation_id > 0)
1378 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1380 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1381 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1382 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1383 `contact`.`id` AS `cid`
1385 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1386 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1387 WHERE `item`.`uid` = %d AND `verb` = '%s'
1388 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1391 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1393 dbesc(ACTIVITY_POST),
1395 intval($start), intval($count)
1398 $ret = api_format_items($r,$user_info, false, $type);
1400 // Set all posts from the query above to seen
1402 foreach ($r AS $item)
1403 $idarray[] = intval($item["id"]);
1405 $idlist = implode(",", $idarray);
1407 if ($idlist != "") {
1408 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1411 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1414 $data = array('status' => $ret);
1418 $data = api_rss_extra($a, $data, $user_info);
1422 return api_format_data("statuses", $type, $data);
1424 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1425 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1427 function api_statuses_public_timeline(&$a, $type){
1428 if (api_user()===false) throw new ForbiddenException();
1430 $user_info = api_get_user($a);
1431 // get last newtork messages
1435 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1436 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1437 if ($page<0) $page=0;
1438 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1439 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1440 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1441 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1442 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1444 $start = $page*$count;
1447 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1448 if ($exclude_replies > 0)
1449 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1450 if ($conversation_id > 0)
1451 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1453 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1454 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1455 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1456 `contact`.`id` AS `cid`,
1457 `user`.`nickname`, `user`.`hidewall`
1459 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1460 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1461 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1462 AND NOT `user`.`hidewall`
1463 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1464 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1465 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1466 AND NOT `item`.`private` AND `item`.`wall`
1469 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1470 dbesc(ACTIVITY_POST),
1475 $ret = api_format_items($r,$user_info, false, $type);
1478 $data = array('status' => $ret);
1482 $data = api_rss_extra($a, $data, $user_info);
1486 return api_format_data("statuses", $type, $data);
1488 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1493 function api_statuses_show(&$a, $type){
1494 if (api_user()===false) throw new ForbiddenException();
1496 $user_info = api_get_user($a);
1499 $id = intval($a->argv[3]);
1502 $id = intval($_REQUEST["id"]);
1506 $id = intval($a->argv[4]);
1508 logger('API: api_statuses_show: '.$id);
1510 $conversation = (x($_REQUEST,'conversation')?1:0);
1514 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1516 $sql_extra .= " AND `item`.`id` = %d";
1518 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1519 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1520 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1521 `contact`.`id` AS `cid`
1523 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1524 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1525 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1526 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1529 dbesc(ACTIVITY_POST),
1534 throw new BadRequestException("There is no status with this id.");
1537 $ret = api_format_items($r,$user_info, false, $type);
1539 if ($conversation) {
1540 $data = array('status' => $ret);
1541 return api_format_data("statuses", $type, $data);
1543 $data = array('status' => $ret[0]);
1544 return api_format_data("status", $type, $data);
1547 api_register_func('api/statuses/show','api_statuses_show', true);
1553 function api_conversation_show(&$a, $type){
1554 if (api_user()===false) throw new ForbiddenException();
1556 $user_info = api_get_user($a);
1559 $id = intval($a->argv[3]);
1560 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1561 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1562 if ($page<0) $page=0;
1563 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1564 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1566 $start = $page*$count;
1569 $id = intval($_REQUEST["id"]);
1573 $id = intval($a->argv[4]);
1575 logger('API: api_conversation_show: '.$id);
1577 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1579 $id = $r[0]["parent"];
1584 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1586 // Not sure why this query was so complicated. We should keep it here for a while,
1587 // just to make sure that we really don't need it.
1588 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1589 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1591 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1592 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1593 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1594 `contact`.`id` AS `cid`
1596 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1597 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1598 WHERE `item`.`parent` = %d AND `item`.`visible`
1599 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1600 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1601 AND `item`.`id`>%d $sql_extra
1602 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1603 intval($id), intval(api_user()),
1604 dbesc(ACTIVITY_POST),
1606 intval($start), intval($count)
1610 throw new BadRequestException("There is no conversation with this id.");
1612 $ret = api_format_items($r,$user_info, false, $type);
1614 $data = array('status' => $ret);
1615 return api_format_data("statuses", $type, $data);
1617 api_register_func('api/conversation/show','api_conversation_show', true);
1618 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1624 function api_statuses_repeat(&$a, $type){
1627 if (api_user()===false) throw new ForbiddenException();
1629 $user_info = api_get_user($a);
1632 $id = intval($a->argv[3]);
1635 $id = intval($_REQUEST["id"]);
1639 $id = intval($a->argv[4]);
1641 logger('API: api_statuses_repeat: '.$id);
1643 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1644 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1645 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1646 `contact`.`id` AS `cid`
1648 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1649 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1650 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1651 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1652 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1654 AND `item`.`id`=%d",
1658 if ($r[0]['body'] != "") {
1659 if (!intval(get_config('system','old_share'))) {
1660 if (strpos($r[0]['body'], "[/share]") !== false) {
1661 $pos = strpos($r[0]['body'], "[share");
1662 $post = substr($r[0]['body'], $pos);
1664 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1666 $post .= $r[0]['body'];
1667 $post .= "[/share]";
1669 $_REQUEST['body'] = $post;
1671 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1673 $_REQUEST['profile_uid'] = api_user();
1674 $_REQUEST['type'] = 'wall';
1675 $_REQUEST['api_source'] = true;
1677 if (!x($_REQUEST, "source"))
1678 $_REQUEST["source"] = api_source();
1682 throw new ForbiddenException();
1684 // this should output the last post (the one we just posted).
1686 return(api_status_show($a,$type));
1688 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1693 function api_statuses_destroy(&$a, $type){
1694 if (api_user()===false) throw new ForbiddenException();
1696 $user_info = api_get_user($a);
1699 $id = intval($a->argv[3]);
1702 $id = intval($_REQUEST["id"]);
1706 $id = intval($a->argv[4]);
1708 logger('API: api_statuses_destroy: '.$id);
1710 $ret = api_statuses_show($a, $type);
1712 drop_item($id, false);
1716 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1720 * http://developer.twitter.com/doc/get/statuses/mentions
1723 function api_statuses_mentions(&$a, $type){
1724 if (api_user()===false) throw new ForbiddenException();
1726 unset($_REQUEST["user_id"]);
1727 unset($_GET["user_id"]);
1729 unset($_REQUEST["screen_name"]);
1730 unset($_GET["screen_name"]);
1732 $user_info = api_get_user($a);
1733 // get last newtork messages
1737 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1738 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1739 if ($page<0) $page=0;
1740 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1741 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1742 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1744 $start = $page*$count;
1746 // Ugly code - should be changed
1747 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1748 $myurl = substr($myurl,strpos($myurl,'://')+3);
1749 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1750 $myurl = str_replace('www.','',$myurl);
1751 $diasp_url = str_replace('/profile/','/u/',$myurl);
1754 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1756 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1757 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1758 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1759 `contact`.`id` AS `cid`
1760 FROM `item` FORCE INDEX (`uid_id`)
1761 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1762 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1763 WHERE `item`.`uid` = %d AND `verb` = '%s'
1764 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1765 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1766 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1769 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1771 dbesc(ACTIVITY_POST),
1772 dbesc(protect_sprintf($myurl)),
1773 dbesc(protect_sprintf($myurl)),
1776 intval($start), intval($count)
1779 $ret = api_format_items($r,$user_info, false, $type);
1782 $data = array('status' => $ret);
1786 $data = api_rss_extra($a, $data, $user_info);
1790 return api_format_data("statuses", $type, $data);
1792 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1793 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1796 function api_statuses_user_timeline(&$a, $type){
1797 if (api_user()===false) throw new ForbiddenException();
1799 $user_info = api_get_user($a);
1800 // get last network messages
1802 logger("api_statuses_user_timeline: api_user: ". api_user() .
1803 "\nuser_info: ".print_r($user_info, true) .
1804 "\n_REQUEST: ".print_r($_REQUEST, true),
1808 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1809 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1810 if ($page<0) $page=0;
1811 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1812 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1813 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1814 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1816 $start = $page*$count;
1819 if ($user_info['self']==1)
1820 $sql_extra .= " AND `item`.`wall` = 1 ";
1822 if ($exclude_replies > 0)
1823 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1824 if ($conversation_id > 0)
1825 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1827 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1828 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1829 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1830 `contact`.`id` AS `cid`
1831 FROM `item` FORCE INDEX (`uid_contactid_id`)
1832 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1833 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1834 WHERE `item`.`uid` = %d AND `verb` = '%s'
1835 AND `item`.`contact-id` = %d
1836 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1839 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1841 dbesc(ACTIVITY_POST),
1842 intval($user_info['cid']),
1844 intval($start), intval($count)
1847 $ret = api_format_items($r,$user_info, true, $type);
1849 $data = array('status' => $ret);
1853 $data = api_rss_extra($a, $data, $user_info);
1856 return api_format_data("statuses", $type, $data);
1858 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1862 * Star/unstar an item
1863 * param: id : id of the item
1865 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1867 function api_favorites_create_destroy(&$a, $type){
1868 if (api_user()===false) throw new ForbiddenException();
1870 // for versioned api.
1871 /// @TODO We need a better global soluton
1873 if ($a->argv[1]=="1.1") $action_argv_id=3;
1875 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1876 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1877 if ($a->argc==$action_argv_id+2) {
1878 $itemid = intval($a->argv[$action_argv_id+1]);
1880 $itemid = intval($_REQUEST['id']);
1883 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1884 $itemid, api_user());
1886 if ($item===false || count($item)==0)
1887 throw new BadRequestException("Invalid item.");
1891 $item[0]['starred']=1;
1894 $item[0]['starred']=0;
1897 throw new BadRequestException("Invalid action ".$action);
1899 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1900 $item[0]['starred'], $itemid, api_user());
1902 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1903 $item[0]['starred'], $itemid, api_user());
1906 throw InternalServerErrorException("DB error");
1909 $user_info = api_get_user($a);
1910 $rets = api_format_items($item,$user_info, false, $type);
1913 $data = array('status' => $ret);
1917 $data = api_rss_extra($a, $data, $user_info);
1920 return api_format_data("status", $type, $data);
1922 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1923 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1925 function api_favorites(&$a, $type){
1928 if (api_user()===false) throw new ForbiddenException();
1930 $called_api= array();
1932 $user_info = api_get_user($a);
1934 // in friendica starred item are private
1935 // return favorites only for self
1936 logger('api_favorites: self:' . $user_info['self']);
1938 if ($user_info['self']==0) {
1944 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1945 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1946 $count = (x($_GET,'count')?$_GET['count']:20);
1947 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1948 if ($page<0) $page=0;
1950 $start = $page*$count;
1953 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1955 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1956 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1957 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1958 `contact`.`id` AS `cid`
1959 FROM `item`, `contact`
1960 WHERE `item`.`uid` = %d
1961 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1962 AND `item`.`starred` = 1
1963 AND `contact`.`id` = `item`.`contact-id`
1964 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1967 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1970 intval($start), intval($count)
1973 $ret = api_format_items($r,$user_info, false, $type);
1977 $data = array('status' => $ret);
1981 $data = api_rss_extra($a, $data, $user_info);
1984 return api_format_data("statuses", $type, $data);
1986 api_register_func('api/favorites','api_favorites', true);
1988 function api_format_messages($item, $recipient, $sender) {
1989 // standard meta information
1991 'id' => $item['id'],
1992 'sender_id' => $sender['id'] ,
1994 'recipient_id' => $recipient['id'],
1995 'created_at' => api_date($item['created']),
1996 'sender_screen_name' => $sender['screen_name'],
1997 'recipient_screen_name' => $recipient['screen_name'],
1998 'sender' => $sender,
1999 'recipient' => $recipient,
2002 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2003 unset($ret["sender"]["uid"]);
2004 unset($ret["sender"]["self"]);
2005 unset($ret["recipient"]["uid"]);
2006 unset($ret["recipient"]["self"]);
2008 //don't send title to regular StatusNET requests to avoid confusing these apps
2009 if (x($_GET, 'getText')) {
2010 $ret['title'] = $item['title'] ;
2011 if ($_GET["getText"] == "html") {
2012 $ret['text'] = bbcode($item['body'], false, false);
2014 elseif ($_GET["getText"] == "plain") {
2015 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2016 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2020 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2022 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2023 unset($ret['sender']);
2024 unset($ret['recipient']);
2030 function api_convert_item($item) {
2031 $body = $item['body'];
2032 $attachments = api_get_attachments($body);
2034 // Workaround for ostatus messages where the title is identically to the body
2035 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2036 $statusbody = trim(html2plain($html, 0));
2038 // handle data: images
2039 $statusbody = api_format_items_embeded_images($item,$statusbody);
2041 $statustitle = trim($item['title']);
2043 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2044 $statustext = trim($statusbody);
2046 $statustext = trim($statustitle."\n\n".$statusbody);
2048 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2049 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2051 $statushtml = trim(bbcode($body, false, false));
2053 $search = array("<br>", "<blockquote>", "</blockquote>",
2054 "<h1>", "</h1>", "<h2>", "</h2>",
2055 "<h3>", "</h3>", "<h4>", "</h4>",
2056 "<h5>", "</h5>", "<h6>", "</h6>");
2057 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2058 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2059 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2060 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2061 $statushtml = str_replace($search, $replace, $statushtml);
2063 if ($item['title'] != "")
2064 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2066 $entities = api_get_entitities($statustext, $body);
2069 "text" => $statustext,
2070 "html" => $statushtml,
2071 "attachments" => $attachments,
2072 "entities" => $entities
2076 function api_get_attachments(&$body) {
2079 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2081 $URLSearchString = "^\[\]";
2082 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2087 $attachments = array();
2089 foreach ($images[1] AS $image) {
2090 $imagedata = get_photo_info($image);
2093 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2096 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2097 foreach ($images[0] AS $orig)
2098 $body = str_replace($orig, "", $body);
2100 return $attachments;
2103 function api_get_entitities(&$text, $bbcode) {
2106 * Links at the first character of the post
2111 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2113 if ($include_entities != "true") {
2115 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2117 foreach ($images[1] AS $image) {
2118 $replace = proxy_url($image);
2119 $text = str_replace($image, $replace, $text);
2124 $bbcode = bb_CleanPictureLinks($bbcode);
2126 // Change pure links in text to bbcode uris
2127 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2129 $entities = array();
2130 $entities["hashtags"] = array();
2131 $entities["symbols"] = array();
2132 $entities["urls"] = array();
2133 $entities["user_mentions"] = array();
2135 $URLSearchString = "^\[\]";
2137 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2139 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2140 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2141 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2143 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2144 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2145 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2147 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2148 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2149 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2151 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2153 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2154 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2156 $ordered_urls = array();
2157 foreach ($urls[1] AS $id=>$url) {
2158 //$start = strpos($text, $url, $offset);
2159 $start = iconv_strpos($text, $url, 0, "UTF-8");
2160 if (!($start === false))
2161 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2164 ksort($ordered_urls);
2167 //foreach ($urls[1] AS $id=>$url) {
2168 foreach ($ordered_urls AS $url) {
2169 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2170 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2171 $display_url = $url["title"];
2173 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2174 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2176 if (strlen($display_url) > 26)
2177 $display_url = substr($display_url, 0, 25)."…";
2180 //$start = strpos($text, $url, $offset);
2181 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2182 if (!($start === false)) {
2183 $entities["urls"][] = array("url" => $url["url"],
2184 "expanded_url" => $url["url"],
2185 "display_url" => $display_url,
2186 "indices" => array($start, $start+strlen($url["url"])));
2187 $offset = $start + 1;
2191 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2192 $ordered_images = array();
2193 foreach ($images[1] AS $image) {
2194 //$start = strpos($text, $url, $offset);
2195 $start = iconv_strpos($text, $image, 0, "UTF-8");
2196 if (!($start === false))
2197 $ordered_images[$start] = $image;
2199 //$entities["media"] = array();
2202 foreach ($ordered_images AS $url) {
2203 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2204 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2206 if (strlen($display_url) > 26)
2207 $display_url = substr($display_url, 0, 25)."…";
2209 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2210 if (!($start === false)) {
2211 $image = get_photo_info($url);
2213 // If image cache is activated, then use the following sizes:
2214 // thumb (150), small (340), medium (600) and large (1024)
2215 if (!get_config("system", "proxy_disabled")) {
2216 $media_url = proxy_url($url);
2219 $scale = scale_image($image[0], $image[1], 150);
2220 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2222 if (($image[0] > 150) OR ($image[1] > 150)) {
2223 $scale = scale_image($image[0], $image[1], 340);
2224 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2227 $scale = scale_image($image[0], $image[1], 600);
2228 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2230 if (($image[0] > 600) OR ($image[1] > 600)) {
2231 $scale = scale_image($image[0], $image[1], 1024);
2232 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2236 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2239 $entities["media"][] = array(
2241 "id_str" => (string)$start+1,
2242 "indices" => array($start, $start+strlen($url)),
2243 "media_url" => normalise_link($media_url),
2244 "media_url_https" => $media_url,
2246 "display_url" => $display_url,
2247 "expanded_url" => $url,
2251 $offset = $start + 1;
2257 function api_format_items_embeded_images(&$item, $text){
2259 $text = preg_replace_callback(
2260 "|data:image/([^;]+)[^=]+=*|m",
2261 function($match) use ($a, $item) {
2262 return $a->get_baseurl()."/display/".$item['guid'];
2270 * @brief return <a href='url'>name</a> as array
2272 * @param string $txt
2277 function api_contactlink_to_array($txt) {
2279 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2280 if ($r && count($match)==3) {
2282 'name' => $match[2],
2296 * @brief return likes, dislikes and attend status for item
2298 * @param array $item
2300 * likes => int count
2301 * dislikes => int count
2303 function api_format_items_activities(&$item, $type = "json") {
2304 $activities = array(
2306 'dislike' => array(),
2307 'attendyes' => array(),
2308 'attendno' => array(),
2309 'attendmaybe' => array()
2311 $items = q('SELECT * FROM item
2312 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2313 intval($item['uid']),
2314 dbesc($item['uri']));
2315 foreach ($items as $i){
2316 builtin_activity_puller($i, $activities);
2319 if ($type == "xml") {
2320 $xml_activities = array();
2321 foreach ($activities as $k => $v)
2322 $xml_activities["friendica:".$k] = $v;
2324 $activities = $xml_activities;
2328 $uri = $item['uri']."-l";
2329 foreach($activities as $k => $v) {
2330 $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2337 * @brief format items to be returned by api
2339 * @param array $r array of items
2340 * @param array $user_info
2341 * @param bool $filter_user filter items by $user_info
2343 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2348 foreach($r as $item) {
2350 localize_item($item);
2351 list($status_user, $owner_user) = api_item_get_user($a,$item);
2353 // Look if the posts are matching if they should be filtered by user id
2354 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2357 if ($item['thr-parent'] != $item['uri']) {
2358 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2360 dbesc($item['thr-parent']));
2362 $in_reply_to_status_id = intval($r[0]['id']);
2364 $in_reply_to_status_id = intval($item['parent']);
2366 $in_reply_to_status_id_str = (string) intval($item['parent']);
2368 $in_reply_to_screen_name = NULL;
2369 $in_reply_to_user_id = NULL;
2370 $in_reply_to_user_id_str = NULL;
2372 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2374 intval($in_reply_to_status_id));
2376 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2379 if ($r[0]['nick'] == "")
2380 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2382 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2383 $in_reply_to_user_id = intval($r[0]['id']);
2384 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2388 $in_reply_to_screen_name = NULL;
2389 $in_reply_to_user_id = NULL;
2390 $in_reply_to_status_id = NULL;
2391 $in_reply_to_user_id_str = NULL;
2392 $in_reply_to_status_id_str = NULL;
2395 $converted = api_convert_item($item);
2398 $geo = "georss:point";
2403 'text' => $converted["text"],
2404 'truncated' => False,
2405 'created_at'=> api_date($item['created']),
2406 'in_reply_to_status_id' => $in_reply_to_status_id,
2407 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2408 'source' => (($item['app']) ? $item['app'] : 'web'),
2409 'id' => intval($item['id']),
2410 'id_str' => (string) intval($item['id']),
2411 'in_reply_to_user_id' => $in_reply_to_user_id,
2412 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2413 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2415 'favorited' => $item['starred'] ? true : false,
2416 'user' => $status_user ,
2417 'friendica_owner' => $owner_user,
2418 //'entities' => NULL,
2419 'statusnet_html' => $converted["html"],
2420 'statusnet_conversation_id' => $item['parent'],
2421 'friendica_activities' => api_format_items_activities($item, $type),
2424 if (count($converted["attachments"]) > 0)
2425 $status["attachments"] = $converted["attachments"];
2427 if (count($converted["entities"]) > 0)
2428 $status["entities"] = $converted["entities"];
2430 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2431 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2432 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2433 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2436 // Retweets are only valid for top postings
2437 // It doesn't work reliable with the link if its a feed
2438 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2440 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2443 if ($item["id"] == $item["parent"]) {
2444 $retweeted_item = api_share_as_retweet($item);
2445 if ($retweeted_item !== false) {
2446 $retweeted_status = $status;
2448 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2449 } catch( BadRequestException $e ) {
2450 // user not found. should be found?
2451 /// @todo check if the user should be always found
2452 $retweeted_status["user"] = array();
2455 $rt_converted = api_convert_item($retweeted_item);
2457 $retweeted_status['text'] = $rt_converted["text"];
2458 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2459 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2460 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2461 $status['retweeted_status'] = $retweeted_status;
2465 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2466 unset($status["user"]["uid"]);
2467 unset($status["user"]["self"]);
2469 if ($item["coord"] != "") {
2470 $coords = explode(' ',$item["coord"]);
2471 if (count($coords) == 2) {
2472 if ($type == "json")
2473 $status["geo"] = array('type' => 'Point',
2474 'coordinates' => array((float) $coords[0],
2475 (float) $coords[1]));
2476 else // Not sure if this is the official format - if someone founds a documentation we can check
2477 $status["georss:point"] = $item["coord"];
2486 function api_account_rate_limit_status(&$a,$type) {
2490 'remaining-hits' => (string) 150,
2491 '@attributes' => array("type" => "integer"),
2492 'hourly-limit' => (string) 150,
2493 '@attributes2' => array("type" => "integer"),
2494 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2495 '@attributes3' => array("type" => "datetime"),
2496 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2497 '@attributes4' => array("type" => "integer"),
2501 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2502 'remaining_hits' => (string) 150,
2503 'hourly_limit' => (string) 150,
2504 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2507 return api_format_data('hash', $type, array('hash' => $hash));
2509 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2511 function api_help_test(&$a,$type) {
2517 return api_format_data('ok', $type, array("ok" => $ok));
2519 api_register_func('api/help/test','api_help_test',false);
2521 function api_lists(&$a,$type) {
2523 return api_format_data('lists', $type, array("lists_list" => $ret));
2525 api_register_func('api/lists','api_lists',true);
2527 function api_lists_list(&$a,$type) {
2529 return api_format_data('lists', $type, array("lists_list" => $ret));
2531 api_register_func('api/lists/list','api_lists_list',true);
2534 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2535 * This function is deprecated by Twitter
2536 * returns: json, xml
2538 function api_statuses_f(&$a, $type, $qtype) {
2539 if (api_user()===false) throw new ForbiddenException();
2540 $user_info = api_get_user($a);
2542 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2543 /* this is to stop Hotot to load friends multiple times
2544 * I'm not sure if I'm missing return something or
2545 * is a bug in hotot. Workaround, meantime
2549 return array('$users' => $ret);*/
2553 if($qtype == 'friends')
2554 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2555 if($qtype == 'followers')
2556 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2558 // friends and followers only for self
2559 if ($user_info['self'] == 0)
2560 $sql_extra = " AND false ";
2562 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2567 foreach($r as $cid){
2568 $user = api_get_user($a, $cid['nurl']);
2569 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2570 unset($user["uid"]);
2571 unset($user["self"]);
2577 return array('user' => $ret);
2580 function api_statuses_friends(&$a, $type){
2581 $data = api_statuses_f($a,$type,"friends");
2582 if ($data===false) return false;
2583 return api_format_data("users", $type, $data);
2585 function api_statuses_followers(&$a, $type){
2586 $data = api_statuses_f($a,$type,"followers");
2587 if ($data===false) return false;
2588 return api_format_data("users", $type, $data);
2590 api_register_func('api/statuses/friends','api_statuses_friends',true);
2591 api_register_func('api/statuses/followers','api_statuses_followers',true);
2598 function api_statusnet_config(&$a,$type) {
2599 $name = $a->config['sitename'];
2600 $server = $a->get_hostname();
2601 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2602 $email = $a->config['admin_email'];
2603 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2604 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2605 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2606 if($a->config['api_import_size'])
2607 $texlimit = string($a->config['api_import_size']);
2608 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2609 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2612 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2613 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2614 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2615 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2616 'shorturllength' => '30',
2617 'friendica' => array(
2618 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2619 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2620 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2621 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2626 return api_format_data('config', $type, array('config' => $config));
2629 api_register_func('api/statusnet/config','api_statusnet_config',false);
2631 function api_statusnet_version(&$a,$type) {
2633 $fake_statusnet_version = "0.9.7";
2635 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2637 api_register_func('api/statusnet/version','api_statusnet_version',false);
2640 * @todo use api_format_data() to return data
2642 function api_ff_ids(&$a,$type,$qtype) {
2643 if(! api_user()) throw new ForbiddenException();
2645 $user_info = api_get_user($a);
2647 if($qtype == 'friends')
2648 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2649 if($qtype == 'followers')
2650 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2652 if (!$user_info["self"])
2653 $sql_extra = " AND false ";
2655 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2657 $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",
2661 if(!dbm::is_result($r))
2669 $ids[] = intval($rr['id']);
2671 return api_format_data("ids", $type, array('id' => $ids));
2674 function api_friends_ids(&$a,$type) {
2675 return api_ff_ids($a,$type,'friends');
2677 function api_followers_ids(&$a,$type) {
2678 return api_ff_ids($a,$type,'followers');
2680 api_register_func('api/friends/ids','api_friends_ids',true);
2681 api_register_func('api/followers/ids','api_followers_ids',true);
2684 function api_direct_messages_new(&$a, $type) {
2685 if (api_user()===false) throw new ForbiddenException();
2687 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2689 $sender = api_get_user($a);
2691 if ($_POST['screen_name']) {
2692 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2694 dbesc($_POST['screen_name']));
2696 // Selecting the id by priority, friendica first
2697 api_best_nickname($r);
2699 $recipient = api_get_user($a, $r[0]['nurl']);
2701 $recipient = api_get_user($a, $_POST['user_id']);
2705 if (x($_REQUEST,'replyto')) {
2706 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2708 intval($_REQUEST['replyto']));
2709 $replyto = $r[0]['parent-uri'];
2710 $sub = $r[0]['title'];
2713 if (x($_REQUEST,'title')) {
2714 $sub = $_REQUEST['title'];
2717 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2721 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2724 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2725 $ret = api_format_messages($r[0], $recipient, $sender);
2728 $ret = array("error"=>$id);
2731 $data = Array('direct_message'=>$ret);
2736 $data = api_rss_extra($a, $data, $user_info);
2739 return api_format_data("direct-messages", $type, $data);
2742 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2744 function api_direct_messages_box(&$a, $type, $box) {
2745 if (api_user()===false) throw new ForbiddenException();
2748 $count = (x($_GET,'count')?$_GET['count']:20);
2749 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2750 if ($page<0) $page=0;
2752 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2753 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2755 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2756 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2759 unset($_REQUEST["user_id"]);
2760 unset($_GET["user_id"]);
2762 unset($_REQUEST["screen_name"]);
2763 unset($_GET["screen_name"]);
2765 $user_info = api_get_user($a);
2766 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2767 $profile_url = $user_info["url"];
2771 $start = $page*$count;
2774 if ($box=="sentbox") {
2775 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2777 elseif ($box=="conversation") {
2778 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2780 elseif ($box=="all") {
2781 $sql_extra = "true";
2783 elseif ($box=="inbox") {
2784 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2788 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2790 if ($user_id !="") {
2791 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2793 elseif($screen_name !=""){
2794 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2797 $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",
2800 intval($start), intval($count)
2805 foreach($r as $item) {
2806 if ($box == "inbox" || $item['from-url'] != $profile_url){
2807 $recipient = $user_info;
2808 $sender = api_get_user($a,normalise_link($item['contact-url']));
2810 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2811 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2812 $sender = $user_info;
2815 $ret[]=api_format_messages($item, $recipient, $sender);
2819 $data = array('direct_message' => $ret);
2823 $data = api_rss_extra($a, $data, $user_info);
2826 return api_format_data("direct-messages", $type, $data);
2830 function api_direct_messages_sentbox(&$a, $type){
2831 return api_direct_messages_box($a, $type, "sentbox");
2833 function api_direct_messages_inbox(&$a, $type){
2834 return api_direct_messages_box($a, $type, "inbox");
2836 function api_direct_messages_all(&$a, $type){
2837 return api_direct_messages_box($a, $type, "all");
2839 function api_direct_messages_conversation(&$a, $type){
2840 return api_direct_messages_box($a, $type, "conversation");
2842 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2843 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2844 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2845 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2849 function api_oauth_request_token(&$a, $type){
2851 $oauth = new FKOAuth1();
2852 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2853 }catch(Exception $e){
2854 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2859 function api_oauth_access_token(&$a, $type){
2861 $oauth = new FKOAuth1();
2862 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2863 }catch(Exception $e){
2864 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2870 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2871 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2874 function api_fr_photos_list(&$a,$type) {
2875 if (api_user()===false) throw new ForbiddenException();
2876 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2877 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2878 intval(local_user())
2881 'image/jpeg' => 'jpg',
2882 'image/png' => 'png',
2883 'image/gif' => 'gif'
2885 $data = array('photo'=>array());
2887 foreach($r as $rr) {
2889 $photo['id'] = $rr['resource-id'];
2890 $photo['album'] = $rr['album'];
2891 $photo['filename'] = $rr['filename'];
2892 $photo['type'] = $rr['type'];
2893 $thumb = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2896 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
2898 $photo['thumb'] = $thumb;
2899 $data['photo'][] = $photo;
2903 return api_format_data("photos", $type, $data);
2906 function api_fr_photo_detail(&$a,$type) {
2907 if (api_user()===false) throw new ForbiddenException();
2908 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2910 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2911 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2912 $data_sql = ($scale === false ? "" : "data, ");
2914 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2915 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2916 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2918 intval(local_user()),
2919 dbesc($_REQUEST['photo_id']),
2924 'image/jpeg' => 'jpg',
2925 'image/png' => 'png',
2926 'image/gif' => 'gif'
2930 $data = array('photo' => $r[0]);
2931 $data['photo']['id'] = $data['photo']['resource-id'];
2932 if ($scale !== false) {
2933 $data['photo']['data'] = base64_encode($data['photo']['data']);
2935 unset($data['photo']['datasize']); //needed only with scale param
2937 if ($type == "xml") {
2938 $data['photo']['links'] = array();
2939 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
2940 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
2942 "href" => $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
2944 $data['photo']['link'] = array();
2945 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2946 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2949 unset($data['photo']['resource-id']);
2950 unset($data['photo']['minscale']);
2951 unset($data['photo']['maxscale']);
2954 throw new NotFoundException();
2957 return api_format_data("photo_detail", $type, $data);
2960 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2961 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2966 * similar as /mod/redir.php
2967 * redirect to 'url' after dfrn auth
2969 * why this when there is mod/redir.php already?
2970 * This use api_user() and api_login()
2973 * c_url: url of remote contact to auth to
2974 * url: string, url to redirect after auth
2976 function api_friendica_remoteauth(&$a) {
2977 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2978 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2980 if ($url === '' || $c_url === '')
2981 throw new BadRequestException("Wrong parameters.");
2983 $c_url = normalise_link($c_url);
2987 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2992 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2993 throw new BadRequestException("Unknown contact");
2997 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2999 if($r[0]['duplex'] && $r[0]['issued-id']) {
3000 $orig_id = $r[0]['issued-id'];
3001 $dfrn_id = '1:' . $orig_id;
3003 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3004 $orig_id = $r[0]['dfrn-id'];
3005 $dfrn_id = '0:' . $orig_id;
3008 $sec = random_string();
3010 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3011 VALUES( %d, %s, '%s', '%s', %d )",
3019 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3020 $dest = (($url) ? '&destination_url=' . $url : '');
3021 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3022 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3023 . '&type=profile&sec=' . $sec . $dest . $quiet );
3025 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3028 * @brief Return the item shared, if the item contains only the [share] tag
3030 * @param array $item Sharer item
3031 * @return array Shared item or false if not a reshare
3033 function api_share_as_retweet(&$item) {
3034 $body = trim($item["body"]);
3036 if (diaspora::is_reshare($body, false)===false) {
3040 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3041 // Skip if there is no shared message in there
3042 // we already checked this in diaspora::is_reshare()
3043 // but better one more than one less...
3044 if ($body == $attributes)
3048 // build the fake reshared item
3049 $reshared_item = $item;
3052 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3053 if ($matches[1] != "")
3054 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3056 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3057 if ($matches[1] != "")
3058 $author = $matches[1];
3061 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3062 if ($matches[1] != "")
3063 $profile = $matches[1];
3065 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3066 if ($matches[1] != "")
3067 $profile = $matches[1];
3070 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3071 if ($matches[1] != "")
3072 $avatar = $matches[1];
3074 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3075 if ($matches[1] != "")
3076 $avatar = $matches[1];
3079 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3080 if ($matches[1] != "")
3081 $link = $matches[1];
3083 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3084 if ($matches[1] != "")
3085 $link = $matches[1];
3088 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3089 if ($matches[1] != "")
3090 $posted= $matches[1];
3092 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3093 if ($matches[1] != "")
3094 $posted = $matches[1];
3096 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3098 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3103 $reshared_item["body"] = $shared_body;
3104 $reshared_item["author-name"] = $author;
3105 $reshared_item["author-link"] = $profile;
3106 $reshared_item["author-avatar"] = $avatar;
3107 $reshared_item["plink"] = $link;
3108 $reshared_item["created"] = $posted;
3109 $reshared_item["edited"] = $posted;
3111 return $reshared_item;
3115 function api_get_nick($profile) {
3117 - remove trailing junk from profile url
3118 - pump.io check has to check the website
3123 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3124 dbesc(normalise_link($profile)));
3126 $nick = $r[0]["nick"];
3129 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3130 dbesc(normalise_link($profile)));
3132 $nick = $r[0]["nick"];
3136 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3137 if ($friendica != $profile)
3142 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3143 if ($diaspora != $profile)
3148 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3149 if ($twitter != $profile)
3155 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3156 if ($StatusnetHost != $profile) {
3157 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3158 if ($StatusnetUser != $profile) {
3159 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3160 $user = json_decode($UserData);
3162 $nick = $user->screen_name;
3167 // To-Do: look at the page if its really a pumpio site
3168 //if (!$nick == "") {
3169 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3170 // if ($pumpio != $profile)
3172 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3182 function api_clean_plain_items($Text) {
3183 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3185 $Text = bb_CleanPictureLinks($Text);
3186 $URLSearchString = "^\[\]";
3188 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3190 if ($include_entities == "true") {
3191 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3194 // Simplify "attachment" element
3195 $Text = api_clean_attachments($Text);
3201 * @brief Removes most sharing information for API text export
3203 * @param string $body The original body
3205 * @return string Cleaned body
3207 function api_clean_attachments($body) {
3208 $data = get_attachment_data($body);
3215 if (isset($data["text"]))
3216 $body = $data["text"];
3218 if (($body == "") AND (isset($data["title"])))
3219 $body = $data["title"];
3221 if (isset($data["url"]))
3222 $body .= "\n".$data["url"];
3224 $body .= $data["after"];
3229 function api_best_nickname(&$contacts) {
3230 $best_contact = array();
3232 if (count($contact) == 0)
3235 foreach ($contacts AS $contact)
3236 if ($contact["network"] == "") {
3237 $contact["network"] = "dfrn";
3238 $best_contact = array($contact);
3241 if (sizeof($best_contact) == 0)
3242 foreach ($contacts AS $contact)
3243 if ($contact["network"] == "dfrn")
3244 $best_contact = array($contact);
3246 if (sizeof($best_contact) == 0)
3247 foreach ($contacts AS $contact)
3248 if ($contact["network"] == "dspr")
3249 $best_contact = array($contact);
3251 if (sizeof($best_contact) == 0)
3252 foreach ($contacts AS $contact)
3253 if ($contact["network"] == "stat")
3254 $best_contact = array($contact);
3256 if (sizeof($best_contact) == 0)
3257 foreach ($contacts AS $contact)
3258 if ($contact["network"] == "pump")
3259 $best_contact = array($contact);
3261 if (sizeof($best_contact) == 0)
3262 foreach ($contacts AS $contact)
3263 if ($contact["network"] == "twit")
3264 $best_contact = array($contact);
3266 if (sizeof($best_contact) == 1)
3267 $contacts = $best_contact;
3269 $contacts = array($contacts[0]);
3272 // return all or a specified group of the user with the containing contacts
3273 function api_friendica_group_show(&$a, $type) {
3274 if (api_user()===false) throw new ForbiddenException();
3277 $user_info = api_get_user($a);
3278 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3279 $uid = $user_info['uid'];
3281 // get data of the specified group id or all groups if not specified
3283 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3286 // error message if specified gid is not in database
3288 throw new BadRequestException("gid not available");
3291 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3294 // loop through all groups and retrieve all members for adding data in the user array
3295 foreach ($r as $rr) {
3296 $members = group_get_members($rr['id']);
3299 if ($type == "xml") {
3300 $user_element = "users";
3302 foreach ($members as $member) {
3303 $user = api_get_user($a, $member['nurl']);
3304 $users[$k++.":user"] = $user;
3307 $user_element = "user";
3308 foreach ($members as $member) {
3309 $user = api_get_user($a, $member['nurl']);
3313 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3315 return api_format_data("groups", $type, array('group' => $grps));
3317 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3320 // delete the specified group of the user
3321 function api_friendica_group_delete(&$a, $type) {
3322 if (api_user()===false) throw new ForbiddenException();
3325 $user_info = api_get_user($a);
3326 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3327 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3328 $uid = $user_info['uid'];
3330 // error if no gid specified
3331 if ($gid == 0 || $name == "")
3332 throw new BadRequestException('gid or name not specified');
3334 // get data of the specified group id
3335 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3338 // error message if specified gid is not in database
3340 throw new BadRequestException('gid not available');
3342 // get data of the specified group id and group name
3343 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3347 // error message if specified gid is not in database
3348 if (count($rname) == 0)
3349 throw new BadRequestException('wrong group name');
3352 $ret = group_rmv($uid, $name);
3355 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3356 return api_format_data("group_delete", $type, array('result' => $success));
3359 throw new BadRequestException('other API error');
3361 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3364 // create the specified group with the posted array of contacts
3365 function api_friendica_group_create(&$a, $type) {
3366 if (api_user()===false) throw new ForbiddenException();
3369 $user_info = api_get_user($a);
3370 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3371 $uid = $user_info['uid'];
3372 $json = json_decode($_POST['json'], true);
3373 $users = $json['user'];
3375 // error if no name specified
3377 throw new BadRequestException('group name not specified');
3379 // get data of the specified group name
3380 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3383 // error message if specified group name already exists
3384 if (count($rname) != 0)
3385 throw new BadRequestException('group name already exists');
3387 // check if specified group name is a deleted group
3388 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3391 // error message if specified group name already exists
3392 if (count($rname) != 0)
3393 $reactivate_group = true;
3396 $ret = group_add($uid, $name);
3398 $gid = group_byname($uid, $name);
3400 throw new BadRequestException('other API error');
3403 $erroraddinguser = false;
3404 $errorusers = array();
3405 foreach ($users as $user) {
3406 $cid = $user['cid'];
3407 // check if user really exists as contact
3408 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3411 if (count($contact))
3412 $result = group_add_member($uid, $name, $cid, $gid);
3414 $erroraddinguser = true;
3415 $errorusers[] = $cid;
3419 // return success message incl. missing users in array
3420 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3421 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3422 return api_format_data("group_create", $type, array('result' => $success));
3424 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3427 // update the specified group with the posted array of contacts
3428 function api_friendica_group_update(&$a, $type) {
3429 if (api_user()===false) throw new ForbiddenException();
3432 $user_info = api_get_user($a);
3433 $uid = $user_info['uid'];
3434 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3435 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3436 $json = json_decode($_POST['json'], true);
3437 $users = $json['user'];
3439 // error if no name specified
3441 throw new BadRequestException('group name not specified');
3443 // error if no gid specified
3445 throw new BadRequestException('gid not specified');
3448 $members = group_get_members($gid);
3449 foreach ($members as $member) {
3450 $cid = $member['id'];
3451 foreach ($users as $user) {
3452 $found = ($user['cid'] == $cid ? true : false);
3455 $ret = group_rmv_member($uid, $name, $cid);
3460 $erroraddinguser = false;
3461 $errorusers = array();
3462 foreach ($users as $user) {
3463 $cid = $user['cid'];
3464 // check if user really exists as contact
3465 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3468 if (count($contact))
3469 $result = group_add_member($uid, $name, $cid, $gid);
3471 $erroraddinguser = true;
3472 $errorusers[] = $cid;
3476 // return success message incl. missing users in array
3477 $status = ($erroraddinguser ? "missing user" : "ok");
3478 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3479 return api_format_data("group_update", $type, array('result' => $success));
3481 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3484 function api_friendica_activity(&$a, $type) {
3485 if (api_user()===false) throw new ForbiddenException();
3486 $verb = strtolower($a->argv[3]);
3487 $verb = preg_replace("|\..*$|", "", $verb);
3489 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3491 $res = do_like($id, $verb);
3498 return api_format_data('ok', $type, array('ok' => $ok));
3500 throw new BadRequestException('Error adding activity');
3504 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3505 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3506 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3507 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3508 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3509 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3510 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3511 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3512 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3513 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3516 * @brief Returns notifications
3519 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3522 function api_friendica_notification(&$a, $type) {
3523 if (api_user()===false) throw new ForbiddenException();
3524 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3525 $nm = new NotificationsManager();
3527 $notes = $nm->getAll(array(), "+seen -date", 50);
3529 if ($type == "xml") {
3530 $xmlnotes = array();
3531 foreach ($notes AS $note)
3532 $xmlnotes[] = array("@attributes" => $note);
3537 return api_format_data("notes", $type, array('note' => $notes));
3541 * @brief Set notification as seen and returns associated item (if possible)
3543 * POST request with 'id' param as notification id
3546 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3549 function api_friendica_notification_seen(&$a, $type){
3550 if (api_user()===false) throw new ForbiddenException();
3551 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3553 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3555 $nm = new NotificationsManager();
3556 $note = $nm->getByID($id);
3557 if (is_null($note)) throw new BadRequestException("Invalid argument");
3559 $nm->setSeen($note);
3560 if ($note['otype']=='item') {
3561 // would be really better with an ItemsManager and $im->getByID() :-P
3562 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3563 intval($note['iid']),
3564 intval(local_user())
3567 // we found the item, return it to the user
3568 $user_info = api_get_user($a);
3569 $ret = api_format_items($r,$user_info, false, $type);
3570 $data = array('status' => $ret);
3571 return api_format_data("status", $type, $data);
3573 // the item can't be found, but we set the note as seen, so we count this as a success
3575 return api_format_data('result', $type, array('result' => "success"));
3578 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3579 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3584 [pagename] => api/1.1/statuses/lookup.json
3585 [id] => 605138389168451584
3586 [include_cards] => true
3587 [cards_platform] => Android-12
3588 [include_entities] => true
3589 [include_my_retweet] => 1
3591 [include_reply_count] => true
3592 [include_descendent_reply_count] => true
3596 Not implemented by now:
3597 statuses/retweets_of_me
3602 account/update_location
3603 account/update_profile_background_image
3604 account/update_profile_image
3608 Not implemented in status.net:
3609 statuses/retweeted_to_me
3610 statuses/retweeted_by_me
3611 direct_messages/destroy
3613 account/update_delivery_device
3614 notifications/follow