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 $owner_user = api_get_user($a, $item["owner-link"]);
731 return (array($status_user, $owner_user));
735 * @brief walks recursively through an array with the possibility to change value and key
737 * @param array $array The array to walk through
738 * @param string $callback The callback function
740 * @return array the transformed array
742 function api_walk_recursive(array &$array, callable $callback) {
744 $new_array = array();
746 foreach ($array as $k => $v) {
748 if ($callback($v, $k))
749 $new_array[$k] = api_walk_recursive($v, $callback);
751 if ($callback($v, $k))
761 * @brief Callback function to transform the array in an array that can be transformed in a XML file
763 * @param variant $item Array item value
764 * @param string $key Array key
766 * @return boolean Should the array item be deleted?
768 function api_reformat_xml(&$item, &$key) {
770 $item = ($item ? "true" : "false");
772 if (substr($key, 0, 10) == "statusnet_")
773 $key = "statusnet:".substr($key, 10);
774 elseif (substr($key, 0, 10) == "friendica_")
775 $key = "friendica:".substr($key, 10);
777 // $key = "default:".$key;
783 * @brief Creates the XML from a JSON style array
785 * @param array $data JSON style array
786 * @param string $root_element Name of the root element
788 * @return string The XML data
790 function api_create_xml($data, $root_element) {
791 $childname = key($data);
792 $data2 = array_pop($data);
795 $namespaces = array("" => "http://api.twitter.com",
796 "statusnet" => "http://status.net/schema/api/1/",
797 "friendica" => "http://friendi.ca/schema/api/1/",
798 "georss" => "http://www.georss.org/georss");
800 /// @todo Auto detection of needed namespaces
801 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
802 $namespaces = array();
804 if (is_array($data2))
805 api_walk_recursive($data2, "api_reformat_xml");
811 foreach ($data2 AS $item)
812 $data4[$i++.":".$childname] = $item;
817 $data3 = array($root_element => $data2);
819 $ret = xml::from_array($data3, $xml, false, $namespaces);
824 * @brief Formats the data according to the data type
826 * @param string $root_element Name of the root element
827 * @param string $type Return type (atom, rss, xml, json)
828 * @param array $data JSON style array
830 * @return (string|object) XML data or JSON data
832 function api_format_data($root_element, $type, $data){
840 $ret = api_create_xml($data, $root_element);
855 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
856 * returns a 401 status code and an error message if not.
857 * http://developer.twitter.com/doc/get/account/verify_credentials
859 function api_account_verify_credentials($type){
863 if (api_user()===false) throw new ForbiddenException();
865 unset($_REQUEST["user_id"]);
866 unset($_GET["user_id"]);
868 unset($_REQUEST["screen_name"]);
869 unset($_GET["screen_name"]);
871 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
873 $user_info = api_get_user($a);
875 // "verified" isn't used here in the standard
876 unset($user_info["verified"]);
878 // - Adding last status
880 $user_info["status"] = api_status_show("raw");
881 if (!count($user_info["status"]))
882 unset($user_info["status"]);
884 unset($user_info["status"]["user"]);
887 // "uid" and "self" are only needed for some internal stuff, so remove it from here
888 unset($user_info["uid"]);
889 unset($user_info["self"]);
891 return api_format_data("user", $type, array('user' => $user_info));
894 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
898 * get data from $_POST or $_GET
900 function requestdata($k){
901 if (isset($_POST[$k])){
904 if (isset($_GET[$k])){
910 /*Waitman Gobble Mod*/
911 function api_statuses_mediap($type) {
915 if (api_user()===false) {
916 logger('api_statuses_update: no user');
917 throw new ForbiddenException();
919 $user_info = api_get_user($a);
921 $_REQUEST['type'] = 'wall';
922 $_REQUEST['profile_uid'] = api_user();
923 $_REQUEST['api_source'] = true;
924 $txt = requestdata('status');
925 //$txt = urldecode(requestdata('status'));
927 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
929 $txt = html2bb_video($txt);
930 $config = HTMLPurifier_Config::createDefault();
931 $config->set('Cache.DefinitionImpl', null);
932 $purifier = new HTMLPurifier($config);
933 $txt = $purifier->purify($txt);
935 $txt = html2bbcode($txt);
937 $a->argv[1]=$user_info['screen_name']; //should be set to username?
939 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
940 $bebop = wall_upload_post($a);
942 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
943 $_REQUEST['body']=$txt."\n\n".$bebop;
946 // this should output the last post (the one we just posted).
947 return api_status_show($type);
949 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
950 /*Waitman Gobble Mod*/
953 function api_statuses_update($type) {
957 if (api_user()===false) {
958 logger('api_statuses_update: no user');
959 throw new ForbiddenException();
962 $user_info = api_get_user($a);
964 // convert $_POST array items to the form we use for web posts.
966 // logger('api_post: ' . print_r($_POST,true));
968 if(requestdata('htmlstatus')) {
969 $txt = requestdata('htmlstatus');
970 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
971 $txt = html2bb_video($txt);
973 $config = HTMLPurifier_Config::createDefault();
974 $config->set('Cache.DefinitionImpl', null);
976 $purifier = new HTMLPurifier($config);
977 $txt = $purifier->purify($txt);
979 $_REQUEST['body'] = html2bbcode($txt);
983 $_REQUEST['body'] = requestdata('status');
985 $_REQUEST['title'] = requestdata('title');
987 $parent = requestdata('in_reply_to_status_id');
989 // Twidere sends "-1" if it is no reply ...
993 if(ctype_digit($parent))
994 $_REQUEST['parent'] = $parent;
996 $_REQUEST['parent_uri'] = $parent;
998 if(requestdata('lat') && requestdata('long'))
999 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
1000 $_REQUEST['profile_uid'] = api_user();
1003 $_REQUEST['type'] = 'net-comment';
1005 // Check for throttling (maximum posts per day, week and month)
1006 $throttle_day = get_config('system','throttle_limit_day');
1007 if ($throttle_day > 0) {
1008 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1010 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1011 AND `created` > '%s' AND `id` = `parent`",
1012 intval(api_user()), dbesc($datefrom));
1015 $posts_day = $r[0]["posts_day"];
1019 if ($posts_day > $throttle_day) {
1020 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1021 #die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1022 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1026 $throttle_week = get_config('system','throttle_limit_week');
1027 if ($throttle_week > 0) {
1028 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1030 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1031 AND `created` > '%s' AND `id` = `parent`",
1032 intval(api_user()), dbesc($datefrom));
1035 $posts_week = $r[0]["posts_week"];
1039 if ($posts_week > $throttle_week) {
1040 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1041 #die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1042 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1047 $throttle_month = get_config('system','throttle_limit_month');
1048 if ($throttle_month > 0) {
1049 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1051 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1052 AND `created` > '%s' AND `id` = `parent`",
1053 intval(api_user()), dbesc($datefrom));
1056 $posts_month = $r[0]["posts_month"];
1060 if ($posts_month > $throttle_month) {
1061 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1062 #die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1063 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1067 $_REQUEST['type'] = 'wall';
1070 if(x($_FILES,'media')) {
1071 // upload the image if we have one
1072 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1073 $media = wall_upload_post($a);
1074 if(strlen($media)>0)
1075 $_REQUEST['body'] .= "\n\n".$media;
1078 // To-Do: Multiple IDs
1079 if (requestdata('media_ids')) {
1080 $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",
1081 intval(requestdata('media_ids')), api_user());
1083 $phototypes = Photo::supportedTypes();
1084 $ext = $phototypes[$r[0]['type']];
1085 $_REQUEST['body'] .= "\n\n".'[url='.App::get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1086 $_REQUEST['body'] .= '[img]'.App::get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1090 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1092 $_REQUEST['api_source'] = true;
1094 if (!x($_REQUEST, "source"))
1095 $_REQUEST["source"] = api_source();
1097 // call out normal post function
1101 // this should output the last post (the one we just posted).
1102 return api_status_show($type);
1104 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1105 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1108 function api_media_upload($type) {
1112 if (api_user()===false) {
1114 throw new ForbiddenException();
1117 $user_info = api_get_user($a);
1119 if(!x($_FILES,'media')) {
1121 throw new BadRequestException("No media.");
1124 $media = wall_upload_post($a, false);
1127 throw new InternalServerErrorException();
1130 $returndata = array();
1131 $returndata["media_id"] = $media["id"];
1132 $returndata["media_id_string"] = (string)$media["id"];
1133 $returndata["size"] = $media["size"];
1134 $returndata["image"] = array("w" => $media["width"],
1135 "h" => $media["height"],
1136 "image_type" => $media["type"]);
1138 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1140 return array("media" => $returndata);
1142 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1144 function api_status_show($type){
1148 $user_info = api_get_user($a);
1150 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1153 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1157 // get last public wall message
1158 $lastwall = q("SELECT `item`.*
1160 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1161 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1162 AND `item`.`type` != 'activity' $privacy_sql
1163 ORDER BY `item`.`id` DESC
1165 intval($user_info['cid']),
1167 dbesc($user_info['url']),
1168 dbesc(normalise_link($user_info['url'])),
1169 dbesc($user_info['url']),
1170 dbesc(normalise_link($user_info['url']))
1173 if (count($lastwall)>0){
1174 $lastwall = $lastwall[0];
1176 $in_reply_to = api_in_reply_to($lastwall);
1178 $converted = api_convert_item($lastwall);
1181 $geo = "georss:point";
1185 $status_info = array(
1186 'created_at' => api_date($lastwall['created']),
1187 'id' => intval($lastwall['id']),
1188 'id_str' => (string) $lastwall['id'],
1189 'text' => $converted["text"],
1190 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1191 'truncated' => false,
1192 'in_reply_to_status_id' => $in_reply_to['status_id'],
1193 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1194 'in_reply_to_user_id' => $in_reply_to['user_id'],
1195 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1196 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1197 'user' => $user_info,
1199 'coordinates' => "",
1201 'contributors' => "",
1202 'is_quote_status' => false,
1203 'retweet_count' => 0,
1204 'favorite_count' => 0,
1205 'favorited' => $lastwall['starred'] ? true : false,
1206 'retweeted' => false,
1207 'possibly_sensitive' => false,
1209 'statusnet_html' => $converted["html"],
1210 'statusnet_conversation_id' => $lastwall['parent'],
1213 if (count($converted["attachments"]) > 0)
1214 $status_info["attachments"] = $converted["attachments"];
1216 if (count($converted["entities"]) > 0)
1217 $status_info["entities"] = $converted["entities"];
1219 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1220 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1221 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1222 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1224 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1225 unset($status_info["user"]["uid"]);
1226 unset($status_info["user"]["self"]);
1229 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1232 return($status_info);
1234 return api_format_data("statuses", $type, array('status' => $status_info));
1243 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1244 * The author's most recent status will be returned inline.
1245 * http://developer.twitter.com/doc/get/users/show
1247 function api_users_show($type){
1251 $user_info = api_get_user($a);
1252 $lastwall = q("SELECT `item`.*
1254 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1255 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1256 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1257 AND `type`!='activity'
1258 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1262 dbesc(ACTIVITY_POST),
1263 intval($user_info['cid']),
1264 dbesc($user_info['url']),
1265 dbesc(normalise_link($user_info['url'])),
1266 dbesc($user_info['url']),
1267 dbesc(normalise_link($user_info['url']))
1270 if (count($lastwall)>0){
1271 $lastwall = $lastwall[0];
1273 $in_reply_to = api_in_reply_to($lastwall);
1275 $converted = api_convert_item($lastwall);
1278 $geo = "georss:point";
1282 $user_info['status'] = array(
1283 'text' => $converted["text"],
1284 'truncated' => false,
1285 'created_at' => api_date($lastwall['created']),
1286 'in_reply_to_status_id' => $in_reply_to['status_id'],
1287 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1288 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1289 'id' => intval($lastwall['contact-id']),
1290 'id_str' => (string) $lastwall['contact-id'],
1291 'in_reply_to_user_id' => $in_reply_to['user_id'],
1292 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1293 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1295 'favorited' => $lastwall['starred'] ? true : false,
1296 'statusnet_html' => $converted["html"],
1297 'statusnet_conversation_id' => $lastwall['parent'],
1300 if (count($converted["attachments"]) > 0)
1301 $user_info["status"]["attachments"] = $converted["attachments"];
1303 if (count($converted["entities"]) > 0)
1304 $user_info["status"]["entities"] = $converted["entities"];
1306 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1307 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1308 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1309 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1313 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1314 unset($user_info["uid"]);
1315 unset($user_info["self"]);
1317 return api_format_data("user", $type, array('user' => $user_info));
1320 api_register_func('api/users/show','api_users_show');
1323 function api_users_search($type) {
1327 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1329 $userlist = array();
1331 if (isset($_GET["q"])) {
1332 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1333 if (!dbm::is_result($r))
1334 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1336 if (dbm::is_result($r)) {
1338 foreach ($r AS $user) {
1339 $user_info = api_get_user($a, $user["id"], "json");
1342 $userlist[$k++.":user"] = $user_info;
1344 $userlist[] = $user_info;
1346 $userlist = array("users" => $userlist);
1348 throw new BadRequestException("User not found.");
1351 throw new BadRequestException("User not found.");
1353 return api_format_data("users", $type, $userlist);
1356 api_register_func('api/users/search','api_users_search');
1360 * http://developer.twitter.com/doc/get/statuses/home_timeline
1362 * TODO: Optional parameters
1363 * TODO: Add reply info
1365 function api_statuses_home_timeline($type){
1369 if (api_user()===false) throw new ForbiddenException();
1371 unset($_REQUEST["user_id"]);
1372 unset($_GET["user_id"]);
1374 unset($_REQUEST["screen_name"]);
1375 unset($_GET["screen_name"]);
1377 $user_info = api_get_user($a);
1378 // get last newtork messages
1381 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1382 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1383 if ($page<0) $page=0;
1384 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1385 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1386 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1387 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1388 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1390 $start = $page*$count;
1394 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1395 if ($exclude_replies > 0)
1396 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1397 if ($conversation_id > 0)
1398 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1400 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1401 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1402 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1403 `contact`.`id` AS `cid`
1405 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1406 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1407 WHERE `item`.`uid` = %d AND `verb` = '%s'
1408 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1411 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1413 dbesc(ACTIVITY_POST),
1415 intval($start), intval($count)
1418 $ret = api_format_items($r,$user_info, false, $type);
1420 // Set all posts from the query above to seen
1422 foreach ($r AS $item)
1423 $idarray[] = intval($item["id"]);
1425 $idlist = implode(",", $idarray);
1427 if ($idlist != "") {
1428 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1431 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1434 $data = array('status' => $ret);
1438 $data = api_rss_extra($a, $data, $user_info);
1442 return api_format_data("statuses", $type, $data);
1444 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1445 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1447 function api_statuses_public_timeline($type){
1451 if (api_user()===false) throw new ForbiddenException();
1453 $user_info = api_get_user($a);
1454 // get last newtork messages
1458 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1459 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1460 if ($page<0) $page=0;
1461 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1462 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1463 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1464 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1465 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1467 $start = $page*$count;
1470 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1471 if ($exclude_replies > 0)
1472 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1473 if ($conversation_id > 0)
1474 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1476 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1477 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1478 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1479 `contact`.`id` AS `cid`,
1480 `user`.`nickname`, `user`.`hidewall`
1482 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1483 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1484 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1485 AND NOT `user`.`hidewall`
1486 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1487 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1488 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1489 AND NOT `item`.`private` AND `item`.`wall`
1492 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1493 dbesc(ACTIVITY_POST),
1498 $ret = api_format_items($r,$user_info, false, $type);
1501 $data = array('status' => $ret);
1505 $data = api_rss_extra($a, $data, $user_info);
1509 return api_format_data("statuses", $type, $data);
1511 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1516 function api_statuses_show($type){
1520 if (api_user()===false) throw new ForbiddenException();
1522 $user_info = api_get_user($a);
1525 $id = intval($a->argv[3]);
1528 $id = intval($_REQUEST["id"]);
1532 $id = intval($a->argv[4]);
1534 logger('API: api_statuses_show: '.$id);
1536 $conversation = (x($_REQUEST,'conversation')?1:0);
1540 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1542 $sql_extra .= " AND `item`.`id` = %d";
1544 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1545 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1546 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1547 `contact`.`id` AS `cid`
1549 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1550 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1551 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1552 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1555 dbesc(ACTIVITY_POST),
1560 throw new BadRequestException("There is no status with this id.");
1563 $ret = api_format_items($r,$user_info, false, $type);
1565 if ($conversation) {
1566 $data = array('status' => $ret);
1567 return api_format_data("statuses", $type, $data);
1569 $data = array('status' => $ret[0]);
1570 return api_format_data("status", $type, $data);
1573 api_register_func('api/statuses/show','api_statuses_show', true);
1579 function api_conversation_show($type){
1583 if (api_user()===false) throw new ForbiddenException();
1585 $user_info = api_get_user($a);
1588 $id = intval($a->argv[3]);
1589 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1590 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1591 if ($page<0) $page=0;
1592 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1593 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1595 $start = $page*$count;
1598 $id = intval($_REQUEST["id"]);
1602 $id = intval($a->argv[4]);
1604 logger('API: api_conversation_show: '.$id);
1606 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1608 $id = $r[0]["parent"];
1613 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1615 // Not sure why this query was so complicated. We should keep it here for a while,
1616 // just to make sure that we really don't need it.
1617 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1618 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1620 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1621 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1622 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1623 `contact`.`id` AS `cid`
1625 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1626 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1627 WHERE `item`.`parent` = %d AND `item`.`visible`
1628 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1629 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1630 AND `item`.`id`>%d $sql_extra
1631 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1632 intval($id), intval(api_user()),
1633 dbesc(ACTIVITY_POST),
1635 intval($start), intval($count)
1639 throw new BadRequestException("There is no conversation with this id.");
1641 $ret = api_format_items($r,$user_info, false, $type);
1643 $data = array('status' => $ret);
1644 return api_format_data("statuses", $type, $data);
1646 api_register_func('api/conversation/show','api_conversation_show', true);
1647 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1653 function api_statuses_repeat($type){
1658 if (api_user()===false) throw new ForbiddenException();
1660 $user_info = api_get_user($a);
1663 $id = intval($a->argv[3]);
1666 $id = intval($_REQUEST["id"]);
1670 $id = intval($a->argv[4]);
1672 logger('API: api_statuses_repeat: '.$id);
1674 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1675 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1676 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1677 `contact`.`id` AS `cid`
1679 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1680 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1681 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1682 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1683 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1685 AND `item`.`id`=%d",
1689 if ($r[0]['body'] != "") {
1690 if (strpos($r[0]['body'], "[/share]") !== false) {
1691 $pos = strpos($r[0]['body'], "[share");
1692 $post = substr($r[0]['body'], $pos);
1694 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1696 $post .= $r[0]['body'];
1697 $post .= "[/share]";
1699 $_REQUEST['body'] = $post;
1700 $_REQUEST['profile_uid'] = api_user();
1701 $_REQUEST['type'] = 'wall';
1702 $_REQUEST['api_source'] = true;
1704 if (!x($_REQUEST, "source"))
1705 $_REQUEST["source"] = api_source();
1709 throw new ForbiddenException();
1711 // this should output the last post (the one we just posted).
1713 return(api_status_show($type));
1715 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1720 function api_statuses_destroy($type){
1724 if (api_user()===false) throw new ForbiddenException();
1726 $user_info = api_get_user($a);
1729 $id = intval($a->argv[3]);
1732 $id = intval($_REQUEST["id"]);
1736 $id = intval($a->argv[4]);
1738 logger('API: api_statuses_destroy: '.$id);
1740 $ret = api_statuses_show($type);
1742 drop_item($id, false);
1746 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1750 * http://developer.twitter.com/doc/get/statuses/mentions
1753 function api_statuses_mentions($type){
1757 if (api_user()===false) throw new ForbiddenException();
1759 unset($_REQUEST["user_id"]);
1760 unset($_GET["user_id"]);
1762 unset($_REQUEST["screen_name"]);
1763 unset($_GET["screen_name"]);
1765 $user_info = api_get_user($a);
1766 // get last newtork messages
1770 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1771 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1772 if ($page<0) $page=0;
1773 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1774 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1775 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1777 $start = $page*$count;
1779 // Ugly code - should be changed
1780 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1781 $myurl = substr($myurl,strpos($myurl,'://')+3);
1782 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1783 $myurl = str_replace('www.','',$myurl);
1784 $diasp_url = str_replace('/profile/','/u/',$myurl);
1787 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1789 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1790 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1791 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1792 `contact`.`id` AS `cid`
1793 FROM `item` FORCE INDEX (`uid_id`)
1794 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1795 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1796 WHERE `item`.`uid` = %d AND `verb` = '%s'
1797 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1798 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1799 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1802 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1804 dbesc(ACTIVITY_POST),
1805 dbesc(protect_sprintf($myurl)),
1806 dbesc(protect_sprintf($myurl)),
1809 intval($start), intval($count)
1812 $ret = api_format_items($r,$user_info, false, $type);
1815 $data = array('status' => $ret);
1819 $data = api_rss_extra($a, $data, $user_info);
1823 return api_format_data("statuses", $type, $data);
1825 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1826 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1829 function api_statuses_user_timeline($type){
1833 if (api_user()===false) throw new ForbiddenException();
1835 $user_info = api_get_user($a);
1836 // get last network messages
1838 logger("api_statuses_user_timeline: api_user: ". api_user() .
1839 "\nuser_info: ".print_r($user_info, true) .
1840 "\n_REQUEST: ".print_r($_REQUEST, true),
1844 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1845 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1846 if ($page<0) $page=0;
1847 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1848 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1849 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1850 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1852 $start = $page*$count;
1855 if ($user_info['self']==1)
1856 $sql_extra .= " AND `item`.`wall` = 1 ";
1858 if ($exclude_replies > 0)
1859 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1860 if ($conversation_id > 0)
1861 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1863 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1864 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1865 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1866 `contact`.`id` AS `cid`
1867 FROM `item` FORCE INDEX (`uid_contactid_id`)
1868 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1869 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1870 WHERE `item`.`uid` = %d AND `verb` = '%s'
1871 AND `item`.`contact-id` = %d
1872 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1875 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1877 dbesc(ACTIVITY_POST),
1878 intval($user_info['cid']),
1880 intval($start), intval($count)
1883 $ret = api_format_items($r,$user_info, true, $type);
1885 $data = array('status' => $ret);
1889 $data = api_rss_extra($a, $data, $user_info);
1892 return api_format_data("statuses", $type, $data);
1894 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1898 * Star/unstar an item
1899 * param: id : id of the item
1901 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1903 function api_favorites_create_destroy($type){
1907 if (api_user()===false) throw new ForbiddenException();
1909 // for versioned api.
1910 /// @TODO We need a better global soluton
1912 if ($a->argv[1]=="1.1") $action_argv_id=3;
1914 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1915 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1916 if ($a->argc==$action_argv_id+2) {
1917 $itemid = intval($a->argv[$action_argv_id+1]);
1919 $itemid = intval($_REQUEST['id']);
1922 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1923 $itemid, api_user());
1925 if ($item===false || count($item)==0)
1926 throw new BadRequestException("Invalid item.");
1930 $item[0]['starred']=1;
1933 $item[0]['starred']=0;
1936 throw new BadRequestException("Invalid action ".$action);
1938 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1939 $item[0]['starred'], $itemid, api_user());
1941 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1942 $item[0]['starred'], $itemid, api_user());
1945 throw InternalServerErrorException("DB error");
1948 $user_info = api_get_user($a);
1949 $rets = api_format_items($item, $user_info, false, $type);
1952 $data = array('status' => $ret);
1956 $data = api_rss_extra($a, $data, $user_info);
1959 return api_format_data("status", $type, $data);
1961 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1962 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1964 function api_favorites($type){
1969 if (api_user()===false) throw new ForbiddenException();
1971 $called_api= array();
1973 $user_info = api_get_user($a);
1975 // in friendica starred item are private
1976 // return favorites only for self
1977 logger('api_favorites: self:' . $user_info['self']);
1979 if ($user_info['self']==0) {
1985 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1986 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1987 $count = (x($_GET,'count')?$_GET['count']:20);
1988 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1989 if ($page<0) $page=0;
1991 $start = $page*$count;
1994 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1996 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1997 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1998 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1999 `contact`.`id` AS `cid`
2000 FROM `item`, `contact`
2001 WHERE `item`.`uid` = %d
2002 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2003 AND `item`.`starred` = 1
2004 AND `contact`.`id` = `item`.`contact-id`
2005 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2008 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2011 intval($start), intval($count)
2014 $ret = api_format_items($r,$user_info, false, $type);
2018 $data = array('status' => $ret);
2022 $data = api_rss_extra($a, $data, $user_info);
2025 return api_format_data("statuses", $type, $data);
2027 api_register_func('api/favorites','api_favorites', true);
2029 function api_format_messages($item, $recipient, $sender) {
2030 // standard meta information
2032 'id' => $item['id'],
2033 'sender_id' => $sender['id'] ,
2035 'recipient_id' => $recipient['id'],
2036 'created_at' => api_date($item['created']),
2037 'sender_screen_name' => $sender['screen_name'],
2038 'recipient_screen_name' => $recipient['screen_name'],
2039 'sender' => $sender,
2040 'recipient' => $recipient,
2042 'friendica_seen' => $item['seen'],
2043 'friendica_parent_uri' => $item['parent-uri'],
2046 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2047 unset($ret["sender"]["uid"]);
2048 unset($ret["sender"]["self"]);
2049 unset($ret["recipient"]["uid"]);
2050 unset($ret["recipient"]["self"]);
2052 //don't send title to regular StatusNET requests to avoid confusing these apps
2053 if (x($_GET, 'getText')) {
2054 $ret['title'] = $item['title'] ;
2055 if ($_GET["getText"] == "html") {
2056 $ret['text'] = bbcode($item['body'], false, false);
2058 elseif ($_GET["getText"] == "plain") {
2059 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2060 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2064 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2066 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2067 unset($ret['sender']);
2068 unset($ret['recipient']);
2074 function api_convert_item($item) {
2075 $body = $item['body'];
2076 $attachments = api_get_attachments($body);
2078 // Workaround for ostatus messages where the title is identically to the body
2079 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2080 $statusbody = trim(html2plain($html, 0));
2082 // handle data: images
2083 $statusbody = api_format_items_embeded_images($item,$statusbody);
2085 $statustitle = trim($item['title']);
2087 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2088 $statustext = trim($statusbody);
2090 $statustext = trim($statustitle."\n\n".$statusbody);
2092 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2093 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2095 $statushtml = trim(bbcode($body, false, false));
2097 $search = array("<br>", "<blockquote>", "</blockquote>",
2098 "<h1>", "</h1>", "<h2>", "</h2>",
2099 "<h3>", "</h3>", "<h4>", "</h4>",
2100 "<h5>", "</h5>", "<h6>", "</h6>");
2101 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2102 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2103 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2104 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2105 $statushtml = str_replace($search, $replace, $statushtml);
2107 if ($item['title'] != "")
2108 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2110 $entities = api_get_entitities($statustext, $body);
2113 "text" => $statustext,
2114 "html" => $statushtml,
2115 "attachments" => $attachments,
2116 "entities" => $entities
2120 function api_get_attachments(&$body) {
2123 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2125 $URLSearchString = "^\[\]";
2126 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2131 $attachments = array();
2133 foreach ($images[1] AS $image) {
2134 $imagedata = get_photo_info($image);
2137 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2140 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2141 foreach ($images[0] AS $orig)
2142 $body = str_replace($orig, "", $body);
2144 return $attachments;
2147 function api_get_entitities(&$text, $bbcode) {
2150 * Links at the first character of the post
2155 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2157 if ($include_entities != "true") {
2159 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2161 foreach ($images[1] AS $image) {
2162 $replace = proxy_url($image);
2163 $text = str_replace($image, $replace, $text);
2168 $bbcode = bb_CleanPictureLinks($bbcode);
2170 // Change pure links in text to bbcode uris
2171 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2173 $entities = array();
2174 $entities["hashtags"] = array();
2175 $entities["symbols"] = array();
2176 $entities["urls"] = array();
2177 $entities["user_mentions"] = array();
2179 $URLSearchString = "^\[\]";
2181 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2183 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2184 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2185 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2187 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2188 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2189 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2191 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2192 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2193 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2195 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2197 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2198 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2200 $ordered_urls = array();
2201 foreach ($urls[1] AS $id=>$url) {
2202 //$start = strpos($text, $url, $offset);
2203 $start = iconv_strpos($text, $url, 0, "UTF-8");
2204 if (!($start === false))
2205 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2208 ksort($ordered_urls);
2211 //foreach ($urls[1] AS $id=>$url) {
2212 foreach ($ordered_urls AS $url) {
2213 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2214 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2215 $display_url = $url["title"];
2217 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2218 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2220 if (strlen($display_url) > 26)
2221 $display_url = substr($display_url, 0, 25)."…";
2224 //$start = strpos($text, $url, $offset);
2225 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2226 if (!($start === false)) {
2227 $entities["urls"][] = array("url" => $url["url"],
2228 "expanded_url" => $url["url"],
2229 "display_url" => $display_url,
2230 "indices" => array($start, $start+strlen($url["url"])));
2231 $offset = $start + 1;
2235 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2236 $ordered_images = array();
2237 foreach ($images[1] AS $image) {
2238 //$start = strpos($text, $url, $offset);
2239 $start = iconv_strpos($text, $image, 0, "UTF-8");
2240 if (!($start === false))
2241 $ordered_images[$start] = $image;
2243 //$entities["media"] = array();
2246 foreach ($ordered_images AS $url) {
2247 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2248 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2250 if (strlen($display_url) > 26)
2251 $display_url = substr($display_url, 0, 25)."…";
2253 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2254 if (!($start === false)) {
2255 $image = get_photo_info($url);
2257 // If image cache is activated, then use the following sizes:
2258 // thumb (150), small (340), medium (600) and large (1024)
2259 if (!get_config("system", "proxy_disabled")) {
2260 $media_url = proxy_url($url);
2263 $scale = scale_image($image[0], $image[1], 150);
2264 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2266 if (($image[0] > 150) OR ($image[1] > 150)) {
2267 $scale = scale_image($image[0], $image[1], 340);
2268 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2271 $scale = scale_image($image[0], $image[1], 600);
2272 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2274 if (($image[0] > 600) OR ($image[1] > 600)) {
2275 $scale = scale_image($image[0], $image[1], 1024);
2276 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2280 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2283 $entities["media"][] = array(
2285 "id_str" => (string)$start+1,
2286 "indices" => array($start, $start+strlen($url)),
2287 "media_url" => normalise_link($media_url),
2288 "media_url_https" => $media_url,
2290 "display_url" => $display_url,
2291 "expanded_url" => $url,
2295 $offset = $start + 1;
2301 function api_format_items_embeded_images(&$item, $text){
2302 $text = preg_replace_callback(
2303 "|data:image/([^;]+)[^=]+=*|m",
2304 function($match) use ($item) {
2305 return App::get_baseurl()."/display/".$item['guid'];
2313 * @brief return <a href='url'>name</a> as array
2315 * @param string $txt
2320 function api_contactlink_to_array($txt) {
2322 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2323 if ($r && count($match)==3) {
2325 'name' => $match[2],
2339 * @brief return likes, dislikes and attend status for item
2341 * @param array $item
2343 * likes => int count
2344 * dislikes => int count
2346 function api_format_items_activities(&$item, $type = "json") {
2350 $activities = array(
2352 'dislike' => array(),
2353 'attendyes' => array(),
2354 'attendno' => array(),
2355 'attendmaybe' => array()
2358 $items = q('SELECT * FROM item
2359 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2360 intval($item['uid']),
2361 dbesc($item['uri']));
2363 foreach ($items as $i){
2364 // not used as result should be structured like other user data
2365 //builtin_activity_puller($i, $activities);
2367 // get user data and add it to the array of the activity
2368 $user = api_get_user($a, $i['author-link']);
2369 switch($i['verb']) {
2371 $activities['like'][] = $user;
2373 case ACTIVITY_DISLIKE:
2374 $activities['dislike'][] = $user;
2376 case ACTIVITY_ATTEND:
2377 $activities['attendyes'][] = $user;
2379 case ACTIVITY_ATTENDNO:
2380 $activities['attendno'][] = $user;
2382 case ACTIVITY_ATTENDMAYBE:
2383 $activities['attendmaybe'][] = $user;
2390 if ($type == "xml") {
2391 $xml_activities = array();
2392 foreach ($activities as $k => $v) {
2393 // change xml element from "like" to "friendica:like"
2394 $xml_activities["friendica:".$k] = $v;
2395 // add user data into xml output
2397 foreach ($v as $user)
2398 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2400 $activities = $xml_activities;
2409 * @brief return data from profiles
2411 * @param array $profile array containing data from db table 'profile'
2412 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2415 function api_format_items_profiles(&$profile = null, $type = "json") {
2416 if ($profile != null) {
2417 $profile = array('profile_id' => $profile['id'],
2418 'profile_name' => $profile['profile-name'],
2419 'is_default' => $profile['is-default'] ? true : false,
2420 'hide_friends'=> $profile['hide-friends'] ? true : false,
2421 'profile_photo' => $profile['photo'],
2422 'profile_thumb' => $profile['thumb'],
2423 'publish' => $profile['publish'] ? true : false,
2424 'net_publish' => $profile['net-publish'] ? true : false,
2425 'description' => $profile['pdesc'],
2426 'date_of_birth' => $profile['dob'],
2427 'address' => $profile['address'],
2428 'city' => $profile['locality'],
2429 'region' => $profile['region'],
2430 'postal_code' => $profile['postal-code'],
2431 'country' => $profile['country-name'],
2432 'hometown' => $profile['hometown'],
2433 'gender' => $profile['gender'],
2434 'marital' => $profile['marital'],
2435 'marital_with' => $profile['with'],
2436 'marital_since' => $profile['howlong'],
2437 'sexual' => $profile['sexual'],
2438 'politic' => $profile['politic'],
2439 'religion' => $profile['religion'],
2440 'public_keywords' => $profile['pub_keywords'],
2441 'private_keywords' => $profile['prv_keywords'],
2442 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2443 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2444 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2445 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2446 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2447 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2448 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2449 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2450 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2451 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2452 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2453 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2454 'homepage' => $profile['homepage'],
2461 * @brief format items to be returned by api
2463 * @param array $r array of items
2464 * @param array $user_info
2465 * @param bool $filter_user filter items by $user_info
2467 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2473 foreach($r as $item) {
2475 localize_item($item);
2476 list($status_user, $owner_user) = api_item_get_user($a,$item);
2478 // Look if the posts are matching if they should be filtered by user id
2479 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2482 $in_reply_to = api_in_reply_to($item);
2484 $converted = api_convert_item($item);
2487 $geo = "georss:point";
2492 'text' => $converted["text"],
2493 'truncated' => False,
2494 'created_at'=> api_date($item['created']),
2495 'in_reply_to_status_id' => $in_reply_to['status_id'],
2496 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2497 'source' => (($item['app']) ? $item['app'] : 'web'),
2498 'id' => intval($item['id']),
2499 'id_str' => (string) intval($item['id']),
2500 'in_reply_to_user_id' => $in_reply_to['user_id'],
2501 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2502 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2504 'favorited' => $item['starred'] ? true : false,
2505 'user' => $status_user ,
2506 'friendica_owner' => $owner_user,
2507 //'entities' => NULL,
2508 'statusnet_html' => $converted["html"],
2509 'statusnet_conversation_id' => $item['parent'],
2510 'friendica_activities' => api_format_items_activities($item, $type),
2513 if (count($converted["attachments"]) > 0)
2514 $status["attachments"] = $converted["attachments"];
2516 if (count($converted["entities"]) > 0)
2517 $status["entities"] = $converted["entities"];
2519 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2520 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2521 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2522 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2525 // Retweets are only valid for top postings
2526 // It doesn't work reliable with the link if its a feed
2527 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2529 // $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2532 if ($item["id"] == $item["parent"]) {
2533 $retweeted_item = api_share_as_retweet($item);
2534 if ($retweeted_item !== false) {
2535 $retweeted_status = $status;
2537 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2538 } catch( BadRequestException $e ) {
2539 // user not found. should be found?
2540 /// @todo check if the user should be always found
2541 $retweeted_status["user"] = array();
2544 $rt_converted = api_convert_item($retweeted_item);
2546 $retweeted_status['text'] = $rt_converted["text"];
2547 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2548 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2549 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2550 $status['retweeted_status'] = $retweeted_status;
2554 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2555 unset($status["user"]["uid"]);
2556 unset($status["user"]["self"]);
2558 if ($item["coord"] != "") {
2559 $coords = explode(' ',$item["coord"]);
2560 if (count($coords) == 2) {
2561 if ($type == "json")
2562 $status["geo"] = array('type' => 'Point',
2563 'coordinates' => array((float) $coords[0],
2564 (float) $coords[1]));
2565 else // Not sure if this is the official format - if someone founds a documentation we can check
2566 $status["georss:point"] = $item["coord"];
2575 function api_account_rate_limit_status($type) {
2579 'remaining-hits' => (string) 150,
2580 '@attributes' => array("type" => "integer"),
2581 'hourly-limit' => (string) 150,
2582 '@attributes2' => array("type" => "integer"),
2583 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2584 '@attributes3' => array("type" => "datetime"),
2585 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2586 '@attributes4' => array("type" => "integer"),
2590 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2591 'remaining_hits' => (string) 150,
2592 'hourly_limit' => (string) 150,
2593 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2596 return api_format_data('hash', $type, array('hash' => $hash));
2598 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2600 function api_help_test($type) {
2606 return api_format_data('ok', $type, array("ok" => $ok));
2608 api_register_func('api/help/test','api_help_test',false);
2610 function api_lists($type) {
2612 return api_format_data('lists', $type, array("lists_list" => $ret));
2614 api_register_func('api/lists','api_lists',true);
2616 function api_lists_list($type) {
2618 return api_format_data('lists', $type, array("lists_list" => $ret));
2620 api_register_func('api/lists/list','api_lists_list',true);
2623 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2624 * This function is deprecated by Twitter
2625 * returns: json, xml
2627 function api_statuses_f($type, $qtype) {
2631 if (api_user()===false) throw new ForbiddenException();
2632 $user_info = api_get_user($a);
2634 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2635 /* this is to stop Hotot to load friends multiple times
2636 * I'm not sure if I'm missing return something or
2637 * is a bug in hotot. Workaround, meantime
2641 return array('$users' => $ret);*/
2645 if($qtype == 'friends')
2646 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2647 if($qtype == 'followers')
2648 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2650 // friends and followers only for self
2651 if ($user_info['self'] == 0)
2652 $sql_extra = " AND false ";
2654 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2659 foreach($r as $cid){
2660 $user = api_get_user($a, $cid['nurl']);
2661 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2662 unset($user["uid"]);
2663 unset($user["self"]);
2669 return array('user' => $ret);
2672 function api_statuses_friends($type){
2673 $data = api_statuses_f($type, "friends");
2674 if ($data===false) return false;
2675 return api_format_data("users", $type, $data);
2677 function api_statuses_followers($type){
2678 $data = api_statuses_f($type, "followers");
2679 if ($data===false) return false;
2680 return api_format_data("users", $type, $data);
2682 api_register_func('api/statuses/friends','api_statuses_friends',true);
2683 api_register_func('api/statuses/followers','api_statuses_followers',true);
2690 function api_statusnet_config($type) {
2694 $name = $a->config['sitename'];
2695 $server = $a->get_hostname();
2696 $logo = App::get_baseurl() . '/images/friendica-64.png';
2697 $email = $a->config['admin_email'];
2698 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2699 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2700 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2701 if($a->config['api_import_size'])
2702 $texlimit = string($a->config['api_import_size']);
2703 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2704 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2707 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2708 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2709 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2710 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2711 'shorturllength' => '30',
2712 'friendica' => array(
2713 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2714 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2715 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2716 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2721 return api_format_data('config', $type, array('config' => $config));
2724 api_register_func('api/gnusocial/config','api_statusnet_config',false);
2725 api_register_func('api/statusnet/config','api_statusnet_config',false);
2727 function api_statusnet_version($type) {
2729 $fake_statusnet_version = "0.9.7";
2731 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2733 api_register_func('api/gnusocial/version','api_statusnet_version',false);
2734 api_register_func('api/statusnet/version','api_statusnet_version',false);
2737 * @todo use api_format_data() to return data
2739 function api_ff_ids($type,$qtype) {
2743 if(! api_user()) throw new ForbiddenException();
2745 $user_info = api_get_user($a);
2747 if($qtype == 'friends')
2748 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2749 if($qtype == 'followers')
2750 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2752 if (!$user_info["self"])
2753 $sql_extra = " AND false ";
2755 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2757 $r = q("SELECT `pcontact`.`id` FROM `contact`
2758 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2759 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2763 if (!dbm::is_result($r))
2771 $ids[] = intval($rr['id']);
2773 return api_format_data("ids", $type, array('id' => $ids));
2776 function api_friends_ids($type) {
2777 return api_ff_ids($type,'friends');
2779 function api_followers_ids($type) {
2780 return api_ff_ids($type,'followers');
2782 api_register_func('api/friends/ids','api_friends_ids',true);
2783 api_register_func('api/followers/ids','api_followers_ids',true);
2786 function api_direct_messages_new($type) {
2790 if (api_user()===false) throw new ForbiddenException();
2792 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2794 $sender = api_get_user($a);
2796 if ($_POST['screen_name']) {
2797 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2799 dbesc($_POST['screen_name']));
2801 // Selecting the id by priority, friendica first
2802 api_best_nickname($r);
2804 $recipient = api_get_user($a, $r[0]['nurl']);
2806 $recipient = api_get_user($a, $_POST['user_id']);
2810 if (x($_REQUEST,'replyto')) {
2811 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2813 intval($_REQUEST['replyto']));
2814 $replyto = $r[0]['parent-uri'];
2815 $sub = $r[0]['title'];
2818 if (x($_REQUEST,'title')) {
2819 $sub = $_REQUEST['title'];
2822 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2826 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2829 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2830 $ret = api_format_messages($r[0], $recipient, $sender);
2833 $ret = array("error"=>$id);
2836 $data = Array('direct_message'=>$ret);
2841 $data = api_rss_extra($a, $data, $user_info);
2844 return api_format_data("direct-messages", $type, $data);
2847 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2851 * @brief delete a direct_message from mail table through api
2853 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2856 function api_direct_messages_destroy($type){
2859 if (api_user()===false) throw new ForbiddenException();
2862 $user_info = api_get_user($a);
2864 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);
2866 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
2867 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
2868 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2870 $uid = $user_info['uid'];
2871 // error if no id or parenturi specified (for clients posting parent-uri as well)
2872 if ($verbose == "true") {
2873 if ($id == 0 || $parenturi == "") {
2874 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
2875 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2879 // BadRequestException if no id specified (for clients using Twitter API)
2880 if ($id == 0) throw new BadRequestException('Message id not specified');
2882 // add parent-uri to sql command if specified by calling app
2883 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
2885 // get data of the specified message id
2886 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2890 // error message if specified id is not in database
2891 if (!dbm::is_result($r)) {
2892 if ($verbose == "true") {
2893 $answer = array('result' => 'error', 'message' => 'message id not in database');
2894 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2896 /// @todo BadRequestException ok for Twitter API clients?
2897 throw new BadRequestException('message id not in database');
2901 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2905 if ($verbose == "true") {
2908 $answer = array('result' => 'ok', 'message' => 'message deleted');
2909 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
2912 $answer = array('result' => 'error', 'message' => 'unknown error');
2913 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2916 /// @todo return JSON data like Twitter API not yet implemented
2919 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2922 function api_direct_messages_box($type, $box, $verbose) {
2926 if (api_user()===false) throw new ForbiddenException();
2929 $count = (x($_GET,'count')?$_GET['count']:20);
2930 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2931 if ($page<0) $page=0;
2933 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2934 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2936 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2937 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2940 unset($_REQUEST["user_id"]);
2941 unset($_GET["user_id"]);
2943 unset($_REQUEST["screen_name"]);
2944 unset($_GET["screen_name"]);
2946 $user_info = api_get_user($a);
2947 $profile_url = $user_info["url"];
2951 $start = $page*$count;
2954 if ($box=="sentbox") {
2955 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2957 elseif ($box=="conversation") {
2958 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2960 elseif ($box=="all") {
2961 $sql_extra = "true";
2963 elseif ($box=="inbox") {
2964 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2968 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2970 if ($user_id !="") {
2971 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2973 elseif($screen_name !=""){
2974 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2977 $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",
2980 intval($start), intval($count)
2982 if ($verbose == "true") {
2983 // stop execution and return error message if no mails available
2985 $answer = array('result' => 'error', 'message' => 'no mails available');
2986 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
2991 foreach($r as $item) {
2992 if ($box == "inbox" || $item['from-url'] != $profile_url){
2993 $recipient = $user_info;
2994 $sender = api_get_user($a,normalise_link($item['contact-url']));
2996 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2997 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2998 $sender = $user_info;
3001 $ret[]=api_format_messages($item, $recipient, $sender);
3005 $data = array('direct_message' => $ret);
3009 $data = api_rss_extra($a, $data, $user_info);
3012 return api_format_data("direct-messages", $type, $data);
3016 function api_direct_messages_sentbox($type){
3017 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3018 return api_direct_messages_box($type, "sentbox", $verbose);
3020 function api_direct_messages_inbox($type){
3021 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3022 return api_direct_messages_box($type, "inbox", $verbose);
3024 function api_direct_messages_all($type){
3025 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3026 return api_direct_messages_box($type, "all", $verbose);
3028 function api_direct_messages_conversation($type){
3029 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3030 return api_direct_messages_box($type, "conversation", $verbose);
3032 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3033 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3034 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3035 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3039 function api_oauth_request_token($type){
3041 $oauth = new FKOAuth1();
3042 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3043 }catch(Exception $e){
3044 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3049 function api_oauth_access_token($type){
3051 $oauth = new FKOAuth1();
3052 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3053 }catch(Exception $e){
3054 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3060 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3061 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3064 function api_fr_photos_list($type) {
3065 if (api_user()===false) throw new ForbiddenException();
3066 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
3067 where uid = %d and album != 'Contact Photos' group by `resource-id`",
3068 intval(local_user())
3071 'image/jpeg' => 'jpg',
3072 'image/png' => 'png',
3073 'image/gif' => 'gif'
3075 $data = array('photo'=>array());
3077 foreach ($r as $rr) {
3079 $photo['id'] = $rr['resource-id'];
3080 $photo['album'] = $rr['album'];
3081 $photo['filename'] = $rr['filename'];
3082 $photo['type'] = $rr['type'];
3083 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
3086 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3088 $photo['thumb'] = $thumb;
3089 $data['photo'][] = $photo;
3093 return api_format_data("photos", $type, $data);
3096 function api_fr_photo_detail($type) {
3097 if (api_user()===false) throw new ForbiddenException();
3098 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
3100 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3101 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
3102 $data_sql = ($scale === false ? "" : "data, ");
3104 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3105 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
3106 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
3108 intval(local_user()),
3109 dbesc($_REQUEST['photo_id']),
3114 'image/jpeg' => 'jpg',
3115 'image/png' => 'png',
3116 'image/gif' => 'gif'
3120 $data = array('photo' => $r[0]);
3121 $data['photo']['id'] = $data['photo']['resource-id'];
3122 if ($scale !== false) {
3123 $data['photo']['data'] = base64_encode($data['photo']['data']);
3125 unset($data['photo']['datasize']); //needed only with scale param
3127 if ($type == "xml") {
3128 $data['photo']['links'] = array();
3129 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
3130 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
3132 "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
3134 $data['photo']['link'] = array();
3135 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
3136 $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
3139 unset($data['photo']['resource-id']);
3140 unset($data['photo']['minscale']);
3141 unset($data['photo']['maxscale']);
3144 throw new NotFoundException();
3147 return api_format_data("photo_detail", $type, $data);
3150 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3151 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3156 * similar as /mod/redir.php
3157 * redirect to 'url' after dfrn auth
3159 * why this when there is mod/redir.php already?
3160 * This use api_user() and api_login()
3163 * c_url: url of remote contact to auth to
3164 * url: string, url to redirect after auth
3166 function api_friendica_remoteauth() {
3167 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
3168 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
3170 if ($url === '' || $c_url === '')
3171 throw new BadRequestException("Wrong parameters.");
3173 $c_url = normalise_link($c_url);
3177 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3182 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN))
3183 throw new BadRequestException("Unknown contact");
3187 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3189 if($r[0]['duplex'] && $r[0]['issued-id']) {
3190 $orig_id = $r[0]['issued-id'];
3191 $dfrn_id = '1:' . $orig_id;
3193 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3194 $orig_id = $r[0]['dfrn-id'];
3195 $dfrn_id = '0:' . $orig_id;
3198 $sec = random_string();
3200 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3201 VALUES( %d, %s, '%s', '%s', %d )",
3209 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3210 $dest = (($url) ? '&destination_url=' . $url : '');
3211 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3212 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3213 . '&type=profile&sec=' . $sec . $dest . $quiet );
3215 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3218 * @brief Return the item shared, if the item contains only the [share] tag
3220 * @param array $item Sharer item
3221 * @return array Shared item or false if not a reshare
3223 function api_share_as_retweet(&$item) {
3224 $body = trim($item["body"]);
3226 if (Diaspora::is_reshare($body, false)===false) {
3230 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3231 // Skip if there is no shared message in there
3232 // we already checked this in diaspora::is_reshare()
3233 // but better one more than one less...
3234 if ($body == $attributes)
3238 // build the fake reshared item
3239 $reshared_item = $item;
3242 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3243 if ($matches[1] != "")
3244 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3246 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3247 if ($matches[1] != "")
3248 $author = $matches[1];
3251 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3252 if ($matches[1] != "")
3253 $profile = $matches[1];
3255 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3256 if ($matches[1] != "")
3257 $profile = $matches[1];
3260 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3261 if ($matches[1] != "")
3262 $avatar = $matches[1];
3264 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3265 if ($matches[1] != "")
3266 $avatar = $matches[1];
3269 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3270 if ($matches[1] != "")
3271 $link = $matches[1];
3273 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3274 if ($matches[1] != "")
3275 $link = $matches[1];
3278 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3279 if ($matches[1] != "")
3280 $posted= $matches[1];
3282 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3283 if ($matches[1] != "")
3284 $posted = $matches[1];
3286 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3288 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3293 $reshared_item["body"] = $shared_body;
3294 $reshared_item["author-name"] = $author;
3295 $reshared_item["author-link"] = $profile;
3296 $reshared_item["author-avatar"] = $avatar;
3297 $reshared_item["plink"] = $link;
3298 $reshared_item["created"] = $posted;
3299 $reshared_item["edited"] = $posted;
3301 return $reshared_item;
3305 function api_get_nick($profile) {
3307 - remove trailing junk from profile url
3308 - pump.io check has to check the website
3313 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3314 dbesc(normalise_link($profile)));
3316 $nick = $r[0]["nick"];
3319 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3320 dbesc(normalise_link($profile)));
3322 $nick = $r[0]["nick"];
3326 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3327 if ($friendica != $profile)
3332 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3333 if ($diaspora != $profile)
3338 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3339 if ($twitter != $profile)
3345 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3346 if ($StatusnetHost != $profile) {
3347 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3348 if ($StatusnetUser != $profile) {
3349 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3350 $user = json_decode($UserData);
3352 $nick = $user->screen_name;
3357 // To-Do: look at the page if its really a pumpio site
3358 //if (!$nick == "") {
3359 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3360 // if ($pumpio != $profile)
3362 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3372 function api_in_reply_to($item) {
3373 $in_reply_to = array();
3375 $in_reply_to['status_id'] = NULL;
3376 $in_reply_to['user_id'] = NULL;
3377 $in_reply_to['status_id_str'] = NULL;
3378 $in_reply_to['user_id_str'] = NULL;
3379 $in_reply_to['screen_name'] = NULL;
3381 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
3382 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
3383 intval($item['uid']),
3384 dbesc($item['thr-parent']));
3386 if (dbm::is_result($r)) {
3387 $in_reply_to['status_id'] = intval($r[0]['id']);
3389 $in_reply_to['status_id'] = intval($item['parent']);
3392 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3394 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
3395 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
3396 WHERE `item`.`id` = %d LIMIT 1",
3397 intval($in_reply_to['status_id'])
3400 if (dbm::is_result($r)) {
3401 if ($r[0]['nick'] == "") {
3402 $r[0]['nick'] = api_get_nick($r[0]["url"]);
3405 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
3406 $in_reply_to['user_id'] = intval($r[0]['id']);
3407 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
3410 // There seems to be situation, where both fields are identical:
3411 // https://github.com/friendica/friendica/issues/1010
3412 // This is a bugfix for that.
3413 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3414 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
3415 $in_reply_to['status_id'] = NULL;
3416 $in_reply_to['user_id'] = NULL;
3417 $in_reply_to['status_id_str'] = NULL;
3418 $in_reply_to['user_id_str'] = NULL;
3419 $in_reply_to['screen_name'] = NULL;
3423 return $in_reply_to;
3426 function api_clean_plain_items($Text) {
3427 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3429 $Text = bb_CleanPictureLinks($Text);
3430 $URLSearchString = "^\[\]";
3432 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3434 if ($include_entities == "true") {
3435 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3438 // Simplify "attachment" element
3439 $Text = api_clean_attachments($Text);
3445 * @brief Removes most sharing information for API text export
3447 * @param string $body The original body
3449 * @return string Cleaned body
3451 function api_clean_attachments($body) {
3452 $data = get_attachment_data($body);
3459 if (isset($data["text"]))
3460 $body = $data["text"];
3462 if (($body == "") AND (isset($data["title"])))
3463 $body = $data["title"];
3465 if (isset($data["url"]))
3466 $body .= "\n".$data["url"];
3468 $body .= $data["after"];
3473 function api_best_nickname(&$contacts) {
3474 $best_contact = array();
3476 if (count($contact) == 0)
3479 foreach ($contacts AS $contact)
3480 if ($contact["network"] == "") {
3481 $contact["network"] = "dfrn";
3482 $best_contact = array($contact);
3485 if (sizeof($best_contact) == 0)
3486 foreach ($contacts AS $contact)
3487 if ($contact["network"] == "dfrn")
3488 $best_contact = array($contact);
3490 if (sizeof($best_contact) == 0)
3491 foreach ($contacts AS $contact)
3492 if ($contact["network"] == "dspr")
3493 $best_contact = array($contact);
3495 if (sizeof($best_contact) == 0)
3496 foreach ($contacts AS $contact)
3497 if ($contact["network"] == "stat")
3498 $best_contact = array($contact);
3500 if (sizeof($best_contact) == 0)
3501 foreach ($contacts AS $contact)
3502 if ($contact["network"] == "pump")
3503 $best_contact = array($contact);
3505 if (sizeof($best_contact) == 0)
3506 foreach ($contacts AS $contact)
3507 if ($contact["network"] == "twit")
3508 $best_contact = array($contact);
3510 if (sizeof($best_contact) == 1)
3511 $contacts = $best_contact;
3513 $contacts = array($contacts[0]);
3516 // return all or a specified group of the user with the containing contacts
3517 function api_friendica_group_show($type) {
3521 if (api_user()===false) throw new ForbiddenException();
3524 $user_info = api_get_user($a);
3525 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3526 $uid = $user_info['uid'];
3528 // get data of the specified group id or all groups if not specified
3530 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3533 // error message if specified gid is not in database
3534 if (!dbm::is_result($r))
3535 throw new BadRequestException("gid not available");
3538 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3541 // loop through all groups and retrieve all members for adding data in the user array
3542 foreach ($r as $rr) {
3543 $members = group_get_members($rr['id']);
3546 if ($type == "xml") {
3547 $user_element = "users";
3549 foreach ($members as $member) {
3550 $user = api_get_user($a, $member['nurl']);
3551 $users[$k++.":user"] = $user;
3554 $user_element = "user";
3555 foreach ($members as $member) {
3556 $user = api_get_user($a, $member['nurl']);
3560 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3562 return api_format_data("groups", $type, array('group' => $grps));
3564 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3567 // delete the specified group of the user
3568 function api_friendica_group_delete($type) {
3572 if (api_user()===false) throw new ForbiddenException();
3575 $user_info = api_get_user($a);
3576 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3577 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3578 $uid = $user_info['uid'];
3580 // error if no gid specified
3581 if ($gid == 0 || $name == "")
3582 throw new BadRequestException('gid or name not specified');
3584 // get data of the specified group id
3585 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3588 // error message if specified gid is not in database
3589 if (!dbm::is_result($r))
3590 throw new BadRequestException('gid not available');
3592 // get data of the specified group id and group name
3593 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3597 // error message if specified gid is not in database
3598 if (!dbm::is_result($rname))
3599 throw new BadRequestException('wrong group name');
3602 $ret = group_rmv($uid, $name);
3605 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3606 return api_format_data("group_delete", $type, array('result' => $success));
3609 throw new BadRequestException('other API error');
3611 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3614 // create the specified group with the posted array of contacts
3615 function api_friendica_group_create($type) {
3619 if (api_user()===false) throw new ForbiddenException();
3622 $user_info = api_get_user($a);
3623 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3624 $uid = $user_info['uid'];
3625 $json = json_decode($_POST['json'], true);
3626 $users = $json['user'];
3628 // error if no name specified
3630 throw new BadRequestException('group name not specified');
3632 // get data of the specified group name
3633 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3636 // error message if specified group name already exists
3637 if (dbm::is_result($rname))
3638 throw new BadRequestException('group name already exists');
3640 // check if specified group name is a deleted group
3641 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3644 // error message if specified group name already exists
3645 if (dbm::is_result($rname))
3646 $reactivate_group = true;
3649 $ret = group_add($uid, $name);
3651 $gid = group_byname($uid, $name);
3653 throw new BadRequestException('other API error');
3656 $erroraddinguser = false;
3657 $errorusers = array();
3658 foreach ($users as $user) {
3659 $cid = $user['cid'];
3660 // check if user really exists as contact
3661 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3664 if (count($contact))
3665 $result = group_add_member($uid, $name, $cid, $gid);
3667 $erroraddinguser = true;
3668 $errorusers[] = $cid;
3672 // return success message incl. missing users in array
3673 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3674 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3675 return api_format_data("group_create", $type, array('result' => $success));
3677 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3680 // update the specified group with the posted array of contacts
3681 function api_friendica_group_update($type) {
3685 if (api_user()===false) throw new ForbiddenException();
3688 $user_info = api_get_user($a);
3689 $uid = $user_info['uid'];
3690 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3691 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3692 $json = json_decode($_POST['json'], true);
3693 $users = $json['user'];
3695 // error if no name specified
3697 throw new BadRequestException('group name not specified');
3699 // error if no gid specified
3701 throw new BadRequestException('gid not specified');
3704 $members = group_get_members($gid);
3705 foreach ($members as $member) {
3706 $cid = $member['id'];
3707 foreach ($users as $user) {
3708 $found = ($user['cid'] == $cid ? true : false);
3711 $ret = group_rmv_member($uid, $name, $cid);
3716 $erroraddinguser = false;
3717 $errorusers = array();
3718 foreach ($users as $user) {
3719 $cid = $user['cid'];
3720 // check if user really exists as contact
3721 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3724 if (count($contact))
3725 $result = group_add_member($uid, $name, $cid, $gid);
3727 $erroraddinguser = true;
3728 $errorusers[] = $cid;
3732 // return success message incl. missing users in array
3733 $status = ($erroraddinguser ? "missing user" : "ok");
3734 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3735 return api_format_data("group_update", $type, array('result' => $success));
3737 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3740 function api_friendica_activity($type) {
3744 if (api_user()===false) throw new ForbiddenException();
3745 $verb = strtolower($a->argv[3]);
3746 $verb = preg_replace("|\..*$|", "", $verb);
3748 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3750 $res = do_like($id, $verb);
3757 return api_format_data('ok', $type, array('ok' => $ok));
3759 throw new BadRequestException('Error adding activity');
3763 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3764 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3765 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3766 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3767 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3768 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3769 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3770 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3771 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3772 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3775 * @brief Returns notifications
3777 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3780 function api_friendica_notification($type) {
3784 if (api_user()===false) throw new ForbiddenException();
3785 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3786 $nm = new NotificationsManager();
3788 $notes = $nm->getAll(array(), "+seen -date", 50);
3790 if ($type == "xml") {
3791 $xmlnotes = array();
3792 foreach ($notes AS $note)
3793 $xmlnotes[] = array("@attributes" => $note);
3798 return api_format_data("notes", $type, array('note' => $notes));
3802 * @brief Set notification as seen and returns associated item (if possible)
3804 * POST request with 'id' param as notification id
3806 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3809 function api_friendica_notification_seen($type){
3813 if (api_user()===false) throw new ForbiddenException();
3814 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3816 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3818 $nm = new NotificationsManager();
3819 $note = $nm->getByID($id);
3820 if (is_null($note)) throw new BadRequestException("Invalid argument");
3822 $nm->setSeen($note);
3823 if ($note['otype']=='item') {
3824 // would be really better with an ItemsManager and $im->getByID() :-P
3825 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3826 intval($note['iid']),
3827 intval(local_user())
3830 // we found the item, return it to the user
3831 $user_info = api_get_user($a);
3832 $ret = api_format_items($r,$user_info, false, $type);
3833 $data = array('status' => $ret);
3834 return api_format_data("status", $type, $data);
3836 // the item can't be found, but we set the note as seen, so we count this as a success
3838 return api_format_data('result', $type, array('result' => "success"));
3841 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3842 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3846 * @brief update a direct_message to seen state
3848 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3849 * @return string (success result=ok, error result=error with error message)
3851 function api_friendica_direct_messages_setseen($type){
3853 if (api_user()===false) throw new ForbiddenException();
3856 $user_info = api_get_user($a);
3857 $uid = $user_info['uid'];
3858 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3860 // return error if id is zero
3862 $answer = array('result' => 'error', 'message' => 'message id not specified');
3863 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3866 // get data of the specified message id
3867 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
3870 // error message if specified id is not in database
3871 if (!dbm::is_result($r)) {
3872 $answer = array('result' => 'error', 'message' => 'message id not in database');
3873 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3876 // update seen indicator
3877 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
3883 $answer = array('result' => 'ok', 'message' => 'message set to seen');
3884 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
3886 $answer = array('result' => 'error', 'message' => 'unknown error');
3887 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3890 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
3896 * @brief search for direct_messages containing a searchstring through api
3898 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3899 * @return string (success: success=true if found and search_result contains found messages
3900 * success=false if nothing was found, search_result='nothing found',
3901 * error: result=error with error message)
3903 function api_friendica_direct_messages_search($type){
3906 if (api_user()===false) throw new ForbiddenException();
3909 $user_info = api_get_user($a);
3910 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");
3911 $uid = $user_info['uid'];
3913 // error if no searchstring specified
3914 if ($searchstring == "") {
3915 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
3916 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
3919 // get data for the specified searchstring
3920 $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",
3922 dbesc('%'.$searchstring.'%')
3925 $profile_url = $user_info["url"];
3926 // message if nothing was found
3927 if (!dbm::is_result($r))
3928 $success = array('success' => false, 'search_results' => 'problem with query');
3929 else if (count($r) == 0)
3930 $success = array('success' => false, 'search_results' => 'nothing found');
3933 foreach($r as $item) {
3934 if ($box == "inbox" || $item['from-url'] != $profile_url){
3935 $recipient = $user_info;
3936 $sender = api_get_user($a,normalise_link($item['contact-url']));
3938 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
3939 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3940 $sender = $user_info;
3942 $ret[]=api_format_messages($item, $recipient, $sender);
3944 $success = array('success' => true, 'search_results' => $ret);
3947 return api_format_data("direct_message_search", $type, array('$result' => $success));
3949 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
3952 * @brief return data of all the profiles a user has to the client
3954 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3957 function api_friendica_profile_show($type){
3960 if (api_user()===false) throw new ForbiddenException();
3963 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);
3965 // retrieve general information about profiles for user
3966 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
3967 $directory = get_config('system', 'directory');
3969 // get data of the specified profile id or all profiles of the user if not specified
3970 if ($profileid != 0) {
3971 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
3973 intval($profileid));
3974 // error message if specified gid is not in database
3975 if (!dbm::is_result($r))
3976 throw new BadRequestException("profile_id not available");
3978 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
3979 intval(api_user()));
3981 // loop through all returned profiles and retrieve data and users
3983 foreach ($r as $rr) {
3984 $profile = api_format_items_profiles($rr, $type);
3986 // select all users from contact table, loop and prepare standard return for user data
3988 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
3990 intval($rr['profile_id']));
3992 foreach ($r as $rr) {
3993 $user = api_get_user($a, $rr['nurl']);
3994 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;
3996 $profile['users'] = $users;
3998 // add prepared profile data to array for final return
3999 if ($type == "xml") {
4000 $profiles[$k++.":profile"] = $profile;
4002 $profiles[] = $profile;
4006 // return settings, authenticated user and profiles data
4007 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4009 $result = array('multi_profiles' => $multi_profiles ? true : false,
4010 'global_dir' => $directory,
4011 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4012 'profiles' => $profiles);
4013 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4015 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4019 [pagename] => api/1.1/statuses/lookup.json
4020 [id] => 605138389168451584
4021 [include_cards] => true
4022 [cards_platform] => Android-12
4023 [include_entities] => true
4024 [include_my_retweet] => 1
4026 [include_reply_count] => true
4027 [include_descendent_reply_count] => true
4031 Not implemented by now:
4032 statuses/retweets_of_me
4037 account/update_location
4038 account/update_profile_background_image
4039 account/update_profile_image
4042 friendica/profile/update
4043 friendica/profile/create
4044 friendica/profile/delete
4046 Not implemented in status.net:
4047 statuses/retweeted_to_me
4048 statuses/retweeted_by_me
4049 direct_messages/destroy
4051 account/update_delivery_device
4052 notifications/follow