3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use \Friendica\Core\Config;
11 require_once('include/HTTPExceptions.php');
13 require_once('include/bbcode.php');
14 require_once('include/datetime.php');
15 require_once('include/conversation.php');
16 require_once('include/oauth.php');
17 require_once('include/html2plain.php');
18 require_once('mod/share.php');
19 require_once('include/Photo.php');
20 require_once('mod/item.php');
21 require_once('include/security.php');
22 require_once('include/contact_selectors.php');
23 require_once('include/html2bbcode.php');
24 require_once('mod/wall_upload.php');
25 require_once('mod/proxy.php');
26 require_once('include/message.php');
27 require_once('include/group.php');
28 require_once('include/like.php');
29 require_once('include/NotificationsManager.php');
30 require_once('include/plaintext.php');
31 require_once('include/xml.php');
34 define('API_METHOD_ANY','*');
35 define('API_METHOD_GET','GET');
36 define('API_METHOD_POST','POST,PUT');
37 define('API_METHOD_DELETE','POST,DELETE');
45 * @brief Auth API user
47 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
48 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
49 * into a page, and visitors will post something without noticing it).
52 if ($_SESSION['allow_api'])
59 * @brief Get source name from API client
61 * Clients can send 'source' parameter to be show in post metadata
62 * as "sent via <source>".
63 * Some clients doesn't send a source param, we support ones we know
67 * Client source name, default to "api" if unset/unknown
69 function api_source() {
70 if (requestdata('source'))
71 return (requestdata('source'));
73 // Support for known clients that doesn't send a source name
74 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
77 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
83 * @brief Format date for API
85 * @param string $str Source date, as UTC
86 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
88 function api_date($str){
89 //Wed May 23 06:01:13 +0000 2007
90 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
94 * @brief Register API endpoint
96 * Register a function to be the endpont for defined API path.
98 * @param string $path API URL path, relative to App::get_baseurl()
99 * @param string $func Function name to call on path request
100 * @param bool $auth API need logged user
101 * @param string $method
102 * HTTP method reqiured to call this endpoint.
103 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
104 * Default to API_METHOD_ANY
106 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
114 // Workaround for hotot
115 $path = str_replace("api/", "api/1.1/", $path);
124 * @brief Login API user
126 * Log in user via OAuth1 or Simple HTTP Auth.
127 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
130 * @hook 'authenticate'
132 * 'username' => username from login form
133 * 'password' => password from login form
134 * 'authenticated' => return status,
135 * 'user_record' => return authenticated user record
137 * array $user logged user record
139 function api_login(App $a){
142 $oauth = new FKOAuth1();
143 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
144 if (!is_null($token)){
145 $oauth->loginUser($token->uid);
146 call_hooks('logged_in', $a->user);
149 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
150 }catch(Exception $e){
156 // workaround for HTTP-auth in CGI mode
157 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
158 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
159 if(strlen($userpass)) {
160 list($name, $password) = explode(':', $userpass);
161 $_SERVER['PHP_AUTH_USER'] = $name;
162 $_SERVER['PHP_AUTH_PW'] = $password;
166 if (!isset($_SERVER['PHP_AUTH_USER'])) {
167 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
168 header('WWW-Authenticate: Basic realm="Friendica"');
169 throw new UnauthorizedException("This API requires login");
172 $user = $_SERVER['PHP_AUTH_USER'];
173 $password = $_SERVER['PHP_AUTH_PW'];
174 $encrypted = hash('whirlpool',trim($password));
176 // allow "user@server" login (but ignore 'server' part)
177 $at=strstr($user, "@", true);
178 if ( $at ) $user=$at;
181 * next code from mod/auth.php. needs better solution
186 'username' => trim($user),
187 'password' => trim($password),
188 'authenticated' => 0,
189 'user_record' => null
194 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
195 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
196 * and later plugins should not interfere with an earlier one that succeeded.
200 call_hooks('authenticate', $addon_auth);
202 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
203 $record = $addon_auth['user_record'];
206 // process normal login request
208 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
209 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
214 if (dbm::is_result($r))
218 if((! $record) || (! count($record))) {
219 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
220 header('WWW-Authenticate: Basic realm="Friendica"');
221 #header('HTTP/1.0 401 Unauthorized');
222 #die('This api requires login');
223 throw new UnauthorizedException("This API requires login");
226 authenticate_success($record);
228 $_SESSION["allow_api"] = true;
230 call_hooks('logged_in', $a->user);
235 * @brief Check HTTP method of called API
237 * API endpoints can define which HTTP method to accept when called.
238 * This function check the current HTTP method agains endpoint
241 * @param string $method Required methods, uppercase, separated by comma
244 function api_check_method($method) {
245 if ($method=="*") return True;
246 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
250 * @brief Main API entry point
252 * Authenticate user, call registered API function, set HTTP headers
255 * @return string API call result
257 function api_call(App $a){
258 global $API, $called_api;
261 if (strpos($a->query_string, ".xml")>0) $type="xml";
262 if (strpos($a->query_string, ".json")>0) $type="json";
263 if (strpos($a->query_string, ".rss")>0) $type="rss";
264 if (strpos($a->query_string, ".atom")>0) $type="atom";
266 foreach ($API as $p=>$info){
267 if (strpos($a->query_string, $p)===0){
268 if (!api_check_method($info['method'])){
269 throw new MethodNotAllowedException();
272 $called_api= explode("/",$p);
273 //unset($_SERVER['PHP_AUTH_USER']);
274 if ($info['auth']===true && api_user()===false) {
278 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
279 logger('API parameters: ' . print_r($_REQUEST,true));
281 $stamp = microtime(true);
282 $r = call_user_func($info['func'], $type);
283 $duration = (float)(microtime(true)-$stamp);
284 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
286 if (get_config("system", "profiler")) {
287 $duration = microtime(true)-$a->performance["start"];
289 logger(parse_url($a->query_string, PHP_URL_PATH).": ".sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
290 round($a->performance["database"] - $a->performance["database_write"], 3),
291 round($a->performance["database_write"], 3),
292 round($a->performance["network"], 2),
293 round($a->performance["file"], 2),
294 round($duration - ($a->performance["database"] + $a->performance["network"]
295 + $a->performance["file"]), 2),
296 round($duration, 2)),
299 if (get_config("rendertime", "callstack")) {
300 $o = "Database Read:\n";
301 foreach ($a->callstack["database"] AS $func => $time) {
302 $time = round($time, 3);
304 $o .= $func.": ".$time."\n";
306 $o .= "\nDatabase Write:\n";
307 foreach ($a->callstack["database_write"] AS $func => $time) {
308 $time = round($time, 3);
310 $o .= $func.": ".$time."\n";
313 $o .= "\nNetwork:\n";
314 foreach ($a->callstack["network"] AS $func => $time) {
315 $time = round($time, 3);
317 $o .= $func.": ".$time."\n";
319 logger($o, LOGGER_DEBUG);
325 // api function returned false withour throw an
326 // exception. This should not happend, throw a 500
327 throw new InternalServerErrorException();
332 header ("Content-Type: text/xml");
336 header ("Content-Type: application/json");
338 $json = json_encode($rr);
339 if ($_GET['callback'])
340 $json = $_GET['callback']."(".$json.")";
344 header ("Content-Type: application/rss+xml");
345 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
348 header ("Content-Type: application/atom+xml");
349 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
355 logger('API call not implemented: '.$a->query_string);
356 throw new NotImplementedException();
357 } catch (HTTPException $e) {
358 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
359 return api_error($type, $e);
364 * @brief Format API error string
366 * @param string $type Return type (xml, json, rss, as)
367 * @param HTTPException $error Error object
368 * @return strin error message formatted as $type
370 function api_error($type, $e) {
374 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
375 # TODO: https://dev.twitter.com/overview/api/response-codes
377 $error = array("error" => $error,
378 "code" => $e->httpcode." ".$e->httpdesc,
379 "request" => $a->query_string);
381 $ret = api_format_data('status', $type, array('status' => $error));
385 header ("Content-Type: text/xml");
389 header ("Content-Type: application/json");
390 return json_encode($ret);
393 header ("Content-Type: application/rss+xml");
397 header ("Content-Type: application/atom+xml");
404 * @brief Set values for RSS template
407 * @param array $arr Array to be passed to template
408 * @param array $user_info
411 function api_rss_extra(App $a, $arr, $user_info){
412 if (is_null($user_info)) $user_info = api_get_user($a);
413 $arr['$user'] = $user_info;
414 $arr['$rss'] = array(
415 'alternate' => $user_info['url'],
416 'self' => App::get_baseurl(). "/". $a->query_string,
417 'base' => App::get_baseurl(),
418 'updated' => api_date(null),
419 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
420 'language' => $user_info['language'],
421 'logo' => App::get_baseurl()."/images/friendica-32.png",
429 * @brief Unique contact to contact url.
431 * @param int $id Contact id
432 * @return bool|string
433 * Contact url or False if contact id is unknown
435 function api_unique_id_to_url($id){
436 $r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
439 return ($r[0]["url"]);
445 * @brief Get user info array.
448 * @param int|string $contact_id Contact ID or URL
449 * @param string $type Return type (for errors)
451 function api_get_user(App $a, $contact_id = Null, $type = "json"){
458 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
460 // Searching for contact URL
461 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
462 $user = dbesc(normalise_link($contact_id));
464 $extra_query = "AND `contact`.`nurl` = '%s' ";
465 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
468 // Searching for contact id with uid = 0
469 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
470 $user = dbesc(api_unique_id_to_url($contact_id));
473 throw new BadRequestException("User not found.");
476 $extra_query = "AND `contact`.`nurl` = '%s' ";
477 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
480 if(is_null($user) && x($_GET, 'user_id')) {
481 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
484 throw new BadRequestException("User not found.");
487 $extra_query = "AND `contact`.`nurl` = '%s' ";
488 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
490 if(is_null($user) && x($_GET, 'screen_name')) {
491 $user = dbesc($_GET['screen_name']);
493 $extra_query = "AND `contact`.`nick` = '%s' ";
494 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
497 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
498 $argid = count($called_api);
499 list($user, $null) = explode(".",$a->argv[$argid]);
500 if(is_numeric($user)){
501 $user = dbesc(api_unique_id_to_url($user));
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
510 $user = dbesc($user);
512 $extra_query = "AND `contact`.`nick` = '%s' ";
513 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
517 logger("api_get_user: user ".$user, LOGGER_DEBUG);
520 if (api_user()===false) {
524 $user = $_SESSION['uid'];
525 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
530 logger('api_user: ' . $extra_query . ', user: ' . $user);
532 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
538 // Selecting the id by priority, friendica first
539 api_best_nickname($uinfo);
541 // if the contact wasn't found, fetch it from the contacts with uid = 0
542 if (count($uinfo)==0) {
546 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
549 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
551 // If no nick where given, extract it from the address
552 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
553 $r[0]['nick'] = api_get_nick($r[0]["url"]);
557 'id_str' => (string) $r[0]["id"],
558 'name' => $r[0]["name"],
559 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
560 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
561 'description' => $r[0]["about"],
562 'profile_image_url' => $r[0]["micro"],
563 'profile_image_url_https' => $r[0]["micro"],
564 'url' => $r[0]["url"],
565 'protected' => false,
566 'followers_count' => 0,
567 'friends_count' => 0,
569 'created_at' => api_date($r[0]["created"]),
570 'favourites_count' => 0,
572 'time_zone' => 'UTC',
573 'geo_enabled' => false,
575 'statuses_count' => 0,
577 'contributors_enabled' => false,
578 'is_translator' => false,
579 'is_translation_enabled' => false,
580 'following' => false,
581 'follow_request_sent' => false,
582 'statusnet_blocking' => false,
583 'notifications' => false,
584 'statusnet_profile_url' => $r[0]["url"],
586 'cid' => get_contact($r[0]["url"], api_user(), true),
588 'network' => $r[0]["network"],
593 throw new BadRequestException("User not found.");
597 if($uinfo[0]['self']) {
599 if ($uinfo[0]['network'] == "")
600 $uinfo[0]['network'] = NETWORK_DFRN;
602 $usr = q("select * from user where uid = %d limit 1",
605 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
609 // Counting is deactivated by now, due to performance issues
610 // count public wall messages
611 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
612 // intval($uinfo[0]['uid'])
614 //$countitms = $r[0]['count'];
617 // Counting is deactivated by now, due to performance issues
618 //$r = q("SELECT count(*) as `count` FROM `item`
619 // WHERE `contact-id` = %d",
620 // intval($uinfo[0]['id'])
622 //$countitms = $r[0]['count'];
626 // Counting is deactivated by now, due to performance issues
628 $r = q("SELECT count(*) as `count` FROM `contact`
629 WHERE `uid` = %d AND `rel` IN ( %d, %d )
630 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
631 intval($uinfo[0]['uid']),
632 intval(CONTACT_IS_SHARING),
633 intval(CONTACT_IS_FRIEND)
635 $countfriends = $r[0]['count'];
637 $r = q("SELECT count(*) as `count` FROM `contact`
638 WHERE `uid` = %d AND `rel` IN ( %d, %d )
639 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
640 intval($uinfo[0]['uid']),
641 intval(CONTACT_IS_FOLLOWER),
642 intval(CONTACT_IS_FRIEND)
644 $countfollowers = $r[0]['count'];
646 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
647 intval($uinfo[0]['uid'])
649 $starred = $r[0]['count'];
652 if(! $uinfo[0]['self']) {
662 // Add a nick if it isn't present there
663 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
664 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
667 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
669 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
672 'id' => intval($pcontact_id),
673 'id_str' => (string) intval($pcontact_id),
674 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
675 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
676 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
677 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
678 'profile_image_url' => $uinfo[0]['micro'],
679 'profile_image_url_https' => $uinfo[0]['micro'],
680 'url' => $uinfo[0]['url'],
681 'protected' => false,
682 'followers_count' => intval($countfollowers),
683 'friends_count' => intval($countfriends),
685 'created_at' => api_date($uinfo[0]['created']),
686 'favourites_count' => intval($starred),
688 'time_zone' => 'UTC',
689 'geo_enabled' => false,
691 'statuses_count' => intval($countitms),
693 'contributors_enabled' => false,
694 'is_translator' => false,
695 'is_translation_enabled' => false,
696 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
697 'follow_request_sent' => false,
698 'statusnet_blocking' => false,
699 'notifications' => false,
700 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
701 'statusnet_profile_url' => $uinfo[0]['url'],
702 'uid' => intval($uinfo[0]['uid']),
703 'cid' => intval($uinfo[0]['cid']),
704 'self' => $uinfo[0]['self'],
705 'network' => $uinfo[0]['network'],
713 * @brief return api-formatted array for item's author and owner
716 * @param array $item : item from db
717 * @return array(array:author, array:owner)
719 function api_item_get_user(App $a, $item) {
721 $status_user = api_get_user($a, $item["author-link"]);
723 $status_user["protected"] = (($item["allow_cid"] != "") OR
724 ($item["allow_gid"] != "") OR
725 ($item["deny_cid"] != "") OR
726 ($item["deny_gid"] != "") OR
729 if ($item['thr-parent'] == $item['uri']) {
730 $owner_user = api_get_user($a, $item["owner-link"]);
732 $owner_user = $status_user;
735 return (array($status_user, $owner_user));
739 * @brief walks recursively through an array with the possibility to change value and key
741 * @param array $array The array to walk through
742 * @param string $callback The callback function
744 * @return array the transformed array
746 function api_walk_recursive(array &$array, callable $callback) {
748 $new_array = array();
750 foreach ($array as $k => $v) {
752 if ($callback($v, $k))
753 $new_array[$k] = api_walk_recursive($v, $callback);
755 if ($callback($v, $k))
765 * @brief Callback function to transform the array in an array that can be transformed in a XML file
767 * @param variant $item Array item value
768 * @param string $key Array key
770 * @return boolean Should the array item be deleted?
772 function api_reformat_xml(&$item, &$key) {
774 $item = ($item ? "true" : "false");
776 if (substr($key, 0, 10) == "statusnet_")
777 $key = "statusnet:".substr($key, 10);
778 elseif (substr($key, 0, 10) == "friendica_")
779 $key = "friendica:".substr($key, 10);
781 // $key = "default:".$key;
787 * @brief Creates the XML from a JSON style array
789 * @param array $data JSON style array
790 * @param string $root_element Name of the root element
792 * @return string The XML data
794 function api_create_xml($data, $root_element) {
795 $childname = key($data);
796 $data2 = array_pop($data);
799 $namespaces = array("" => "http://api.twitter.com",
800 "statusnet" => "http://status.net/schema/api/1/",
801 "friendica" => "http://friendi.ca/schema/api/1/",
802 "georss" => "http://www.georss.org/georss");
804 /// @todo Auto detection of needed namespaces
805 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
806 $namespaces = array();
808 if (is_array($data2))
809 api_walk_recursive($data2, "api_reformat_xml");
815 foreach ($data2 AS $item)
816 $data4[$i++.":".$childname] = $item;
821 $data3 = array($root_element => $data2);
823 $ret = xml::from_array($data3, $xml, false, $namespaces);
828 * @brief Formats the data according to the data type
830 * @param string $root_element Name of the root element
831 * @param string $type Return type (atom, rss, xml, json)
832 * @param array $data JSON style array
834 * @return (string|object) XML data or JSON data
836 function api_format_data($root_element, $type, $data){
844 $ret = api_create_xml($data, $root_element);
859 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
860 * returns a 401 status code and an error message if not.
861 * http://developer.twitter.com/doc/get/account/verify_credentials
863 function api_account_verify_credentials($type){
867 if (api_user()===false) throw new ForbiddenException();
869 unset($_REQUEST["user_id"]);
870 unset($_GET["user_id"]);
872 unset($_REQUEST["screen_name"]);
873 unset($_GET["screen_name"]);
875 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
877 $user_info = api_get_user($a);
879 // "verified" isn't used here in the standard
880 unset($user_info["verified"]);
882 // - Adding last status
884 $user_info["status"] = api_status_show("raw");
885 if (!count($user_info["status"]))
886 unset($user_info["status"]);
888 unset($user_info["status"]["user"]);
891 // "uid" and "self" are only needed for some internal stuff, so remove it from here
892 unset($user_info["uid"]);
893 unset($user_info["self"]);
895 return api_format_data("user", $type, array('user' => $user_info));
898 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
902 * get data from $_POST or $_GET
904 function requestdata($k){
905 if (isset($_POST[$k])){
908 if (isset($_GET[$k])){
914 /*Waitman Gobble Mod*/
915 function api_statuses_mediap($type) {
919 if (api_user()===false) {
920 logger('api_statuses_update: no user');
921 throw new ForbiddenException();
923 $user_info = api_get_user($a);
925 $_REQUEST['type'] = 'wall';
926 $_REQUEST['profile_uid'] = api_user();
927 $_REQUEST['api_source'] = true;
928 $txt = requestdata('status');
929 //$txt = urldecode(requestdata('status'));
931 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
933 $txt = html2bb_video($txt);
934 $config = HTMLPurifier_Config::createDefault();
935 $config->set('Cache.DefinitionImpl', null);
936 $purifier = new HTMLPurifier($config);
937 $txt = $purifier->purify($txt);
939 $txt = html2bbcode($txt);
941 $a->argv[1]=$user_info['screen_name']; //should be set to username?
943 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
944 $bebop = wall_upload_post($a);
946 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
947 $_REQUEST['body']=$txt."\n\n".$bebop;
950 // this should output the last post (the one we just posted).
951 return api_status_show($type);
953 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
954 /*Waitman Gobble Mod*/
957 function api_statuses_update($type) {
961 if (api_user()===false) {
962 logger('api_statuses_update: no user');
963 throw new ForbiddenException();
966 $user_info = api_get_user($a);
968 // convert $_POST array items to the form we use for web posts.
970 // logger('api_post: ' . print_r($_POST,true));
972 if(requestdata('htmlstatus')) {
973 $txt = requestdata('htmlstatus');
974 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
975 $txt = html2bb_video($txt);
977 $config = HTMLPurifier_Config::createDefault();
978 $config->set('Cache.DefinitionImpl', null);
980 $purifier = new HTMLPurifier($config);
981 $txt = $purifier->purify($txt);
983 $_REQUEST['body'] = html2bbcode($txt);
987 $_REQUEST['body'] = requestdata('status');
989 $_REQUEST['title'] = requestdata('title');
991 $parent = requestdata('in_reply_to_status_id');
993 // Twidere sends "-1" if it is no reply ...
997 if(ctype_digit($parent))
998 $_REQUEST['parent'] = $parent;
1000 $_REQUEST['parent_uri'] = $parent;
1002 if(requestdata('lat') && requestdata('long'))
1003 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
1004 $_REQUEST['profile_uid'] = api_user();
1007 $_REQUEST['type'] = 'net-comment';
1009 // Check for throttling (maximum posts per day, week and month)
1010 $throttle_day = get_config('system','throttle_limit_day');
1011 if ($throttle_day > 0) {
1012 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1014 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1015 AND `created` > '%s' AND `id` = `parent`",
1016 intval(api_user()), dbesc($datefrom));
1019 $posts_day = $r[0]["posts_day"];
1023 if ($posts_day > $throttle_day) {
1024 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1025 #die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1026 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1030 $throttle_week = get_config('system','throttle_limit_week');
1031 if ($throttle_week > 0) {
1032 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1034 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1035 AND `created` > '%s' AND `id` = `parent`",
1036 intval(api_user()), dbesc($datefrom));
1039 $posts_week = $r[0]["posts_week"];
1043 if ($posts_week > $throttle_week) {
1044 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1045 #die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1046 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1051 $throttle_month = get_config('system','throttle_limit_month');
1052 if ($throttle_month > 0) {
1053 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1055 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1056 AND `created` > '%s' AND `id` = `parent`",
1057 intval(api_user()), dbesc($datefrom));
1060 $posts_month = $r[0]["posts_month"];
1064 if ($posts_month > $throttle_month) {
1065 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1066 #die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1067 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1071 $_REQUEST['type'] = 'wall';
1074 if(x($_FILES,'media')) {
1075 // upload the image if we have one
1076 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1077 $media = wall_upload_post($a);
1078 if(strlen($media)>0)
1079 $_REQUEST['body'] .= "\n\n".$media;
1082 // To-Do: Multiple IDs
1083 if (requestdata('media_ids')) {
1084 $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",
1085 intval(requestdata('media_ids')), api_user());
1087 $phototypes = Photo::supportedTypes();
1088 $ext = $phototypes[$r[0]['type']];
1089 $_REQUEST['body'] .= "\n\n".'[url='.App::get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1090 $_REQUEST['body'] .= '[img]'.App::get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1094 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1096 $_REQUEST['api_source'] = true;
1098 if (!x($_REQUEST, "source"))
1099 $_REQUEST["source"] = api_source();
1101 // call out normal post function
1105 // this should output the last post (the one we just posted).
1106 return api_status_show($type);
1108 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1109 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1112 function api_media_upload($type) {
1116 if (api_user()===false) {
1118 throw new ForbiddenException();
1121 $user_info = api_get_user($a);
1123 if(!x($_FILES,'media')) {
1125 throw new BadRequestException("No media.");
1128 $media = wall_upload_post($a, false);
1131 throw new InternalServerErrorException();
1134 $returndata = array();
1135 $returndata["media_id"] = $media["id"];
1136 $returndata["media_id_string"] = (string)$media["id"];
1137 $returndata["size"] = $media["size"];
1138 $returndata["image"] = array("w" => $media["width"],
1139 "h" => $media["height"],
1140 "image_type" => $media["type"]);
1142 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1144 return array("media" => $returndata);
1146 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1148 function api_status_show($type){
1152 $user_info = api_get_user($a);
1154 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1157 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1161 // get last public wall message
1162 $lastwall = q("SELECT `item`.*
1164 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1165 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1166 AND `item`.`type` != 'activity' $privacy_sql
1167 ORDER BY `item`.`id` DESC
1169 intval($user_info['cid']),
1171 dbesc($user_info['url']),
1172 dbesc(normalise_link($user_info['url'])),
1173 dbesc($user_info['url']),
1174 dbesc(normalise_link($user_info['url']))
1177 if (count($lastwall)>0){
1178 $lastwall = $lastwall[0];
1180 $in_reply_to = api_in_reply_to($lastwall);
1182 $converted = api_convert_item($lastwall);
1185 $geo = "georss:point";
1189 $status_info = array(
1190 'created_at' => api_date($lastwall['created']),
1191 'id' => intval($lastwall['id']),
1192 'id_str' => (string) $lastwall['id'],
1193 'text' => $converted["text"],
1194 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1195 'truncated' => false,
1196 'in_reply_to_status_id' => $in_reply_to['status_id'],
1197 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1198 'in_reply_to_user_id' => $in_reply_to['user_id'],
1199 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1200 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1201 'user' => $user_info,
1203 'coordinates' => "",
1205 'contributors' => "",
1206 'is_quote_status' => false,
1207 'retweet_count' => 0,
1208 'favorite_count' => 0,
1209 'favorited' => $lastwall['starred'] ? true : false,
1210 'retweeted' => false,
1211 'possibly_sensitive' => false,
1213 'statusnet_html' => $converted["html"],
1214 'statusnet_conversation_id' => $lastwall['parent'],
1217 if (count($converted["attachments"]) > 0)
1218 $status_info["attachments"] = $converted["attachments"];
1220 if (count($converted["entities"]) > 0)
1221 $status_info["entities"] = $converted["entities"];
1223 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1224 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1225 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1226 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1228 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1229 unset($status_info["user"]["uid"]);
1230 unset($status_info["user"]["self"]);
1233 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1236 return($status_info);
1238 return api_format_data("statuses", $type, array('status' => $status_info));
1247 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1248 * The author's most recent status will be returned inline.
1249 * http://developer.twitter.com/doc/get/users/show
1251 function api_users_show($type){
1255 $user_info = api_get_user($a);
1256 $lastwall = q("SELECT `item`.*
1258 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1259 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1260 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1261 AND `type`!='activity'
1262 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1266 dbesc(ACTIVITY_POST),
1267 intval($user_info['cid']),
1268 dbesc($user_info['url']),
1269 dbesc(normalise_link($user_info['url'])),
1270 dbesc($user_info['url']),
1271 dbesc(normalise_link($user_info['url']))
1274 if (count($lastwall)>0){
1275 $lastwall = $lastwall[0];
1277 $in_reply_to = api_in_reply_to($lastwall);
1279 $converted = api_convert_item($lastwall);
1282 $geo = "georss:point";
1286 $user_info['status'] = array(
1287 'text' => $converted["text"],
1288 'truncated' => false,
1289 'created_at' => api_date($lastwall['created']),
1290 'in_reply_to_status_id' => $in_reply_to['status_id'],
1291 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1292 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1293 'id' => intval($lastwall['contact-id']),
1294 'id_str' => (string) $lastwall['contact-id'],
1295 'in_reply_to_user_id' => $in_reply_to['user_id'],
1296 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1297 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1299 'favorited' => $lastwall['starred'] ? true : false,
1300 'statusnet_html' => $converted["html"],
1301 'statusnet_conversation_id' => $lastwall['parent'],
1304 if (count($converted["attachments"]) > 0)
1305 $user_info["status"]["attachments"] = $converted["attachments"];
1307 if (count($converted["entities"]) > 0)
1308 $user_info["status"]["entities"] = $converted["entities"];
1310 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1311 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1312 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1313 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1317 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1318 unset($user_info["uid"]);
1319 unset($user_info["self"]);
1321 return api_format_data("user", $type, array('user' => $user_info));
1324 api_register_func('api/users/show','api_users_show');
1327 function api_users_search($type) {
1331 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1333 $userlist = array();
1335 if (isset($_GET["q"])) {
1336 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1337 if (!dbm::is_result($r))
1338 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1340 if (dbm::is_result($r)) {
1342 foreach ($r AS $user) {
1343 $user_info = api_get_user($a, $user["id"], "json");
1346 $userlist[$k++.":user"] = $user_info;
1348 $userlist[] = $user_info;
1350 $userlist = array("users" => $userlist);
1352 throw new BadRequestException("User not found.");
1355 throw new BadRequestException("User not found.");
1357 return api_format_data("users", $type, $userlist);
1360 api_register_func('api/users/search','api_users_search');
1364 * http://developer.twitter.com/doc/get/statuses/home_timeline
1366 * TODO: Optional parameters
1367 * TODO: Add reply info
1369 function api_statuses_home_timeline($type){
1373 if (api_user()===false) throw new ForbiddenException();
1375 unset($_REQUEST["user_id"]);
1376 unset($_GET["user_id"]);
1378 unset($_REQUEST["screen_name"]);
1379 unset($_GET["screen_name"]);
1381 $user_info = api_get_user($a);
1382 // get last newtork messages
1385 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1386 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1387 if ($page<0) $page=0;
1388 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1389 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1390 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1391 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1392 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1394 $start = $page*$count;
1398 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1399 if ($exclude_replies > 0)
1400 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1401 if ($conversation_id > 0)
1402 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1404 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1405 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1406 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1407 `contact`.`id` AS `cid`
1409 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1410 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1411 WHERE `item`.`uid` = %d AND `verb` = '%s'
1412 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1415 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1417 dbesc(ACTIVITY_POST),
1419 intval($start), intval($count)
1422 $ret = api_format_items($r,$user_info, false, $type);
1424 // Set all posts from the query above to seen
1426 foreach ($r AS $item)
1427 $idarray[] = intval($item["id"]);
1429 $idlist = implode(",", $idarray);
1431 if ($idlist != "") {
1432 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1435 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1438 $data = array('status' => $ret);
1442 $data = api_rss_extra($a, $data, $user_info);
1446 return api_format_data("statuses", $type, $data);
1448 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1449 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1451 function api_statuses_public_timeline($type){
1455 if (api_user()===false) throw new ForbiddenException();
1457 $user_info = api_get_user($a);
1458 // get last newtork messages
1462 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1463 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1464 if ($page<0) $page=0;
1465 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1466 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1467 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1468 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1469 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1471 $start = $page*$count;
1474 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1475 if ($exclude_replies > 0)
1476 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1477 if ($conversation_id > 0)
1478 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1480 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1481 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1482 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1483 `contact`.`id` AS `cid`,
1484 `user`.`nickname`, `user`.`hidewall`
1486 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1487 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1488 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1489 AND NOT `user`.`hidewall`
1490 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1491 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1492 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1493 AND NOT `item`.`private` AND `item`.`wall`
1496 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1497 dbesc(ACTIVITY_POST),
1502 $ret = api_format_items($r,$user_info, false, $type);
1505 $data = array('status' => $ret);
1509 $data = api_rss_extra($a, $data, $user_info);
1513 return api_format_data("statuses", $type, $data);
1515 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1520 function api_statuses_show($type){
1524 if (api_user()===false) throw new ForbiddenException();
1526 $user_info = api_get_user($a);
1529 $id = intval($a->argv[3]);
1532 $id = intval($_REQUEST["id"]);
1536 $id = intval($a->argv[4]);
1538 logger('API: api_statuses_show: '.$id);
1540 $conversation = (x($_REQUEST,'conversation')?1:0);
1544 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1546 $sql_extra .= " AND `item`.`id` = %d";
1548 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1549 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1550 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1551 `contact`.`id` AS `cid`
1553 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1554 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1555 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1556 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1559 dbesc(ACTIVITY_POST),
1564 throw new BadRequestException("There is no status with this id.");
1567 $ret = api_format_items($r,$user_info, false, $type);
1569 if ($conversation) {
1570 $data = array('status' => $ret);
1571 return api_format_data("statuses", $type, $data);
1573 $data = array('status' => $ret[0]);
1574 return api_format_data("status", $type, $data);
1577 api_register_func('api/statuses/show','api_statuses_show', true);
1583 function api_conversation_show($type){
1587 if (api_user()===false) throw new ForbiddenException();
1589 $user_info = api_get_user($a);
1592 $id = intval($a->argv[3]);
1593 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1594 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1595 if ($page<0) $page=0;
1596 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1597 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1599 $start = $page*$count;
1602 $id = intval($_REQUEST["id"]);
1606 $id = intval($a->argv[4]);
1608 logger('API: api_conversation_show: '.$id);
1610 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1612 $id = $r[0]["parent"];
1617 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1619 // Not sure why this query was so complicated. We should keep it here for a while,
1620 // just to make sure that we really don't need it.
1621 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1622 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1624 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1625 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1626 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1627 `contact`.`id` AS `cid`
1629 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1630 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1631 WHERE `item`.`parent` = %d AND `item`.`visible`
1632 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1633 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1634 AND `item`.`id`>%d $sql_extra
1635 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1636 intval($id), intval(api_user()),
1637 dbesc(ACTIVITY_POST),
1639 intval($start), intval($count)
1643 throw new BadRequestException("There is no conversation with this id.");
1645 $ret = api_format_items($r,$user_info, false, $type);
1647 $data = array('status' => $ret);
1648 return api_format_data("statuses", $type, $data);
1650 api_register_func('api/conversation/show','api_conversation_show', true);
1651 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1657 function api_statuses_repeat($type){
1662 if (api_user()===false) throw new ForbiddenException();
1664 $user_info = api_get_user($a);
1667 $id = intval($a->argv[3]);
1670 $id = intval($_REQUEST["id"]);
1674 $id = intval($a->argv[4]);
1676 logger('API: api_statuses_repeat: '.$id);
1678 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1679 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1680 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1681 `contact`.`id` AS `cid`
1683 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1684 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1685 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1686 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1687 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1689 AND `item`.`id`=%d",
1693 if ($r[0]['body'] != "") {
1694 if (strpos($r[0]['body'], "[/share]") !== false) {
1695 $pos = strpos($r[0]['body'], "[share");
1696 $post = substr($r[0]['body'], $pos);
1698 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1700 $post .= $r[0]['body'];
1701 $post .= "[/share]";
1703 $_REQUEST['body'] = $post;
1704 $_REQUEST['profile_uid'] = api_user();
1705 $_REQUEST['type'] = 'wall';
1706 $_REQUEST['api_source'] = true;
1708 if (!x($_REQUEST, "source"))
1709 $_REQUEST["source"] = api_source();
1713 throw new ForbiddenException();
1715 // this should output the last post (the one we just posted).
1717 return(api_status_show($type));
1719 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1724 function api_statuses_destroy($type){
1728 if (api_user()===false) throw new ForbiddenException();
1730 $user_info = api_get_user($a);
1733 $id = intval($a->argv[3]);
1736 $id = intval($_REQUEST["id"]);
1740 $id = intval($a->argv[4]);
1742 logger('API: api_statuses_destroy: '.$id);
1744 $ret = api_statuses_show($type);
1746 drop_item($id, false);
1750 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1754 * http://developer.twitter.com/doc/get/statuses/mentions
1757 function api_statuses_mentions($type){
1761 if (api_user()===false) throw new ForbiddenException();
1763 unset($_REQUEST["user_id"]);
1764 unset($_GET["user_id"]);
1766 unset($_REQUEST["screen_name"]);
1767 unset($_GET["screen_name"]);
1769 $user_info = api_get_user($a);
1770 // get last newtork messages
1774 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1775 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1776 if ($page<0) $page=0;
1777 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1778 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1779 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1781 $start = $page*$count;
1783 // Ugly code - should be changed
1784 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1785 $myurl = substr($myurl,strpos($myurl,'://')+3);
1786 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1787 $myurl = str_replace('www.','',$myurl);
1788 $diasp_url = str_replace('/profile/','/u/',$myurl);
1791 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1793 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1794 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1795 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1796 `contact`.`id` AS `cid`
1797 FROM `item` FORCE INDEX (`uid_id`)
1798 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1799 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1800 WHERE `item`.`uid` = %d AND `verb` = '%s'
1801 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1802 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1803 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1806 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1808 dbesc(ACTIVITY_POST),
1809 dbesc(protect_sprintf($myurl)),
1810 dbesc(protect_sprintf($myurl)),
1813 intval($start), intval($count)
1816 $ret = api_format_items($r,$user_info, false, $type);
1819 $data = array('status' => $ret);
1823 $data = api_rss_extra($a, $data, $user_info);
1827 return api_format_data("statuses", $type, $data);
1829 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1830 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1833 function api_statuses_user_timeline($type){
1837 if (api_user()===false) throw new ForbiddenException();
1839 $user_info = api_get_user($a);
1840 // get last network messages
1842 logger("api_statuses_user_timeline: api_user: ". api_user() .
1843 "\nuser_info: ".print_r($user_info, true) .
1844 "\n_REQUEST: ".print_r($_REQUEST, true),
1848 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1849 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1850 if ($page<0) $page=0;
1851 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1852 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1853 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1854 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1856 $start = $page*$count;
1859 if ($user_info['self']==1)
1860 $sql_extra .= " AND `item`.`wall` = 1 ";
1862 if ($exclude_replies > 0)
1863 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1864 if ($conversation_id > 0)
1865 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1867 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1868 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1869 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1870 `contact`.`id` AS `cid`
1871 FROM `item` FORCE INDEX (`uid_contactid_id`)
1872 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1873 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1874 WHERE `item`.`uid` = %d AND `verb` = '%s'
1875 AND `item`.`contact-id` = %d
1876 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1879 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1881 dbesc(ACTIVITY_POST),
1882 intval($user_info['cid']),
1884 intval($start), intval($count)
1887 $ret = api_format_items($r,$user_info, true, $type);
1889 $data = array('status' => $ret);
1893 $data = api_rss_extra($a, $data, $user_info);
1896 return api_format_data("statuses", $type, $data);
1898 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1902 * Star/unstar an item
1903 * param: id : id of the item
1905 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1907 function api_favorites_create_destroy($type){
1911 if (api_user()===false) throw new ForbiddenException();
1913 // for versioned api.
1914 /// @TODO We need a better global soluton
1916 if ($a->argv[1]=="1.1") $action_argv_id=3;
1918 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1919 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1920 if ($a->argc==$action_argv_id+2) {
1921 $itemid = intval($a->argv[$action_argv_id+1]);
1923 $itemid = intval($_REQUEST['id']);
1926 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1927 $itemid, api_user());
1929 if ($item===false || count($item)==0)
1930 throw new BadRequestException("Invalid item.");
1934 $item[0]['starred']=1;
1937 $item[0]['starred']=0;
1940 throw new BadRequestException("Invalid action ".$action);
1942 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1943 $item[0]['starred'], $itemid, api_user());
1945 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1946 $item[0]['starred'], $itemid, api_user());
1949 throw InternalServerErrorException("DB error");
1952 $user_info = api_get_user($a);
1953 $rets = api_format_items($item, $user_info, false, $type);
1956 $data = array('status' => $ret);
1960 $data = api_rss_extra($a, $data, $user_info);
1963 return api_format_data("status", $type, $data);
1965 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1966 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1968 function api_favorites($type){
1973 if (api_user()===false) throw new ForbiddenException();
1975 $called_api= array();
1977 $user_info = api_get_user($a);
1979 // in friendica starred item are private
1980 // return favorites only for self
1981 logger('api_favorites: self:' . $user_info['self']);
1983 if ($user_info['self']==0) {
1989 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1990 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1991 $count = (x($_GET,'count')?$_GET['count']:20);
1992 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1993 if ($page<0) $page=0;
1995 $start = $page*$count;
1998 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
2000 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2001 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2002 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2003 `contact`.`id` AS `cid`
2004 FROM `item`, `contact`
2005 WHERE `item`.`uid` = %d
2006 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2007 AND `item`.`starred` = 1
2008 AND `contact`.`id` = `item`.`contact-id`
2009 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2012 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2015 intval($start), intval($count)
2018 $ret = api_format_items($r,$user_info, false, $type);
2022 $data = array('status' => $ret);
2026 $data = api_rss_extra($a, $data, $user_info);
2029 return api_format_data("statuses", $type, $data);
2031 api_register_func('api/favorites','api_favorites', true);
2033 function api_format_messages($item, $recipient, $sender) {
2034 // standard meta information
2036 'id' => $item['id'],
2037 'sender_id' => $sender['id'] ,
2039 'recipient_id' => $recipient['id'],
2040 'created_at' => api_date($item['created']),
2041 'sender_screen_name' => $sender['screen_name'],
2042 'recipient_screen_name' => $recipient['screen_name'],
2043 'sender' => $sender,
2044 'recipient' => $recipient,
2046 'friendica_seen' => $item['seen'],
2047 'friendica_parent_uri' => $item['parent-uri'],
2050 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2051 unset($ret["sender"]["uid"]);
2052 unset($ret["sender"]["self"]);
2053 unset($ret["recipient"]["uid"]);
2054 unset($ret["recipient"]["self"]);
2056 //don't send title to regular StatusNET requests to avoid confusing these apps
2057 if (x($_GET, 'getText')) {
2058 $ret['title'] = $item['title'] ;
2059 if ($_GET["getText"] == "html") {
2060 $ret['text'] = bbcode($item['body'], false, false);
2062 elseif ($_GET["getText"] == "plain") {
2063 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2064 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2068 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2070 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2071 unset($ret['sender']);
2072 unset($ret['recipient']);
2078 function api_convert_item($item) {
2079 $body = $item['body'];
2080 $attachments = api_get_attachments($body);
2082 // Workaround for ostatus messages where the title is identically to the body
2083 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2084 $statusbody = trim(html2plain($html, 0));
2086 // handle data: images
2087 $statusbody = api_format_items_embeded_images($item,$statusbody);
2089 $statustitle = trim($item['title']);
2091 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2092 $statustext = trim($statusbody);
2094 $statustext = trim($statustitle."\n\n".$statusbody);
2096 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2097 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2099 $statushtml = trim(bbcode($body, false, false));
2101 $search = array("<br>", "<blockquote>", "</blockquote>",
2102 "<h1>", "</h1>", "<h2>", "</h2>",
2103 "<h3>", "</h3>", "<h4>", "</h4>",
2104 "<h5>", "</h5>", "<h6>", "</h6>");
2105 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2106 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2107 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2108 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2109 $statushtml = str_replace($search, $replace, $statushtml);
2111 if ($item['title'] != "")
2112 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2114 $entities = api_get_entitities($statustext, $body);
2117 "text" => $statustext,
2118 "html" => $statushtml,
2119 "attachments" => $attachments,
2120 "entities" => $entities
2124 function api_get_attachments(&$body) {
2127 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2129 $URLSearchString = "^\[\]";
2130 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2135 $attachments = array();
2137 foreach ($images[1] AS $image) {
2138 $imagedata = get_photo_info($image);
2141 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2144 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2145 foreach ($images[0] AS $orig)
2146 $body = str_replace($orig, "", $body);
2148 return $attachments;
2151 function api_get_entitities(&$text, $bbcode) {
2154 * Links at the first character of the post
2159 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2161 if ($include_entities != "true") {
2163 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2165 foreach ($images[1] AS $image) {
2166 $replace = proxy_url($image);
2167 $text = str_replace($image, $replace, $text);
2172 $bbcode = bb_CleanPictureLinks($bbcode);
2174 // Change pure links in text to bbcode uris
2175 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2177 $entities = array();
2178 $entities["hashtags"] = array();
2179 $entities["symbols"] = array();
2180 $entities["urls"] = array();
2181 $entities["user_mentions"] = array();
2183 $URLSearchString = "^\[\]";
2185 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2187 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2188 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2189 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2191 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2192 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2193 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2195 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2196 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2197 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2199 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2201 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2202 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2204 $ordered_urls = array();
2205 foreach ($urls[1] AS $id=>$url) {
2206 //$start = strpos($text, $url, $offset);
2207 $start = iconv_strpos($text, $url, 0, "UTF-8");
2208 if (!($start === false))
2209 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2212 ksort($ordered_urls);
2215 //foreach ($urls[1] AS $id=>$url) {
2216 foreach ($ordered_urls AS $url) {
2217 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2218 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2219 $display_url = $url["title"];
2221 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2222 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2224 if (strlen($display_url) > 26)
2225 $display_url = substr($display_url, 0, 25)."…";
2228 //$start = strpos($text, $url, $offset);
2229 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2230 if (!($start === false)) {
2231 $entities["urls"][] = array("url" => $url["url"],
2232 "expanded_url" => $url["url"],
2233 "display_url" => $display_url,
2234 "indices" => array($start, $start+strlen($url["url"])));
2235 $offset = $start + 1;
2239 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2240 $ordered_images = array();
2241 foreach ($images[1] AS $image) {
2242 //$start = strpos($text, $url, $offset);
2243 $start = iconv_strpos($text, $image, 0, "UTF-8");
2244 if (!($start === false))
2245 $ordered_images[$start] = $image;
2247 //$entities["media"] = array();
2250 foreach ($ordered_images AS $url) {
2251 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2252 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2254 if (strlen($display_url) > 26)
2255 $display_url = substr($display_url, 0, 25)."…";
2257 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2258 if (!($start === false)) {
2259 $image = get_photo_info($url);
2261 // If image cache is activated, then use the following sizes:
2262 // thumb (150), small (340), medium (600) and large (1024)
2263 if (!get_config("system", "proxy_disabled")) {
2264 $media_url = proxy_url($url);
2267 $scale = scale_image($image[0], $image[1], 150);
2268 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2270 if (($image[0] > 150) OR ($image[1] > 150)) {
2271 $scale = scale_image($image[0], $image[1], 340);
2272 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2275 $scale = scale_image($image[0], $image[1], 600);
2276 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2278 if (($image[0] > 600) OR ($image[1] > 600)) {
2279 $scale = scale_image($image[0], $image[1], 1024);
2280 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2284 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2287 $entities["media"][] = array(
2289 "id_str" => (string)$start+1,
2290 "indices" => array($start, $start+strlen($url)),
2291 "media_url" => normalise_link($media_url),
2292 "media_url_https" => $media_url,
2294 "display_url" => $display_url,
2295 "expanded_url" => $url,
2299 $offset = $start + 1;
2305 function api_format_items_embeded_images(&$item, $text){
2306 $text = preg_replace_callback(
2307 "|data:image/([^;]+)[^=]+=*|m",
2308 function($match) use ($item) {
2309 return App::get_baseurl()."/display/".$item['guid'];
2317 * @brief return <a href='url'>name</a> as array
2319 * @param string $txt
2324 function api_contactlink_to_array($txt) {
2326 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2327 if ($r && count($match)==3) {
2329 'name' => $match[2],
2343 * @brief return likes, dislikes and attend status for item
2345 * @param array $item
2347 * likes => int count
2348 * dislikes => int count
2350 function api_format_items_activities(&$item, $type = "json") {
2354 $activities = array(
2356 'dislike' => array(),
2357 'attendyes' => array(),
2358 'attendno' => array(),
2359 'attendmaybe' => array()
2362 $items = q('SELECT * FROM item
2363 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2364 intval($item['uid']),
2365 dbesc($item['uri']));
2367 foreach ($items as $i){
2368 // not used as result should be structured like other user data
2369 //builtin_activity_puller($i, $activities);
2371 // get user data and add it to the array of the activity
2372 $user = api_get_user($a, $i['author-link']);
2373 switch($i['verb']) {
2375 $activities['like'][] = $user;
2377 case ACTIVITY_DISLIKE:
2378 $activities['dislike'][] = $user;
2380 case ACTIVITY_ATTEND:
2381 $activities['attendyes'][] = $user;
2383 case ACTIVITY_ATTENDNO:
2384 $activities['attendno'][] = $user;
2386 case ACTIVITY_ATTENDMAYBE:
2387 $activities['attendmaybe'][] = $user;
2394 if ($type == "xml") {
2395 $xml_activities = array();
2396 foreach ($activities as $k => $v) {
2397 // change xml element from "like" to "friendica:like"
2398 $xml_activities["friendica:".$k] = $v;
2399 // add user data into xml output
2401 foreach ($v as $user)
2402 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2404 $activities = $xml_activities;
2413 * @brief return data from profiles
2415 * @param array $profile array containing data from db table 'profile'
2416 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2419 function api_format_items_profiles(&$profile = null, $type = "json") {
2420 if ($profile != null) {
2421 $profile = array('profile_id' => $profile['id'],
2422 'profile_name' => $profile['profile-name'],
2423 'is_default' => $profile['is-default'] ? true : false,
2424 'hide_friends'=> $profile['hide-friends'] ? true : false,
2425 'profile_photo' => $profile['photo'],
2426 'profile_thumb' => $profile['thumb'],
2427 'publish' => $profile['publish'] ? true : false,
2428 'net_publish' => $profile['net-publish'] ? true : false,
2429 'description' => $profile['pdesc'],
2430 'date_of_birth' => $profile['dob'],
2431 'address' => $profile['address'],
2432 'city' => $profile['locality'],
2433 'region' => $profile['region'],
2434 'postal_code' => $profile['postal-code'],
2435 'country' => $profile['country-name'],
2436 'hometown' => $profile['hometown'],
2437 'gender' => $profile['gender'],
2438 'marital' => $profile['marital'],
2439 'marital_with' => $profile['with'],
2440 'marital_since' => $profile['howlong'],
2441 'sexual' => $profile['sexual'],
2442 'politic' => $profile['politic'],
2443 'religion' => $profile['religion'],
2444 'public_keywords' => $profile['pub_keywords'],
2445 'private_keywords' => $profile['prv_keywords'],
2446 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2447 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2448 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2449 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2450 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2451 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2452 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2453 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2454 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2455 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2456 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2457 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2458 'homepage' => $profile['homepage'],
2465 * @brief format items to be returned by api
2467 * @param array $r array of items
2468 * @param array $user_info
2469 * @param bool $filter_user filter items by $user_info
2471 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2477 foreach($r as $item) {
2479 localize_item($item);
2480 list($status_user, $owner_user) = api_item_get_user($a,$item);
2482 // Look if the posts are matching if they should be filtered by user id
2483 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2486 $in_reply_to = api_in_reply_to($item);
2488 $converted = api_convert_item($item);
2491 $geo = "georss:point";
2496 'text' => $converted["text"],
2497 'truncated' => False,
2498 'created_at'=> api_date($item['created']),
2499 'in_reply_to_status_id' => $in_reply_to['status_id'],
2500 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2501 'source' => (($item['app']) ? $item['app'] : 'web'),
2502 'id' => intval($item['id']),
2503 'id_str' => (string) intval($item['id']),
2504 'in_reply_to_user_id' => $in_reply_to['user_id'],
2505 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2506 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2508 'favorited' => $item['starred'] ? true : false,
2509 'user' => $status_user ,
2510 'friendica_owner' => $owner_user,
2511 //'entities' => NULL,
2512 'statusnet_html' => $converted["html"],
2513 'statusnet_conversation_id' => $item['parent'],
2514 'friendica_activities' => api_format_items_activities($item, $type),
2517 if (count($converted["attachments"]) > 0)
2518 $status["attachments"] = $converted["attachments"];
2520 if (count($converted["entities"]) > 0)
2521 $status["entities"] = $converted["entities"];
2523 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2524 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2525 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2526 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2529 // Retweets are only valid for top postings
2530 // It doesn't work reliable with the link if its a feed
2531 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2533 // $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2536 if ($item["id"] == $item["parent"]) {
2537 $retweeted_item = api_share_as_retweet($item);
2538 if ($retweeted_item !== false) {
2539 $retweeted_status = $status;
2541 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2542 } catch( BadRequestException $e ) {
2543 // user not found. should be found?
2544 /// @todo check if the user should be always found
2545 $retweeted_status["user"] = array();
2548 $rt_converted = api_convert_item($retweeted_item);
2550 $retweeted_status['text'] = $rt_converted["text"];
2551 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2552 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2553 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2554 $status['retweeted_status'] = $retweeted_status;
2558 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2559 unset($status["user"]["uid"]);
2560 unset($status["user"]["self"]);
2562 if ($item["coord"] != "") {
2563 $coords = explode(' ',$item["coord"]);
2564 if (count($coords) == 2) {
2565 if ($type == "json")
2566 $status["geo"] = array('type' => 'Point',
2567 'coordinates' => array((float) $coords[0],
2568 (float) $coords[1]));
2569 else // Not sure if this is the official format - if someone founds a documentation we can check
2570 $status["georss:point"] = $item["coord"];
2579 function api_account_rate_limit_status($type) {
2583 'remaining-hits' => (string) 150,
2584 '@attributes' => array("type" => "integer"),
2585 'hourly-limit' => (string) 150,
2586 '@attributes2' => array("type" => "integer"),
2587 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2588 '@attributes3' => array("type" => "datetime"),
2589 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2590 '@attributes4' => array("type" => "integer"),
2594 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2595 'remaining_hits' => (string) 150,
2596 'hourly_limit' => (string) 150,
2597 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2600 return api_format_data('hash', $type, array('hash' => $hash));
2602 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2604 function api_help_test($type) {
2610 return api_format_data('ok', $type, array("ok" => $ok));
2612 api_register_func('api/help/test','api_help_test',false);
2614 function api_lists($type) {
2616 return api_format_data('lists', $type, array("lists_list" => $ret));
2618 api_register_func('api/lists','api_lists',true);
2620 function api_lists_list($type) {
2622 return api_format_data('lists', $type, array("lists_list" => $ret));
2624 api_register_func('api/lists/list','api_lists_list',true);
2627 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2628 * This function is deprecated by Twitter
2629 * returns: json, xml
2631 function api_statuses_f($type, $qtype) {
2635 if (api_user()===false) throw new ForbiddenException();
2636 $user_info = api_get_user($a);
2638 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2639 /* this is to stop Hotot to load friends multiple times
2640 * I'm not sure if I'm missing return something or
2641 * is a bug in hotot. Workaround, meantime
2645 return array('$users' => $ret);*/
2649 if($qtype == 'friends')
2650 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2651 if($qtype == 'followers')
2652 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2654 // friends and followers only for self
2655 if ($user_info['self'] == 0)
2656 $sql_extra = " AND false ";
2658 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2663 foreach($r as $cid){
2664 $user = api_get_user($a, $cid['nurl']);
2665 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2666 unset($user["uid"]);
2667 unset($user["self"]);
2673 return array('user' => $ret);
2676 function api_statuses_friends($type){
2677 $data = api_statuses_f($type, "friends");
2678 if ($data===false) return false;
2679 return api_format_data("users", $type, $data);
2681 function api_statuses_followers($type){
2682 $data = api_statuses_f($type, "followers");
2683 if ($data===false) return false;
2684 return api_format_data("users", $type, $data);
2686 api_register_func('api/statuses/friends','api_statuses_friends',true);
2687 api_register_func('api/statuses/followers','api_statuses_followers',true);
2694 function api_statusnet_config($type) {
2698 $name = $a->config['sitename'];
2699 $server = $a->get_hostname();
2700 $logo = App::get_baseurl() . '/images/friendica-64.png';
2701 $email = $a->config['admin_email'];
2702 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2703 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2704 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2705 if($a->config['api_import_size'])
2706 $texlimit = string($a->config['api_import_size']);
2707 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2708 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2711 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2712 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2713 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2714 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2715 'shorturllength' => '30',
2716 'friendica' => array(
2717 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2718 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2719 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2720 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2725 return api_format_data('config', $type, array('config' => $config));
2728 api_register_func('api/gnusocial/config','api_statusnet_config',false);
2729 api_register_func('api/statusnet/config','api_statusnet_config',false);
2731 function api_statusnet_version($type) {
2733 $fake_statusnet_version = "0.9.7";
2735 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2737 api_register_func('api/gnusocial/version','api_statusnet_version',false);
2738 api_register_func('api/statusnet/version','api_statusnet_version',false);
2741 * @todo use api_format_data() to return data
2743 function api_ff_ids($type,$qtype) {
2747 if(! api_user()) throw new ForbiddenException();
2749 $user_info = api_get_user($a);
2751 if($qtype == 'friends')
2752 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2753 if($qtype == 'followers')
2754 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2756 if (!$user_info["self"])
2757 $sql_extra = " AND false ";
2759 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2761 $r = q("SELECT `pcontact`.`id` FROM `contact`
2762 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2763 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2767 if (!dbm::is_result($r))
2775 $ids[] = intval($rr['id']);
2777 return api_format_data("ids", $type, array('id' => $ids));
2780 function api_friends_ids($type) {
2781 return api_ff_ids($type,'friends');
2783 function api_followers_ids($type) {
2784 return api_ff_ids($type,'followers');
2786 api_register_func('api/friends/ids','api_friends_ids',true);
2787 api_register_func('api/followers/ids','api_followers_ids',true);
2790 function api_direct_messages_new($type) {
2794 if (api_user()===false) throw new ForbiddenException();
2796 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2798 $sender = api_get_user($a);
2800 if ($_POST['screen_name']) {
2801 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2803 dbesc($_POST['screen_name']));
2805 // Selecting the id by priority, friendica first
2806 api_best_nickname($r);
2808 $recipient = api_get_user($a, $r[0]['nurl']);
2810 $recipient = api_get_user($a, $_POST['user_id']);
2814 if (x($_REQUEST,'replyto')) {
2815 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2817 intval($_REQUEST['replyto']));
2818 $replyto = $r[0]['parent-uri'];
2819 $sub = $r[0]['title'];
2822 if (x($_REQUEST,'title')) {
2823 $sub = $_REQUEST['title'];
2826 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2830 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2833 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2834 $ret = api_format_messages($r[0], $recipient, $sender);
2837 $ret = array("error"=>$id);
2840 $data = Array('direct_message'=>$ret);
2845 $data = api_rss_extra($a, $data, $user_info);
2848 return api_format_data("direct-messages", $type, $data);
2851 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2855 * @brief delete a direct_message from mail table through api
2857 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2860 function api_direct_messages_destroy($type){
2863 if (api_user()===false) throw new ForbiddenException();
2866 $user_info = api_get_user($a);
2868 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);
2870 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
2871 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
2872 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2874 $uid = $user_info['uid'];
2875 // error if no id or parenturi specified (for clients posting parent-uri as well)
2876 if ($verbose == "true") {
2877 if ($id == 0 || $parenturi == "") {
2878 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
2879 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2883 // BadRequestException if no id specified (for clients using Twitter API)
2884 if ($id == 0) throw new BadRequestException('Message id not specified');
2886 // add parent-uri to sql command if specified by calling app
2887 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
2889 // get data of the specified message id
2890 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2894 // error message if specified id is not in database
2895 if (!dbm::is_result($r)) {
2896 if ($verbose == "true") {
2897 $answer = array('result' => 'error', 'message' => 'message id not in database');
2898 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2900 /// @todo BadRequestException ok for Twitter API clients?
2901 throw new BadRequestException('message id not in database');
2905 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2909 if ($verbose == "true") {
2912 $answer = array('result' => 'ok', 'message' => 'message deleted');
2913 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
2916 $answer = array('result' => 'error', 'message' => 'unknown error');
2917 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2920 /// @todo return JSON data like Twitter API not yet implemented
2923 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2926 function api_direct_messages_box($type, $box, $verbose) {
2930 if (api_user()===false) throw new ForbiddenException();
2933 $count = (x($_GET,'count')?$_GET['count']:20);
2934 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2935 if ($page<0) $page=0;
2937 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2938 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2940 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2941 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2944 unset($_REQUEST["user_id"]);
2945 unset($_GET["user_id"]);
2947 unset($_REQUEST["screen_name"]);
2948 unset($_GET["screen_name"]);
2950 $user_info = api_get_user($a);
2951 $profile_url = $user_info["url"];
2955 $start = $page*$count;
2958 if ($box=="sentbox") {
2959 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2961 elseif ($box=="conversation") {
2962 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2964 elseif ($box=="all") {
2965 $sql_extra = "true";
2967 elseif ($box=="inbox") {
2968 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2972 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2974 if ($user_id !="") {
2975 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2977 elseif($screen_name !=""){
2978 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2981 $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",
2984 intval($start), intval($count)
2986 if ($verbose == "true") {
2987 // stop execution and return error message if no mails available
2989 $answer = array('result' => 'error', 'message' => 'no mails available');
2990 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
2995 foreach($r as $item) {
2996 if ($box == "inbox" || $item['from-url'] != $profile_url){
2997 $recipient = $user_info;
2998 $sender = api_get_user($a,normalise_link($item['contact-url']));
3000 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
3001 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3002 $sender = $user_info;
3005 $ret[]=api_format_messages($item, $recipient, $sender);
3009 $data = array('direct_message' => $ret);
3013 $data = api_rss_extra($a, $data, $user_info);
3016 return api_format_data("direct-messages", $type, $data);
3020 function api_direct_messages_sentbox($type){
3021 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3022 return api_direct_messages_box($type, "sentbox", $verbose);
3024 function api_direct_messages_inbox($type){
3025 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3026 return api_direct_messages_box($type, "inbox", $verbose);
3028 function api_direct_messages_all($type){
3029 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3030 return api_direct_messages_box($type, "all", $verbose);
3032 function api_direct_messages_conversation($type){
3033 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3034 return api_direct_messages_box($type, "conversation", $verbose);
3036 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3037 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3038 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3039 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3043 function api_oauth_request_token($type){
3045 $oauth = new FKOAuth1();
3046 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3047 }catch(Exception $e){
3048 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3053 function api_oauth_access_token($type){
3055 $oauth = new FKOAuth1();
3056 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3057 }catch(Exception $e){
3058 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3064 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3065 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3068 function api_fr_photos_list($type) {
3069 if (api_user()===false) throw new ForbiddenException();
3070 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
3071 where uid = %d and album != 'Contact Photos' group by `resource-id`, album, filename, type",
3072 intval(local_user())
3075 'image/jpeg' => 'jpg',
3076 'image/png' => 'png',
3077 'image/gif' => 'gif'
3079 $data = array('photo'=>array());
3081 foreach ($r as $rr) {
3083 $photo['id'] = $rr['resource-id'];
3084 $photo['album'] = $rr['album'];
3085 $photo['filename'] = $rr['filename'];
3086 $photo['type'] = $rr['type'];
3087 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
3090 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3092 $photo['thumb'] = $thumb;
3093 $data['photo'][] = $photo;
3097 return api_format_data("photos", $type, $data);
3100 function api_fr_photo_detail($type) {
3101 if (api_user()===false) throw new ForbiddenException();
3102 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
3104 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3105 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
3106 $data_sql = ($scale === false ? "" : "ANY_VALUE(data) AS data,");
3108 $r = q("select %s ANY_VALUE(`resource-id`) AS `resource-id`, ANY_VALUE(`created`) AS `created`,
3109 ANY_VALUE(`edited`) AS `edited`, ANY_VALUE(`title`) AS `title`, ANY_VALUE(`desc`) AS `desc`,
3110 ANY_VALUE(`album`) AS `album`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
3111 ANY_VALUE(`height`) AS `height`, ANY_VALUE(`width`) AS `width`, ANY_VALUE(`datasize`) AS `datasize`,
3112 ANY_VALUE(`profile`) AS `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
3113 from photo where `uid` = %d and `resource-id` = '%s' %s",
3115 intval(local_user()),
3116 dbesc($_REQUEST['photo_id']),
3121 'image/jpeg' => 'jpg',
3122 'image/png' => 'png',
3123 'image/gif' => 'gif'
3127 $data = array('photo' => $r[0]);
3128 $data['photo']['id'] = $data['photo']['resource-id'];
3129 if ($scale !== false) {
3130 $data['photo']['data'] = base64_encode($data['photo']['data']);
3132 unset($data['photo']['datasize']); //needed only with scale param
3134 if ($type == "xml") {
3135 $data['photo']['links'] = array();
3136 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
3137 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
3139 "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
3141 $data['photo']['link'] = array();
3142 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
3143 $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
3146 unset($data['photo']['resource-id']);
3147 unset($data['photo']['minscale']);
3148 unset($data['photo']['maxscale']);
3151 throw new NotFoundException();
3154 return api_format_data("photo_detail", $type, $data);
3157 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3158 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3163 * similar as /mod/redir.php
3164 * redirect to 'url' after dfrn auth
3166 * why this when there is mod/redir.php already?
3167 * This use api_user() and api_login()
3170 * c_url: url of remote contact to auth to
3171 * url: string, url to redirect after auth
3173 function api_friendica_remoteauth() {
3174 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
3175 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
3177 if ($url === '' || $c_url === '')
3178 throw new BadRequestException("Wrong parameters.");
3180 $c_url = normalise_link($c_url);
3184 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3189 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN))
3190 throw new BadRequestException("Unknown contact");
3194 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3196 if($r[0]['duplex'] && $r[0]['issued-id']) {
3197 $orig_id = $r[0]['issued-id'];
3198 $dfrn_id = '1:' . $orig_id;
3200 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3201 $orig_id = $r[0]['dfrn-id'];
3202 $dfrn_id = '0:' . $orig_id;
3205 $sec = random_string();
3207 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3208 VALUES( %d, %s, '%s', '%s', %d )",
3216 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3217 $dest = (($url) ? '&destination_url=' . $url : '');
3218 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3219 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3220 . '&type=profile&sec=' . $sec . $dest . $quiet );
3222 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3225 * @brief Return the item shared, if the item contains only the [share] tag
3227 * @param array $item Sharer item
3228 * @return array Shared item or false if not a reshare
3230 function api_share_as_retweet(&$item) {
3231 $body = trim($item["body"]);
3233 if (Diaspora::is_reshare($body, false)===false) {
3237 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3238 // Skip if there is no shared message in there
3239 // we already checked this in diaspora::is_reshare()
3240 // but better one more than one less...
3241 if ($body == $attributes)
3245 // build the fake reshared item
3246 $reshared_item = $item;
3249 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3250 if ($matches[1] != "")
3251 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3253 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3254 if ($matches[1] != "")
3255 $author = $matches[1];
3258 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3259 if ($matches[1] != "")
3260 $profile = $matches[1];
3262 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3263 if ($matches[1] != "")
3264 $profile = $matches[1];
3267 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3268 if ($matches[1] != "")
3269 $avatar = $matches[1];
3271 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3272 if ($matches[1] != "")
3273 $avatar = $matches[1];
3276 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3277 if ($matches[1] != "")
3278 $link = $matches[1];
3280 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3281 if ($matches[1] != "")
3282 $link = $matches[1];
3285 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3286 if ($matches[1] != "")
3287 $posted= $matches[1];
3289 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3290 if ($matches[1] != "")
3291 $posted = $matches[1];
3293 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3295 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3300 $reshared_item["body"] = $shared_body;
3301 $reshared_item["author-name"] = $author;
3302 $reshared_item["author-link"] = $profile;
3303 $reshared_item["author-avatar"] = $avatar;
3304 $reshared_item["plink"] = $link;
3305 $reshared_item["created"] = $posted;
3306 $reshared_item["edited"] = $posted;
3308 return $reshared_item;
3312 function api_get_nick($profile) {
3314 - remove trailing junk from profile url
3315 - pump.io check has to check the website
3320 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3321 dbesc(normalise_link($profile)));
3323 $nick = $r[0]["nick"];
3326 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3327 dbesc(normalise_link($profile)));
3329 $nick = $r[0]["nick"];
3333 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3334 if ($friendica != $profile)
3339 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3340 if ($diaspora != $profile)
3345 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3346 if ($twitter != $profile)
3352 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3353 if ($StatusnetHost != $profile) {
3354 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3355 if ($StatusnetUser != $profile) {
3356 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3357 $user = json_decode($UserData);
3359 $nick = $user->screen_name;
3364 // To-Do: look at the page if its really a pumpio site
3365 //if (!$nick == "") {
3366 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3367 // if ($pumpio != $profile)
3369 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3379 function api_in_reply_to($item) {
3380 $in_reply_to = array();
3382 $in_reply_to['status_id'] = NULL;
3383 $in_reply_to['user_id'] = NULL;
3384 $in_reply_to['status_id_str'] = NULL;
3385 $in_reply_to['user_id_str'] = NULL;
3386 $in_reply_to['screen_name'] = NULL;
3388 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
3389 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
3390 intval($item['uid']),
3391 dbesc($item['thr-parent']));
3393 if (dbm::is_result($r)) {
3394 $in_reply_to['status_id'] = intval($r[0]['id']);
3396 $in_reply_to['status_id'] = intval($item['parent']);
3399 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3401 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
3402 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
3403 WHERE `item`.`id` = %d LIMIT 1",
3404 intval($in_reply_to['status_id'])
3407 if (dbm::is_result($r)) {
3408 if ($r[0]['nick'] == "") {
3409 $r[0]['nick'] = api_get_nick($r[0]["url"]);
3412 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
3413 $in_reply_to['user_id'] = intval($r[0]['id']);
3414 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
3417 // There seems to be situation, where both fields are identical:
3418 // https://github.com/friendica/friendica/issues/1010
3419 // This is a bugfix for that.
3420 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3421 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
3422 $in_reply_to['status_id'] = NULL;
3423 $in_reply_to['user_id'] = NULL;
3424 $in_reply_to['status_id_str'] = NULL;
3425 $in_reply_to['user_id_str'] = NULL;
3426 $in_reply_to['screen_name'] = NULL;
3430 return $in_reply_to;
3433 function api_clean_plain_items($Text) {
3434 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3436 $Text = bb_CleanPictureLinks($Text);
3437 $URLSearchString = "^\[\]";
3439 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3441 if ($include_entities == "true") {
3442 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3445 // Simplify "attachment" element
3446 $Text = api_clean_attachments($Text);
3452 * @brief Removes most sharing information for API text export
3454 * @param string $body The original body
3456 * @return string Cleaned body
3458 function api_clean_attachments($body) {
3459 $data = get_attachment_data($body);
3466 if (isset($data["text"]))
3467 $body = $data["text"];
3469 if (($body == "") AND (isset($data["title"])))
3470 $body = $data["title"];
3472 if (isset($data["url"]))
3473 $body .= "\n".$data["url"];
3475 $body .= $data["after"];
3480 function api_best_nickname(&$contacts) {
3481 $best_contact = array();
3483 if (count($contact) == 0)
3486 foreach ($contacts AS $contact)
3487 if ($contact["network"] == "") {
3488 $contact["network"] = "dfrn";
3489 $best_contact = array($contact);
3492 if (sizeof($best_contact) == 0)
3493 foreach ($contacts AS $contact)
3494 if ($contact["network"] == "dfrn")
3495 $best_contact = array($contact);
3497 if (sizeof($best_contact) == 0)
3498 foreach ($contacts AS $contact)
3499 if ($contact["network"] == "dspr")
3500 $best_contact = array($contact);
3502 if (sizeof($best_contact) == 0)
3503 foreach ($contacts AS $contact)
3504 if ($contact["network"] == "stat")
3505 $best_contact = array($contact);
3507 if (sizeof($best_contact) == 0)
3508 foreach ($contacts AS $contact)
3509 if ($contact["network"] == "pump")
3510 $best_contact = array($contact);
3512 if (sizeof($best_contact) == 0)
3513 foreach ($contacts AS $contact)
3514 if ($contact["network"] == "twit")
3515 $best_contact = array($contact);
3517 if (sizeof($best_contact) == 1)
3518 $contacts = $best_contact;
3520 $contacts = array($contacts[0]);
3523 // return all or a specified group of the user with the containing contacts
3524 function api_friendica_group_show($type) {
3528 if (api_user()===false) throw new ForbiddenException();
3531 $user_info = api_get_user($a);
3532 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3533 $uid = $user_info['uid'];
3535 // get data of the specified group id or all groups if not specified
3537 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3540 // error message if specified gid is not in database
3541 if (!dbm::is_result($r))
3542 throw new BadRequestException("gid not available");
3545 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3548 // loop through all groups and retrieve all members for adding data in the user array
3549 foreach ($r as $rr) {
3550 $members = group_get_members($rr['id']);
3553 if ($type == "xml") {
3554 $user_element = "users";
3556 foreach ($members as $member) {
3557 $user = api_get_user($a, $member['nurl']);
3558 $users[$k++.":user"] = $user;
3561 $user_element = "user";
3562 foreach ($members as $member) {
3563 $user = api_get_user($a, $member['nurl']);
3567 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3569 return api_format_data("groups", $type, array('group' => $grps));
3571 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3574 // delete the specified group of the user
3575 function api_friendica_group_delete($type) {
3579 if (api_user()===false) throw new ForbiddenException();
3582 $user_info = api_get_user($a);
3583 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3584 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3585 $uid = $user_info['uid'];
3587 // error if no gid specified
3588 if ($gid == 0 || $name == "")
3589 throw new BadRequestException('gid or name not specified');
3591 // get data of the specified group id
3592 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3595 // error message if specified gid is not in database
3596 if (!dbm::is_result($r))
3597 throw new BadRequestException('gid not available');
3599 // get data of the specified group id and group name
3600 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3604 // error message if specified gid is not in database
3605 if (!dbm::is_result($rname))
3606 throw new BadRequestException('wrong group name');
3609 $ret = group_rmv($uid, $name);
3612 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3613 return api_format_data("group_delete", $type, array('result' => $success));
3616 throw new BadRequestException('other API error');
3618 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3621 // create the specified group with the posted array of contacts
3622 function api_friendica_group_create($type) {
3626 if (api_user()===false) throw new ForbiddenException();
3629 $user_info = api_get_user($a);
3630 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3631 $uid = $user_info['uid'];
3632 $json = json_decode($_POST['json'], true);
3633 $users = $json['user'];
3635 // error if no name specified
3637 throw new BadRequestException('group name not specified');
3639 // get data of the specified group name
3640 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3643 // error message if specified group name already exists
3644 if (dbm::is_result($rname))
3645 throw new BadRequestException('group name already exists');
3647 // check if specified group name is a deleted group
3648 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3651 // error message if specified group name already exists
3652 if (dbm::is_result($rname))
3653 $reactivate_group = true;
3656 $ret = group_add($uid, $name);
3658 $gid = group_byname($uid, $name);
3660 throw new BadRequestException('other API error');
3663 $erroraddinguser = false;
3664 $errorusers = array();
3665 foreach ($users as $user) {
3666 $cid = $user['cid'];
3667 // check if user really exists as contact
3668 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3671 if (count($contact))
3672 $result = group_add_member($uid, $name, $cid, $gid);
3674 $erroraddinguser = true;
3675 $errorusers[] = $cid;
3679 // return success message incl. missing users in array
3680 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3681 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3682 return api_format_data("group_create", $type, array('result' => $success));
3684 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3687 // update the specified group with the posted array of contacts
3688 function api_friendica_group_update($type) {
3692 if (api_user()===false) throw new ForbiddenException();
3695 $user_info = api_get_user($a);
3696 $uid = $user_info['uid'];
3697 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3698 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3699 $json = json_decode($_POST['json'], true);
3700 $users = $json['user'];
3702 // error if no name specified
3704 throw new BadRequestException('group name not specified');
3706 // error if no gid specified
3708 throw new BadRequestException('gid not specified');
3711 $members = group_get_members($gid);
3712 foreach ($members as $member) {
3713 $cid = $member['id'];
3714 foreach ($users as $user) {
3715 $found = ($user['cid'] == $cid ? true : false);
3718 $ret = group_rmv_member($uid, $name, $cid);
3723 $erroraddinguser = false;
3724 $errorusers = array();
3725 foreach ($users as $user) {
3726 $cid = $user['cid'];
3727 // check if user really exists as contact
3728 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3731 if (count($contact))
3732 $result = group_add_member($uid, $name, $cid, $gid);
3734 $erroraddinguser = true;
3735 $errorusers[] = $cid;
3739 // return success message incl. missing users in array
3740 $status = ($erroraddinguser ? "missing user" : "ok");
3741 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3742 return api_format_data("group_update", $type, array('result' => $success));
3744 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3747 function api_friendica_activity($type) {
3751 if (api_user()===false) throw new ForbiddenException();
3752 $verb = strtolower($a->argv[3]);
3753 $verb = preg_replace("|\..*$|", "", $verb);
3755 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3757 $res = do_like($id, $verb);
3764 return api_format_data('ok', $type, array('ok' => $ok));
3766 throw new BadRequestException('Error adding activity');
3770 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3771 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3772 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3773 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3774 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3775 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3776 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3777 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3778 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3779 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3782 * @brief Returns notifications
3784 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3787 function api_friendica_notification($type) {
3791 if (api_user()===false) throw new ForbiddenException();
3792 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3793 $nm = new NotificationsManager();
3795 $notes = $nm->getAll(array(), "+seen -date", 50);
3797 if ($type == "xml") {
3798 $xmlnotes = array();
3799 foreach ($notes AS $note)
3800 $xmlnotes[] = array("@attributes" => $note);
3805 return api_format_data("notes", $type, array('note' => $notes));
3809 * @brief Set notification as seen and returns associated item (if possible)
3811 * POST request with 'id' param as notification id
3813 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3816 function api_friendica_notification_seen($type){
3820 if (api_user()===false) throw new ForbiddenException();
3821 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3823 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3825 $nm = new NotificationsManager();
3826 $note = $nm->getByID($id);
3827 if (is_null($note)) throw new BadRequestException("Invalid argument");
3829 $nm->setSeen($note);
3830 if ($note['otype']=='item') {
3831 // would be really better with an ItemsManager and $im->getByID() :-P
3832 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3833 intval($note['iid']),
3834 intval(local_user())
3837 // we found the item, return it to the user
3838 $user_info = api_get_user($a);
3839 $ret = api_format_items($r,$user_info, false, $type);
3840 $data = array('status' => $ret);
3841 return api_format_data("status", $type, $data);
3843 // the item can't be found, but we set the note as seen, so we count this as a success
3845 return api_format_data('result', $type, array('result' => "success"));
3848 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3849 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3853 * @brief update a direct_message to seen state
3855 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3856 * @return string (success result=ok, error result=error with error message)
3858 function api_friendica_direct_messages_setseen($type){
3860 if (api_user()===false) throw new ForbiddenException();
3863 $user_info = api_get_user($a);
3864 $uid = $user_info['uid'];
3865 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3867 // return error if id is zero
3869 $answer = array('result' => 'error', 'message' => 'message id not specified');
3870 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3873 // get data of the specified message id
3874 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
3877 // error message if specified id is not in database
3878 if (!dbm::is_result($r)) {
3879 $answer = array('result' => 'error', 'message' => 'message id not in database');
3880 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3883 // update seen indicator
3884 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
3890 $answer = array('result' => 'ok', 'message' => 'message set to seen');
3891 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
3893 $answer = array('result' => 'error', 'message' => 'unknown error');
3894 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3897 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
3903 * @brief search for direct_messages containing a searchstring through api
3905 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3906 * @return string (success: success=true if found and search_result contains found messages
3907 * success=false if nothing was found, search_result='nothing found',
3908 * error: result=error with error message)
3910 function api_friendica_direct_messages_search($type){
3913 if (api_user()===false) throw new ForbiddenException();
3916 $user_info = api_get_user($a);
3917 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");
3918 $uid = $user_info['uid'];
3920 // error if no searchstring specified
3921 if ($searchstring == "") {
3922 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
3923 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
3926 // get data for the specified searchstring
3927 $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",
3929 dbesc('%'.$searchstring.'%')
3932 $profile_url = $user_info["url"];
3933 // message if nothing was found
3934 if (!dbm::is_result($r))
3935 $success = array('success' => false, 'search_results' => 'problem with query');
3936 else if (count($r) == 0)
3937 $success = array('success' => false, 'search_results' => 'nothing found');
3940 foreach($r as $item) {
3941 if ($box == "inbox" || $item['from-url'] != $profile_url){
3942 $recipient = $user_info;
3943 $sender = api_get_user($a,normalise_link($item['contact-url']));
3945 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
3946 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3947 $sender = $user_info;
3949 $ret[]=api_format_messages($item, $recipient, $sender);
3951 $success = array('success' => true, 'search_results' => $ret);
3954 return api_format_data("direct_message_search", $type, array('$result' => $success));
3956 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
3959 * @brief return data of all the profiles a user has to the client
3961 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3964 function api_friendica_profile_show($type){
3967 if (api_user()===false) throw new ForbiddenException();
3970 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);
3972 // retrieve general information about profiles for user
3973 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
3974 $directory = get_config('system', 'directory');
3976 // get data of the specified profile id or all profiles of the user if not specified
3977 if ($profileid != 0) {
3978 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
3980 intval($profileid));
3981 // error message if specified gid is not in database
3982 if (!dbm::is_result($r))
3983 throw new BadRequestException("profile_id not available");
3985 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
3986 intval(api_user()));
3988 // loop through all returned profiles and retrieve data and users
3990 foreach ($r as $rr) {
3991 $profile = api_format_items_profiles($rr, $type);
3993 // select all users from contact table, loop and prepare standard return for user data
3995 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
3997 intval($rr['profile_id']));
3999 foreach ($r as $rr) {
4000 $user = api_get_user($a, $rr['nurl']);
4001 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;
4003 $profile['users'] = $users;
4005 // add prepared profile data to array for final return
4006 if ($type == "xml") {
4007 $profiles[$k++.":profile"] = $profile;
4009 $profiles[] = $profile;
4013 // return settings, authenticated user and profiles data
4014 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4016 $result = array('multi_profiles' => $multi_profiles ? true : false,
4017 'global_dir' => $directory,
4018 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4019 'profiles' => $profiles);
4020 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4022 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4026 [pagename] => api/1.1/statuses/lookup.json
4027 [id] => 605138389168451584
4028 [include_cards] => true
4029 [cards_platform] => Android-12
4030 [include_entities] => true
4031 [include_my_retweet] => 1
4033 [include_reply_count] => true
4034 [include_descendent_reply_count] => true
4038 Not implemented by now:
4039 statuses/retweets_of_me
4044 account/update_location
4045 account/update_profile_background_image
4046 account/update_profile_image
4049 friendica/profile/update
4050 friendica/profile/create
4051 friendica/profile/delete
4053 Not implemented in status.net:
4054 statuses/retweeted_to_me
4055 statuses/retweeted_by_me
4056 direct_messages/destroy
4058 account/update_delivery_device
4059 notifications/follow