3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
27 require_once('include/plaintext.php');
28 require_once('include/xml.php');
31 define('API_METHOD_ANY','*');
32 define('API_METHOD_GET','GET');
33 define('API_METHOD_POST','POST,PUT');
34 define('API_METHOD_DELETE','POST,DELETE');
42 * @brief Auth API user
44 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
45 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
46 * into a page, and visitors will post something without noticing it).
49 if ($_SESSION['allow_api'])
56 * @brief Get source name from API client
58 * Clients can send 'source' parameter to be show in post metadata
59 * as "sent via <source>".
60 * Some clients doesn't send a source param, we support ones we know
64 * Client source name, default to "api" if unset/unknown
66 function api_source() {
67 if (requestdata('source'))
68 return (requestdata('source'));
70 // Support for known clients that doesn't send a source name
71 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
74 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
80 * @brief Format date for API
82 * @param string $str Source date, as UTC
83 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
85 function api_date($str){
86 //Wed May 23 06:01:13 +0000 2007
87 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
91 * @brief Register API endpoint
93 * Register a function to be the endpont for defined API path.
95 * @param string $path API URL path, relative to $a->get_baseurl()
96 * @param string $func Function name to call on path request
97 * @param bool $auth API need logged user
98 * @param string $method
99 * HTTP method reqiured to call this endpoint.
100 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
101 * Default to API_METHOD_ANY
103 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
111 // Workaround for hotot
112 $path = str_replace("api/", "api/1.1/", $path);
121 * @brief Login API user
123 * Log in user via OAuth1 or Simple HTTP Auth.
124 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
127 * @hook 'authenticate'
129 * 'username' => username from login form
130 * 'password' => password from login form
131 * 'authenticated' => return status,
132 * 'user_record' => return authenticated user record
134 * array $user logged user record
136 function api_login(&$a){
139 $oauth = new FKOAuth1();
140 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
141 if (!is_null($token)){
142 $oauth->loginUser($token->uid);
143 call_hooks('logged_in', $a->user);
146 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
147 }catch(Exception $e){
153 // workaround for HTTP-auth in CGI mode
154 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
155 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
156 if(strlen($userpass)) {
157 list($name, $password) = explode(':', $userpass);
158 $_SERVER['PHP_AUTH_USER'] = $name;
159 $_SERVER['PHP_AUTH_PW'] = $password;
163 if (!isset($_SERVER['PHP_AUTH_USER'])) {
164 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
165 header('WWW-Authenticate: Basic realm="Friendica"');
166 throw new UnauthorizedException("This API requires login");
169 $user = $_SERVER['PHP_AUTH_USER'];
170 $password = $_SERVER['PHP_AUTH_PW'];
171 $encrypted = hash('whirlpool',trim($password));
173 // allow "user@server" login (but ignore 'server' part)
174 $at=strstr($user, "@", true);
175 if ( $at ) $user=$at;
178 * next code from mod/auth.php. needs better solution
183 'username' => trim($user),
184 'password' => trim($password),
185 'authenticated' => 0,
186 'user_record' => null
191 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
192 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
193 * and later plugins should not interfere with an earlier one that succeeded.
197 call_hooks('authenticate', $addon_auth);
199 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
200 $record = $addon_auth['user_record'];
203 // process normal login request
205 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
206 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
215 if((! $record) || (! count($record))) {
216 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
217 header('WWW-Authenticate: Basic realm="Friendica"');
218 #header('HTTP/1.0 401 Unauthorized');
219 #die('This api requires login');
220 throw new UnauthorizedException("This API requires login");
223 authenticate_success($record); $_SESSION["allow_api"] = true;
225 call_hooks('logged_in', $a->user);
230 * @brief Check HTTP method of called API
232 * API endpoints can define which HTTP method to accept when called.
233 * This function check the current HTTP method agains endpoint
236 * @param string $method Required methods, uppercase, separated by comma
239 function api_check_method($method) {
240 if ($method=="*") return True;
241 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
245 * @brief Main API entry point
247 * Authenticate user, call registered API function, set HTTP headers
250 * @return string API call result
252 function api_call(&$a){
253 GLOBAL $API, $called_api;
256 if (strpos($a->query_string, ".xml")>0) $type="xml";
257 if (strpos($a->query_string, ".json")>0) $type="json";
258 if (strpos($a->query_string, ".rss")>0) $type="rss";
259 if (strpos($a->query_string, ".atom")>0) $type="atom";
260 if (strpos($a->query_string, ".as")>0) $type="as";
262 foreach ($API as $p=>$info){
263 if (strpos($a->query_string, $p)===0){
264 if (!api_check_method($info['method'])){
265 throw new MethodNotAllowedException();
268 $called_api= explode("/",$p);
269 //unset($_SERVER['PHP_AUTH_USER']);
270 if ($info['auth']===true && api_user()===false) {
274 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
275 logger('API parameters: ' . print_r($_REQUEST,true));
277 $stamp = microtime(true);
278 $r = call_user_func($info['func'], $a, $type);
279 $duration = (float)(microtime(true)-$stamp);
280 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
283 // api function returned false withour throw an
284 // exception. This should not happend, throw a 500
285 throw new InternalServerErrorException();
290 header ("Content-Type: text/xml");
292 if (substr($r, 0, 5) == "<?xml")
295 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
296 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
299 header ("Content-Type: application/json");
301 $json = json_encode($rr);
302 if ($_GET['callback'])
303 $json = $_GET['callback']."(".$json.")";
307 header ("Content-Type: application/rss+xml");
308 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
311 header ("Content-Type: application/atom+xml");
312 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
315 //header ("Content-Type: application/json");
317 // return json_encode($rr);
318 return json_encode($r);
324 throw new NotImplementedException();
325 } catch (HTTPException $e) {
326 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
327 return api_error($a, $type, $e);
332 * @brief Format API error string
335 * @param string $type Return type (xml, json, rss, as)
336 * @param HTTPException $error Error object
337 * @return strin error message formatted as $type
339 function api_error(&$a, $type, $e) {
340 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
341 # TODO: https://dev.twitter.com/overview/api/response-codes
342 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
345 header ("Content-Type: text/xml");
346 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
349 header ("Content-Type: application/json");
350 return json_encode(array(
352 'request' => $a->query_string,
353 'code' => $e->httpcode." ".$e->httpdesc
357 header ("Content-Type: application/rss+xml");
358 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
361 header ("Content-Type: application/atom+xml");
362 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
368 * @brief Set values for RSS template
371 * @param array $arr Array to be passed to template
372 * @param array $user_info
375 function api_rss_extra(&$a, $arr, $user_info){
376 if (is_null($user_info)) $user_info = api_get_user($a);
377 $arr['$user'] = $user_info;
378 $arr['$rss'] = array(
379 'alternate' => $user_info['url'],
380 'self' => $a->get_baseurl(). "/". $a->query_string,
381 'base' => $a->get_baseurl(),
382 'updated' => api_date(null),
383 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
384 'language' => $user_info['language'],
385 'logo' => $a->get_baseurl()."/images/friendica-32.png",
393 * @brief Unique contact to contact url.
395 * @param int $id Contact id
396 * @return bool|string
397 * Contact url or False if contact id is unknown
399 function api_unique_id_to_url($id){
400 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
403 return ($r[0]["url"]);
409 * @brief Get user info array.
412 * @param int|string $contact_id Contact ID or URL
413 * @param string $type Return type (for errors)
415 function api_get_user(&$a, $contact_id = Null, $type = "json"){
422 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
424 // Searching for contact URL
425 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
426 $user = dbesc(normalise_link($contact_id));
428 $extra_query = "AND `contact`.`nurl` = '%s' ";
429 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
432 // Searching for unique contact id
433 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
434 $user = dbesc(api_unique_id_to_url($contact_id));
437 throw new BadRequestException("User not found.");
440 $extra_query = "AND `contact`.`nurl` = '%s' ";
441 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
444 if(is_null($user) && x($_GET, 'user_id')) {
445 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
448 throw new BadRequestException("User not found.");
451 $extra_query = "AND `contact`.`nurl` = '%s' ";
452 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
454 if(is_null($user) && x($_GET, 'screen_name')) {
455 $user = dbesc($_GET['screen_name']);
457 $extra_query = "AND `contact`.`nick` = '%s' ";
458 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
461 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
462 $argid = count($called_api);
463 list($user, $null) = explode(".",$a->argv[$argid]);
464 if(is_numeric($user)){
465 $user = dbesc(api_unique_id_to_url($user));
471 $extra_query = "AND `contact`.`nurl` = '%s' ";
472 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
474 $user = dbesc($user);
476 $extra_query = "AND `contact`.`nick` = '%s' ";
477 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
481 logger("api_get_user: user ".$user, LOGGER_DEBUG);
484 if (api_user()===false) {
488 $user = $_SESSION['uid'];
489 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
494 logger('api_user: ' . $extra_query . ', user: ' . $user);
496 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
502 // Selecting the id by priority, friendica first
503 api_best_nickname($uinfo);
505 // if the contact wasn't found, fetch it from the unique contacts
506 if (count($uinfo)==0) {
510 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
513 // If no nick where given, extract it from the address
514 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
515 $r[0]['nick'] = api_get_nick($r[0]["url"]);
519 'id_str' => (string) $r[0]["id"],
520 'name' => $r[0]["name"],
521 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
522 'location' => $r[0]["location"],
523 'description' => $r[0]["about"],
524 'url' => $r[0]["url"],
525 'protected' => false,
526 'followers_count' => 0,
527 'friends_count' => 0,
529 'created_at' => api_date($r[0]["created"]),
530 'favourites_count' => 0,
532 'time_zone' => 'UTC',
533 'geo_enabled' => false,
535 'statuses_count' => 0,
537 'contributors_enabled' => false,
538 'is_translator' => false,
539 'is_translation_enabled' => false,
540 'profile_image_url' => $r[0]["photo"],
541 'profile_image_url_https' => $r[0]["photo"],
542 'following' => false,
543 'follow_request_sent' => false,
544 'notifications' => false,
545 'statusnet_blocking' => false,
546 'notifications' => false,
547 'statusnet_profile_url' => $r[0]["url"],
551 'network' => $r[0]["network"],
556 throw new BadRequestException("User not found.");
560 if($uinfo[0]['self']) {
561 $usr = q("select * from user where uid = %d limit 1",
564 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
568 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
569 // count public wall messages
570 $r = q("SELECT count(*) as `count` FROM `item`
573 intval($uinfo[0]['uid'])
575 $countitms = $r[0]['count'];
578 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
579 $r = q("SELECT count(*) as `count` FROM `item`
580 WHERE `contact-id` = %d",
581 intval($uinfo[0]['id'])
583 $countitms = $r[0]['count'];
587 $r = q("SELECT count(*) as `count` FROM `contact`
588 WHERE `uid` = %d AND `rel` IN ( %d, %d )
589 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
590 intval($uinfo[0]['uid']),
591 intval(CONTACT_IS_SHARING),
592 intval(CONTACT_IS_FRIEND)
594 $countfriends = $r[0]['count'];
596 $r = q("SELECT count(*) as `count` FROM `contact`
597 WHERE `uid` = %d AND `rel` IN ( %d, %d )
598 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
599 intval($uinfo[0]['uid']),
600 intval(CONTACT_IS_FOLLOWER),
601 intval(CONTACT_IS_FRIEND)
603 $countfollowers = $r[0]['count'];
605 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
606 intval($uinfo[0]['uid'])
608 $starred = $r[0]['count'];
611 if(! $uinfo[0]['self']) {
617 // Add a nick if it isn't present there
618 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
619 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
622 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
624 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
625 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
628 'id' => intval($gcontact_id),
629 'id_str' => (string) intval($gcontact_id),
630 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
631 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
632 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
633 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
634 'profile_image_url' => $uinfo[0]['micro'],
635 'profile_image_url_https' => $uinfo[0]['micro'],
636 'url' => $uinfo[0]['url'],
637 'protected' => false,
638 'followers_count' => intval($countfollowers),
639 'friends_count' => intval($countfriends),
640 'created_at' => api_date($uinfo[0]['created']),
641 'favourites_count' => intval($starred),
643 'time_zone' => 'UTC',
644 'statuses_count' => intval($countitms),
645 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
647 'statusnet_blocking' => false,
648 'notifications' => false,
649 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
650 'statusnet_profile_url' => $uinfo[0]['url'],
651 'uid' => intval($uinfo[0]['uid']),
652 'cid' => intval($uinfo[0]['cid']),
653 'self' => $uinfo[0]['self'],
654 'network' => $uinfo[0]['network'],
661 function api_item_get_user(&$a, $item) {
663 // Make sure that there is an entry in the global contacts for author and owner
664 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
665 "photo" => $item['author-avatar'], "name" => $item['author-name']));
667 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
668 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
670 // Comments in threads may appear as wall-to-wall postings.
671 // So only take the owner at the top posting.
672 if ($item["id"] == $item["parent"])
673 $status_user = api_get_user($a,$item["owner-link"]);
675 $status_user = api_get_user($a,$item["author-link"]);
677 $status_user["protected"] = (($item["allow_cid"] != "") OR
678 ($item["allow_gid"] != "") OR
679 ($item["deny_cid"] != "") OR
680 ($item["deny_gid"] != "") OR
683 return ($status_user);
688 * @brief transform $data array in xml without a template
691 * @return string xml string
693 function api_array_to_xml($data, $ename="") {
696 if (count($data)==1 && !is_array($data[0])) {
697 $ename = array_keys($data)[0];
699 return "<$ename>$v</$ename>";
701 foreach($data as $k=>$v) {
704 $attrs .= sprintf('%s="%s" ', $k, $v);
706 if (is_numeric($k)) $k=trim($ename,'s');
707 $childs.=api_array_to_xml($v, $k);
711 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
716 function api_walk_recursive(array &$array, callable $callback) {
718 $new_array = array();
720 foreach ($array as $k => $v) {
722 if ($callback($v, $k))
723 $new_array[$k] = api_walk_recursive($v, $callback);
725 if ($callback($v, $k))
734 function api_reformat_xml(&$item, &$key) {
736 $item = ($item ? "true" : "false");
738 if (substr($key, 0, 10) == "statusnet_")
739 $key = "statusnet:".substr($key, 10);
740 elseif (substr($key, 0, 10) == "friendica_")
741 $key = "friendica:".substr($key, 10);
742 elseif (in_array($key, array("like", "dislike", "attendyes", "attendno", "attendmaybe")))
743 $key = "friendica:".$key;
745 return ($key != "attachments");
748 function api_create_xml($data, $templatename) {
749 $data2 = array_pop($data);
752 if (is_array($data2))
753 api_walk_recursive($data2, "api_reformat_xml");
758 foreach ($data2 AS $item)
759 $data4[$i++.":status"] = $item;
760 $data3 = array("statuses" => $data4);
762 $data3 = array($templatename => $data2);
764 $namespaces = array("statusnet" => "http://status.net/schema/api/1/",
765 "friendica" => "http://friendi.ca/schema/api/1/");
767 $ret = xml::from_array($data3, $xml, false, $namespaces);
773 * load api $templatename for $type and replace $data array
775 function api_apply_template($templatename, $type, $data){
783 //$ret = api_create_xml($data, $templatename);
786 $data = array_xmlify($data);
787 if ($templatename==="<auto>") {
788 $ret = api_array_to_xml($data);
790 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
792 header ("Content-Type: text/xml");
793 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
796 $ret = replace_macros($tpl, $data);
812 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
813 * returns a 401 status code and an error message if not.
814 * http://developer.twitter.com/doc/get/account/verify_credentials
816 function api_account_verify_credentials(&$a, $type){
817 if (api_user()===false) throw new ForbiddenException();
819 unset($_REQUEST["user_id"]);
820 unset($_GET["user_id"]);
822 unset($_REQUEST["screen_name"]);
823 unset($_GET["screen_name"]);
825 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
827 $user_info = api_get_user($a);
829 // "verified" isn't used here in the standard
830 unset($user_info["verified"]);
832 // - Adding last status
834 $user_info["status"] = api_status_show($a,"raw");
835 if (!count($user_info["status"]))
836 unset($user_info["status"]);
838 unset($user_info["status"]["user"]);
841 // "uid" and "self" are only needed for some internal stuff, so remove it from here
842 unset($user_info["uid"]);
843 unset($user_info["self"]);
845 return api_apply_template("user", $type, array('$user' => $user_info));
848 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
852 * get data from $_POST or $_GET
854 function requestdata($k){
855 if (isset($_POST[$k])){
858 if (isset($_GET[$k])){
864 /*Waitman Gobble Mod*/
865 function api_statuses_mediap(&$a, $type) {
866 if (api_user()===false) {
867 logger('api_statuses_update: no user');
868 throw new ForbiddenException();
870 $user_info = api_get_user($a);
872 $_REQUEST['type'] = 'wall';
873 $_REQUEST['profile_uid'] = api_user();
874 $_REQUEST['api_source'] = true;
875 $txt = requestdata('status');
876 //$txt = urldecode(requestdata('status'));
878 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
880 $txt = html2bb_video($txt);
881 $config = HTMLPurifier_Config::createDefault();
882 $config->set('Cache.DefinitionImpl', null);
883 $purifier = new HTMLPurifier($config);
884 $txt = $purifier->purify($txt);
886 $txt = html2bbcode($txt);
888 $a->argv[1]=$user_info['screen_name']; //should be set to username?
890 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
891 $bebop = wall_upload_post($a);
893 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
894 $_REQUEST['body']=$txt."\n\n".$bebop;
897 // this should output the last post (the one we just posted).
898 return api_status_show($a,$type);
900 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
901 /*Waitman Gobble Mod*/
904 function api_statuses_update(&$a, $type) {
905 if (api_user()===false) {
906 logger('api_statuses_update: no user');
907 throw new ForbiddenException();
910 $user_info = api_get_user($a);
912 // convert $_POST array items to the form we use for web posts.
914 // logger('api_post: ' . print_r($_POST,true));
916 if(requestdata('htmlstatus')) {
917 $txt = requestdata('htmlstatus');
918 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
919 $txt = html2bb_video($txt);
921 $config = HTMLPurifier_Config::createDefault();
922 $config->set('Cache.DefinitionImpl', null);
924 $purifier = new HTMLPurifier($config);
925 $txt = $purifier->purify($txt);
927 $_REQUEST['body'] = html2bbcode($txt);
931 $_REQUEST['body'] = requestdata('status');
933 $_REQUEST['title'] = requestdata('title');
935 $parent = requestdata('in_reply_to_status_id');
937 // Twidere sends "-1" if it is no reply ...
941 if(ctype_digit($parent))
942 $_REQUEST['parent'] = $parent;
944 $_REQUEST['parent_uri'] = $parent;
946 if(requestdata('lat') && requestdata('long'))
947 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
948 $_REQUEST['profile_uid'] = api_user();
951 $_REQUEST['type'] = 'net-comment';
953 // Check for throttling (maximum posts per day, week and month)
954 $throttle_day = get_config('system','throttle_limit_day');
955 if ($throttle_day > 0) {
956 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
958 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
959 AND `created` > '%s' AND `id` = `parent`",
960 intval(api_user()), dbesc($datefrom));
963 $posts_day = $r[0]["posts_day"];
967 if ($posts_day > $throttle_day) {
968 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
969 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
970 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
974 $throttle_week = get_config('system','throttle_limit_week');
975 if ($throttle_week > 0) {
976 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
978 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
979 AND `created` > '%s' AND `id` = `parent`",
980 intval(api_user()), dbesc($datefrom));
983 $posts_week = $r[0]["posts_week"];
987 if ($posts_week > $throttle_week) {
988 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
989 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
990 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
995 $throttle_month = get_config('system','throttle_limit_month');
996 if ($throttle_month > 0) {
997 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
999 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1000 AND `created` > '%s' AND `id` = `parent`",
1001 intval(api_user()), dbesc($datefrom));
1004 $posts_month = $r[0]["posts_month"];
1008 if ($posts_month > $throttle_month) {
1009 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1010 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1011 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1015 $_REQUEST['type'] = 'wall';
1018 if(x($_FILES,'media')) {
1019 // upload the image if we have one
1020 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1021 $media = wall_upload_post($a);
1022 if(strlen($media)>0)
1023 $_REQUEST['body'] .= "\n\n".$media;
1026 // To-Do: Multiple IDs
1027 if (requestdata('media_ids')) {
1028 $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",
1029 intval(requestdata('media_ids')), api_user());
1031 $phototypes = Photo::supportedTypes();
1032 $ext = $phototypes[$r[0]['type']];
1033 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1034 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1038 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1040 $_REQUEST['api_source'] = true;
1042 if (!x($_REQUEST, "source"))
1043 $_REQUEST["source"] = api_source();
1045 // call out normal post function
1049 // this should output the last post (the one we just posted).
1050 return api_status_show($a,$type);
1052 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1053 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1056 function api_media_upload(&$a, $type) {
1057 if (api_user()===false) {
1059 throw new ForbiddenException();
1062 $user_info = api_get_user($a);
1064 if(!x($_FILES,'media')) {
1066 throw new BadRequestException("No media.");
1069 $media = wall_upload_post($a, false);
1072 throw new InternalServerErrorException();
1075 $returndata = array();
1076 $returndata["media_id"] = $media["id"];
1077 $returndata["media_id_string"] = (string)$media["id"];
1078 $returndata["size"] = $media["size"];
1079 $returndata["image"] = array("w" => $media["width"],
1080 "h" => $media["height"],
1081 "image_type" => $media["type"]);
1083 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1085 return array("media" => $returndata);
1087 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1089 function api_status_show(&$a, $type){
1090 $user_info = api_get_user($a);
1092 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1095 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1099 // get last public wall message
1100 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1101 FROM `item`, `item` as `i`
1102 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1103 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1104 AND `i`.`id` = `item`.`parent`
1105 AND `item`.`type`!='activity' $privacy_sql
1106 ORDER BY `item`.`created` DESC
1108 intval($user_info['cid']),
1110 dbesc($user_info['url']),
1111 dbesc(normalise_link($user_info['url'])),
1112 dbesc($user_info['url']),
1113 dbesc(normalise_link($user_info['url']))
1116 if (count($lastwall)>0){
1117 $lastwall = $lastwall[0];
1119 $in_reply_to_status_id = NULL;
1120 $in_reply_to_user_id = NULL;
1121 $in_reply_to_status_id_str = NULL;
1122 $in_reply_to_user_id_str = NULL;
1123 $in_reply_to_screen_name = NULL;
1124 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1125 $in_reply_to_status_id= intval($lastwall['parent']);
1126 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1128 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1130 if ($r[0]['nick'] == "")
1131 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1133 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1134 $in_reply_to_user_id = intval($r[0]['id']);
1135 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1139 // There seems to be situation, where both fields are identical:
1140 // https://github.com/friendica/friendica/issues/1010
1141 // This is a bugfix for that.
1142 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1143 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1144 $in_reply_to_status_id = NULL;
1145 $in_reply_to_user_id = NULL;
1146 $in_reply_to_status_id_str = NULL;
1147 $in_reply_to_user_id_str = NULL;
1148 $in_reply_to_screen_name = NULL;
1151 $converted = api_convert_item($lastwall);
1153 $status_info = array(
1154 'created_at' => api_date($lastwall['created']),
1155 'id' => intval($lastwall['id']),
1156 'id_str' => (string) $lastwall['id'],
1157 'text' => $converted["text"],
1158 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1159 'truncated' => false,
1160 'in_reply_to_status_id' => $in_reply_to_status_id,
1161 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1162 'in_reply_to_user_id' => $in_reply_to_user_id,
1163 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1164 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1165 'user' => $user_info,
1167 'coordinates' => "",
1169 'contributors' => "",
1170 'is_quote_status' => false,
1171 'retweet_count' => 0,
1172 'favorite_count' => 0,
1173 'favorited' => $lastwall['starred'] ? true : false,
1174 'retweeted' => false,
1175 'possibly_sensitive' => false,
1177 'statusnet_html' => $converted["html"],
1178 'statusnet_conversation_id' => $lastwall['parent'],
1181 if (count($converted["attachments"]) > 0)
1182 $status_info["attachments"] = $converted["attachments"];
1184 if (count($converted["entities"]) > 0)
1185 $status_info["entities"] = $converted["entities"];
1187 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1188 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1189 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1190 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1192 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1193 unset($status_info["user"]["uid"]);
1194 unset($status_info["user"]["self"]);
1197 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1200 return($status_info);
1202 return api_apply_template("status", $type, array('$status' => $status_info));
1211 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1212 * The author's most recent status will be returned inline.
1213 * http://developer.twitter.com/doc/get/users/show
1215 function api_users_show(&$a, $type){
1216 $user_info = api_get_user($a);
1218 $lastwall = q("SELECT `item`.*
1219 FROM `item`, `contact`
1220 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1221 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1222 AND `contact`.`id`=`item`.`contact-id`
1223 AND `type`!='activity'
1224 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1225 ORDER BY `created` DESC
1228 dbesc(ACTIVITY_POST),
1229 intval($user_info['cid']),
1230 dbesc($user_info['url']),
1231 dbesc(normalise_link($user_info['url'])),
1232 dbesc($user_info['url']),
1233 dbesc(normalise_link($user_info['url']))
1235 if (count($lastwall)>0){
1236 $lastwall = $lastwall[0];
1238 $in_reply_to_status_id = NULL;
1239 $in_reply_to_user_id = NULL;
1240 $in_reply_to_status_id_str = NULL;
1241 $in_reply_to_user_id_str = NULL;
1242 $in_reply_to_screen_name = NULL;
1243 if ($lastwall['parent']!=$lastwall['id']) {
1244 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1245 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1246 if (count($reply)>0) {
1247 $in_reply_to_status_id = intval($lastwall['parent']);
1248 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1250 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1252 if ($r[0]['nick'] == "")
1253 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1255 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1256 $in_reply_to_user_id = intval($r[0]['id']);
1257 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1262 $converted = api_convert_item($lastwall);
1264 $user_info['status'] = array(
1265 'text' => $converted["text"],
1266 'truncated' => false,
1267 'created_at' => api_date($lastwall['created']),
1268 'in_reply_to_status_id' => $in_reply_to_status_id,
1269 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1270 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1271 'id' => intval($lastwall['contact-id']),
1272 'id_str' => (string) $lastwall['contact-id'],
1273 'in_reply_to_user_id' => $in_reply_to_user_id,
1274 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1275 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1277 'favorited' => $lastwall['starred'] ? true : false,
1278 'statusnet_html' => $converted["html"],
1279 'statusnet_conversation_id' => $lastwall['parent'],
1282 if (count($converted["attachments"]) > 0)
1283 $user_info["status"]["attachments"] = $converted["attachments"];
1285 if (count($converted["entities"]) > 0)
1286 $user_info["status"]["entities"] = $converted["entities"];
1288 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1289 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1290 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1291 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1295 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1296 unset($user_info["uid"]);
1297 unset($user_info["self"]);
1299 return api_apply_template("user", $type, array('$user' => $user_info));
1302 api_register_func('api/users/show','api_users_show');
1305 function api_users_search(&$a, $type) {
1306 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1308 $userlist = array();
1310 if (isset($_GET["q"])) {
1311 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1313 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1316 foreach ($r AS $user) {
1317 $user_info = api_get_user($a, $user["id"]);
1318 //echo print_r($user_info, true)."\n";
1319 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1320 $userlist[] = $userdata["user"];
1322 $userlist = array("users" => $userlist);
1324 throw new BadRequestException("User not found.");
1327 throw new BadRequestException("User not found.");
1332 api_register_func('api/users/search','api_users_search');
1336 * http://developer.twitter.com/doc/get/statuses/home_timeline
1338 * TODO: Optional parameters
1339 * TODO: Add reply info
1341 function api_statuses_home_timeline(&$a, $type){
1342 if (api_user()===false) throw new ForbiddenException();
1344 unset($_REQUEST["user_id"]);
1345 unset($_GET["user_id"]);
1347 unset($_REQUEST["screen_name"]);
1348 unset($_GET["screen_name"]);
1350 $user_info = api_get_user($a);
1351 // get last newtork messages
1355 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1356 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1357 if ($page<0) $page=0;
1358 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1359 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1360 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1361 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1362 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1364 $start = $page*$count;
1368 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1369 if ($exclude_replies > 0)
1370 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1371 if ($conversation_id > 0)
1372 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1374 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1375 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1376 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1377 `contact`.`id` AS `cid`
1378 FROM `item`, `contact`
1379 WHERE `item`.`uid` = %d AND `verb` = '%s'
1380 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1381 AND `contact`.`id` = `item`.`contact-id`
1382 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1385 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1387 dbesc(ACTIVITY_POST),
1389 intval($start), intval($count)
1392 $ret = api_format_items($r,$user_info);
1394 // Set all posts from the query above to seen
1396 foreach ($r AS $item)
1397 $idarray[] = intval($item["id"]);
1399 $idlist = implode(",", $idarray);
1401 if ($idlist != "") {
1402 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1405 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1408 $data = array('$statuses' => $ret);
1412 $data = api_rss_extra($a, $data, $user_info);
1415 $as = api_format_as($a, $ret, $user_info);
1416 $as['title'] = $a->config['sitename']." Home Timeline";
1417 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1422 return api_apply_template("timeline", $type, $data);
1424 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1425 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1427 function api_statuses_public_timeline(&$a, $type){
1428 if (api_user()===false) throw new ForbiddenException();
1430 $user_info = api_get_user($a);
1431 // get last newtork messages
1435 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1436 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1437 if ($page<0) $page=0;
1438 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1439 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1440 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1441 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1442 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1444 $start = $page*$count;
1447 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1448 if ($exclude_replies > 0)
1449 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1450 if ($conversation_id > 0)
1451 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1453 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1454 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1455 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1456 `contact`.`id` AS `cid`,
1457 `user`.`nickname`, `user`.`hidewall`
1458 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1459 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1460 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1461 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1462 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1463 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1464 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1467 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1468 dbesc(ACTIVITY_POST),
1473 $ret = api_format_items($r,$user_info);
1476 $data = array('$statuses' => $ret);
1480 $data = api_rss_extra($a, $data, $user_info);
1483 $as = api_format_as($a, $ret, $user_info);
1484 $as['title'] = $a->config['sitename']." Public Timeline";
1485 $as['link']['url'] = $a->get_baseurl()."/";
1490 return api_apply_template("timeline", $type, $data);
1492 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1497 function api_statuses_show(&$a, $type){
1498 if (api_user()===false) throw new ForbiddenException();
1500 $user_info = api_get_user($a);
1503 $id = intval($a->argv[3]);
1506 $id = intval($_REQUEST["id"]);
1510 $id = intval($a->argv[4]);
1512 logger('API: api_statuses_show: '.$id);
1514 $conversation = (x($_REQUEST,'conversation')?1:0);
1518 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1520 $sql_extra .= " AND `item`.`id` = %d";
1522 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1523 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1524 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1525 `contact`.`id` AS `cid`
1526 FROM `item`, `contact`
1527 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1528 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1529 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1532 dbesc(ACTIVITY_POST),
1537 throw new BadRequestException("There is no status with this id.");
1540 $ret = api_format_items($r,$user_info);
1542 if ($conversation) {
1543 $data = array('$statuses' => $ret);
1544 return api_apply_template("timeline", $type, $data);
1546 $data = array('$status' => $ret[0]);
1550 $data = api_rss_extra($a, $data, $user_info);
1552 return api_apply_template("status", $type, $data);
1555 api_register_func('api/statuses/show','api_statuses_show', true);
1561 function api_conversation_show(&$a, $type){
1562 if (api_user()===false) throw new ForbiddenException();
1564 $user_info = api_get_user($a);
1567 $id = intval($a->argv[3]);
1568 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1569 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1570 if ($page<0) $page=0;
1571 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1572 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1574 $start = $page*$count;
1577 $id = intval($_REQUEST["id"]);
1581 $id = intval($a->argv[4]);
1583 logger('API: api_conversation_show: '.$id);
1585 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1587 $id = $r[0]["parent"];
1592 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1594 // Not sure why this query was so complicated. We should keep it here for a while,
1595 // just to make sure that we really don't need it.
1596 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1597 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1599 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1600 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1601 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1602 `contact`.`id` AS `cid`
1604 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1605 WHERE `item`.`parent` = %d AND `item`.`visible`
1606 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1607 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1608 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1609 AND `item`.`id`>%d $sql_extra
1610 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1611 intval($id), intval(api_user()),
1612 dbesc(ACTIVITY_POST),
1614 intval($start), intval($count)
1618 throw new BadRequestException("There is no conversation with this id.");
1620 $ret = api_format_items($r,$user_info);
1622 $data = array('$statuses' => $ret);
1623 return api_apply_template("timeline", $type, $data);
1625 api_register_func('api/conversation/show','api_conversation_show', true);
1626 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1632 function api_statuses_repeat(&$a, $type){
1635 if (api_user()===false) throw new ForbiddenException();
1637 $user_info = api_get_user($a);
1640 $id = intval($a->argv[3]);
1643 $id = intval($_REQUEST["id"]);
1647 $id = intval($a->argv[4]);
1649 logger('API: api_statuses_repeat: '.$id);
1651 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1652 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1653 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1654 `contact`.`id` AS `cid`
1655 FROM `item`, `contact`
1656 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1657 AND `contact`.`id` = `item`.`contact-id`
1658 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1659 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1660 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1662 AND `item`.`id`=%d",
1666 if ($r[0]['body'] != "") {
1667 if (!intval(get_config('system','old_share'))) {
1668 if (strpos($r[0]['body'], "[/share]") !== false) {
1669 $pos = strpos($r[0]['body'], "[share");
1670 $post = substr($r[0]['body'], $pos);
1672 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1674 $post .= $r[0]['body'];
1675 $post .= "[/share]";
1677 $_REQUEST['body'] = $post;
1679 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1681 $_REQUEST['profile_uid'] = api_user();
1682 $_REQUEST['type'] = 'wall';
1683 $_REQUEST['api_source'] = true;
1685 if (!x($_REQUEST, "source"))
1686 $_REQUEST["source"] = api_source();
1690 throw new ForbiddenException();
1692 // this should output the last post (the one we just posted).
1694 return(api_status_show($a,$type));
1696 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1701 function api_statuses_destroy(&$a, $type){
1702 if (api_user()===false) throw new ForbiddenException();
1704 $user_info = api_get_user($a);
1707 $id = intval($a->argv[3]);
1710 $id = intval($_REQUEST["id"]);
1714 $id = intval($a->argv[4]);
1716 logger('API: api_statuses_destroy: '.$id);
1718 $ret = api_statuses_show($a, $type);
1720 drop_item($id, false);
1724 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1728 * http://developer.twitter.com/doc/get/statuses/mentions
1731 function api_statuses_mentions(&$a, $type){
1732 if (api_user()===false) throw new ForbiddenException();
1734 unset($_REQUEST["user_id"]);
1735 unset($_GET["user_id"]);
1737 unset($_REQUEST["screen_name"]);
1738 unset($_GET["screen_name"]);
1740 $user_info = api_get_user($a);
1741 // get last newtork messages
1745 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1746 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1747 if ($page<0) $page=0;
1748 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1749 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1750 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1752 $start = $page*$count;
1754 // Ugly code - should be changed
1755 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1756 $myurl = substr($myurl,strpos($myurl,'://')+3);
1757 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1758 $myurl = str_replace('www.','',$myurl);
1759 $diasp_url = str_replace('/profile/','/u/',$myurl);
1762 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1764 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1765 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1766 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1767 `contact`.`id` AS `cid`
1768 FROM `item` FORCE INDEX (`uid_id`), `contact`
1769 WHERE `item`.`uid` = %d AND `verb` = '%s'
1770 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1771 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1772 AND `contact`.`id` = `item`.`contact-id`
1773 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1774 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1777 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1779 dbesc(ACTIVITY_POST),
1780 dbesc(protect_sprintf($myurl)),
1781 dbesc(protect_sprintf($myurl)),
1784 intval($start), intval($count)
1787 $ret = api_format_items($r,$user_info);
1790 $data = array('$statuses' => $ret);
1794 $data = api_rss_extra($a, $data, $user_info);
1797 $as = api_format_as($a, $ret, $user_info);
1798 $as["title"] = $a->config['sitename']." Mentions";
1799 $as['link']['url'] = $a->get_baseurl()."/";
1804 return api_apply_template("timeline", $type, $data);
1806 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1807 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1810 function api_statuses_user_timeline(&$a, $type){
1811 if (api_user()===false) throw new ForbiddenException();
1813 $user_info = api_get_user($a);
1814 // get last network messages
1816 logger("api_statuses_user_timeline: api_user: ". api_user() .
1817 "\nuser_info: ".print_r($user_info, true) .
1818 "\n_REQUEST: ".print_r($_REQUEST, true),
1822 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1823 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1824 if ($page<0) $page=0;
1825 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1826 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1827 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1828 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1830 $start = $page*$count;
1833 if ($user_info['self']==1)
1834 $sql_extra .= " AND `item`.`wall` = 1 ";
1836 if ($exclude_replies > 0)
1837 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1838 if ($conversation_id > 0)
1839 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1841 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1842 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1843 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1844 `contact`.`id` AS `cid`
1845 FROM `item`, `contact`
1846 WHERE `item`.`uid` = %d AND `verb` = '%s'
1847 AND `item`.`contact-id` = %d
1848 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1849 AND `contact`.`id` = `item`.`contact-id`
1850 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1853 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1855 dbesc(ACTIVITY_POST),
1856 intval($user_info['cid']),
1858 intval($start), intval($count)
1861 $ret = api_format_items($r,$user_info, true);
1863 $data = array('$statuses' => $ret);
1867 $data = api_rss_extra($a, $data, $user_info);
1870 return api_apply_template("timeline", $type, $data);
1872 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1876 * Star/unstar an item
1877 * param: id : id of the item
1879 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1881 function api_favorites_create_destroy(&$a, $type){
1882 if (api_user()===false) throw new ForbiddenException();
1884 // for versioned api.
1885 /// @TODO We need a better global soluton
1887 if ($a->argv[1]=="1.1") $action_argv_id=3;
1889 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1890 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1891 if ($a->argc==$action_argv_id+2) {
1892 $itemid = intval($a->argv[$action_argv_id+1]);
1894 $itemid = intval($_REQUEST['id']);
1897 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1898 $itemid, api_user());
1900 if ($item===false || count($item)==0)
1901 throw new BadRequestException("Invalid item.");
1905 $item[0]['starred']=1;
1908 $item[0]['starred']=0;
1911 throw new BadRequestException("Invalid action ".$action);
1913 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1914 $item[0]['starred'], $itemid, api_user());
1916 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1917 $item[0]['starred'], $itemid, api_user());
1920 throw InternalServerErrorException("DB error");
1923 $user_info = api_get_user($a);
1924 $rets = api_format_items($item,$user_info);
1927 $data = array('$status' => $ret);
1931 $data = api_rss_extra($a, $data, $user_info);
1934 return api_apply_template("status", $type, $data);
1936 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1937 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1939 function api_favorites(&$a, $type){
1942 if (api_user()===false) throw new ForbiddenException();
1944 $called_api= array();
1946 $user_info = api_get_user($a);
1948 // in friendica starred item are private
1949 // return favorites only for self
1950 logger('api_favorites: self:' . $user_info['self']);
1952 if ($user_info['self']==0) {
1958 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1959 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1960 $count = (x($_GET,'count')?$_GET['count']:20);
1961 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1962 if ($page<0) $page=0;
1964 $start = $page*$count;
1967 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1969 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1970 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1971 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1972 `contact`.`id` AS `cid`
1973 FROM `item`, `contact`
1974 WHERE `item`.`uid` = %d
1975 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1976 AND `item`.`starred` = 1
1977 AND `contact`.`id` = `item`.`contact-id`
1978 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1981 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1984 intval($start), intval($count)
1987 $ret = api_format_items($r,$user_info);
1991 $data = array('$statuses' => $ret);
1995 $data = api_rss_extra($a, $data, $user_info);
1998 return api_apply_template("timeline", $type, $data);
2000 api_register_func('api/favorites','api_favorites', true);
2005 function api_format_as($a, $ret, $user_info) {
2007 $as['title'] = $a->config['sitename']." Public Timeline";
2009 foreach ($ret as $item) {
2010 $singleitem["actor"]["displayName"] = $item["user"]["name"];
2011 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
2012 $avatar[0]["url"] = $item["user"]["profile_image_url"];
2013 $avatar[0]["rel"] = "avatar";
2014 $avatar[0]["type"] = "";
2015 $avatar[0]["width"] = 96;
2016 $avatar[0]["height"] = 96;
2017 $avatar[1]["url"] = $item["user"]["profile_image_url"];
2018 $avatar[1]["rel"] = "avatar";
2019 $avatar[1]["type"] = "";
2020 $avatar[1]["width"] = 48;
2021 $avatar[1]["height"] = 48;
2022 $avatar[2]["url"] = $item["user"]["profile_image_url"];
2023 $avatar[2]["rel"] = "avatar";
2024 $avatar[2]["type"] = "";
2025 $avatar[2]["width"] = 24;
2026 $avatar[2]["height"] = 24;
2027 $singleitem["actor"]["avatarLinks"] = $avatar;
2029 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
2030 $singleitem["actor"]["image"]["rel"] = "avatar";
2031 $singleitem["actor"]["image"]["type"] = "";
2032 $singleitem["actor"]["image"]["width"] = 96;
2033 $singleitem["actor"]["image"]["height"] = 96;
2034 $singleitem["actor"]["type"] = "person";
2035 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
2036 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
2037 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
2038 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
2039 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
2040 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
2041 $singleitem["actor"]["contact"]["addresses"] = "";
2043 $singleitem["body"] = $item["text"];
2044 $singleitem["object"]["displayName"] = $item["text"];
2045 $singleitem["object"]["id"] = $item["url"];
2046 $singleitem["object"]["type"] = "note";
2047 $singleitem["object"]["url"] = $item["url"];
2048 //$singleitem["context"] =;
2049 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
2050 $singleitem["provider"]["objectType"] = "service";
2051 $singleitem["provider"]["displayName"] = "Test";
2052 $singleitem["provider"]["url"] = "http://test.tld";
2053 $singleitem["title"] = $item["text"];
2054 $singleitem["verb"] = "post";
2055 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
2056 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
2057 $singleitem["statusnet:notice_info"]["favorite"] = "false";
2058 $singleitem["statusnet:notice_info"]["repeated"] = "false";
2059 //$singleitem["original"] = $item;
2060 $items[] = $singleitem;
2062 $as['items'] = $items;
2063 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
2064 $as['link']['rel'] = "alternate";
2065 $as['link']['type'] = "text/html";
2069 function api_format_messages($item, $recipient, $sender) {
2070 // standard meta information
2072 'id' => $item['id'],
2073 'sender_id' => $sender['id'] ,
2075 'recipient_id' => $recipient['id'],
2076 'created_at' => api_date($item['created']),
2077 'sender_screen_name' => $sender['screen_name'],
2078 'recipient_screen_name' => $recipient['screen_name'],
2079 'sender' => $sender,
2080 'recipient' => $recipient,
2083 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2084 unset($ret["sender"]["uid"]);
2085 unset($ret["sender"]["self"]);
2086 unset($ret["recipient"]["uid"]);
2087 unset($ret["recipient"]["self"]);
2089 //don't send title to regular StatusNET requests to avoid confusing these apps
2090 if (x($_GET, 'getText')) {
2091 $ret['title'] = $item['title'] ;
2092 if ($_GET["getText"] == "html") {
2093 $ret['text'] = bbcode($item['body'], false, false);
2095 elseif ($_GET["getText"] == "plain") {
2096 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2097 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2101 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2103 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2104 unset($ret['sender']);
2105 unset($ret['recipient']);
2111 function api_convert_item($item) {
2113 $body = $item['body'];
2114 $attachments = api_get_attachments($body);
2116 // Workaround for ostatus messages where the title is identically to the body
2117 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2118 $statusbody = trim(html2plain($html, 0));
2120 // handle data: images
2121 $statusbody = api_format_items_embeded_images($item,$statusbody);
2123 $statustitle = trim($item['title']);
2125 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2126 $statustext = trim($statusbody);
2128 $statustext = trim($statustitle."\n\n".$statusbody);
2130 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2131 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2133 $statushtml = trim(bbcode($body, false, false));
2135 $search = array("<br>", "<blockquote>", "</blockquote>",
2136 "<h1>", "</h1>", "<h2>", "</h2>",
2137 "<h3>", "</h3>", "<h4>", "</h4>",
2138 "<h5>", "</h5>", "<h6>", "</h6>");
2139 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2140 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2141 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2142 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2143 $statushtml = str_replace($search, $replace, $statushtml);
2145 if ($item['title'] != "")
2146 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2148 $entities = api_get_entitities($statustext, $body);
2150 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2153 function api_get_attachments(&$body) {
2156 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2158 $URLSearchString = "^\[\]";
2159 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2164 $attachments = array();
2166 foreach ($images[1] AS $image) {
2167 $imagedata = get_photo_info($image);
2170 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2173 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2174 foreach ($images[0] AS $orig)
2175 $body = str_replace($orig, "", $body);
2177 return $attachments;
2180 function api_get_entitities(&$text, $bbcode) {
2183 * Links at the first character of the post
2188 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2190 if ($include_entities != "true") {
2192 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2194 foreach ($images[1] AS $image) {
2195 $replace = proxy_url($image);
2196 $text = str_replace($image, $replace, $text);
2201 $bbcode = bb_CleanPictureLinks($bbcode);
2203 // Change pure links in text to bbcode uris
2204 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2206 $entities = array();
2207 $entities["hashtags"] = array();
2208 $entities["symbols"] = array();
2209 $entities["urls"] = array();
2210 $entities["user_mentions"] = array();
2212 $URLSearchString = "^\[\]";
2214 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2216 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2217 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2218 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2220 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2221 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2222 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2224 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2225 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2226 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2228 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2230 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2231 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2233 $ordered_urls = array();
2234 foreach ($urls[1] AS $id=>$url) {
2235 //$start = strpos($text, $url, $offset);
2236 $start = iconv_strpos($text, $url, 0, "UTF-8");
2237 if (!($start === false))
2238 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2241 ksort($ordered_urls);
2244 //foreach ($urls[1] AS $id=>$url) {
2245 foreach ($ordered_urls AS $url) {
2246 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2247 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2248 $display_url = $url["title"];
2250 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2251 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2253 if (strlen($display_url) > 26)
2254 $display_url = substr($display_url, 0, 25)."…";
2257 //$start = strpos($text, $url, $offset);
2258 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2259 if (!($start === false)) {
2260 $entities["urls"][] = array("url" => $url["url"],
2261 "expanded_url" => $url["url"],
2262 "display_url" => $display_url,
2263 "indices" => array($start, $start+strlen($url["url"])));
2264 $offset = $start + 1;
2268 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2269 $ordered_images = array();
2270 foreach ($images[1] AS $image) {
2271 //$start = strpos($text, $url, $offset);
2272 $start = iconv_strpos($text, $image, 0, "UTF-8");
2273 if (!($start === false))
2274 $ordered_images[$start] = $image;
2276 //$entities["media"] = array();
2279 foreach ($ordered_images AS $url) {
2280 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2281 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2283 if (strlen($display_url) > 26)
2284 $display_url = substr($display_url, 0, 25)."…";
2286 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2287 if (!($start === false)) {
2288 $image = get_photo_info($url);
2290 // If image cache is activated, then use the following sizes:
2291 // thumb (150), small (340), medium (600) and large (1024)
2292 if (!get_config("system", "proxy_disabled")) {
2293 $media_url = proxy_url($url);
2296 $scale = scale_image($image[0], $image[1], 150);
2297 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2299 if (($image[0] > 150) OR ($image[1] > 150)) {
2300 $scale = scale_image($image[0], $image[1], 340);
2301 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2304 $scale = scale_image($image[0], $image[1], 600);
2305 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2307 if (($image[0] > 600) OR ($image[1] > 600)) {
2308 $scale = scale_image($image[0], $image[1], 1024);
2309 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2313 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2316 $entities["media"][] = array(
2318 "id_str" => (string)$start+1,
2319 "indices" => array($start, $start+strlen($url)),
2320 "media_url" => normalise_link($media_url),
2321 "media_url_https" => $media_url,
2323 "display_url" => $display_url,
2324 "expanded_url" => $url,
2328 $offset = $start + 1;
2334 function api_format_items_embeded_images(&$item, $text){
2336 $text = preg_replace_callback(
2337 "|data:image/([^;]+)[^=]+=*|m",
2338 function($match) use ($a, $item) {
2339 return $a->get_baseurl()."/display/".$item['guid'];
2346 * @brief return likes, dislikes and attend status for item
2348 * @param array $item
2350 * likes => int count
2351 * dislikes => int count
2353 function api_format_items_likes(&$item) {
2354 $activities = array(
2356 'dislike' => array(),
2357 'attendyes' => array(),
2358 'attendno' => array(),
2359 'attendmaybe' => array()
2361 $items = q('SELECT * FROM item
2362 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2363 intval($item['uid']),
2364 dbesc($item['uri']));
2365 foreach ($items as $i){
2366 builtin_activity_puller($i, $activities);
2370 $uri = $item['uri'];
2371 foreach($activities as $k => $v) {
2372 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2379 * @brief format items to be returned by api
2381 * @param array $r array of items
2382 * @param array $user_info
2383 * @param bool $filter_user filter items by $user_info
2385 function api_format_items($r,$user_info, $filter_user = false) {
2390 foreach($r as $item) {
2391 api_share_as_retweet($item);
2393 localize_item($item);
2394 $status_user = api_item_get_user($a,$item);
2396 // Look if the posts are matching if they should be filtered by user id
2397 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2400 if ($item['thr-parent'] != $item['uri']) {
2401 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2403 dbesc($item['thr-parent']));
2405 $in_reply_to_status_id = intval($r[0]['id']);
2407 $in_reply_to_status_id = intval($item['parent']);
2409 $in_reply_to_status_id_str = (string) intval($item['parent']);
2411 $in_reply_to_screen_name = NULL;
2412 $in_reply_to_user_id = NULL;
2413 $in_reply_to_user_id_str = NULL;
2415 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2417 intval($in_reply_to_status_id));
2419 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2422 if ($r[0]['nick'] == "")
2423 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2425 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2426 $in_reply_to_user_id = intval($r[0]['id']);
2427 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2431 $in_reply_to_screen_name = NULL;
2432 $in_reply_to_user_id = NULL;
2433 $in_reply_to_status_id = NULL;
2434 $in_reply_to_user_id_str = NULL;
2435 $in_reply_to_status_id_str = NULL;
2438 $converted = api_convert_item($item);
2441 'text' => $converted["text"],
2442 'truncated' => False,
2443 'created_at'=> api_date($item['created']),
2444 'in_reply_to_status_id' => $in_reply_to_status_id,
2445 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2446 'source' => (($item['app']) ? $item['app'] : 'web'),
2447 'id' => intval($item['id']),
2448 'id_str' => (string) intval($item['id']),
2449 'in_reply_to_user_id' => $in_reply_to_user_id,
2450 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2451 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2453 'favorited' => $item['starred'] ? true : false,
2454 'user' => $status_user ,
2455 //'entities' => NULL,
2456 'statusnet_html' => $converted["html"],
2457 'statusnet_conversation_id' => $item['parent'],
2458 'friendica_activities' => api_format_items_likes($item),
2461 if (count($converted["attachments"]) > 0)
2462 $status["attachments"] = $converted["attachments"];
2464 if (count($converted["entities"]) > 0)
2465 $status["entities"] = $converted["entities"];
2467 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2468 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2469 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2470 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2473 // Retweets are only valid for top postings
2474 // It doesn't work reliable with the link if its a feed
2475 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2477 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2479 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2480 $retweeted_status = $status;
2481 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2483 $status["retweeted_status"] = $retweeted_status;
2486 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2487 unset($status["user"]["uid"]);
2488 unset($status["user"]["self"]);
2490 if ($item["coord"] != "") {
2491 $coords = explode(' ',$item["coord"]);
2492 if (count($coords) == 2) {
2493 $status["geo"] = array('type' => 'Point',
2494 'coordinates' => array((float) $coords[0],
2495 (float) $coords[1]));
2505 function api_account_rate_limit_status(&$a,$type) {
2507 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2508 'remaining_hits' => (string) 150,
2509 'hourly_limit' => (string) 150,
2510 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2513 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2515 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2517 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2519 function api_help_test(&$a,$type) {
2525 return api_apply_template('test', $type, array("$ok" => $ok));
2527 api_register_func('api/help/test','api_help_test',false);
2529 function api_lists(&$a,$type) {
2533 api_register_func('api/lists','api_lists',true);
2535 function api_lists_list(&$a,$type) {
2539 api_register_func('api/lists/list','api_lists_list',true);
2542 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2543 * This function is deprecated by Twitter
2544 * returns: json, xml
2546 function api_statuses_f(&$a, $type, $qtype) {
2547 if (api_user()===false) throw new ForbiddenException();
2548 $user_info = api_get_user($a);
2550 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2551 /* this is to stop Hotot to load friends multiple times
2552 * I'm not sure if I'm missing return something or
2553 * is a bug in hotot. Workaround, meantime
2557 return array('$users' => $ret);*/
2561 if($qtype == 'friends')
2562 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2563 if($qtype == 'followers')
2564 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2566 // friends and followers only for self
2567 if ($user_info['self'] == 0)
2568 $sql_extra = " AND false ";
2570 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2575 foreach($r as $cid){
2576 $user = api_get_user($a, $cid['nurl']);
2577 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2578 unset($user["uid"]);
2579 unset($user["self"]);
2585 return array('$users' => $ret);
2588 function api_statuses_friends(&$a, $type){
2589 $data = api_statuses_f($a,$type,"friends");
2590 if ($data===false) return false;
2591 return api_apply_template("friends", $type, $data);
2593 function api_statuses_followers(&$a, $type){
2594 $data = api_statuses_f($a,$type,"followers");
2595 if ($data===false) return false;
2596 return api_apply_template("friends", $type, $data);
2598 api_register_func('api/statuses/friends','api_statuses_friends',true);
2599 api_register_func('api/statuses/followers','api_statuses_followers',true);
2606 function api_statusnet_config(&$a,$type) {
2607 $name = $a->config['sitename'];
2608 $server = $a->get_hostname();
2609 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2610 $email = $a->config['admin_email'];
2611 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2612 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2613 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2614 if($a->config['api_import_size'])
2615 $texlimit = string($a->config['api_import_size']);
2616 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2617 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2620 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2621 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2622 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2623 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2624 'shorturllength' => '30',
2625 'friendica' => array(
2626 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2627 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2628 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2629 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2634 return api_apply_template('config', $type, array('$config' => $config));
2637 api_register_func('api/statusnet/config','api_statusnet_config',false);
2639 function api_statusnet_version(&$a,$type) {
2641 $fake_statusnet_version = "0.9.7";
2643 if($type === 'xml') {
2644 header("Content-type: application/xml");
2645 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2648 elseif($type === 'json') {
2649 header("Content-type: application/json");
2650 echo '"'.$fake_statusnet_version.'"';
2654 api_register_func('api/statusnet/version','api_statusnet_version',false);
2657 * @todo use api_apply_template() to return data
2659 function api_ff_ids(&$a,$type,$qtype) {
2660 if(! api_user()) throw new ForbiddenException();
2662 $user_info = api_get_user($a);
2664 if($qtype == 'friends')
2665 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2666 if($qtype == 'followers')
2667 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2669 if (!$user_info["self"])
2670 $sql_extra = " AND false ";
2672 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2674 $r = q("SELECT `gcontact`.`id` FROM `contact`, `gcontact` WHERE `contact`.`nurl` = `gcontact`.`nurl` AND `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` $sql_extra",
2680 if($type === 'xml') {
2681 header("Content-type: application/xml");
2682 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2684 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2685 echo '</ids>' . "\r\n";
2688 elseif($type === 'json') {
2690 header("Content-type: application/json");
2695 $ret[] = intval($rr['id']);
2697 echo json_encode($ret);
2703 function api_friends_ids(&$a,$type) {
2704 api_ff_ids($a,$type,'friends');
2706 function api_followers_ids(&$a,$type) {
2707 api_ff_ids($a,$type,'followers');
2709 api_register_func('api/friends/ids','api_friends_ids',true);
2710 api_register_func('api/followers/ids','api_followers_ids',true);
2713 function api_direct_messages_new(&$a, $type) {
2714 if (api_user()===false) throw new ForbiddenException();
2716 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2718 $sender = api_get_user($a);
2720 if ($_POST['screen_name']) {
2721 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2723 dbesc($_POST['screen_name']));
2725 // Selecting the id by priority, friendica first
2726 api_best_nickname($r);
2728 $recipient = api_get_user($a, $r[0]['nurl']);
2730 $recipient = api_get_user($a, $_POST['user_id']);
2734 if (x($_REQUEST,'replyto')) {
2735 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2737 intval($_REQUEST['replyto']));
2738 $replyto = $r[0]['parent-uri'];
2739 $sub = $r[0]['title'];
2742 if (x($_REQUEST,'title')) {
2743 $sub = $_REQUEST['title'];
2746 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2750 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2753 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2754 $ret = api_format_messages($r[0], $recipient, $sender);
2757 $ret = array("error"=>$id);
2760 $data = Array('$messages'=>$ret);
2765 $data = api_rss_extra($a, $data, $user_info);
2768 return api_apply_template("direct_messages", $type, $data);
2771 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2773 function api_direct_messages_box(&$a, $type, $box) {
2774 if (api_user()===false) throw new ForbiddenException();
2777 $count = (x($_GET,'count')?$_GET['count']:20);
2778 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2779 if ($page<0) $page=0;
2781 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2782 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2784 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2785 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2788 unset($_REQUEST["user_id"]);
2789 unset($_GET["user_id"]);
2791 unset($_REQUEST["screen_name"]);
2792 unset($_GET["screen_name"]);
2794 $user_info = api_get_user($a);
2795 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2796 $profile_url = $user_info["url"];
2800 $start = $page*$count;
2803 if ($box=="sentbox") {
2804 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2806 elseif ($box=="conversation") {
2807 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2809 elseif ($box=="all") {
2810 $sql_extra = "true";
2812 elseif ($box=="inbox") {
2813 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2817 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2819 if ($user_id !="") {
2820 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2822 elseif($screen_name !=""){
2823 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2826 $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",
2829 intval($start), intval($count)
2834 foreach($r as $item) {
2835 if ($box == "inbox" || $item['from-url'] != $profile_url){
2836 $recipient = $user_info;
2837 $sender = api_get_user($a,normalise_link($item['contact-url']));
2839 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2840 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2841 $sender = $user_info;
2844 $ret[]=api_format_messages($item, $recipient, $sender);
2848 $data = array('$messages' => $ret);
2852 $data = api_rss_extra($a, $data, $user_info);
2855 return api_apply_template("direct_messages", $type, $data);
2859 function api_direct_messages_sentbox(&$a, $type){
2860 return api_direct_messages_box($a, $type, "sentbox");
2862 function api_direct_messages_inbox(&$a, $type){
2863 return api_direct_messages_box($a, $type, "inbox");
2865 function api_direct_messages_all(&$a, $type){
2866 return api_direct_messages_box($a, $type, "all");
2868 function api_direct_messages_conversation(&$a, $type){
2869 return api_direct_messages_box($a, $type, "conversation");
2871 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2872 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2873 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2874 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2878 function api_oauth_request_token(&$a, $type){
2880 $oauth = new FKOAuth1();
2881 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2882 }catch(Exception $e){
2883 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2888 function api_oauth_access_token(&$a, $type){
2890 $oauth = new FKOAuth1();
2891 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2892 }catch(Exception $e){
2893 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2899 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2900 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2903 function api_fr_photos_list(&$a,$type) {
2904 if (api_user()===false) throw new ForbiddenException();
2905 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2906 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2907 intval(local_user())
2910 'image/jpeg' => 'jpg',
2911 'image/png' => 'png',
2912 'image/gif' => 'gif'
2914 $data = array('photos'=>array());
2916 foreach($r as $rr) {
2918 $photo['id'] = $rr['resource-id'];
2919 $photo['album'] = $rr['album'];
2920 $photo['filename'] = $rr['filename'];
2921 $photo['type'] = $rr['type'];
2922 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2923 $data['photos'][] = $photo;
2926 return api_apply_template("photos_list", $type, $data);
2929 function api_fr_photo_detail(&$a,$type) {
2930 if (api_user()===false) throw new ForbiddenException();
2931 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2933 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2934 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2935 $data_sql = ($scale === false ? "" : "data, ");
2937 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2938 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2939 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2941 intval(local_user()),
2942 dbesc($_REQUEST['photo_id']),
2947 'image/jpeg' => 'jpg',
2948 'image/png' => 'png',
2949 'image/gif' => 'gif'
2953 $data = array('photo' => $r[0]);
2954 if ($scale !== false) {
2955 $data['photo']['data'] = base64_encode($data['photo']['data']);
2957 unset($data['photo']['datasize']); //needed only with scale param
2959 $data['photo']['link'] = array();
2960 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2961 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2963 $data['photo']['id'] = $data['photo']['resource-id'];
2964 unset($data['photo']['resource-id']);
2965 unset($data['photo']['minscale']);
2966 unset($data['photo']['maxscale']);
2969 throw new NotFoundException();
2972 return api_apply_template("photo_detail", $type, $data);
2975 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2976 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2981 * similar as /mod/redir.php
2982 * redirect to 'url' after dfrn auth
2984 * why this when there is mod/redir.php already?
2985 * This use api_user() and api_login()
2988 * c_url: url of remote contact to auth to
2989 * url: string, url to redirect after auth
2991 function api_friendica_remoteauth(&$a) {
2992 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2993 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2995 if ($url === '' || $c_url === '')
2996 throw new BadRequestException("Wrong parameters.");
2998 $c_url = normalise_link($c_url);
3002 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3007 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
3008 throw new BadRequestException("Unknown contact");
3012 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3014 if($r[0]['duplex'] && $r[0]['issued-id']) {
3015 $orig_id = $r[0]['issued-id'];
3016 $dfrn_id = '1:' . $orig_id;
3018 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3019 $orig_id = $r[0]['dfrn-id'];
3020 $dfrn_id = '0:' . $orig_id;
3023 $sec = random_string();
3025 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3026 VALUES( %d, %s, '%s', '%s', %d )",
3034 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3035 $dest = (($url) ? '&destination_url=' . $url : '');
3036 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3037 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3038 . '&type=profile&sec=' . $sec . $dest . $quiet );
3040 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3043 function api_share_as_retweet(&$item) {
3044 $body = trim($item["body"]);
3046 // Skip if it isn't a pure repeated messages
3047 // Does it start with a share?
3048 if (strpos($body, "[share") > 0)
3051 // Does it end with a share?
3052 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3055 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3056 // Skip if there is no shared message in there
3057 if ($body == $attributes)
3061 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3062 if ($matches[1] != "")
3063 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3065 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3066 if ($matches[1] != "")
3067 $author = $matches[1];
3070 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3071 if ($matches[1] != "")
3072 $profile = $matches[1];
3074 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3075 if ($matches[1] != "")
3076 $profile = $matches[1];
3079 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3080 if ($matches[1] != "")
3081 $avatar = $matches[1];
3083 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3084 if ($matches[1] != "")
3085 $avatar = $matches[1];
3088 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3089 if ($matches[1] != "")
3090 $link = $matches[1];
3092 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3093 if ($matches[1] != "")
3094 $link = $matches[1];
3096 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3098 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
3101 $item["body"] = $shared_body;
3102 $item["author-name"] = $author;
3103 $item["author-link"] = $profile;
3104 $item["author-avatar"] = $avatar;
3105 $item["plink"] = $link;
3111 function api_get_nick($profile) {
3113 - remove trailing junk from profile url
3114 - pump.io check has to check the website
3119 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3120 dbesc(normalise_link($profile)));
3122 $nick = $r[0]["nick"];
3125 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3126 dbesc(normalise_link($profile)));
3128 $nick = $r[0]["nick"];
3132 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3133 if ($friendica != $profile)
3138 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3139 if ($diaspora != $profile)
3144 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3145 if ($twitter != $profile)
3151 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3152 if ($StatusnetHost != $profile) {
3153 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3154 if ($StatusnetUser != $profile) {
3155 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3156 $user = json_decode($UserData);
3158 $nick = $user->screen_name;
3163 // To-Do: look at the page if its really a pumpio site
3164 //if (!$nick == "") {
3165 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3166 // if ($pumpio != $profile)
3168 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3178 function api_clean_plain_items($Text) {
3179 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3181 $Text = bb_CleanPictureLinks($Text);
3183 $URLSearchString = "^\[\]";
3185 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3187 if ($include_entities == "true") {
3188 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3191 // Simplify "attachment" element
3192 $Text = api_clean_attachments($Text);
3198 * @brief Removes most sharing information for API text export
3200 * @param string $body The original body
3202 * @return string Cleaned body
3204 function api_clean_attachments($body) {
3205 $data = get_attachment_data($body);
3212 if (isset($data["text"]))
3213 $body = $data["text"];
3215 if (($body == "") AND (isset($data["title"])))
3216 $body = $data["title"];
3218 if (isset($data["url"]))
3219 $body .= "\n".$data["url"];
3224 function api_best_nickname(&$contacts) {
3225 $best_contact = array();
3227 if (count($contact) == 0)
3230 foreach ($contacts AS $contact)
3231 if ($contact["network"] == "") {
3232 $contact["network"] = "dfrn";
3233 $best_contact = array($contact);
3236 if (sizeof($best_contact) == 0)
3237 foreach ($contacts AS $contact)
3238 if ($contact["network"] == "dfrn")
3239 $best_contact = array($contact);
3241 if (sizeof($best_contact) == 0)
3242 foreach ($contacts AS $contact)
3243 if ($contact["network"] == "dspr")
3244 $best_contact = array($contact);
3246 if (sizeof($best_contact) == 0)
3247 foreach ($contacts AS $contact)
3248 if ($contact["network"] == "stat")
3249 $best_contact = array($contact);
3251 if (sizeof($best_contact) == 0)
3252 foreach ($contacts AS $contact)
3253 if ($contact["network"] == "pump")
3254 $best_contact = array($contact);
3256 if (sizeof($best_contact) == 0)
3257 foreach ($contacts AS $contact)
3258 if ($contact["network"] == "twit")
3259 $best_contact = array($contact);
3261 if (sizeof($best_contact) == 1)
3262 $contacts = $best_contact;
3264 $contacts = array($contacts[0]);
3267 // return all or a specified group of the user with the containing contacts
3268 function api_friendica_group_show(&$a, $type) {
3269 if (api_user()===false) throw new ForbiddenException();
3272 $user_info = api_get_user($a);
3273 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3274 $uid = $user_info['uid'];
3276 // get data of the specified group id or all groups if not specified
3278 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3281 // error message if specified gid is not in database
3283 throw new BadRequestException("gid not available");
3286 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3289 // loop through all groups and retrieve all members for adding data in the user array
3290 foreach ($r as $rr) {
3291 $members = group_get_members($rr['id']);
3293 foreach ($members as $member) {
3294 $user = api_get_user($a, $member['nurl']);
3297 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3299 return api_apply_template("group_show", $type, array('$groups' => $grps));
3301 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3304 // delete the specified group of the user
3305 function api_friendica_group_delete(&$a, $type) {
3306 if (api_user()===false) throw new ForbiddenException();
3309 $user_info = api_get_user($a);
3310 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3311 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3312 $uid = $user_info['uid'];
3314 // error if no gid specified
3315 if ($gid == 0 || $name == "")
3316 throw new BadRequestException('gid or name not specified');
3318 // get data of the specified group id
3319 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3322 // error message if specified gid is not in database
3324 throw new BadRequestException('gid not available');
3326 // get data of the specified group id and group name
3327 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3331 // error message if specified gid is not in database
3332 if (count($rname) == 0)
3333 throw new BadRequestException('wrong group name');
3336 $ret = group_rmv($uid, $name);
3339 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3340 return api_apply_template("group_delete", $type, array('$result' => $success));
3343 throw new BadRequestException('other API error');
3345 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3348 // create the specified group with the posted array of contacts
3349 function api_friendica_group_create(&$a, $type) {
3350 if (api_user()===false) throw new ForbiddenException();
3353 $user_info = api_get_user($a);
3354 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3355 $uid = $user_info['uid'];
3356 $json = json_decode($_POST['json'], true);
3357 $users = $json['user'];
3359 // error if no name specified
3361 throw new BadRequestException('group name not specified');
3363 // get data of the specified group name
3364 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3367 // error message if specified group name already exists
3368 if (count($rname) != 0)
3369 throw new BadRequestException('group name already exists');
3371 // check if specified group name is a deleted group
3372 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3375 // error message if specified group name already exists
3376 if (count($rname) != 0)
3377 $reactivate_group = true;
3380 $ret = group_add($uid, $name);
3382 $gid = group_byname($uid, $name);
3384 throw new BadRequestException('other API error');
3387 $erroraddinguser = false;
3388 $errorusers = array();
3389 foreach ($users as $user) {
3390 $cid = $user['cid'];
3391 // check if user really exists as contact
3392 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3395 if (count($contact))
3396 $result = group_add_member($uid, $name, $cid, $gid);
3398 $erroraddinguser = true;
3399 $errorusers[] = $cid;
3403 // return success message incl. missing users in array
3404 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3405 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3406 return api_apply_template("group_create", $type, array('result' => $success));
3408 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3411 // update the specified group with the posted array of contacts
3412 function api_friendica_group_update(&$a, $type) {
3413 if (api_user()===false) throw new ForbiddenException();
3416 $user_info = api_get_user($a);
3417 $uid = $user_info['uid'];
3418 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3419 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3420 $json = json_decode($_POST['json'], true);
3421 $users = $json['user'];
3423 // error if no name specified
3425 throw new BadRequestException('group name not specified');
3427 // error if no gid specified
3429 throw new BadRequestException('gid not specified');
3432 $members = group_get_members($gid);
3433 foreach ($members as $member) {
3434 $cid = $member['id'];
3435 foreach ($users as $user) {
3436 $found = ($user['cid'] == $cid ? true : false);
3439 $ret = group_rmv_member($uid, $name, $cid);
3444 $erroraddinguser = false;
3445 $errorusers = array();
3446 foreach ($users as $user) {
3447 $cid = $user['cid'];
3448 // check if user really exists as contact
3449 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3452 if (count($contact))
3453 $result = group_add_member($uid, $name, $cid, $gid);
3455 $erroraddinguser = true;
3456 $errorusers[] = $cid;
3460 // return success message incl. missing users in array
3461 $status = ($erroraddinguser ? "missing user" : "ok");
3462 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3463 return api_apply_template("group_update", $type, array('result' => $success));
3465 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3468 function api_friendica_activity(&$a, $type) {
3469 if (api_user()===false) throw new ForbiddenException();
3470 $verb = strtolower($a->argv[3]);
3471 $verb = preg_replace("|\..*$|", "", $verb);
3473 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3475 $res = do_like($id, $verb);
3482 return api_apply_template('test', $type, array('ok' => $ok));
3484 throw new BadRequestException('Error adding activity');
3488 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3489 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3490 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3491 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3492 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3493 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3494 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3495 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3496 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3497 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3500 * @brief Returns notifications
3503 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3506 function api_friendica_notification(&$a, $type) {
3507 if (api_user()===false) throw new ForbiddenException();
3508 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3509 $nm = new NotificationsManager();
3511 $notes = $nm->getAll(array(), "+seen -date", 50);
3512 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3516 * @brief Set notification as seen and returns associated item (if possible)
3518 * POST request with 'id' param as notification id
3521 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3524 function api_friendica_notification_seen(&$a, $type){
3525 if (api_user()===false) throw new ForbiddenException();
3526 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3528 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3530 $nm = new NotificationsManager();
3531 $note = $nm->getByID($id);
3532 if (is_null($note)) throw new BadRequestException("Invalid argument");
3534 $nm->setSeen($note);
3535 if ($note['otype']=='item') {
3536 // would be really better with an ItemsManager and $im->getByID() :-P
3537 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3538 intval($note['iid']),
3539 intval(local_user())
3542 // we found the item, return it to the user
3543 $user_info = api_get_user($a);
3544 $ret = api_format_items($r,$user_info);
3545 $data = array('$statuses' => $ret);
3546 return api_apply_template("timeline", $type, $data);
3548 // the item can't be found, but we set the note as seen, so we count this as a success
3550 return api_apply_template('<auto>', $type, array('status' => "success"));
3553 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3554 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3559 [pagename] => api/1.1/statuses/lookup.json
3560 [id] => 605138389168451584
3561 [include_cards] => true
3562 [cards_platform] => Android-12
3563 [include_entities] => true
3564 [include_my_retweet] => 1
3566 [include_reply_count] => true
3567 [include_descendent_reply_count] => true
3571 Not implemented by now:
3572 statuses/retweets_of_me
3577 account/update_location
3578 account/update_profile_background_image
3579 account/update_profile_image
3583 Not implemented in status.net:
3584 statuses/retweeted_to_me
3585 statuses/retweeted_by_me
3586 direct_messages/destroy
3588 account/update_delivery_device
3589 notifications/follow