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 App::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'], $type);
280 $duration = (float)(microtime(true)-$stamp);
281 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
283 if (get_config("system", "profiler")) {
284 logger(sprintf("Database: %s/%s, Network: %s, Rendering: %s, Session: %s, I/O: %s, Other: %s, Total: %s",
285 round($a->performance["database"] - $a->performance["database_write"], 3),
286 round($a->performance["database_write"], 3),
287 round($a->performance["network"], 2),
288 round($a->performance["rendering"], 2),
289 round($a->performance["parser"], 2),
290 round($a->performance["file"], 2),
291 round($duration - $a->performance["database"]
292 - $a->performance["network"] - $a->performance["rendering"]
293 - $a->performance["parser"] - $a->performance["file"], 2),
294 round($duration, 2)),
297 if (get_config("rendertime", "callstack")) {
298 $o = "Database Read:\n";
299 foreach ($a->callstack["database"] AS $func => $time) {
300 $time = round($time, 3);
302 $o .= $func.": ".$time."\n";
304 $o .= "\nDatabase Write:\n";
305 foreach ($a->callstack["database_write"] AS $func => $time) {
306 $time = round($time, 3);
308 $o .= $func.": ".$time."\n";
311 $o .= "\nNetwork:\n";
312 foreach ($a->callstack["network"] AS $func => $time) {
313 $time = round($time, 3);
315 $o .= $func.": ".$time."\n";
317 logger($o, LOGGER_DEBUG);
323 // api function returned false withour throw an
324 // exception. This should not happend, throw a 500
325 throw new InternalServerErrorException();
330 header ("Content-Type: text/xml");
334 header ("Content-Type: application/json");
336 $json = json_encode($rr);
337 if ($_GET['callback'])
338 $json = $_GET['callback']."(".$json.")";
342 header ("Content-Type: application/rss+xml");
343 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
346 header ("Content-Type: application/atom+xml");
347 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
353 throw new NotImplementedException();
354 } catch (HTTPException $e) {
355 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
356 return api_error($type, $e);
361 * @brief Format API error string
363 * @param string $type Return type (xml, json, rss, as)
364 * @param HTTPException $error Error object
365 * @return strin error message formatted as $type
367 function api_error($type, $e) {
371 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
372 # TODO: https://dev.twitter.com/overview/api/response-codes
374 $error = array("error" => $error,
375 "code" => $e->httpcode." ".$e->httpdesc,
376 "request" => $a->query_string);
378 $ret = api_format_data('status', $type, array('status' => $error));
382 header ("Content-Type: text/xml");
386 header ("Content-Type: application/json");
387 return json_encode($ret);
390 header ("Content-Type: application/rss+xml");
394 header ("Content-Type: application/atom+xml");
401 * @brief Set values for RSS template
404 * @param array $arr Array to be passed to template
405 * @param array $user_info
408 function api_rss_extra(&$a, $arr, $user_info){
409 if (is_null($user_info)) $user_info = api_get_user($a);
410 $arr['$user'] = $user_info;
411 $arr['$rss'] = array(
412 'alternate' => $user_info['url'],
413 'self' => App::get_baseurl(). "/". $a->query_string,
414 'base' => App::get_baseurl(),
415 'updated' => api_date(null),
416 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
417 'language' => $user_info['language'],
418 'logo' => App::get_baseurl()."/images/friendica-32.png",
426 * @brief Unique contact to contact url.
428 * @param int $id Contact id
429 * @return bool|string
430 * Contact url or False if contact id is unknown
432 function api_unique_id_to_url($id){
433 $r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
436 return ($r[0]["url"]);
442 * @brief Get user info array.
445 * @param int|string $contact_id Contact ID or URL
446 * @param string $type Return type (for errors)
448 function api_get_user(&$a, $contact_id = Null, $type = "json"){
455 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
457 // Searching for contact URL
458 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
459 $user = dbesc(normalise_link($contact_id));
461 $extra_query = "AND `contact`.`nurl` = '%s' ";
462 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
465 // Searching for contact id with uid = 0
466 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
467 $user = dbesc(api_unique_id_to_url($contact_id));
470 throw new BadRequestException("User not found.");
473 $extra_query = "AND `contact`.`nurl` = '%s' ";
474 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
477 if(is_null($user) && x($_GET, 'user_id')) {
478 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
481 throw new BadRequestException("User not found.");
484 $extra_query = "AND `contact`.`nurl` = '%s' ";
485 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
487 if(is_null($user) && x($_GET, 'screen_name')) {
488 $user = dbesc($_GET['screen_name']);
490 $extra_query = "AND `contact`.`nick` = '%s' ";
491 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
494 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
495 $argid = count($called_api);
496 list($user, $null) = explode(".",$a->argv[$argid]);
497 if(is_numeric($user)){
498 $user = dbesc(api_unique_id_to_url($user));
504 $extra_query = "AND `contact`.`nurl` = '%s' ";
505 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
507 $user = dbesc($user);
509 $extra_query = "AND `contact`.`nick` = '%s' ";
510 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
514 logger("api_get_user: user ".$user, LOGGER_DEBUG);
517 if (api_user()===false) {
521 $user = $_SESSION['uid'];
522 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
527 logger('api_user: ' . $extra_query . ', user: ' . $user);
529 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
535 // Selecting the id by priority, friendica first
536 api_best_nickname($uinfo);
538 // if the contact wasn't found, fetch it from the contacts with uid = 0
539 if (count($uinfo)==0) {
543 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
546 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
548 // If no nick where given, extract it from the address
549 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
550 $r[0]['nick'] = api_get_nick($r[0]["url"]);
554 'id_str' => (string) $r[0]["id"],
555 'name' => $r[0]["name"],
556 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
557 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
558 'description' => $r[0]["about"],
559 'profile_image_url' => $r[0]["micro"],
560 'profile_image_url_https' => $r[0]["micro"],
561 'url' => $r[0]["url"],
562 'protected' => false,
563 'followers_count' => 0,
564 'friends_count' => 0,
566 'created_at' => api_date($r[0]["created"]),
567 'favourites_count' => 0,
569 'time_zone' => 'UTC',
570 'geo_enabled' => false,
572 'statuses_count' => 0,
574 'contributors_enabled' => false,
575 'is_translator' => false,
576 'is_translation_enabled' => false,
577 'following' => false,
578 'follow_request_sent' => false,
579 'statusnet_blocking' => false,
580 'notifications' => false,
581 'statusnet_profile_url' => $r[0]["url"],
583 'cid' => get_contact($r[0]["url"], api_user(), true),
585 'network' => $r[0]["network"],
590 throw new BadRequestException("User not found.");
594 if($uinfo[0]['self']) {
596 if ($uinfo[0]['network'] == "")
597 $uinfo[0]['network'] = NETWORK_DFRN;
599 $usr = q("select * from user where uid = %d limit 1",
602 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
606 // Counting is deactivated by now, due to performance issues
607 // count public wall messages
608 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
609 // intval($uinfo[0]['uid'])
611 //$countitms = $r[0]['count'];
614 // Counting is deactivated by now, due to performance issues
615 //$r = q("SELECT count(*) as `count` FROM `item`
616 // WHERE `contact-id` = %d",
617 // intval($uinfo[0]['id'])
619 //$countitms = $r[0]['count'];
623 // Counting is deactivated by now, due to performance issues
625 $r = q("SELECT count(*) as `count` FROM `contact`
626 WHERE `uid` = %d AND `rel` IN ( %d, %d )
627 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
628 intval($uinfo[0]['uid']),
629 intval(CONTACT_IS_SHARING),
630 intval(CONTACT_IS_FRIEND)
632 $countfriends = $r[0]['count'];
634 $r = q("SELECT count(*) as `count` FROM `contact`
635 WHERE `uid` = %d AND `rel` IN ( %d, %d )
636 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
637 intval($uinfo[0]['uid']),
638 intval(CONTACT_IS_FOLLOWER),
639 intval(CONTACT_IS_FRIEND)
641 $countfollowers = $r[0]['count'];
643 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
644 intval($uinfo[0]['uid'])
646 $starred = $r[0]['count'];
649 if(! $uinfo[0]['self']) {
659 // Add a nick if it isn't present there
660 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
661 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
664 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
666 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
669 'id' => intval($pcontact_id),
670 'id_str' => (string) intval($pcontact_id),
671 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
672 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
673 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
674 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
675 'profile_image_url' => $uinfo[0]['micro'],
676 'profile_image_url_https' => $uinfo[0]['micro'],
677 'url' => $uinfo[0]['url'],
678 'protected' => false,
679 'followers_count' => intval($countfollowers),
680 'friends_count' => intval($countfriends),
682 'created_at' => api_date($uinfo[0]['created']),
683 'favourites_count' => intval($starred),
685 'time_zone' => 'UTC',
686 'geo_enabled' => false,
688 'statuses_count' => intval($countitms),
690 'contributors_enabled' => false,
691 'is_translator' => false,
692 'is_translation_enabled' => false,
693 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
694 'follow_request_sent' => false,
695 'statusnet_blocking' => false,
696 'notifications' => false,
697 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
698 'statusnet_profile_url' => $uinfo[0]['url'],
699 'uid' => intval($uinfo[0]['uid']),
700 'cid' => intval($uinfo[0]['cid']),
701 'self' => $uinfo[0]['self'],
702 'network' => $uinfo[0]['network'],
710 * @brief return api-formatted array for item's author and owner
713 * @param array $item : item from db
714 * @return array(array:author, array:owner)
716 function api_item_get_user(&$a, $item) {
718 $status_user = api_get_user($a, $item["author-link"]);
720 $status_user["protected"] = (($item["allow_cid"] != "") OR
721 ($item["allow_gid"] != "") OR
722 ($item["deny_cid"] != "") OR
723 ($item["deny_gid"] != "") OR
726 $owner_user = api_get_user($a, $item["owner-link"]);
728 return (array($status_user, $owner_user));
732 * @brief walks recursively through an array with the possibility to change value and key
734 * @param array $array The array to walk through
735 * @param string $callback The callback function
737 * @return array the transformed array
739 function api_walk_recursive(array &$array, callable $callback) {
741 $new_array = array();
743 foreach ($array as $k => $v) {
745 if ($callback($v, $k))
746 $new_array[$k] = api_walk_recursive($v, $callback);
748 if ($callback($v, $k))
758 * @brief Callback function to transform the array in an array that can be transformed in a XML file
760 * @param variant $item Array item value
761 * @param string $key Array key
763 * @return boolean Should the array item be deleted?
765 function api_reformat_xml(&$item, &$key) {
767 $item = ($item ? "true" : "false");
769 if (substr($key, 0, 10) == "statusnet_")
770 $key = "statusnet:".substr($key, 10);
771 elseif (substr($key, 0, 10) == "friendica_")
772 $key = "friendica:".substr($key, 10);
774 // $key = "default:".$key;
780 * @brief Creates the XML from a JSON style array
782 * @param array $data JSON style array
783 * @param string $root_element Name of the root element
785 * @return string The XML data
787 function api_create_xml($data, $root_element) {
788 $childname = key($data);
789 $data2 = array_pop($data);
792 $namespaces = array("" => "http://api.twitter.com",
793 "statusnet" => "http://status.net/schema/api/1/",
794 "friendica" => "http://friendi.ca/schema/api/1/",
795 "georss" => "http://www.georss.org/georss");
797 /// @todo Auto detection of needed namespaces
798 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
799 $namespaces = array();
801 if (is_array($data2))
802 api_walk_recursive($data2, "api_reformat_xml");
808 foreach ($data2 AS $item)
809 $data4[$i++.":".$childname] = $item;
814 $data3 = array($root_element => $data2);
816 $ret = xml::from_array($data3, $xml, false, $namespaces);
821 * @brief Formats the data according to the data type
823 * @param string $root_element Name of the root element
824 * @param string $type Return type (atom, rss, xml, json)
825 * @param array $data JSON style array
827 * @return (string|object) XML data or JSON data
829 function api_format_data($root_element, $type, $data){
837 $ret = api_create_xml($data, $root_element);
852 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
853 * returns a 401 status code and an error message if not.
854 * http://developer.twitter.com/doc/get/account/verify_credentials
856 function api_account_verify_credentials($type){
860 if (api_user()===false) throw new ForbiddenException();
862 unset($_REQUEST["user_id"]);
863 unset($_GET["user_id"]);
865 unset($_REQUEST["screen_name"]);
866 unset($_GET["screen_name"]);
868 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
870 $user_info = api_get_user($a);
872 // "verified" isn't used here in the standard
873 unset($user_info["verified"]);
875 // - Adding last status
877 $user_info["status"] = api_status_show("raw");
878 if (!count($user_info["status"]))
879 unset($user_info["status"]);
881 unset($user_info["status"]["user"]);
884 // "uid" and "self" are only needed for some internal stuff, so remove it from here
885 unset($user_info["uid"]);
886 unset($user_info["self"]);
888 return api_format_data("user", $type, array('user' => $user_info));
891 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
895 * get data from $_POST or $_GET
897 function requestdata($k){
898 if (isset($_POST[$k])){
901 if (isset($_GET[$k])){
907 /*Waitman Gobble Mod*/
908 function api_statuses_mediap($type) {
912 if (api_user()===false) {
913 logger('api_statuses_update: no user');
914 throw new ForbiddenException();
916 $user_info = api_get_user($a);
918 $_REQUEST['type'] = 'wall';
919 $_REQUEST['profile_uid'] = api_user();
920 $_REQUEST['api_source'] = true;
921 $txt = requestdata('status');
922 //$txt = urldecode(requestdata('status'));
924 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
926 $txt = html2bb_video($txt);
927 $config = HTMLPurifier_Config::createDefault();
928 $config->set('Cache.DefinitionImpl', null);
929 $purifier = new HTMLPurifier($config);
930 $txt = $purifier->purify($txt);
932 $txt = html2bbcode($txt);
934 $a->argv[1]=$user_info['screen_name']; //should be set to username?
936 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
937 $bebop = wall_upload_post($a);
939 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
940 $_REQUEST['body']=$txt."\n\n".$bebop;
943 // this should output the last post (the one we just posted).
944 return api_status_show($type);
946 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
947 /*Waitman Gobble Mod*/
950 function api_statuses_update($type) {
954 if (api_user()===false) {
955 logger('api_statuses_update: no user');
956 throw new ForbiddenException();
959 $user_info = api_get_user($a);
961 // convert $_POST array items to the form we use for web posts.
963 // logger('api_post: ' . print_r($_POST,true));
965 if(requestdata('htmlstatus')) {
966 $txt = requestdata('htmlstatus');
967 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
968 $txt = html2bb_video($txt);
970 $config = HTMLPurifier_Config::createDefault();
971 $config->set('Cache.DefinitionImpl', null);
973 $purifier = new HTMLPurifier($config);
974 $txt = $purifier->purify($txt);
976 $_REQUEST['body'] = html2bbcode($txt);
980 $_REQUEST['body'] = requestdata('status');
982 $_REQUEST['title'] = requestdata('title');
984 $parent = requestdata('in_reply_to_status_id');
986 // Twidere sends "-1" if it is no reply ...
990 if(ctype_digit($parent))
991 $_REQUEST['parent'] = $parent;
993 $_REQUEST['parent_uri'] = $parent;
995 if(requestdata('lat') && requestdata('long'))
996 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
997 $_REQUEST['profile_uid'] = api_user();
1000 $_REQUEST['type'] = 'net-comment';
1002 // Check for throttling (maximum posts per day, week and month)
1003 $throttle_day = get_config('system','throttle_limit_day');
1004 if ($throttle_day > 0) {
1005 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1007 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1008 AND `created` > '%s' AND `id` = `parent`",
1009 intval(api_user()), dbesc($datefrom));
1012 $posts_day = $r[0]["posts_day"];
1016 if ($posts_day > $throttle_day) {
1017 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1018 #die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1019 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1023 $throttle_week = get_config('system','throttle_limit_week');
1024 if ($throttle_week > 0) {
1025 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1027 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1028 AND `created` > '%s' AND `id` = `parent`",
1029 intval(api_user()), dbesc($datefrom));
1032 $posts_week = $r[0]["posts_week"];
1036 if ($posts_week > $throttle_week) {
1037 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1038 #die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1039 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1044 $throttle_month = get_config('system','throttle_limit_month');
1045 if ($throttle_month > 0) {
1046 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1048 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1049 AND `created` > '%s' AND `id` = `parent`",
1050 intval(api_user()), dbesc($datefrom));
1053 $posts_month = $r[0]["posts_month"];
1057 if ($posts_month > $throttle_month) {
1058 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1059 #die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1060 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1064 $_REQUEST['type'] = 'wall';
1067 if(x($_FILES,'media')) {
1068 // upload the image if we have one
1069 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1070 $media = wall_upload_post($a);
1071 if(strlen($media)>0)
1072 $_REQUEST['body'] .= "\n\n".$media;
1075 // To-Do: Multiple IDs
1076 if (requestdata('media_ids')) {
1077 $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",
1078 intval(requestdata('media_ids')), api_user());
1080 $phototypes = Photo::supportedTypes();
1081 $ext = $phototypes[$r[0]['type']];
1082 $_REQUEST['body'] .= "\n\n".'[url='.App::get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1083 $_REQUEST['body'] .= '[img]'.App::get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1087 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1089 $_REQUEST['api_source'] = true;
1091 if (!x($_REQUEST, "source"))
1092 $_REQUEST["source"] = api_source();
1094 // call out normal post function
1098 // this should output the last post (the one we just posted).
1099 return api_status_show($type);
1101 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1102 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1105 function api_media_upload($type) {
1109 if (api_user()===false) {
1111 throw new ForbiddenException();
1114 $user_info = api_get_user($a);
1116 if(!x($_FILES,'media')) {
1118 throw new BadRequestException("No media.");
1121 $media = wall_upload_post($a, false);
1124 throw new InternalServerErrorException();
1127 $returndata = array();
1128 $returndata["media_id"] = $media["id"];
1129 $returndata["media_id_string"] = (string)$media["id"];
1130 $returndata["size"] = $media["size"];
1131 $returndata["image"] = array("w" => $media["width"],
1132 "h" => $media["height"],
1133 "image_type" => $media["type"]);
1135 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1137 return array("media" => $returndata);
1139 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1141 function api_status_show($type){
1145 $user_info = api_get_user($a);
1147 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1150 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1154 // get last public wall message
1155 $lastwall = q("SELECT `item`.*
1157 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1158 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1159 AND `item`.`type` != 'activity' $privacy_sql
1160 ORDER BY `item`.`id` DESC
1162 intval($user_info['cid']),
1164 dbesc($user_info['url']),
1165 dbesc(normalise_link($user_info['url'])),
1166 dbesc($user_info['url']),
1167 dbesc(normalise_link($user_info['url']))
1170 if (count($lastwall)>0){
1171 $lastwall = $lastwall[0];
1173 $in_reply_to = api_in_reply_to($lastwall);
1175 $converted = api_convert_item($lastwall);
1178 $geo = "georss:point";
1182 $status_info = array(
1183 'created_at' => api_date($lastwall['created']),
1184 'id' => intval($lastwall['id']),
1185 'id_str' => (string) $lastwall['id'],
1186 'text' => $converted["text"],
1187 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1188 'truncated' => false,
1189 'in_reply_to_status_id' => $in_reply_to['status_id'],
1190 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1191 'in_reply_to_user_id' => $in_reply_to['user_id'],
1192 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1193 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1194 'user' => $user_info,
1196 'coordinates' => "",
1198 'contributors' => "",
1199 'is_quote_status' => false,
1200 'retweet_count' => 0,
1201 'favorite_count' => 0,
1202 'favorited' => $lastwall['starred'] ? true : false,
1203 'retweeted' => false,
1204 'possibly_sensitive' => false,
1206 'statusnet_html' => $converted["html"],
1207 'statusnet_conversation_id' => $lastwall['parent'],
1210 if (count($converted["attachments"]) > 0)
1211 $status_info["attachments"] = $converted["attachments"];
1213 if (count($converted["entities"]) > 0)
1214 $status_info["entities"] = $converted["entities"];
1216 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1217 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1218 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1219 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1221 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1222 unset($status_info["user"]["uid"]);
1223 unset($status_info["user"]["self"]);
1226 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1229 return($status_info);
1231 return api_format_data("statuses", $type, array('status' => $status_info));
1240 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1241 * The author's most recent status will be returned inline.
1242 * http://developer.twitter.com/doc/get/users/show
1244 function api_users_show($type){
1248 $user_info = api_get_user($a);
1249 $lastwall = q("SELECT `item`.*
1251 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1252 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1253 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1254 AND `type`!='activity'
1255 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1259 dbesc(ACTIVITY_POST),
1260 intval($user_info['cid']),
1261 dbesc($user_info['url']),
1262 dbesc(normalise_link($user_info['url'])),
1263 dbesc($user_info['url']),
1264 dbesc(normalise_link($user_info['url']))
1267 if (count($lastwall)>0){
1268 $lastwall = $lastwall[0];
1270 $in_reply_to = api_in_reply_to($lastwall);
1272 $converted = api_convert_item($lastwall);
1275 $geo = "georss:point";
1279 $user_info['status'] = array(
1280 'text' => $converted["text"],
1281 'truncated' => false,
1282 'created_at' => api_date($lastwall['created']),
1283 'in_reply_to_status_id' => $in_reply_to['status_id'],
1284 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1285 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1286 'id' => intval($lastwall['contact-id']),
1287 'id_str' => (string) $lastwall['contact-id'],
1288 'in_reply_to_user_id' => $in_reply_to['user_id'],
1289 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1290 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1292 'favorited' => $lastwall['starred'] ? true : false,
1293 'statusnet_html' => $converted["html"],
1294 'statusnet_conversation_id' => $lastwall['parent'],
1297 if (count($converted["attachments"]) > 0)
1298 $user_info["status"]["attachments"] = $converted["attachments"];
1300 if (count($converted["entities"]) > 0)
1301 $user_info["status"]["entities"] = $converted["entities"];
1303 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1304 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1305 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1306 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1310 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1311 unset($user_info["uid"]);
1312 unset($user_info["self"]);
1314 return api_format_data("user", $type, array('user' => $user_info));
1317 api_register_func('api/users/show','api_users_show');
1320 function api_users_search($type) {
1324 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1326 $userlist = array();
1328 if (isset($_GET["q"])) {
1329 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1331 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1335 foreach ($r AS $user) {
1336 $user_info = api_get_user($a, $user["id"], "json");
1339 $userlist[$k++.":user"] = $user_info;
1341 $userlist[] = $user_info;
1343 $userlist = array("users" => $userlist);
1345 throw new BadRequestException("User not found.");
1348 throw new BadRequestException("User not found.");
1350 return api_format_data("users", $type, $userlist);
1353 api_register_func('api/users/search','api_users_search');
1357 * http://developer.twitter.com/doc/get/statuses/home_timeline
1359 * TODO: Optional parameters
1360 * TODO: Add reply info
1362 function api_statuses_home_timeline($type){
1366 if (api_user()===false) throw new ForbiddenException();
1368 unset($_REQUEST["user_id"]);
1369 unset($_GET["user_id"]);
1371 unset($_REQUEST["screen_name"]);
1372 unset($_GET["screen_name"]);
1374 $user_info = api_get_user($a);
1375 // get last newtork messages
1378 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1379 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1380 if ($page<0) $page=0;
1381 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1382 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1383 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1384 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1385 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1387 $start = $page*$count;
1391 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1392 if ($exclude_replies > 0)
1393 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1394 if ($conversation_id > 0)
1395 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1397 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1398 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1399 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1400 `contact`.`id` AS `cid`
1402 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1403 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1404 WHERE `item`.`uid` = %d AND `verb` = '%s'
1405 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1408 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1410 dbesc(ACTIVITY_POST),
1412 intval($start), intval($count)
1415 $ret = api_format_items($r,$user_info, false, $type);
1417 // Set all posts from the query above to seen
1419 foreach ($r AS $item)
1420 $idarray[] = intval($item["id"]);
1422 $idlist = implode(",", $idarray);
1424 if ($idlist != "") {
1425 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1428 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1431 $data = array('status' => $ret);
1435 $data = api_rss_extra($a, $data, $user_info);
1439 return api_format_data("statuses", $type, $data);
1441 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1442 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1444 function api_statuses_public_timeline($type){
1448 if (api_user()===false) throw new ForbiddenException();
1450 $user_info = api_get_user($a);
1451 // get last newtork messages
1455 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1456 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1457 if ($page<0) $page=0;
1458 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1459 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1460 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1461 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1462 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1464 $start = $page*$count;
1467 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1468 if ($exclude_replies > 0)
1469 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1470 if ($conversation_id > 0)
1471 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1473 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1474 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1475 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1476 `contact`.`id` AS `cid`,
1477 `user`.`nickname`, `user`.`hidewall`
1479 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1480 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1481 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1482 AND NOT `user`.`hidewall`
1483 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1484 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1485 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1486 AND NOT `item`.`private` AND `item`.`wall`
1489 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1490 dbesc(ACTIVITY_POST),
1495 $ret = api_format_items($r,$user_info, false, $type);
1498 $data = array('status' => $ret);
1502 $data = api_rss_extra($a, $data, $user_info);
1506 return api_format_data("statuses", $type, $data);
1508 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1513 function api_statuses_show($type){
1517 if (api_user()===false) throw new ForbiddenException();
1519 $user_info = api_get_user($a);
1522 $id = intval($a->argv[3]);
1525 $id = intval($_REQUEST["id"]);
1529 $id = intval($a->argv[4]);
1531 logger('API: api_statuses_show: '.$id);
1533 $conversation = (x($_REQUEST,'conversation')?1:0);
1537 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1539 $sql_extra .= " AND `item`.`id` = %d";
1541 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1542 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1543 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1544 `contact`.`id` AS `cid`
1546 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1547 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1548 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1549 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1552 dbesc(ACTIVITY_POST),
1557 throw new BadRequestException("There is no status with this id.");
1560 $ret = api_format_items($r,$user_info, false, $type);
1562 if ($conversation) {
1563 $data = array('status' => $ret);
1564 return api_format_data("statuses", $type, $data);
1566 $data = array('status' => $ret[0]);
1567 return api_format_data("status", $type, $data);
1570 api_register_func('api/statuses/show','api_statuses_show', true);
1576 function api_conversation_show($type){
1580 if (api_user()===false) throw new ForbiddenException();
1582 $user_info = api_get_user($a);
1585 $id = intval($a->argv[3]);
1586 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1587 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1588 if ($page<0) $page=0;
1589 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1590 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1592 $start = $page*$count;
1595 $id = intval($_REQUEST["id"]);
1599 $id = intval($a->argv[4]);
1601 logger('API: api_conversation_show: '.$id);
1603 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1605 $id = $r[0]["parent"];
1610 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1612 // Not sure why this query was so complicated. We should keep it here for a while,
1613 // just to make sure that we really don't need it.
1614 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1615 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1617 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1618 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1619 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1620 `contact`.`id` AS `cid`
1622 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1623 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1624 WHERE `item`.`parent` = %d AND `item`.`visible`
1625 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1626 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1627 AND `item`.`id`>%d $sql_extra
1628 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1629 intval($id), intval(api_user()),
1630 dbesc(ACTIVITY_POST),
1632 intval($start), intval($count)
1636 throw new BadRequestException("There is no conversation with this id.");
1638 $ret = api_format_items($r,$user_info, false, $type);
1640 $data = array('status' => $ret);
1641 return api_format_data("statuses", $type, $data);
1643 api_register_func('api/conversation/show','api_conversation_show', true);
1644 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1650 function api_statuses_repeat($type){
1655 if (api_user()===false) throw new ForbiddenException();
1657 $user_info = api_get_user($a);
1660 $id = intval($a->argv[3]);
1663 $id = intval($_REQUEST["id"]);
1667 $id = intval($a->argv[4]);
1669 logger('API: api_statuses_repeat: '.$id);
1671 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1672 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1673 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1674 `contact`.`id` AS `cid`
1676 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1677 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1678 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1679 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1680 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1682 AND `item`.`id`=%d",
1686 if ($r[0]['body'] != "") {
1687 if (!intval(get_config('system','old_share'))) {
1688 if (strpos($r[0]['body'], "[/share]") !== false) {
1689 $pos = strpos($r[0]['body'], "[share");
1690 $post = substr($r[0]['body'], $pos);
1692 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1694 $post .= $r[0]['body'];
1695 $post .= "[/share]";
1697 $_REQUEST['body'] = $post;
1699 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1701 $_REQUEST['profile_uid'] = api_user();
1702 $_REQUEST['type'] = 'wall';
1703 $_REQUEST['api_source'] = true;
1705 if (!x($_REQUEST, "source"))
1706 $_REQUEST["source"] = api_source();
1710 throw new ForbiddenException();
1712 // this should output the last post (the one we just posted).
1714 return(api_status_show($type));
1716 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1721 function api_statuses_destroy($type){
1725 if (api_user()===false) throw new ForbiddenException();
1727 $user_info = api_get_user($a);
1730 $id = intval($a->argv[3]);
1733 $id = intval($_REQUEST["id"]);
1737 $id = intval($a->argv[4]);
1739 logger('API: api_statuses_destroy: '.$id);
1741 $ret = api_statuses_show($type);
1743 drop_item($id, false);
1747 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1751 * http://developer.twitter.com/doc/get/statuses/mentions
1754 function api_statuses_mentions($type){
1758 if (api_user()===false) throw new ForbiddenException();
1760 unset($_REQUEST["user_id"]);
1761 unset($_GET["user_id"]);
1763 unset($_REQUEST["screen_name"]);
1764 unset($_GET["screen_name"]);
1766 $user_info = api_get_user($a);
1767 // get last newtork messages
1771 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1772 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1773 if ($page<0) $page=0;
1774 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1775 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1776 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1778 $start = $page*$count;
1780 // Ugly code - should be changed
1781 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1782 $myurl = substr($myurl,strpos($myurl,'://')+3);
1783 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1784 $myurl = str_replace('www.','',$myurl);
1785 $diasp_url = str_replace('/profile/','/u/',$myurl);
1788 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1790 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1791 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1792 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1793 `contact`.`id` AS `cid`
1794 FROM `item` FORCE INDEX (`uid_id`)
1795 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1796 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1797 WHERE `item`.`uid` = %d AND `verb` = '%s'
1798 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1799 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1800 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1803 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1805 dbesc(ACTIVITY_POST),
1806 dbesc(protect_sprintf($myurl)),
1807 dbesc(protect_sprintf($myurl)),
1810 intval($start), intval($count)
1813 $ret = api_format_items($r,$user_info, false, $type);
1816 $data = array('status' => $ret);
1820 $data = api_rss_extra($a, $data, $user_info);
1824 return api_format_data("statuses", $type, $data);
1826 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1827 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1830 function api_statuses_user_timeline($type){
1834 if (api_user()===false) throw new ForbiddenException();
1836 $user_info = api_get_user($a);
1837 // get last network messages
1839 logger("api_statuses_user_timeline: api_user: ". api_user() .
1840 "\nuser_info: ".print_r($user_info, true) .
1841 "\n_REQUEST: ".print_r($_REQUEST, true),
1845 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1846 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1847 if ($page<0) $page=0;
1848 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1849 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1850 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1851 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1853 $start = $page*$count;
1856 if ($user_info['self']==1)
1857 $sql_extra .= " AND `item`.`wall` = 1 ";
1859 if ($exclude_replies > 0)
1860 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1861 if ($conversation_id > 0)
1862 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1864 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1865 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1866 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1867 `contact`.`id` AS `cid`
1868 FROM `item` FORCE INDEX (`uid_contactid_id`)
1869 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1870 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1871 WHERE `item`.`uid` = %d AND `verb` = '%s'
1872 AND `item`.`contact-id` = %d
1873 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1876 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1878 dbesc(ACTIVITY_POST),
1879 intval($user_info['cid']),
1881 intval($start), intval($count)
1884 $ret = api_format_items($r,$user_info, true, $type);
1886 $data = array('status' => $ret);
1890 $data = api_rss_extra($a, $data, $user_info);
1893 return api_format_data("statuses", $type, $data);
1895 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1899 * Star/unstar an item
1900 * param: id : id of the item
1902 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1904 function api_favorites_create_destroy($type){
1908 if (api_user()===false) throw new ForbiddenException();
1910 // for versioned api.
1911 /// @TODO We need a better global soluton
1913 if ($a->argv[1]=="1.1") $action_argv_id=3;
1915 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1916 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1917 if ($a->argc==$action_argv_id+2) {
1918 $itemid = intval($a->argv[$action_argv_id+1]);
1920 $itemid = intval($_REQUEST['id']);
1923 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1924 $itemid, api_user());
1926 if ($item===false || count($item)==0)
1927 throw new BadRequestException("Invalid item.");
1931 $item[0]['starred']=1;
1934 $item[0]['starred']=0;
1937 throw new BadRequestException("Invalid action ".$action);
1939 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1940 $item[0]['starred'], $itemid, api_user());
1942 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1943 $item[0]['starred'], $itemid, api_user());
1946 throw InternalServerErrorException("DB error");
1949 $user_info = api_get_user($a);
1950 $rets = api_format_items($item, $user_info, false, $type);
1953 $data = array('status' => $ret);
1957 $data = api_rss_extra($a, $data, $user_info);
1960 return api_format_data("status", $type, $data);
1962 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1963 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1965 function api_favorites($type){
1970 if (api_user()===false) throw new ForbiddenException();
1972 $called_api= array();
1974 $user_info = api_get_user($a);
1976 // in friendica starred item are private
1977 // return favorites only for self
1978 logger('api_favorites: self:' . $user_info['self']);
1980 if ($user_info['self']==0) {
1986 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1987 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1988 $count = (x($_GET,'count')?$_GET['count']:20);
1989 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1990 if ($page<0) $page=0;
1992 $start = $page*$count;
1995 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1997 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1998 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1999 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2000 `contact`.`id` AS `cid`
2001 FROM `item`, `contact`
2002 WHERE `item`.`uid` = %d
2003 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2004 AND `item`.`starred` = 1
2005 AND `contact`.`id` = `item`.`contact-id`
2006 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
2009 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2012 intval($start), intval($count)
2015 $ret = api_format_items($r,$user_info, false, $type);
2019 $data = array('status' => $ret);
2023 $data = api_rss_extra($a, $data, $user_info);
2026 return api_format_data("statuses", $type, $data);
2028 api_register_func('api/favorites','api_favorites', true);
2030 function api_format_messages($item, $recipient, $sender) {
2031 // standard meta information
2033 'id' => $item['id'],
2034 'sender_id' => $sender['id'] ,
2036 'recipient_id' => $recipient['id'],
2037 'created_at' => api_date($item['created']),
2038 'sender_screen_name' => $sender['screen_name'],
2039 'recipient_screen_name' => $recipient['screen_name'],
2040 'sender' => $sender,
2041 'recipient' => $recipient,
2043 'friendica_seen' => $item['seen'],
2044 'friendica_parent_uri' => $item['parent-uri'],
2047 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2048 unset($ret["sender"]["uid"]);
2049 unset($ret["sender"]["self"]);
2050 unset($ret["recipient"]["uid"]);
2051 unset($ret["recipient"]["self"]);
2053 //don't send title to regular StatusNET requests to avoid confusing these apps
2054 if (x($_GET, 'getText')) {
2055 $ret['title'] = $item['title'] ;
2056 if ($_GET["getText"] == "html") {
2057 $ret['text'] = bbcode($item['body'], false, false);
2059 elseif ($_GET["getText"] == "plain") {
2060 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2061 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2065 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2067 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2068 unset($ret['sender']);
2069 unset($ret['recipient']);
2075 function api_convert_item($item) {
2076 $body = $item['body'];
2077 $attachments = api_get_attachments($body);
2079 // Workaround for ostatus messages where the title is identically to the body
2080 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2081 $statusbody = trim(html2plain($html, 0));
2083 // handle data: images
2084 $statusbody = api_format_items_embeded_images($item,$statusbody);
2086 $statustitle = trim($item['title']);
2088 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2089 $statustext = trim($statusbody);
2091 $statustext = trim($statustitle."\n\n".$statusbody);
2093 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2094 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2096 $statushtml = trim(bbcode($body, false, false));
2098 $search = array("<br>", "<blockquote>", "</blockquote>",
2099 "<h1>", "</h1>", "<h2>", "</h2>",
2100 "<h3>", "</h3>", "<h4>", "</h4>",
2101 "<h5>", "</h5>", "<h6>", "</h6>");
2102 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2103 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2104 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2105 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2106 $statushtml = str_replace($search, $replace, $statushtml);
2108 if ($item['title'] != "")
2109 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2111 $entities = api_get_entitities($statustext, $body);
2114 "text" => $statustext,
2115 "html" => $statushtml,
2116 "attachments" => $attachments,
2117 "entities" => $entities
2121 function api_get_attachments(&$body) {
2124 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2126 $URLSearchString = "^\[\]";
2127 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2132 $attachments = array();
2134 foreach ($images[1] AS $image) {
2135 $imagedata = get_photo_info($image);
2138 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2141 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2142 foreach ($images[0] AS $orig)
2143 $body = str_replace($orig, "", $body);
2145 return $attachments;
2148 function api_get_entitities(&$text, $bbcode) {
2151 * Links at the first character of the post
2156 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2158 if ($include_entities != "true") {
2160 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2162 foreach ($images[1] AS $image) {
2163 $replace = proxy_url($image);
2164 $text = str_replace($image, $replace, $text);
2169 $bbcode = bb_CleanPictureLinks($bbcode);
2171 // Change pure links in text to bbcode uris
2172 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2174 $entities = array();
2175 $entities["hashtags"] = array();
2176 $entities["symbols"] = array();
2177 $entities["urls"] = array();
2178 $entities["user_mentions"] = array();
2180 $URLSearchString = "^\[\]";
2182 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2184 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2185 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2186 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2188 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2189 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2190 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2192 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2193 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2194 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2196 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2198 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2199 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2201 $ordered_urls = array();
2202 foreach ($urls[1] AS $id=>$url) {
2203 //$start = strpos($text, $url, $offset);
2204 $start = iconv_strpos($text, $url, 0, "UTF-8");
2205 if (!($start === false))
2206 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2209 ksort($ordered_urls);
2212 //foreach ($urls[1] AS $id=>$url) {
2213 foreach ($ordered_urls AS $url) {
2214 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2215 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2216 $display_url = $url["title"];
2218 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2219 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2221 if (strlen($display_url) > 26)
2222 $display_url = substr($display_url, 0, 25)."…";
2225 //$start = strpos($text, $url, $offset);
2226 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2227 if (!($start === false)) {
2228 $entities["urls"][] = array("url" => $url["url"],
2229 "expanded_url" => $url["url"],
2230 "display_url" => $display_url,
2231 "indices" => array($start, $start+strlen($url["url"])));
2232 $offset = $start + 1;
2236 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2237 $ordered_images = array();
2238 foreach ($images[1] AS $image) {
2239 //$start = strpos($text, $url, $offset);
2240 $start = iconv_strpos($text, $image, 0, "UTF-8");
2241 if (!($start === false))
2242 $ordered_images[$start] = $image;
2244 //$entities["media"] = array();
2247 foreach ($ordered_images AS $url) {
2248 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2249 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2251 if (strlen($display_url) > 26)
2252 $display_url = substr($display_url, 0, 25)."…";
2254 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2255 if (!($start === false)) {
2256 $image = get_photo_info($url);
2258 // If image cache is activated, then use the following sizes:
2259 // thumb (150), small (340), medium (600) and large (1024)
2260 if (!get_config("system", "proxy_disabled")) {
2261 $media_url = proxy_url($url);
2264 $scale = scale_image($image[0], $image[1], 150);
2265 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2267 if (($image[0] > 150) OR ($image[1] > 150)) {
2268 $scale = scale_image($image[0], $image[1], 340);
2269 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2272 $scale = scale_image($image[0], $image[1], 600);
2273 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2275 if (($image[0] > 600) OR ($image[1] > 600)) {
2276 $scale = scale_image($image[0], $image[1], 1024);
2277 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2281 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2284 $entities["media"][] = array(
2286 "id_str" => (string)$start+1,
2287 "indices" => array($start, $start+strlen($url)),
2288 "media_url" => normalise_link($media_url),
2289 "media_url_https" => $media_url,
2291 "display_url" => $display_url,
2292 "expanded_url" => $url,
2296 $offset = $start + 1;
2302 function api_format_items_embeded_images(&$item, $text){
2303 $text = preg_replace_callback(
2304 "|data:image/([^;]+)[^=]+=*|m",
2305 function($match) use ($item) {
2306 return App::get_baseurl()."/display/".$item['guid'];
2314 * @brief return <a href='url'>name</a> as array
2316 * @param string $txt
2321 function api_contactlink_to_array($txt) {
2323 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2324 if ($r && count($match)==3) {
2326 'name' => $match[2],
2340 * @brief return likes, dislikes and attend status for item
2342 * @param array $item
2344 * likes => int count
2345 * dislikes => int count
2347 function api_format_items_activities(&$item, $type = "json") {
2348 $activities = array(
2350 'dislike' => array(),
2351 'attendyes' => array(),
2352 'attendno' => array(),
2353 'attendmaybe' => array()
2356 $items = q('SELECT * FROM item
2357 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2358 intval($item['uid']),
2359 dbesc($item['uri']));
2361 foreach ($items as $i){
2362 // not used as result should be structured like other user data
2363 //builtin_activity_puller($i, $activities);
2365 // get user data and add it to the array of the activity
2366 $user = api_get_user($a, $i['author-link']);
2367 switch($i['verb']) {
2369 $activities['like'][] = $user;
2371 case ACTIVITY_DISLIKE:
2372 $activities['dislike'][] = $user;
2374 case ACTIVITY_ATTEND:
2375 $activities['attendyes'][] = $user;
2377 case ACTIVITY_ATTENDNO:
2378 $activities['attendno'][] = $user;
2380 case ACTIVITY_ATTENDMAYBE:
2381 $activities['attendmaybe'][] = $user;
2388 if ($type == "xml") {
2389 $xml_activities = array();
2390 foreach ($activities as $k => $v) {
2391 // change xml element from "like" to "friendica:like"
2392 $xml_activities["friendica:".$k] = $v;
2393 // add user data into xml output
2395 foreach ($v as $user)
2396 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2398 $activities = $xml_activities;
2407 * @brief return data from profiles
2409 * @param array $profile array containing data from db table 'profile'
2410 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2413 function api_format_items_profiles(&$profile = null, $type = "json") {
2414 if ($profile != null) {
2415 $profile = array('profile_id' => $profile['id'],
2416 'profile_name' => $profile['profile-name'],
2417 'is_default' => $profile['is-default'] ? true : false,
2418 'hide_friends'=> $profile['hide-friends'] ? true : false,
2419 'profile_photo' => $profile['photo'],
2420 'profile_thumb' => $profile['thumb'],
2421 'publish' => $profile['publish'] ? true : false,
2422 'net_publish' => $profile['net-publish'] ? true : false,
2423 'description' => $profile['pdesc'],
2424 'date_of_birth' => $profile['dob'],
2425 'address' => $profile['address'],
2426 'city' => $profile['locality'],
2427 'region' => $profile['region'],
2428 'postal_code' => $profile['postal-code'],
2429 'country' => $profile['country-name'],
2430 'hometown' => $profile['hometown'],
2431 'gender' => $profile['gender'],
2432 'marital' => $profile['marital'],
2433 'marital_with' => $profile['with'],
2434 'marital_since' => $profile['howlong'],
2435 'sexual' => $profile['sexual'],
2436 'politic' => $profile['politic'],
2437 'religion' => $profile['religion'],
2438 'public_keywords' => $profile['pub_keywords'],
2439 'private_keywords' => $profile['prv_keywords'],
2440 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, true),
2441 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, true),
2442 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, true),
2443 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, true),
2444 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, true),
2445 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, true),
2446 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, true),
2447 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, true),
2448 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, true),
2449 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, true),
2450 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, true),
2451 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, true),
2452 'homepage' => $profile['homepage'],
2459 * @brief format items to be returned by api
2461 * @param array $r array of items
2462 * @param array $user_info
2463 * @param bool $filter_user filter items by $user_info
2465 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2471 foreach($r as $item) {
2473 localize_item($item);
2474 list($status_user, $owner_user) = api_item_get_user($a,$item);
2476 // Look if the posts are matching if they should be filtered by user id
2477 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2480 $in_reply_to = api_in_reply_to($item);
2482 $converted = api_convert_item($item);
2485 $geo = "georss:point";
2490 'text' => $converted["text"],
2491 'truncated' => False,
2492 'created_at'=> api_date($item['created']),
2493 'in_reply_to_status_id' => $in_reply_to['status_id'],
2494 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2495 'source' => (($item['app']) ? $item['app'] : 'web'),
2496 'id' => intval($item['id']),
2497 'id_str' => (string) intval($item['id']),
2498 'in_reply_to_user_id' => $in_reply_to['user_id'],
2499 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2500 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2502 'favorited' => $item['starred'] ? true : false,
2503 'user' => $status_user ,
2504 'friendica_owner' => $owner_user,
2505 //'entities' => NULL,
2506 'statusnet_html' => $converted["html"],
2507 'statusnet_conversation_id' => $item['parent'],
2508 'friendica_activities' => api_format_items_activities($item, $type),
2511 if (count($converted["attachments"]) > 0)
2512 $status["attachments"] = $converted["attachments"];
2514 if (count($converted["entities"]) > 0)
2515 $status["entities"] = $converted["entities"];
2517 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2518 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2519 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2520 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2523 // Retweets are only valid for top postings
2524 // It doesn't work reliable with the link if its a feed
2525 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2527 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2530 if ($item["id"] == $item["parent"]) {
2531 $retweeted_item = api_share_as_retweet($item);
2532 if ($retweeted_item !== false) {
2533 $retweeted_status = $status;
2535 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2536 } catch( BadRequestException $e ) {
2537 // user not found. should be found?
2538 /// @todo check if the user should be always found
2539 $retweeted_status["user"] = array();
2542 $rt_converted = api_convert_item($retweeted_item);
2544 $retweeted_status['text'] = $rt_converted["text"];
2545 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2546 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2547 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2548 $status['retweeted_status'] = $retweeted_status;
2552 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2553 unset($status["user"]["uid"]);
2554 unset($status["user"]["self"]);
2556 if ($item["coord"] != "") {
2557 $coords = explode(' ',$item["coord"]);
2558 if (count($coords) == 2) {
2559 if ($type == "json")
2560 $status["geo"] = array('type' => 'Point',
2561 'coordinates' => array((float) $coords[0],
2562 (float) $coords[1]));
2563 else // Not sure if this is the official format - if someone founds a documentation we can check
2564 $status["georss:point"] = $item["coord"];
2573 function api_account_rate_limit_status($type) {
2577 'remaining-hits' => (string) 150,
2578 '@attributes' => array("type" => "integer"),
2579 'hourly-limit' => (string) 150,
2580 '@attributes2' => array("type" => "integer"),
2581 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2582 '@attributes3' => array("type" => "datetime"),
2583 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2584 '@attributes4' => array("type" => "integer"),
2588 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2589 'remaining_hits' => (string) 150,
2590 'hourly_limit' => (string) 150,
2591 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2594 return api_format_data('hash', $type, array('hash' => $hash));
2596 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2598 function api_help_test($type) {
2604 return api_format_data('ok', $type, array("ok" => $ok));
2606 api_register_func('api/help/test','api_help_test',false);
2608 function api_lists($type) {
2610 return api_format_data('lists', $type, array("lists_list" => $ret));
2612 api_register_func('api/lists','api_lists',true);
2614 function api_lists_list($type) {
2616 return api_format_data('lists', $type, array("lists_list" => $ret));
2618 api_register_func('api/lists/list','api_lists_list',true);
2621 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2622 * This function is deprecated by Twitter
2623 * returns: json, xml
2625 function api_statuses_f($type, $qtype) {
2629 if (api_user()===false) throw new ForbiddenException();
2630 $user_info = api_get_user($a);
2632 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2633 /* this is to stop Hotot to load friends multiple times
2634 * I'm not sure if I'm missing return something or
2635 * is a bug in hotot. Workaround, meantime
2639 return array('$users' => $ret);*/
2643 if($qtype == 'friends')
2644 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2645 if($qtype == 'followers')
2646 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2648 // friends and followers only for self
2649 if ($user_info['self'] == 0)
2650 $sql_extra = " AND false ";
2652 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2657 foreach($r as $cid){
2658 $user = api_get_user($a, $cid['nurl']);
2659 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2660 unset($user["uid"]);
2661 unset($user["self"]);
2667 return array('user' => $ret);
2670 function api_statuses_friends($type){
2671 $data = api_statuses_f($type, "friends");
2672 if ($data===false) return false;
2673 return api_format_data("users", $type, $data);
2675 function api_statuses_followers($type){
2676 $data = api_statuses_f($type, "followers");
2677 if ($data===false) return false;
2678 return api_format_data("users", $type, $data);
2680 api_register_func('api/statuses/friends','api_statuses_friends',true);
2681 api_register_func('api/statuses/followers','api_statuses_followers',true);
2688 function api_statusnet_config($type) {
2692 $name = $a->config['sitename'];
2693 $server = $a->get_hostname();
2694 $logo = App::get_baseurl() . '/images/friendica-64.png';
2695 $email = $a->config['admin_email'];
2696 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2697 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2698 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2699 if($a->config['api_import_size'])
2700 $texlimit = string($a->config['api_import_size']);
2701 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2702 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2705 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2706 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2707 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2708 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2709 'shorturllength' => '30',
2710 'friendica' => array(
2711 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2712 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2713 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2714 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2719 return api_format_data('config', $type, array('config' => $config));
2722 api_register_func('api/statusnet/config','api_statusnet_config',false);
2724 function api_statusnet_version($type) {
2726 $fake_statusnet_version = "0.9.7";
2728 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2730 api_register_func('api/statusnet/version','api_statusnet_version',false);
2733 * @todo use api_format_data() to return data
2735 function api_ff_ids($type,$qtype) {
2739 if(! api_user()) throw new ForbiddenException();
2741 $user_info = api_get_user($a);
2743 if($qtype == 'friends')
2744 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2745 if($qtype == 'followers')
2746 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2748 if (!$user_info["self"])
2749 $sql_extra = " AND false ";
2751 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2753 $r = q("SELECT `pcontact`.`id` FROM `contact`
2754 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2755 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2759 if(!dbm::is_result($r))
2767 $ids[] = intval($rr['id']);
2769 return api_format_data("ids", $type, array('id' => $ids));
2772 function api_friends_ids($type) {
2773 return api_ff_ids($type,'friends');
2775 function api_followers_ids($type) {
2776 return api_ff_ids($type,'followers');
2778 api_register_func('api/friends/ids','api_friends_ids',true);
2779 api_register_func('api/followers/ids','api_followers_ids',true);
2782 function api_direct_messages_new($type) {
2786 if (api_user()===false) throw new ForbiddenException();
2788 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2790 $sender = api_get_user($a);
2792 if ($_POST['screen_name']) {
2793 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2795 dbesc($_POST['screen_name']));
2797 // Selecting the id by priority, friendica first
2798 api_best_nickname($r);
2800 $recipient = api_get_user($a, $r[0]['nurl']);
2802 $recipient = api_get_user($a, $_POST['user_id']);
2806 if (x($_REQUEST,'replyto')) {
2807 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2809 intval($_REQUEST['replyto']));
2810 $replyto = $r[0]['parent-uri'];
2811 $sub = $r[0]['title'];
2814 if (x($_REQUEST,'title')) {
2815 $sub = $_REQUEST['title'];
2818 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2822 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2825 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2826 $ret = api_format_messages($r[0], $recipient, $sender);
2829 $ret = array("error"=>$id);
2832 $data = Array('direct_message'=>$ret);
2837 $data = api_rss_extra($a, $data, $user_info);
2840 return api_format_data("direct-messages", $type, $data);
2843 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2847 * @brief delete a direct_message from mail table through api
2849 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2852 function api_direct_messages_destroy($type){
2855 if (api_user()===false) throw new ForbiddenException();
2858 $user_info = api_get_user($a);
2860 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);
2862 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
2863 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
2864 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2866 $uid = $user_info['uid'];
2867 // error if no id or parenturi specified (for clients posting parent-uri as well)
2868 if ($verbose == "true") {
2869 if ($id == 0 || $parenturi == "") {
2870 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
2871 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2875 // BadRequestException if no id specified (for clients using Twitter API)
2876 if ($id == 0) throw new BadRequestException('Message id not specified');
2878 // add parent-uri to sql command if specified by calling app
2879 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
2881 // get data of the specified message id
2882 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2886 // error message if specified id is not in database
2887 if (!dbm::is_result($r)) {
2888 if ($verbose == "true") {
2889 $answer = array('result' => 'error', 'message' => 'message id not in database');
2890 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2892 /// @todo BadRequestException ok for Twitter API clients?
2893 throw new BadRequestException('message id not in database');
2897 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2901 if ($verbose == "true") {
2904 $answer = array('result' => 'ok', 'message' => 'message deleted');
2905 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
2908 $answer = array('result' => 'error', 'message' => 'unknown error');
2909 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2912 /// @todo return JSON data like Twitter API not yet implemented
2915 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2918 function api_direct_messages_box($type, $box, $verbose) {
2922 if (api_user()===false) throw new ForbiddenException();
2925 $count = (x($_GET,'count')?$_GET['count']:20);
2926 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2927 if ($page<0) $page=0;
2929 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2930 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2932 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2933 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2936 unset($_REQUEST["user_id"]);
2937 unset($_GET["user_id"]);
2939 unset($_REQUEST["screen_name"]);
2940 unset($_GET["screen_name"]);
2942 $user_info = api_get_user($a);
2943 $profile_url = $user_info["url"];
2947 $start = $page*$count;
2950 if ($box=="sentbox") {
2951 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2953 elseif ($box=="conversation") {
2954 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2956 elseif ($box=="all") {
2957 $sql_extra = "true";
2959 elseif ($box=="inbox") {
2960 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2964 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2966 if ($user_id !="") {
2967 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2969 elseif($screen_name !=""){
2970 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2973 $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",
2976 intval($start), intval($count)
2978 if ($verbose == "true") {
2979 // stop execution and return error message if no mails available
2981 $answer = array('result' => 'error', 'message' => 'no mails available');
2982 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
2987 foreach($r as $item) {
2988 if ($box == "inbox" || $item['from-url'] != $profile_url){
2989 $recipient = $user_info;
2990 $sender = api_get_user($a,normalise_link($item['contact-url']));
2992 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2993 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2994 $sender = $user_info;
2997 $ret[]=api_format_messages($item, $recipient, $sender);
3001 $data = array('direct_message' => $ret);
3005 $data = api_rss_extra($a, $data, $user_info);
3008 return api_format_data("direct-messages", $type, $data);
3012 function api_direct_messages_sentbox($type){
3013 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3014 return api_direct_messages_box($type, "sentbox", $verbose);
3016 function api_direct_messages_inbox($type){
3017 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3018 return api_direct_messages_box($type, "inbox", $verbose);
3020 function api_direct_messages_all($type){
3021 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3022 return api_direct_messages_box($type, "all", $verbose);
3024 function api_direct_messages_conversation($type){
3025 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3026 return api_direct_messages_box($type, "conversation", $verbose);
3028 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3029 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3030 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3031 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3035 function api_oauth_request_token($type){
3037 $oauth = new FKOAuth1();
3038 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3039 }catch(Exception $e){
3040 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3045 function api_oauth_access_token($type){
3047 $oauth = new FKOAuth1();
3048 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3049 }catch(Exception $e){
3050 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3056 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3057 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3060 function api_fr_photos_list($type) {
3061 if (api_user()===false) throw new ForbiddenException();
3062 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
3063 where uid = %d and album != 'Contact Photos' group by `resource-id`",
3064 intval(local_user())
3067 'image/jpeg' => 'jpg',
3068 'image/png' => 'png',
3069 'image/gif' => 'gif'
3071 $data = array('photo'=>array());
3073 foreach($r as $rr) {
3075 $photo['id'] = $rr['resource-id'];
3076 $photo['album'] = $rr['album'];
3077 $photo['filename'] = $rr['filename'];
3078 $photo['type'] = $rr['type'];
3079 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
3082 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3084 $photo['thumb'] = $thumb;
3085 $data['photo'][] = $photo;
3089 return api_format_data("photos", $type, $data);
3092 function api_fr_photo_detail($type) {
3093 if (api_user()===false) throw new ForbiddenException();
3094 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
3096 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3097 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
3098 $data_sql = ($scale === false ? "" : "data, ");
3100 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3101 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
3102 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
3104 intval(local_user()),
3105 dbesc($_REQUEST['photo_id']),
3110 'image/jpeg' => 'jpg',
3111 'image/png' => 'png',
3112 'image/gif' => 'gif'
3116 $data = array('photo' => $r[0]);
3117 $data['photo']['id'] = $data['photo']['resource-id'];
3118 if ($scale !== false) {
3119 $data['photo']['data'] = base64_encode($data['photo']['data']);
3121 unset($data['photo']['datasize']); //needed only with scale param
3123 if ($type == "xml") {
3124 $data['photo']['links'] = array();
3125 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
3126 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
3128 "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
3130 $data['photo']['link'] = array();
3131 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
3132 $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
3135 unset($data['photo']['resource-id']);
3136 unset($data['photo']['minscale']);
3137 unset($data['photo']['maxscale']);
3140 throw new NotFoundException();
3143 return api_format_data("photo_detail", $type, $data);
3146 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3147 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3152 * similar as /mod/redir.php
3153 * redirect to 'url' after dfrn auth
3155 * why this when there is mod/redir.php already?
3156 * This use api_user() and api_login()
3159 * c_url: url of remote contact to auth to
3160 * url: string, url to redirect after auth
3162 function api_friendica_remoteauth() {
3163 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
3164 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
3166 if ($url === '' || $c_url === '')
3167 throw new BadRequestException("Wrong parameters.");
3169 $c_url = normalise_link($c_url);
3173 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3178 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
3179 throw new BadRequestException("Unknown contact");
3183 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3185 if($r[0]['duplex'] && $r[0]['issued-id']) {
3186 $orig_id = $r[0]['issued-id'];
3187 $dfrn_id = '1:' . $orig_id;
3189 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3190 $orig_id = $r[0]['dfrn-id'];
3191 $dfrn_id = '0:' . $orig_id;
3194 $sec = random_string();
3196 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3197 VALUES( %d, %s, '%s', '%s', %d )",
3205 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3206 $dest = (($url) ? '&destination_url=' . $url : '');
3207 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3208 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3209 . '&type=profile&sec=' . $sec . $dest . $quiet );
3211 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3214 * @brief Return the item shared, if the item contains only the [share] tag
3216 * @param array $item Sharer item
3217 * @return array Shared item or false if not a reshare
3219 function api_share_as_retweet(&$item) {
3220 $body = trim($item["body"]);
3222 if (diaspora::is_reshare($body, false)===false) {
3226 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3227 // Skip if there is no shared message in there
3228 // we already checked this in diaspora::is_reshare()
3229 // but better one more than one less...
3230 if ($body == $attributes)
3234 // build the fake reshared item
3235 $reshared_item = $item;
3238 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3239 if ($matches[1] != "")
3240 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3242 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3243 if ($matches[1] != "")
3244 $author = $matches[1];
3247 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3248 if ($matches[1] != "")
3249 $profile = $matches[1];
3251 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3252 if ($matches[1] != "")
3253 $profile = $matches[1];
3256 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3257 if ($matches[1] != "")
3258 $avatar = $matches[1];
3260 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3261 if ($matches[1] != "")
3262 $avatar = $matches[1];
3265 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3266 if ($matches[1] != "")
3267 $link = $matches[1];
3269 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3270 if ($matches[1] != "")
3271 $link = $matches[1];
3274 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3275 if ($matches[1] != "")
3276 $posted= $matches[1];
3278 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3279 if ($matches[1] != "")
3280 $posted = $matches[1];
3282 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3284 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3289 $reshared_item["body"] = $shared_body;
3290 $reshared_item["author-name"] = $author;
3291 $reshared_item["author-link"] = $profile;
3292 $reshared_item["author-avatar"] = $avatar;
3293 $reshared_item["plink"] = $link;
3294 $reshared_item["created"] = $posted;
3295 $reshared_item["edited"] = $posted;
3297 return $reshared_item;
3301 function api_get_nick($profile) {
3303 - remove trailing junk from profile url
3304 - pump.io check has to check the website
3309 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3310 dbesc(normalise_link($profile)));
3312 $nick = $r[0]["nick"];
3315 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3316 dbesc(normalise_link($profile)));
3318 $nick = $r[0]["nick"];
3322 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3323 if ($friendica != $profile)
3328 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3329 if ($diaspora != $profile)
3334 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3335 if ($twitter != $profile)
3341 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3342 if ($StatusnetHost != $profile) {
3343 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3344 if ($StatusnetUser != $profile) {
3345 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3346 $user = json_decode($UserData);
3348 $nick = $user->screen_name;
3353 // To-Do: look at the page if its really a pumpio site
3354 //if (!$nick == "") {
3355 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3356 // if ($pumpio != $profile)
3358 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3368 function api_in_reply_to($item) {
3369 $in_reply_to = array();
3371 $in_reply_to['status_id'] = NULL;
3372 $in_reply_to['user_id'] = NULL;
3373 $in_reply_to['status_id_str'] = NULL;
3374 $in_reply_to['user_id_str'] = NULL;
3375 $in_reply_to['screen_name'] = NULL;
3377 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
3378 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
3379 intval($item['uid']),
3380 dbesc($item['thr-parent']));
3382 if (dbm::is_result($r)) {
3383 $in_reply_to['status_id'] = intval($r[0]['id']);
3385 $in_reply_to['status_id'] = intval($item['parent']);
3388 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3390 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
3391 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
3392 WHERE `item`.`id` = %d LIMIT 1",
3393 intval($in_reply_to['status_id'])
3396 if (dbm::is_result($r)) {
3397 if ($r[0]['nick'] == "") {
3398 $r[0]['nick'] = api_get_nick($r[0]["url"]);
3401 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
3402 $in_reply_to['user_id'] = intval($r[0]['id']);
3403 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
3406 // There seems to be situation, where both fields are identical:
3407 // https://github.com/friendica/friendica/issues/1010
3408 // This is a bugfix for that.
3409 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3410 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
3411 $in_reply_to['status_id'] = NULL;
3412 $in_reply_to['user_id'] = NULL;
3413 $in_reply_to['status_id_str'] = NULL;
3414 $in_reply_to['user_id_str'] = NULL;
3415 $in_reply_to['screen_name'] = NULL;
3419 return $in_reply_to;
3422 function api_clean_plain_items($Text) {
3423 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3425 $Text = bb_CleanPictureLinks($Text);
3426 $URLSearchString = "^\[\]";
3428 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3430 if ($include_entities == "true") {
3431 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3434 // Simplify "attachment" element
3435 $Text = api_clean_attachments($Text);
3441 * @brief Removes most sharing information for API text export
3443 * @param string $body The original body
3445 * @return string Cleaned body
3447 function api_clean_attachments($body) {
3448 $data = get_attachment_data($body);
3455 if (isset($data["text"]))
3456 $body = $data["text"];
3458 if (($body == "") AND (isset($data["title"])))
3459 $body = $data["title"];
3461 if (isset($data["url"]))
3462 $body .= "\n".$data["url"];
3464 $body .= $data["after"];
3469 function api_best_nickname(&$contacts) {
3470 $best_contact = array();
3472 if (count($contact) == 0)
3475 foreach ($contacts AS $contact)
3476 if ($contact["network"] == "") {
3477 $contact["network"] = "dfrn";
3478 $best_contact = array($contact);
3481 if (sizeof($best_contact) == 0)
3482 foreach ($contacts AS $contact)
3483 if ($contact["network"] == "dfrn")
3484 $best_contact = array($contact);
3486 if (sizeof($best_contact) == 0)
3487 foreach ($contacts AS $contact)
3488 if ($contact["network"] == "dspr")
3489 $best_contact = array($contact);
3491 if (sizeof($best_contact) == 0)
3492 foreach ($contacts AS $contact)
3493 if ($contact["network"] == "stat")
3494 $best_contact = array($contact);
3496 if (sizeof($best_contact) == 0)
3497 foreach ($contacts AS $contact)
3498 if ($contact["network"] == "pump")
3499 $best_contact = array($contact);
3501 if (sizeof($best_contact) == 0)
3502 foreach ($contacts AS $contact)
3503 if ($contact["network"] == "twit")
3504 $best_contact = array($contact);
3506 if (sizeof($best_contact) == 1)
3507 $contacts = $best_contact;
3509 $contacts = array($contacts[0]);
3512 // return all or a specified group of the user with the containing contacts
3513 function api_friendica_group_show($type) {
3517 if (api_user()===false) throw new ForbiddenException();
3520 $user_info = api_get_user($a);
3521 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3522 $uid = $user_info['uid'];
3524 // get data of the specified group id or all groups if not specified
3526 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3529 // error message if specified gid is not in database
3531 throw new BadRequestException("gid not available");
3534 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3537 // loop through all groups and retrieve all members for adding data in the user array
3538 foreach ($r as $rr) {
3539 $members = group_get_members($rr['id']);
3542 if ($type == "xml") {
3543 $user_element = "users";
3545 foreach ($members as $member) {
3546 $user = api_get_user($a, $member['nurl']);
3547 $users[$k++.":user"] = $user;
3550 $user_element = "user";
3551 foreach ($members as $member) {
3552 $user = api_get_user($a, $member['nurl']);
3556 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3558 return api_format_data("groups", $type, array('group' => $grps));
3560 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3563 // delete the specified group of the user
3564 function api_friendica_group_delete($type) {
3568 if (api_user()===false) throw new ForbiddenException();
3571 $user_info = api_get_user($a);
3572 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3573 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3574 $uid = $user_info['uid'];
3576 // error if no gid specified
3577 if ($gid == 0 || $name == "")
3578 throw new BadRequestException('gid or name not specified');
3580 // get data of the specified group id
3581 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3584 // error message if specified gid is not in database
3586 throw new BadRequestException('gid not available');
3588 // get data of the specified group id and group name
3589 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3593 // error message if specified gid is not in database
3594 if (count($rname) == 0)
3595 throw new BadRequestException('wrong group name');
3598 $ret = group_rmv($uid, $name);
3601 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3602 return api_format_data("group_delete", $type, array('result' => $success));
3605 throw new BadRequestException('other API error');
3607 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3610 // create the specified group with the posted array of contacts
3611 function api_friendica_group_create($type) {
3615 if (api_user()===false) throw new ForbiddenException();
3618 $user_info = api_get_user($a);
3619 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3620 $uid = $user_info['uid'];
3621 $json = json_decode($_POST['json'], true);
3622 $users = $json['user'];
3624 // error if no name specified
3626 throw new BadRequestException('group name not specified');
3628 // get data of the specified group name
3629 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3632 // error message if specified group name already exists
3633 if (count($rname) != 0)
3634 throw new BadRequestException('group name already exists');
3636 // check if specified group name is a deleted group
3637 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3640 // error message if specified group name already exists
3641 if (count($rname) != 0)
3642 $reactivate_group = true;
3645 $ret = group_add($uid, $name);
3647 $gid = group_byname($uid, $name);
3649 throw new BadRequestException('other API error');
3652 $erroraddinguser = false;
3653 $errorusers = array();
3654 foreach ($users as $user) {
3655 $cid = $user['cid'];
3656 // check if user really exists as contact
3657 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3660 if (count($contact))
3661 $result = group_add_member($uid, $name, $cid, $gid);
3663 $erroraddinguser = true;
3664 $errorusers[] = $cid;
3668 // return success message incl. missing users in array
3669 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3670 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3671 return api_format_data("group_create", $type, array('result' => $success));
3673 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3676 // update the specified group with the posted array of contacts
3677 function api_friendica_group_update($type) {
3681 if (api_user()===false) throw new ForbiddenException();
3684 $user_info = api_get_user($a);
3685 $uid = $user_info['uid'];
3686 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3687 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3688 $json = json_decode($_POST['json'], true);
3689 $users = $json['user'];
3691 // error if no name specified
3693 throw new BadRequestException('group name not specified');
3695 // error if no gid specified
3697 throw new BadRequestException('gid not specified');
3700 $members = group_get_members($gid);
3701 foreach ($members as $member) {
3702 $cid = $member['id'];
3703 foreach ($users as $user) {
3704 $found = ($user['cid'] == $cid ? true : false);
3707 $ret = group_rmv_member($uid, $name, $cid);
3712 $erroraddinguser = false;
3713 $errorusers = array();
3714 foreach ($users as $user) {
3715 $cid = $user['cid'];
3716 // check if user really exists as contact
3717 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3720 if (count($contact))
3721 $result = group_add_member($uid, $name, $cid, $gid);
3723 $erroraddinguser = true;
3724 $errorusers[] = $cid;
3728 // return success message incl. missing users in array
3729 $status = ($erroraddinguser ? "missing user" : "ok");
3730 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3731 return api_format_data("group_update", $type, array('result' => $success));
3733 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3736 function api_friendica_activity($type) {
3740 if (api_user()===false) throw new ForbiddenException();
3741 $verb = strtolower($a->argv[3]);
3742 $verb = preg_replace("|\..*$|", "", $verb);
3744 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3746 $res = do_like($id, $verb);
3753 return api_format_data('ok', $type, array('ok' => $ok));
3755 throw new BadRequestException('Error adding activity');
3759 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3760 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3761 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3762 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3763 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3764 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3765 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3766 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3767 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3768 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3771 * @brief Returns notifications
3773 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3776 function api_friendica_notification($type) {
3780 if (api_user()===false) throw new ForbiddenException();
3781 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3782 $nm = new NotificationsManager();
3784 $notes = $nm->getAll(array(), "+seen -date", 50);
3786 if ($type == "xml") {
3787 $xmlnotes = array();
3788 foreach ($notes AS $note)
3789 $xmlnotes[] = array("@attributes" => $note);
3794 return api_format_data("notes", $type, array('note' => $notes));
3798 * @brief Set notification as seen and returns associated item (if possible)
3800 * POST request with 'id' param as notification id
3802 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3805 function api_friendica_notification_seen($type){
3809 if (api_user()===false) throw new ForbiddenException();
3810 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3812 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3814 $nm = new NotificationsManager();
3815 $note = $nm->getByID($id);
3816 if (is_null($note)) throw new BadRequestException("Invalid argument");
3818 $nm->setSeen($note);
3819 if ($note['otype']=='item') {
3820 // would be really better with an ItemsManager and $im->getByID() :-P
3821 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3822 intval($note['iid']),
3823 intval(local_user())
3826 // we found the item, return it to the user
3827 $user_info = api_get_user($a);
3828 $ret = api_format_items($r,$user_info, false, $type);
3829 $data = array('status' => $ret);
3830 return api_format_data("status", $type, $data);
3832 // the item can't be found, but we set the note as seen, so we count this as a success
3834 return api_format_data('result', $type, array('result' => "success"));
3837 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3838 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3842 * @brief update a direct_message to seen state
3844 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3845 * @return string (success result=ok, error result=error with error message)
3847 function api_friendica_direct_messages_setseen($type){
3849 if (api_user()===false) throw new ForbiddenException();
3852 $user_info = api_get_user($a);
3853 $uid = $user_info['uid'];
3854 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3856 // return error if id is zero
3858 $answer = array('result' => 'error', 'message' => 'message id not specified');
3859 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3862 // get data of the specified message id
3863 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
3866 // error message if specified id is not in database
3867 if (!dbm::is_result($r)) {
3868 $answer = array('result' => 'error', 'message' => 'message id not in database');
3869 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3872 // update seen indicator
3873 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
3879 $answer = array('result' => 'ok', 'message' => 'message set to seen');
3880 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
3882 $answer = array('result' => 'error', 'message' => 'unknown error');
3883 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3886 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
3892 * @brief search for direct_messages containing a searchstring through api
3894 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3895 * @return string (success: success=true if found and search_result contains found messages
3896 * success=false if nothing was found, search_result='nothing found',
3897 * error: result=error with error message)
3899 function api_friendica_direct_messages_search($type){
3902 if (api_user()===false) throw new ForbiddenException();
3905 $user_info = api_get_user($a);
3906 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");
3907 $uid = $user_info['uid'];
3909 // error if no searchstring specified
3910 if ($searchstring == "") {
3911 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
3912 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
3915 // get data for the specified searchstring
3916 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
3918 dbesc('%'.$searchstring.'%')
3921 $profile_url = $user_info["url"];
3922 // message if nothing was found
3924 $success = array('success' => false, 'search_results' => 'nothing found');
3927 foreach($r as $item) {
3928 if ($box == "inbox" || $item['from-url'] != $profile_url){
3929 $recipient = $user_info;
3930 $sender = api_get_user($a,normalise_link($item['contact-url']));
3932 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
3933 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3934 $sender = $user_info;
3936 $ret[]=api_format_messages($item, $recipient, $sender);
3938 $success = array('success' => true, 'search_results' => $ret);
3941 return api_format_data("direct_message_search", $type, array('$result' => $success));
3943 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
3947 * @brief return data of all the profiles a user has to the client
3949 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3952 function api_friendica_profile_show($type){
3955 if (api_user()===false) throw new ForbiddenException();
3958 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);
3960 // retrieve general information about profiles for user
3961 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
3962 $directory = get_config('system', 'directory');
3964 // get data of the specified profile id or all profiles of the user if not specified
3965 if ($profileid != 0) {
3966 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
3968 intval($profileid));
3969 // error message if specified gid is not in database
3971 throw new BadRequestException("profile_id not available");
3974 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
3975 intval(api_user()));
3977 // loop through all returned profiles and retrieve data and users
3979 foreach ($r as $rr) {
3980 $profile = api_format_items_profiles($rr, $type);
3982 // select all users from contact table, loop and prepare standard return for user data
3984 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
3986 intval($rr['profile_id']));
3988 foreach ($r as $rr) {
3989 $user = api_get_user($a, $rr['nurl']);
3990 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;
3992 $profile['users'] = $users;
3994 // add prepared profile data to array for final return
3995 if ($type == "xml") {
3996 $profiles[$k++.":profile"] = $profile;
3998 $profiles[] = $profile;
4002 // return settings, authenticated user and profiles data
4003 $result = array('multi_profiles' => $multi_profiles ? true : false,
4004 'global_dir' => $directory,
4005 'friendica_owner' => api_get_user($a, intval(api_user())),
4006 'profiles' => $profiles);
4007 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4009 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4013 [pagename] => api/1.1/statuses/lookup.json
4014 [id] => 605138389168451584
4015 [include_cards] => true
4016 [cards_platform] => Android-12
4017 [include_entities] => true
4018 [include_my_retweet] => 1
4020 [include_reply_count] => true
4021 [include_descendent_reply_count] => true
4025 Not implemented by now:
4026 statuses/retweets_of_me
4031 account/update_location
4032 account/update_profile_background_image
4033 account/update_profile_image
4036 friendica/profile/update
4037 friendica/profile/create
4038 friendica/profile/delete
4040 Not implemented in status.net:
4041 statuses/retweeted_to_me
4042 statuses/retweeted_by_me
4043 direct_messages/destroy
4045 account/update_delivery_device
4046 notifications/follow