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";
261 foreach ($API as $p=>$info){
262 if (strpos($a->query_string, $p)===0){
263 if (!api_check_method($info['method'])){
264 throw new MethodNotAllowedException();
267 $called_api= explode("/",$p);
268 //unset($_SERVER['PHP_AUTH_USER']);
269 if ($info['auth']===true && api_user()===false) {
273 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
274 logger('API parameters: ' . print_r($_REQUEST,true));
276 $stamp = microtime(true);
277 $r = call_user_func($info['func'], $a, $type);
278 $duration = (float)(microtime(true)-$stamp);
279 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
282 // api function returned false withour throw an
283 // exception. This should not happend, throw a 500
284 throw new InternalServerErrorException();
289 header ("Content-Type: text/xml");
291 if (substr($r, 0, 5) == "<?xml")
294 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
295 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
298 header ("Content-Type: application/json");
300 $json = json_encode($rr);
301 if ($_GET['callback'])
302 $json = $_GET['callback']."(".$json.")";
306 header ("Content-Type: application/rss+xml");
307 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
310 header ("Content-Type: application/atom+xml");
311 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
317 throw new NotImplementedException();
318 } catch (HTTPException $e) {
319 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
320 return api_error($a, $type, $e);
325 * @brief Format API error string
328 * @param string $type Return type (xml, json, rss, as)
329 * @param HTTPException $error Error object
330 * @return strin error message formatted as $type
332 function api_error(&$a, $type, $e) {
333 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
334 # TODO: https://dev.twitter.com/overview/api/response-codes
335 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
338 header ("Content-Type: text/xml");
339 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
342 header ("Content-Type: application/json");
343 return json_encode(array(
345 'request' => $a->query_string,
346 'code' => $e->httpcode." ".$e->httpdesc
350 header ("Content-Type: application/rss+xml");
351 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
354 header ("Content-Type: application/atom+xml");
355 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
361 * @brief Set values for RSS template
364 * @param array $arr Array to be passed to template
365 * @param array $user_info
368 function api_rss_extra(&$a, $arr, $user_info){
369 if (is_null($user_info)) $user_info = api_get_user($a);
370 $arr['$user'] = $user_info;
371 $arr['$rss'] = array(
372 'alternate' => $user_info['url'],
373 'self' => $a->get_baseurl(). "/". $a->query_string,
374 'base' => $a->get_baseurl(),
375 'updated' => api_date(null),
376 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
377 'language' => $user_info['language'],
378 'logo' => $a->get_baseurl()."/images/friendica-32.png",
386 * @brief Unique contact to contact url.
388 * @param int $id Contact id
389 * @return bool|string
390 * Contact url or False if contact id is unknown
392 function api_unique_id_to_url($id){
393 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
396 return ($r[0]["url"]);
402 * @brief Get user info array.
405 * @param int|string $contact_id Contact ID or URL
406 * @param string $type Return type (for errors)
408 function api_get_user(&$a, $contact_id = Null, $type = "json"){
415 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
417 // Searching for contact URL
418 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
419 $user = dbesc(normalise_link($contact_id));
421 $extra_query = "AND `contact`.`nurl` = '%s' ";
422 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
425 // Searching for unique contact id
426 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
427 $user = dbesc(api_unique_id_to_url($contact_id));
430 throw new BadRequestException("User not found.");
433 $extra_query = "AND `contact`.`nurl` = '%s' ";
434 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
437 if(is_null($user) && x($_GET, 'user_id')) {
438 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
441 throw new BadRequestException("User not found.");
444 $extra_query = "AND `contact`.`nurl` = '%s' ";
445 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
447 if(is_null($user) && x($_GET, 'screen_name')) {
448 $user = dbesc($_GET['screen_name']);
450 $extra_query = "AND `contact`.`nick` = '%s' ";
451 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
454 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
455 $argid = count($called_api);
456 list($user, $null) = explode(".",$a->argv[$argid]);
457 if(is_numeric($user)){
458 $user = dbesc(api_unique_id_to_url($user));
464 $extra_query = "AND `contact`.`nurl` = '%s' ";
465 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
467 $user = dbesc($user);
469 $extra_query = "AND `contact`.`nick` = '%s' ";
470 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
474 logger("api_get_user: user ".$user, LOGGER_DEBUG);
477 if (api_user()===false) {
481 $user = $_SESSION['uid'];
482 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
487 logger('api_user: ' . $extra_query . ', user: ' . $user);
489 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
495 // Selecting the id by priority, friendica first
496 api_best_nickname($uinfo);
498 // if the contact wasn't found, fetch it from the unique contacts
499 if (count($uinfo)==0) {
503 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
506 // If no nick where given, extract it from the address
507 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
508 $r[0]['nick'] = api_get_nick($r[0]["url"]);
512 'id_str' => (string) $r[0]["id"],
513 'name' => $r[0]["name"],
514 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
515 'location' => $r[0]["location"],
516 'description' => $r[0]["about"],
517 'url' => $r[0]["url"],
518 'protected' => false,
519 'followers_count' => 0,
520 'friends_count' => 0,
522 'created_at' => api_date($r[0]["created"]),
523 'favourites_count' => 0,
525 'time_zone' => 'UTC',
526 'geo_enabled' => false,
528 'statuses_count' => 0,
530 'contributors_enabled' => false,
531 'is_translator' => false,
532 'is_translation_enabled' => false,
533 'profile_image_url' => $r[0]["photo"],
534 'profile_image_url_https' => $r[0]["photo"],
535 'following' => false,
536 'follow_request_sent' => false,
537 'notifications' => false,
538 'statusnet_blocking' => false,
539 'notifications' => false,
540 'statusnet_profile_url' => $r[0]["url"],
544 'network' => $r[0]["network"],
549 throw new BadRequestException("User not found.");
553 if($uinfo[0]['self']) {
554 $usr = q("select * from user where uid = %d limit 1",
557 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
561 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
562 // count public wall messages
563 $r = q("SELECT count(*) as `count` FROM `item`
566 intval($uinfo[0]['uid'])
568 $countitms = $r[0]['count'];
571 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
572 $r = q("SELECT count(*) as `count` FROM `item`
573 WHERE `contact-id` = %d",
574 intval($uinfo[0]['id'])
576 $countitms = $r[0]['count'];
580 $r = q("SELECT count(*) as `count` FROM `contact`
581 WHERE `uid` = %d AND `rel` IN ( %d, %d )
582 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
583 intval($uinfo[0]['uid']),
584 intval(CONTACT_IS_SHARING),
585 intval(CONTACT_IS_FRIEND)
587 $countfriends = $r[0]['count'];
589 $r = q("SELECT count(*) as `count` FROM `contact`
590 WHERE `uid` = %d AND `rel` IN ( %d, %d )
591 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
592 intval($uinfo[0]['uid']),
593 intval(CONTACT_IS_FOLLOWER),
594 intval(CONTACT_IS_FRIEND)
596 $countfollowers = $r[0]['count'];
598 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
599 intval($uinfo[0]['uid'])
601 $starred = $r[0]['count'];
604 if(! $uinfo[0]['self']) {
610 // Add a nick if it isn't present there
611 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
612 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
615 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
617 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
618 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
621 'id' => intval($gcontact_id),
622 'id_str' => (string) intval($gcontact_id),
623 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
624 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
625 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
626 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
627 'profile_image_url' => $uinfo[0]['micro'],
628 'profile_image_url_https' => $uinfo[0]['micro'],
629 'url' => $uinfo[0]['url'],
630 'protected' => false,
631 'followers_count' => intval($countfollowers),
632 'friends_count' => intval($countfriends),
633 'created_at' => api_date($uinfo[0]['created']),
634 'favourites_count' => intval($starred),
636 'time_zone' => 'UTC',
637 'statuses_count' => intval($countitms),
638 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
640 'statusnet_blocking' => false,
641 'notifications' => false,
642 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
643 'statusnet_profile_url' => $uinfo[0]['url'],
644 'uid' => intval($uinfo[0]['uid']),
645 'cid' => intval($uinfo[0]['cid']),
646 'self' => $uinfo[0]['self'],
647 'network' => $uinfo[0]['network'],
655 * @brief return api-formatted array for item's author and owner
658 * @param array $item : item from db
659 * @return array(array:author, array:owner)
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 $status_user = api_get_user($a,$item["author-link"]);
671 $status_user["protected"] = (($item["allow_cid"] != "") OR
672 ($item["allow_gid"] != "") OR
673 ($item["deny_cid"] != "") OR
674 ($item["deny_gid"] != "") OR
677 $owner_user = api_get_user($a,$item["owner-link"]);
679 return (array($status_user, $owner_user));
684 * @brief transform $data array in xml without a template
687 * @return string xml string
689 function api_array_to_xml($data, $ename="") {
692 if (count($data)==1 && !is_array($data[array_keys($data)[0]])) {
693 $ename = array_keys($data)[0];
694 $ename = trim($ename,'$');
696 return "<$ename>$v</$ename>";
698 foreach($data as $k=>$v) {
701 $attrs .= sprintf('%s="%s" ', $k, $v);
703 if (is_numeric($k)) $k=trim($ename,'s');
704 $childs.=api_array_to_xml($v, $k);
708 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
714 * @brief walks recursively through an array with the possibility to change value and key
716 * @param array $array The array to walk through
717 * @param string $callback The callback function
719 * @return array the transformed array
721 function api_walk_recursive(array &$array, callable $callback) {
723 $new_array = array();
725 foreach ($array as $k => $v) {
727 if ($callback($v, $k))
728 $new_array[$k] = api_walk_recursive($v, $callback);
730 if ($callback($v, $k))
740 * @brief Callback function to transform the array in an array that can be transformed in a XML file
742 * @param variant $item Array item value
743 * @param string $key Array key
745 * @return boolean Should the array item be deleted?
747 function api_reformat_xml(&$item, &$key) {
749 $item = ($item ? "true" : "false");
751 if (substr($key, 0, 10) == "statusnet_")
752 $key = "statusnet:".substr($key, 10);
753 elseif (substr($key, 0, 10) == "friendica_")
754 $key = "friendica:".substr($key, 10);
755 elseif (in_array($key, array("like", "dislike", "attendyes", "attendno", "attendmaybe")))
756 $key = "friendica:".$key;
758 return (!in_array($key, array("attachments", "friendica:activities", "coordinates")));
762 * @brief Creates the XML from a JSON style array
764 * @param array $data JSON style array
765 * @param string $template Name of the root element
767 * @return boolean string The XML data
769 function api_create_xml($data, $root_element) {
771 $childname = key($data);
772 $data2 = array_pop($data);
775 $namespaces = array("statusnet" => "http://status.net/schema/api/1/",
776 "friendica" => "http://friendi.ca/schema/api/1/");
778 /// @todo Auto detection of needed namespaces
779 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
780 $namespaces = array();
782 if (is_array($data2))
783 api_walk_recursive($data2, "api_reformat_xml");
789 foreach ($data2 AS $item)
790 $data4[$i++.":".$childname] = $item;
795 $data3 = array($root_element => $data2);
796 $ret = xml::from_array($data3, $xml, false, $namespaces);
801 * load api $templatename for $type and replace $data array
803 function api_apply_template($templatename, $type, $data){
811 $ret = api_create_xml($data, $templatename);
814 $data = array_xmlify($data);
815 if ($templatename==="<auto>") {
816 $ret = api_array_to_xml($data);
818 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
820 header ("Content-Type: text/xml");
821 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
824 $ret = replace_macros($tpl, $data);
840 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
841 * returns a 401 status code and an error message if not.
842 * http://developer.twitter.com/doc/get/account/verify_credentials
844 function api_account_verify_credentials(&$a, $type){
845 if (api_user()===false) throw new ForbiddenException();
847 unset($_REQUEST["user_id"]);
848 unset($_GET["user_id"]);
850 unset($_REQUEST["screen_name"]);
851 unset($_GET["screen_name"]);
853 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
855 $user_info = api_get_user($a);
857 // "verified" isn't used here in the standard
858 unset($user_info["verified"]);
860 // - Adding last status
862 $user_info["status"] = api_status_show($a,"raw");
863 if (!count($user_info["status"]))
864 unset($user_info["status"]);
866 unset($user_info["status"]["user"]);
869 // "uid" and "self" are only needed for some internal stuff, so remove it from here
870 unset($user_info["uid"]);
871 unset($user_info["self"]);
873 return api_apply_template("user", $type, array('user' => $user_info));
876 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
880 * get data from $_POST or $_GET
882 function requestdata($k){
883 if (isset($_POST[$k])){
886 if (isset($_GET[$k])){
892 /*Waitman Gobble Mod*/
893 function api_statuses_mediap(&$a, $type) {
894 if (api_user()===false) {
895 logger('api_statuses_update: no user');
896 throw new ForbiddenException();
898 $user_info = api_get_user($a);
900 $_REQUEST['type'] = 'wall';
901 $_REQUEST['profile_uid'] = api_user();
902 $_REQUEST['api_source'] = true;
903 $txt = requestdata('status');
904 //$txt = urldecode(requestdata('status'));
906 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
908 $txt = html2bb_video($txt);
909 $config = HTMLPurifier_Config::createDefault();
910 $config->set('Cache.DefinitionImpl', null);
911 $purifier = new HTMLPurifier($config);
912 $txt = $purifier->purify($txt);
914 $txt = html2bbcode($txt);
916 $a->argv[1]=$user_info['screen_name']; //should be set to username?
918 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
919 $bebop = wall_upload_post($a);
921 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
922 $_REQUEST['body']=$txt."\n\n".$bebop;
925 // this should output the last post (the one we just posted).
926 return api_status_show($a,$type);
928 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
929 /*Waitman Gobble Mod*/
932 function api_statuses_update(&$a, $type) {
933 if (api_user()===false) {
934 logger('api_statuses_update: no user');
935 throw new ForbiddenException();
938 $user_info = api_get_user($a);
940 // convert $_POST array items to the form we use for web posts.
942 // logger('api_post: ' . print_r($_POST,true));
944 if(requestdata('htmlstatus')) {
945 $txt = requestdata('htmlstatus');
946 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
947 $txt = html2bb_video($txt);
949 $config = HTMLPurifier_Config::createDefault();
950 $config->set('Cache.DefinitionImpl', null);
952 $purifier = new HTMLPurifier($config);
953 $txt = $purifier->purify($txt);
955 $_REQUEST['body'] = html2bbcode($txt);
959 $_REQUEST['body'] = requestdata('status');
961 $_REQUEST['title'] = requestdata('title');
963 $parent = requestdata('in_reply_to_status_id');
965 // Twidere sends "-1" if it is no reply ...
969 if(ctype_digit($parent))
970 $_REQUEST['parent'] = $parent;
972 $_REQUEST['parent_uri'] = $parent;
974 if(requestdata('lat') && requestdata('long'))
975 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
976 $_REQUEST['profile_uid'] = api_user();
979 $_REQUEST['type'] = 'net-comment';
981 // Check for throttling (maximum posts per day, week and month)
982 $throttle_day = get_config('system','throttle_limit_day');
983 if ($throttle_day > 0) {
984 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
986 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
987 AND `created` > '%s' AND `id` = `parent`",
988 intval(api_user()), dbesc($datefrom));
991 $posts_day = $r[0]["posts_day"];
995 if ($posts_day > $throttle_day) {
996 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
997 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
998 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1002 $throttle_week = get_config('system','throttle_limit_week');
1003 if ($throttle_week > 0) {
1004 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1006 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1007 AND `created` > '%s' AND `id` = `parent`",
1008 intval(api_user()), dbesc($datefrom));
1011 $posts_week = $r[0]["posts_week"];
1015 if ($posts_week > $throttle_week) {
1016 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1017 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1018 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1023 $throttle_month = get_config('system','throttle_limit_month');
1024 if ($throttle_month > 0) {
1025 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1027 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1028 AND `created` > '%s' AND `id` = `parent`",
1029 intval(api_user()), dbesc($datefrom));
1032 $posts_month = $r[0]["posts_month"];
1036 if ($posts_month > $throttle_month) {
1037 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1038 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1039 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1043 $_REQUEST['type'] = 'wall';
1046 if(x($_FILES,'media')) {
1047 // upload the image if we have one
1048 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1049 $media = wall_upload_post($a);
1050 if(strlen($media)>0)
1051 $_REQUEST['body'] .= "\n\n".$media;
1054 // To-Do: Multiple IDs
1055 if (requestdata('media_ids')) {
1056 $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",
1057 intval(requestdata('media_ids')), api_user());
1059 $phototypes = Photo::supportedTypes();
1060 $ext = $phototypes[$r[0]['type']];
1061 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1062 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1066 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1068 $_REQUEST['api_source'] = true;
1070 if (!x($_REQUEST, "source"))
1071 $_REQUEST["source"] = api_source();
1073 // call out normal post function
1077 // this should output the last post (the one we just posted).
1078 return api_status_show($a,$type);
1080 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1081 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1084 function api_media_upload(&$a, $type) {
1085 if (api_user()===false) {
1087 throw new ForbiddenException();
1090 $user_info = api_get_user($a);
1092 if(!x($_FILES,'media')) {
1094 throw new BadRequestException("No media.");
1097 $media = wall_upload_post($a, false);
1100 throw new InternalServerErrorException();
1103 $returndata = array();
1104 $returndata["media_id"] = $media["id"];
1105 $returndata["media_id_string"] = (string)$media["id"];
1106 $returndata["size"] = $media["size"];
1107 $returndata["image"] = array("w" => $media["width"],
1108 "h" => $media["height"],
1109 "image_type" => $media["type"]);
1111 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1113 return array("media" => $returndata);
1115 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1117 function api_status_show(&$a, $type){
1118 $user_info = api_get_user($a);
1120 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1123 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1127 // get last public wall message
1128 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1129 FROM `item`, `item` as `i`
1130 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1131 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1132 AND `i`.`id` = `item`.`parent`
1133 AND `item`.`type`!='activity' $privacy_sql
1134 ORDER BY `item`.`created` DESC
1136 intval($user_info['cid']),
1138 dbesc($user_info['url']),
1139 dbesc(normalise_link($user_info['url'])),
1140 dbesc($user_info['url']),
1141 dbesc(normalise_link($user_info['url']))
1144 if (count($lastwall)>0){
1145 $lastwall = $lastwall[0];
1147 $in_reply_to_status_id = NULL;
1148 $in_reply_to_user_id = NULL;
1149 $in_reply_to_status_id_str = NULL;
1150 $in_reply_to_user_id_str = NULL;
1151 $in_reply_to_screen_name = NULL;
1152 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1153 $in_reply_to_status_id= intval($lastwall['parent']);
1154 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1156 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1158 if ($r[0]['nick'] == "")
1159 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1161 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1162 $in_reply_to_user_id = intval($r[0]['id']);
1163 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1167 // There seems to be situation, where both fields are identical:
1168 // https://github.com/friendica/friendica/issues/1010
1169 // This is a bugfix for that.
1170 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1171 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1172 $in_reply_to_status_id = NULL;
1173 $in_reply_to_user_id = NULL;
1174 $in_reply_to_status_id_str = NULL;
1175 $in_reply_to_user_id_str = NULL;
1176 $in_reply_to_screen_name = NULL;
1179 $converted = api_convert_item($lastwall);
1181 $status_info = array(
1182 'created_at' => api_date($lastwall['created']),
1183 'id' => intval($lastwall['id']),
1184 'id_str' => (string) $lastwall['id'],
1185 'text' => $converted["text"],
1186 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1187 'truncated' => false,
1188 'in_reply_to_status_id' => $in_reply_to_status_id,
1189 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1190 'in_reply_to_user_id' => $in_reply_to_user_id,
1191 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1192 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1193 'user' => $user_info,
1195 'coordinates' => "",
1197 'contributors' => "",
1198 'is_quote_status' => false,
1199 'retweet_count' => 0,
1200 'favorite_count' => 0,
1201 'favorited' => $lastwall['starred'] ? true : false,
1202 'retweeted' => false,
1203 'possibly_sensitive' => false,
1205 'statusnet_html' => $converted["html"],
1206 'statusnet_conversation_id' => $lastwall['parent'],
1209 if (count($converted["attachments"]) > 0)
1210 $status_info["attachments"] = $converted["attachments"];
1212 if (count($converted["entities"]) > 0)
1213 $status_info["entities"] = $converted["entities"];
1215 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1216 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1217 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1218 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1220 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1221 unset($status_info["user"]["uid"]);
1222 unset($status_info["user"]["self"]);
1225 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1228 return($status_info);
1230 return api_apply_template("statuses", $type, array('status' => $status_info));
1239 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1240 * The author's most recent status will be returned inline.
1241 * http://developer.twitter.com/doc/get/users/show
1243 function api_users_show(&$a, $type){
1244 $user_info = api_get_user($a);
1246 $lastwall = q("SELECT `item`.*
1247 FROM `item`, `contact`
1248 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1249 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1250 AND `contact`.`id`=`item`.`contact-id`
1251 AND `type`!='activity'
1252 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1253 ORDER BY `created` DESC
1256 dbesc(ACTIVITY_POST),
1257 intval($user_info['cid']),
1258 dbesc($user_info['url']),
1259 dbesc(normalise_link($user_info['url'])),
1260 dbesc($user_info['url']),
1261 dbesc(normalise_link($user_info['url']))
1263 if (count($lastwall)>0){
1264 $lastwall = $lastwall[0];
1266 $in_reply_to_status_id = NULL;
1267 $in_reply_to_user_id = NULL;
1268 $in_reply_to_status_id_str = NULL;
1269 $in_reply_to_user_id_str = NULL;
1270 $in_reply_to_screen_name = NULL;
1271 if ($lastwall['parent']!=$lastwall['id']) {
1272 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1273 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1274 if (count($reply)>0) {
1275 $in_reply_to_status_id = intval($lastwall['parent']);
1276 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1278 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1280 if ($r[0]['nick'] == "")
1281 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1283 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1284 $in_reply_to_user_id = intval($r[0]['id']);
1285 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1290 $converted = api_convert_item($lastwall);
1292 $user_info['status'] = array(
1293 'text' => $converted["text"],
1294 'truncated' => false,
1295 'created_at' => api_date($lastwall['created']),
1296 'in_reply_to_status_id' => $in_reply_to_status_id,
1297 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1298 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1299 'id' => intval($lastwall['contact-id']),
1300 'id_str' => (string) $lastwall['contact-id'],
1301 'in_reply_to_user_id' => $in_reply_to_user_id,
1302 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1303 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1305 'favorited' => $lastwall['starred'] ? true : false,
1306 'statusnet_html' => $converted["html"],
1307 'statusnet_conversation_id' => $lastwall['parent'],
1310 if (count($converted["attachments"]) > 0)
1311 $user_info["status"]["attachments"] = $converted["attachments"];
1313 if (count($converted["entities"]) > 0)
1314 $user_info["status"]["entities"] = $converted["entities"];
1316 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1317 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1318 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1319 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1323 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1324 unset($user_info["uid"]);
1325 unset($user_info["self"]);
1327 return api_apply_template("user", $type, array('user' => $user_info));
1330 api_register_func('api/users/show','api_users_show');
1333 function api_users_search(&$a, $type) {
1334 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1336 $userlist = array();
1338 if (isset($_GET["q"])) {
1339 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1341 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1344 foreach ($r AS $user) {
1345 $user_info = api_get_user($a, $user["id"]);
1346 //echo print_r($user_info, true)."\n";
1347 $userdata = api_apply_template("user", $type, array('users' => $user_info));
1348 $userlist[] = $userdata["user"];
1350 $userlist = array("users" => $userlist);
1352 throw new BadRequestException("User not found.");
1355 throw new BadRequestException("User not found.");
1360 api_register_func('api/users/search','api_users_search');
1364 * http://developer.twitter.com/doc/get/statuses/home_timeline
1366 * TODO: Optional parameters
1367 * TODO: Add reply info
1369 function api_statuses_home_timeline(&$a, $type){
1370 if (api_user()===false) throw new ForbiddenException();
1372 unset($_REQUEST["user_id"]);
1373 unset($_GET["user_id"]);
1375 unset($_REQUEST["screen_name"]);
1376 unset($_GET["screen_name"]);
1378 $user_info = api_get_user($a);
1379 // get last newtork messages
1383 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1384 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1385 if ($page<0) $page=0;
1386 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1387 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1388 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1389 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1390 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1392 $start = $page*$count;
1396 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1397 if ($exclude_replies > 0)
1398 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1399 if ($conversation_id > 0)
1400 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1402 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1403 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1404 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1405 `contact`.`id` AS `cid`
1406 FROM `item`, `contact`
1407 WHERE `item`.`uid` = %d AND `verb` = '%s'
1408 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1409 AND `contact`.`id` = `item`.`contact-id`
1410 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1413 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1415 dbesc(ACTIVITY_POST),
1417 intval($start), intval($count)
1420 $ret = api_format_items($r,$user_info);
1422 // Set all posts from the query above to seen
1424 foreach ($r AS $item)
1425 $idarray[] = intval($item["id"]);
1427 $idlist = implode(",", $idarray);
1429 if ($idlist != "") {
1430 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1433 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1436 $data = array('status' => $ret);
1440 $data = api_rss_extra($a, $data, $user_info);
1444 return api_apply_template("statuses", $type, $data);
1446 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1447 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1449 function api_statuses_public_timeline(&$a, $type){
1450 if (api_user()===false) throw new ForbiddenException();
1452 $user_info = api_get_user($a);
1453 // get last newtork messages
1457 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1458 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1459 if ($page<0) $page=0;
1460 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1461 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1462 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1463 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1464 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1466 $start = $page*$count;
1469 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1470 if ($exclude_replies > 0)
1471 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1472 if ($conversation_id > 0)
1473 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1475 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1476 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1477 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1478 `contact`.`id` AS `cid`,
1479 `user`.`nickname`, `user`.`hidewall`
1480 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1481 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1482 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1483 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1484 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1485 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1486 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1489 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1490 dbesc(ACTIVITY_POST),
1495 $ret = api_format_items($r,$user_info);
1498 $data = array('status' => $ret);
1502 $data = api_rss_extra($a, $data, $user_info);
1506 return api_apply_template("statuses", $type, $data);
1508 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1513 function api_statuses_show(&$a, $type){
1514 if (api_user()===false) throw new ForbiddenException();
1516 $user_info = api_get_user($a);
1519 $id = intval($a->argv[3]);
1522 $id = intval($_REQUEST["id"]);
1526 $id = intval($a->argv[4]);
1528 logger('API: api_statuses_show: '.$id);
1530 $conversation = (x($_REQUEST,'conversation')?1:0);
1534 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1536 $sql_extra .= " AND `item`.`id` = %d";
1538 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1539 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1540 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1541 `contact`.`id` AS `cid`
1542 FROM `item`, `contact`
1543 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1544 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1545 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1548 dbesc(ACTIVITY_POST),
1553 throw new BadRequestException("There is no status with this id.");
1556 $ret = api_format_items($r,$user_info);
1558 if ($conversation) {
1559 $data = array('status' => $ret);
1560 return api_apply_template("statuses", $type, $data);
1562 $data = array('status' => $ret[0]);
1563 return api_apply_template("status", $type, $data);
1566 api_register_func('api/statuses/show','api_statuses_show', true);
1572 function api_conversation_show(&$a, $type){
1573 if (api_user()===false) throw new ForbiddenException();
1575 $user_info = api_get_user($a);
1578 $id = intval($a->argv[3]);
1579 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1580 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1581 if ($page<0) $page=0;
1582 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1583 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1585 $start = $page*$count;
1588 $id = intval($_REQUEST["id"]);
1592 $id = intval($a->argv[4]);
1594 logger('API: api_conversation_show: '.$id);
1596 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1598 $id = $r[0]["parent"];
1603 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1605 // Not sure why this query was so complicated. We should keep it here for a while,
1606 // just to make sure that we really don't need it.
1607 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1608 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1610 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1611 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1612 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1613 `contact`.`id` AS `cid`
1615 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1616 WHERE `item`.`parent` = %d AND `item`.`visible`
1617 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1618 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1619 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1620 AND `item`.`id`>%d $sql_extra
1621 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1622 intval($id), intval(api_user()),
1623 dbesc(ACTIVITY_POST),
1625 intval($start), intval($count)
1629 throw new BadRequestException("There is no conversation with this id.");
1631 $ret = api_format_items($r,$user_info);
1633 $data = array('status' => $ret);
1634 return api_apply_template("statuses", $type, $data);
1636 api_register_func('api/conversation/show','api_conversation_show', true);
1637 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1643 function api_statuses_repeat(&$a, $type){
1646 if (api_user()===false) throw new ForbiddenException();
1648 $user_info = api_get_user($a);
1651 $id = intval($a->argv[3]);
1654 $id = intval($_REQUEST["id"]);
1658 $id = intval($a->argv[4]);
1660 logger('API: api_statuses_repeat: '.$id);
1662 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1663 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1664 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1665 `contact`.`id` AS `cid`
1666 FROM `item`, `contact`
1667 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1668 AND `contact`.`id` = `item`.`contact-id`
1669 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1670 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1671 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1673 AND `item`.`id`=%d",
1677 if ($r[0]['body'] != "") {
1678 if (!intval(get_config('system','old_share'))) {
1679 if (strpos($r[0]['body'], "[/share]") !== false) {
1680 $pos = strpos($r[0]['body'], "[share");
1681 $post = substr($r[0]['body'], $pos);
1683 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1685 $post .= $r[0]['body'];
1686 $post .= "[/share]";
1688 $_REQUEST['body'] = $post;
1690 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1692 $_REQUEST['profile_uid'] = api_user();
1693 $_REQUEST['type'] = 'wall';
1694 $_REQUEST['api_source'] = true;
1696 if (!x($_REQUEST, "source"))
1697 $_REQUEST["source"] = api_source();
1701 throw new ForbiddenException();
1703 // this should output the last post (the one we just posted).
1705 return(api_status_show($a,$type));
1707 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1712 function api_statuses_destroy(&$a, $type){
1713 if (api_user()===false) throw new ForbiddenException();
1715 $user_info = api_get_user($a);
1718 $id = intval($a->argv[3]);
1721 $id = intval($_REQUEST["id"]);
1725 $id = intval($a->argv[4]);
1727 logger('API: api_statuses_destroy: '.$id);
1729 $ret = api_statuses_show($a, $type);
1731 drop_item($id, false);
1735 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1739 * http://developer.twitter.com/doc/get/statuses/mentions
1742 function api_statuses_mentions(&$a, $type){
1743 if (api_user()===false) throw new ForbiddenException();
1745 unset($_REQUEST["user_id"]);
1746 unset($_GET["user_id"]);
1748 unset($_REQUEST["screen_name"]);
1749 unset($_GET["screen_name"]);
1751 $user_info = api_get_user($a);
1752 // get last newtork messages
1756 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1757 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1758 if ($page<0) $page=0;
1759 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1760 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1761 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1763 $start = $page*$count;
1765 // Ugly code - should be changed
1766 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1767 $myurl = substr($myurl,strpos($myurl,'://')+3);
1768 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1769 $myurl = str_replace('www.','',$myurl);
1770 $diasp_url = str_replace('/profile/','/u/',$myurl);
1773 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1775 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1776 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1777 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1778 `contact`.`id` AS `cid`
1779 FROM `item` FORCE INDEX (`uid_id`), `contact`
1780 WHERE `item`.`uid` = %d AND `verb` = '%s'
1781 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1782 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1783 AND `contact`.`id` = `item`.`contact-id`
1784 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1785 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1788 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1790 dbesc(ACTIVITY_POST),
1791 dbesc(protect_sprintf($myurl)),
1792 dbesc(protect_sprintf($myurl)),
1795 intval($start), intval($count)
1798 $ret = api_format_items($r,$user_info);
1801 $data = array('status' => $ret);
1805 $data = api_rss_extra($a, $data, $user_info);
1809 return api_apply_template("statuses", $type, $data);
1811 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1812 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1815 function api_statuses_user_timeline(&$a, $type){
1816 if (api_user()===false) throw new ForbiddenException();
1818 $user_info = api_get_user($a);
1819 // get last network messages
1821 logger("api_statuses_user_timeline: api_user: ". api_user() .
1822 "\nuser_info: ".print_r($user_info, true) .
1823 "\n_REQUEST: ".print_r($_REQUEST, true),
1827 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1828 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1829 if ($page<0) $page=0;
1830 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1831 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1832 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1833 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1835 $start = $page*$count;
1838 if ($user_info['self']==1)
1839 $sql_extra .= " AND `item`.`wall` = 1 ";
1841 if ($exclude_replies > 0)
1842 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1843 if ($conversation_id > 0)
1844 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1846 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1847 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1848 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1849 `contact`.`id` AS `cid`
1851 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1852 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1853 WHERE `item`.`uid` = %d AND `verb` = '%s'
1854 AND `item`.`contact-id` = %d
1855 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1858 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1860 dbesc(ACTIVITY_POST),
1861 intval($user_info['cid']),
1863 intval($start), intval($count)
1866 $ret = api_format_items($r,$user_info, true);
1868 $data = array('status' => $ret);
1872 $data = api_rss_extra($a, $data, $user_info);
1875 return api_apply_template("statuses", $type, $data);
1877 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1881 * Star/unstar an item
1882 * param: id : id of the item
1884 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1886 function api_favorites_create_destroy(&$a, $type){
1887 if (api_user()===false) throw new ForbiddenException();
1889 // for versioned api.
1890 /// @TODO We need a better global soluton
1892 if ($a->argv[1]=="1.1") $action_argv_id=3;
1894 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1895 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1896 if ($a->argc==$action_argv_id+2) {
1897 $itemid = intval($a->argv[$action_argv_id+1]);
1899 $itemid = intval($_REQUEST['id']);
1902 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1903 $itemid, api_user());
1905 if ($item===false || count($item)==0)
1906 throw new BadRequestException("Invalid item.");
1910 $item[0]['starred']=1;
1913 $item[0]['starred']=0;
1916 throw new BadRequestException("Invalid action ".$action);
1918 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1919 $item[0]['starred'], $itemid, api_user());
1921 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1922 $item[0]['starred'], $itemid, api_user());
1925 throw InternalServerErrorException("DB error");
1928 $user_info = api_get_user($a);
1929 $rets = api_format_items($item,$user_info);
1932 $data = array('status' => $ret);
1936 $data = api_rss_extra($a, $data, $user_info);
1939 return api_apply_template("status", $type, $data);
1941 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1942 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1944 function api_favorites(&$a, $type){
1947 if (api_user()===false) throw new ForbiddenException();
1949 $called_api= array();
1951 $user_info = api_get_user($a);
1953 // in friendica starred item are private
1954 // return favorites only for self
1955 logger('api_favorites: self:' . $user_info['self']);
1957 if ($user_info['self']==0) {
1963 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1964 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1965 $count = (x($_GET,'count')?$_GET['count']:20);
1966 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1967 if ($page<0) $page=0;
1969 $start = $page*$count;
1972 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1974 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1975 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1976 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1977 `contact`.`id` AS `cid`
1978 FROM `item`, `contact`
1979 WHERE `item`.`uid` = %d
1980 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1981 AND `item`.`starred` = 1
1982 AND `contact`.`id` = `item`.`contact-id`
1983 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1986 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1989 intval($start), intval($count)
1992 $ret = api_format_items($r,$user_info);
1996 $data = array('status' => $ret);
2000 $data = api_rss_extra($a, $data, $user_info);
2003 return api_apply_template("statuses", $type, $data);
2005 api_register_func('api/favorites','api_favorites', true);
2007 function api_format_messages($item, $recipient, $sender) {
2008 // standard meta information
2010 'id' => $item['id'],
2011 'sender_id' => $sender['id'] ,
2013 'recipient_id' => $recipient['id'],
2014 'created_at' => api_date($item['created']),
2015 'sender_screen_name' => $sender['screen_name'],
2016 'recipient_screen_name' => $recipient['screen_name'],
2017 'sender' => $sender,
2018 'recipient' => $recipient,
2021 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2022 unset($ret["sender"]["uid"]);
2023 unset($ret["sender"]["self"]);
2024 unset($ret["recipient"]["uid"]);
2025 unset($ret["recipient"]["self"]);
2027 //don't send title to regular StatusNET requests to avoid confusing these apps
2028 if (x($_GET, 'getText')) {
2029 $ret['title'] = $item['title'] ;
2030 if ($_GET["getText"] == "html") {
2031 $ret['text'] = bbcode($item['body'], false, false);
2033 elseif ($_GET["getText"] == "plain") {
2034 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2035 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2039 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2041 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2042 unset($ret['sender']);
2043 unset($ret['recipient']);
2049 function api_convert_item($item) {
2050 $body = $item['body'];
2051 $attachments = api_get_attachments($body);
2053 // Workaround for ostatus messages where the title is identically to the body
2054 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2055 $statusbody = trim(html2plain($html, 0));
2057 // handle data: images
2058 $statusbody = api_format_items_embeded_images($item,$statusbody);
2060 $statustitle = trim($item['title']);
2062 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2063 $statustext = trim($statusbody);
2065 $statustext = trim($statustitle."\n\n".$statusbody);
2067 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2068 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2070 $statushtml = trim(bbcode($body, false, false));
2072 $search = array("<br>", "<blockquote>", "</blockquote>",
2073 "<h1>", "</h1>", "<h2>", "</h2>",
2074 "<h3>", "</h3>", "<h4>", "</h4>",
2075 "<h5>", "</h5>", "<h6>", "</h6>");
2076 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2077 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2078 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2079 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2080 $statushtml = str_replace($search, $replace, $statushtml);
2082 if ($item['title'] != "")
2083 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2085 $entities = api_get_entitities($statustext, $body);
2088 "text" => $statustext,
2089 "html" => $statushtml,
2090 "attachments" => $attachments,
2091 "entities" => $entities
2095 function api_get_attachments(&$body) {
2098 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2100 $URLSearchString = "^\[\]";
2101 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2106 $attachments = array();
2108 foreach ($images[1] AS $image) {
2109 $imagedata = get_photo_info($image);
2112 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2115 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2116 foreach ($images[0] AS $orig)
2117 $body = str_replace($orig, "", $body);
2119 return $attachments;
2122 function api_get_entitities(&$text, $bbcode) {
2125 * Links at the first character of the post
2130 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2132 if ($include_entities != "true") {
2134 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2136 foreach ($images[1] AS $image) {
2137 $replace = proxy_url($image);
2138 $text = str_replace($image, $replace, $text);
2143 $bbcode = bb_CleanPictureLinks($bbcode);
2145 // Change pure links in text to bbcode uris
2146 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2148 $entities = array();
2149 $entities["hashtags"] = array();
2150 $entities["symbols"] = array();
2151 $entities["urls"] = array();
2152 $entities["user_mentions"] = array();
2154 $URLSearchString = "^\[\]";
2156 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2158 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2159 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2160 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2162 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2163 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2164 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2166 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2167 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2168 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2170 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2172 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2173 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2175 $ordered_urls = array();
2176 foreach ($urls[1] AS $id=>$url) {
2177 //$start = strpos($text, $url, $offset);
2178 $start = iconv_strpos($text, $url, 0, "UTF-8");
2179 if (!($start === false))
2180 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2183 ksort($ordered_urls);
2186 //foreach ($urls[1] AS $id=>$url) {
2187 foreach ($ordered_urls AS $url) {
2188 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2189 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2190 $display_url = $url["title"];
2192 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2193 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2195 if (strlen($display_url) > 26)
2196 $display_url = substr($display_url, 0, 25)."…";
2199 //$start = strpos($text, $url, $offset);
2200 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2201 if (!($start === false)) {
2202 $entities["urls"][] = array("url" => $url["url"],
2203 "expanded_url" => $url["url"],
2204 "display_url" => $display_url,
2205 "indices" => array($start, $start+strlen($url["url"])));
2206 $offset = $start + 1;
2210 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2211 $ordered_images = array();
2212 foreach ($images[1] AS $image) {
2213 //$start = strpos($text, $url, $offset);
2214 $start = iconv_strpos($text, $image, 0, "UTF-8");
2215 if (!($start === false))
2216 $ordered_images[$start] = $image;
2218 //$entities["media"] = array();
2221 foreach ($ordered_images AS $url) {
2222 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2223 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2225 if (strlen($display_url) > 26)
2226 $display_url = substr($display_url, 0, 25)."…";
2228 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2229 if (!($start === false)) {
2230 $image = get_photo_info($url);
2232 // If image cache is activated, then use the following sizes:
2233 // thumb (150), small (340), medium (600) and large (1024)
2234 if (!get_config("system", "proxy_disabled")) {
2235 $media_url = proxy_url($url);
2238 $scale = scale_image($image[0], $image[1], 150);
2239 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2241 if (($image[0] > 150) OR ($image[1] > 150)) {
2242 $scale = scale_image($image[0], $image[1], 340);
2243 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2246 $scale = scale_image($image[0], $image[1], 600);
2247 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2249 if (($image[0] > 600) OR ($image[1] > 600)) {
2250 $scale = scale_image($image[0], $image[1], 1024);
2251 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2255 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2258 $entities["media"][] = array(
2260 "id_str" => (string)$start+1,
2261 "indices" => array($start, $start+strlen($url)),
2262 "media_url" => normalise_link($media_url),
2263 "media_url_https" => $media_url,
2265 "display_url" => $display_url,
2266 "expanded_url" => $url,
2270 $offset = $start + 1;
2276 function api_format_items_embeded_images(&$item, $text){
2278 $text = preg_replace_callback(
2279 "|data:image/([^;]+)[^=]+=*|m",
2280 function($match) use ($a, $item) {
2281 return $a->get_baseurl()."/display/".$item['guid'];
2289 * @brief return <a href='url'>name</a> as array
2291 * @param string $txt
2296 function api_contactlink_to_array($txt) {
2298 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2299 if ($r && count($match)==3) {
2301 'name' => $match[2],
2315 * @brief return likes, dislikes and attend status for item
2317 * @param array $item
2319 * likes => int count
2320 * dislikes => int count
2322 function api_format_items_activities(&$item) {
2323 $activities = array(
2325 'dislike' => array(),
2326 'attendyes' => array(),
2327 'attendno' => array(),
2328 'attendmaybe' => array()
2330 $items = q('SELECT * FROM item
2331 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2332 intval($item['uid']),
2333 dbesc($item['uri']));
2334 foreach ($items as $i){
2335 builtin_activity_puller($i, $activities);
2339 $uri = $item['uri']."-l";
2340 foreach($activities as $k => $v) {
2341 $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2348 * @brief format items to be returned by api
2350 * @param array $r array of items
2351 * @param array $user_info
2352 * @param bool $filter_user filter items by $user_info
2354 function api_format_items($r,$user_info, $filter_user = false) {
2359 foreach($r as $item) {
2361 localize_item($item);
2362 list($status_user, $owner_user) = api_item_get_user($a,$item);
2364 // Look if the posts are matching if they should be filtered by user id
2365 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2368 if ($item['thr-parent'] != $item['uri']) {
2369 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2371 dbesc($item['thr-parent']));
2373 $in_reply_to_status_id = intval($r[0]['id']);
2375 $in_reply_to_status_id = intval($item['parent']);
2377 $in_reply_to_status_id_str = (string) intval($item['parent']);
2379 $in_reply_to_screen_name = NULL;
2380 $in_reply_to_user_id = NULL;
2381 $in_reply_to_user_id_str = NULL;
2383 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2385 intval($in_reply_to_status_id));
2387 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2390 if ($r[0]['nick'] == "")
2391 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2393 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2394 $in_reply_to_user_id = intval($r[0]['id']);
2395 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2399 $in_reply_to_screen_name = NULL;
2400 $in_reply_to_user_id = NULL;
2401 $in_reply_to_status_id = NULL;
2402 $in_reply_to_user_id_str = NULL;
2403 $in_reply_to_status_id_str = NULL;
2406 $converted = api_convert_item($item);
2409 'text' => $converted["text"],
2410 'truncated' => False,
2411 'created_at'=> api_date($item['created']),
2412 'in_reply_to_status_id' => $in_reply_to_status_id,
2413 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2414 'source' => (($item['app']) ? $item['app'] : 'web'),
2415 'id' => intval($item['id']),
2416 'id_str' => (string) intval($item['id']),
2417 'in_reply_to_user_id' => $in_reply_to_user_id,
2418 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2419 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2421 'favorited' => $item['starred'] ? true : false,
2422 'user' => $status_user ,
2423 'friendica_owner' => $owner_user,
2424 //'entities' => NULL,
2425 'statusnet_html' => $converted["html"],
2426 'statusnet_conversation_id' => $item['parent'],
2427 'friendica_activities' => api_format_items_activities($item),
2430 if (count($converted["attachments"]) > 0)
2431 $status["attachments"] = $converted["attachments"];
2433 if (count($converted["entities"]) > 0)
2434 $status["entities"] = $converted["entities"];
2436 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2437 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2438 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2439 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2442 // Retweets are only valid for top postings
2443 // It doesn't work reliable with the link if its a feed
2444 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2446 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2449 if ($item["id"] == $item["parent"]) {
2450 $retweeted_item = api_share_as_retweet($item);
2451 if ($retweeted_item !== false) {
2452 $retweeted_status = $status;
2454 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2455 } catch( BadRequestException $e ) {
2456 // user not found. should be found?
2457 /// @todo check if the user should be always found
2458 $retweeted_status["user"] = array();
2461 $rt_converted = api_convert_item($retweeted_item);
2463 $retweeted_status['text'] = $rt_converted["text"];
2464 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2465 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item);
2466 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2467 $status['retweeted_status'] = $retweeted_status;
2471 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2472 unset($status["user"]["uid"]);
2473 unset($status["user"]["self"]);
2475 if ($item["coord"] != "") {
2476 $coords = explode(' ',$item["coord"]);
2477 if (count($coords) == 2) {
2478 $status["geo"] = array('type' => 'Point',
2479 'coordinates' => array((float) $coords[0],
2480 (float) $coords[1]));
2490 function api_account_rate_limit_status(&$a,$type) {
2492 if ($type == "json")
2494 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2495 'remaining_hits' => (string) 150,
2496 'hourly_limit' => (string) 150,
2497 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2501 'remaining-hits' => (string) 150,
2502 '@attributes' => array("type" => "integer"),
2503 'hourly-limit' => (string) 150,
2504 '@attributes2' => array("type" => "integer"),
2505 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2506 '@attributes3' => array("type" => "datetime"),
2507 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2508 '@attributes4' => array("type" => "integer"),
2511 return api_apply_template('hash', $type, array('hash' => $hash));
2513 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2515 function api_help_test(&$a,$type) {
2521 return api_apply_template('ok', $type, array("ok" => $ok));
2523 api_register_func('api/help/test','api_help_test',false);
2525 function api_lists(&$a,$type) {
2527 return api_apply_template('lists', $type, array("lists_list" => $ret));
2529 api_register_func('api/lists','api_lists',true);
2531 function api_lists_list(&$a,$type) {
2533 return api_apply_template('lists', $type, array("lists_list" => $ret));
2535 api_register_func('api/lists/list','api_lists_list',true);
2538 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2539 * This function is deprecated by Twitter
2540 * returns: json, xml
2542 function api_statuses_f(&$a, $type, $qtype) {
2543 if (api_user()===false) throw new ForbiddenException();
2544 $user_info = api_get_user($a);
2546 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2547 /* this is to stop Hotot to load friends multiple times
2548 * I'm not sure if I'm missing return something or
2549 * is a bug in hotot. Workaround, meantime
2553 return array('$users' => $ret);*/
2557 if($qtype == 'friends')
2558 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2559 if($qtype == 'followers')
2560 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2562 // friends and followers only for self
2563 if ($user_info['self'] == 0)
2564 $sql_extra = " AND false ";
2566 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2571 foreach($r as $cid){
2572 $user = api_get_user($a, $cid['nurl']);
2573 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2574 unset($user["uid"]);
2575 unset($user["self"]);
2581 return array('user' => $ret);
2584 function api_statuses_friends(&$a, $type){
2585 $data = api_statuses_f($a,$type,"friends");
2586 if ($data===false) return false;
2587 return api_apply_template("users", $type, $data);
2589 function api_statuses_followers(&$a, $type){
2590 $data = api_statuses_f($a,$type,"followers");
2591 if ($data===false) return false;
2592 return api_apply_template("users", $type, $data);
2594 api_register_func('api/statuses/friends','api_statuses_friends',true);
2595 api_register_func('api/statuses/followers','api_statuses_followers',true);
2602 function api_statusnet_config(&$a,$type) {
2603 $name = $a->config['sitename'];
2604 $server = $a->get_hostname();
2605 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2606 $email = $a->config['admin_email'];
2607 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2608 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2609 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2610 if($a->config['api_import_size'])
2611 $texlimit = string($a->config['api_import_size']);
2612 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2613 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2616 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2617 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2618 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2619 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2620 'shorturllength' => '30',
2621 'friendica' => array(
2622 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2623 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2624 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2625 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2630 return api_apply_template('config', $type, array('config' => $config));
2633 api_register_func('api/statusnet/config','api_statusnet_config',false);
2635 function api_statusnet_version(&$a,$type) {
2637 $fake_statusnet_version = "0.9.7";
2639 return api_apply_template('version', $type, array('version' => $fake_statusnet_version));
2641 api_register_func('api/statusnet/version','api_statusnet_version',false);
2644 * @todo use api_apply_template() to return data
2646 function api_ff_ids(&$a,$type,$qtype) {
2647 if(! api_user()) throw new ForbiddenException();
2649 $user_info = api_get_user($a);
2651 if($qtype == 'friends')
2652 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2653 if($qtype == 'followers')
2654 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2656 if (!$user_info["self"])
2657 $sql_extra = " AND false ";
2659 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2661 $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",
2665 if(!dbm::is_result($r))
2673 $ids[] = intval($rr['id']);
2675 return api_apply_template("ids", $type, array('id' => $ids));
2678 function api_friends_ids(&$a,$type) {
2679 return api_ff_ids($a,$type,'friends');
2681 function api_followers_ids(&$a,$type) {
2682 return api_ff_ids($a,$type,'followers');
2684 api_register_func('api/friends/ids','api_friends_ids',true);
2685 api_register_func('api/followers/ids','api_followers_ids',true);
2688 function api_direct_messages_new(&$a, $type) {
2689 if (api_user()===false) throw new ForbiddenException();
2691 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2693 $sender = api_get_user($a);
2695 if ($_POST['screen_name']) {
2696 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2698 dbesc($_POST['screen_name']));
2700 // Selecting the id by priority, friendica first
2701 api_best_nickname($r);
2703 $recipient = api_get_user($a, $r[0]['nurl']);
2705 $recipient = api_get_user($a, $_POST['user_id']);
2709 if (x($_REQUEST,'replyto')) {
2710 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2712 intval($_REQUEST['replyto']));
2713 $replyto = $r[0]['parent-uri'];
2714 $sub = $r[0]['title'];
2717 if (x($_REQUEST,'title')) {
2718 $sub = $_REQUEST['title'];
2721 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2725 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2728 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2729 $ret = api_format_messages($r[0], $recipient, $sender);
2732 $ret = array("error"=>$id);
2735 $data = Array('direct_message'=>$ret);
2740 $data = api_rss_extra($a, $data, $user_info);
2743 return api_apply_template("direct-messages", $type, $data);
2746 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2748 function api_direct_messages_box(&$a, $type, $box) {
2749 if (api_user()===false) throw new ForbiddenException();
2752 $count = (x($_GET,'count')?$_GET['count']:20);
2753 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2754 if ($page<0) $page=0;
2756 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2757 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2759 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2760 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2763 unset($_REQUEST["user_id"]);
2764 unset($_GET["user_id"]);
2766 unset($_REQUEST["screen_name"]);
2767 unset($_GET["screen_name"]);
2769 $user_info = api_get_user($a);
2770 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2771 $profile_url = $user_info["url"];
2775 $start = $page*$count;
2778 if ($box=="sentbox") {
2779 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2781 elseif ($box=="conversation") {
2782 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2784 elseif ($box=="all") {
2785 $sql_extra = "true";
2787 elseif ($box=="inbox") {
2788 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2792 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2794 if ($user_id !="") {
2795 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2797 elseif($screen_name !=""){
2798 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2801 $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",
2804 intval($start), intval($count)
2809 foreach($r as $item) {
2810 if ($box == "inbox" || $item['from-url'] != $profile_url){
2811 $recipient = $user_info;
2812 $sender = api_get_user($a,normalise_link($item['contact-url']));
2814 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2815 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2816 $sender = $user_info;
2819 $ret[]=api_format_messages($item, $recipient, $sender);
2823 $data = array('direct_message' => $ret);
2827 $data = api_rss_extra($a, $data, $user_info);
2830 return api_apply_template("direct-messages", $type, $data);
2834 function api_direct_messages_sentbox(&$a, $type){
2835 return api_direct_messages_box($a, $type, "sentbox");
2837 function api_direct_messages_inbox(&$a, $type){
2838 return api_direct_messages_box($a, $type, "inbox");
2840 function api_direct_messages_all(&$a, $type){
2841 return api_direct_messages_box($a, $type, "all");
2843 function api_direct_messages_conversation(&$a, $type){
2844 return api_direct_messages_box($a, $type, "conversation");
2846 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2847 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2848 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2849 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2853 function api_oauth_request_token(&$a, $type){
2855 $oauth = new FKOAuth1();
2856 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2857 }catch(Exception $e){
2858 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2863 function api_oauth_access_token(&$a, $type){
2865 $oauth = new FKOAuth1();
2866 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2867 }catch(Exception $e){
2868 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2874 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2875 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2878 function api_fr_photos_list(&$a,$type) {
2879 if (api_user()===false) throw new ForbiddenException();
2880 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2881 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2882 intval(local_user())
2885 'image/jpeg' => 'jpg',
2886 'image/png' => 'png',
2887 'image/gif' => 'gif'
2889 $data = array('photo'=>array());
2891 foreach($r as $rr) {
2893 $photo['id'] = $rr['resource-id'];
2894 $photo['album'] = $rr['album'];
2895 $photo['filename'] = $rr['filename'];
2896 $photo['type'] = $rr['type'];
2897 $thumb = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2899 if ($type == "json") {
2900 $photo['thumb'] = $thumb;
2901 $data['photo'][] = $photo;
2903 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
2907 return api_apply_template("photos", $type, $data);
2910 function api_fr_photo_detail(&$a,$type) {
2911 if (api_user()===false) throw new ForbiddenException();
2912 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2914 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2915 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2916 $data_sql = ($scale === false ? "" : "data, ");
2918 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2919 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2920 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2922 intval(local_user()),
2923 dbesc($_REQUEST['photo_id']),
2928 'image/jpeg' => 'jpg',
2929 'image/png' => 'png',
2930 'image/gif' => 'gif'
2934 $data = array('photo' => $r[0]);
2935 if ($scale !== false) {
2936 $data['photo']['data'] = base64_encode($data['photo']['data']);
2938 unset($data['photo']['datasize']); //needed only with scale param
2940 $data['photo']['link'] = array();
2941 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2942 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2944 $data['photo']['id'] = $data['photo']['resource-id'];
2945 unset($data['photo']['resource-id']);
2946 unset($data['photo']['minscale']);
2947 unset($data['photo']['maxscale']);
2950 throw new NotFoundException();
2953 return api_apply_template("photo_detail", $type, $data);
2956 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2957 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2962 * similar as /mod/redir.php
2963 * redirect to 'url' after dfrn auth
2965 * why this when there is mod/redir.php already?
2966 * This use api_user() and api_login()
2969 * c_url: url of remote contact to auth to
2970 * url: string, url to redirect after auth
2972 function api_friendica_remoteauth(&$a) {
2973 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2974 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2976 if ($url === '' || $c_url === '')
2977 throw new BadRequestException("Wrong parameters.");
2979 $c_url = normalise_link($c_url);
2983 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2988 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2989 throw new BadRequestException("Unknown contact");
2993 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2995 if($r[0]['duplex'] && $r[0]['issued-id']) {
2996 $orig_id = $r[0]['issued-id'];
2997 $dfrn_id = '1:' . $orig_id;
2999 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3000 $orig_id = $r[0]['dfrn-id'];
3001 $dfrn_id = '0:' . $orig_id;
3004 $sec = random_string();
3006 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3007 VALUES( %d, %s, '%s', '%s', %d )",
3015 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3016 $dest = (($url) ? '&destination_url=' . $url : '');
3017 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3018 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3019 . '&type=profile&sec=' . $sec . $dest . $quiet );
3021 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3024 * @brief Return the item shared, if the item contains only the [share] tag
3026 * @param array $item Sharer item
3027 * @return array Shared item or false if not a reshare
3029 function api_share_as_retweet(&$item) {
3030 $body = trim($item["body"]);
3032 if (diaspora::is_reshare($body, false)===false) {
3036 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3037 // Skip if there is no shared message in there
3038 // we already checked this in diaspora::is_reshare()
3039 // but better one more than one less...
3040 if ($body == $attributes)
3044 // build the fake reshared item
3045 $reshared_item = $item;
3048 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3049 if ($matches[1] != "")
3050 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3052 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3053 if ($matches[1] != "")
3054 $author = $matches[1];
3057 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3058 if ($matches[1] != "")
3059 $profile = $matches[1];
3061 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3062 if ($matches[1] != "")
3063 $profile = $matches[1];
3066 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3067 if ($matches[1] != "")
3068 $avatar = $matches[1];
3070 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3071 if ($matches[1] != "")
3072 $avatar = $matches[1];
3075 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3076 if ($matches[1] != "")
3077 $link = $matches[1];
3079 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3080 if ($matches[1] != "")
3081 $link = $matches[1];
3084 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3085 if ($matches[1] != "")
3086 $posted= $matches[1];
3088 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3089 if ($matches[1] != "")
3090 $posted = $matches[1];
3092 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3094 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3099 $reshared_item["body"] = $shared_body;
3100 $reshared_item["author-name"] = $author;
3101 $reshared_item["author-link"] = $profile;
3102 $reshared_item["author-avatar"] = $avatar;
3103 $reshared_item["plink"] = $link;
3104 $reshared_item["created"] = $posted;
3105 $reshared_item["edited"] = $posted;
3107 return $reshared_item;
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);
3182 $URLSearchString = "^\[\]";
3184 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3186 if ($include_entities == "true") {
3187 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3190 // Simplify "attachment" element
3191 $Text = api_clean_attachments($Text);
3197 * @brief Removes most sharing information for API text export
3199 * @param string $body The original body
3201 * @return string Cleaned body
3203 function api_clean_attachments($body) {
3204 $data = get_attachment_data($body);
3211 if (isset($data["text"]))
3212 $body = $data["text"];
3214 if (($body == "") AND (isset($data["title"])))
3215 $body = $data["title"];
3217 if (isset($data["url"]))
3218 $body .= "\n".$data["url"];
3220 $body .= $data["after"];
3225 function api_best_nickname(&$contacts) {
3226 $best_contact = array();
3228 if (count($contact) == 0)
3231 foreach ($contacts AS $contact)
3232 if ($contact["network"] == "") {
3233 $contact["network"] = "dfrn";
3234 $best_contact = array($contact);
3237 if (sizeof($best_contact) == 0)
3238 foreach ($contacts AS $contact)
3239 if ($contact["network"] == "dfrn")
3240 $best_contact = array($contact);
3242 if (sizeof($best_contact) == 0)
3243 foreach ($contacts AS $contact)
3244 if ($contact["network"] == "dspr")
3245 $best_contact = array($contact);
3247 if (sizeof($best_contact) == 0)
3248 foreach ($contacts AS $contact)
3249 if ($contact["network"] == "stat")
3250 $best_contact = array($contact);
3252 if (sizeof($best_contact) == 0)
3253 foreach ($contacts AS $contact)
3254 if ($contact["network"] == "pump")
3255 $best_contact = array($contact);
3257 if (sizeof($best_contact) == 0)
3258 foreach ($contacts AS $contact)
3259 if ($contact["network"] == "twit")
3260 $best_contact = array($contact);
3262 if (sizeof($best_contact) == 1)
3263 $contacts = $best_contact;
3265 $contacts = array($contacts[0]);
3268 // return all or a specified group of the user with the containing contacts
3269 function api_friendica_group_show(&$a, $type) {
3270 if (api_user()===false) throw new ForbiddenException();
3273 $user_info = api_get_user($a);
3274 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3275 $uid = $user_info['uid'];
3277 // get data of the specified group id or all groups if not specified
3279 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3282 // error message if specified gid is not in database
3284 throw new BadRequestException("gid not available");
3287 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3290 // loop through all groups and retrieve all members for adding data in the user array
3291 foreach ($r as $rr) {
3292 $members = group_get_members($rr['id']);
3294 foreach ($members as $member) {
3295 $user = api_get_user($a, $member['nurl']);
3298 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3300 return api_apply_template("group_show", $type, array('groups' => $grps));
3302 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3305 // delete the specified group of the user
3306 function api_friendica_group_delete(&$a, $type) {
3307 if (api_user()===false) throw new ForbiddenException();
3310 $user_info = api_get_user($a);
3311 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3312 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3313 $uid = $user_info['uid'];
3315 // error if no gid specified
3316 if ($gid == 0 || $name == "")
3317 throw new BadRequestException('gid or name not specified');
3319 // get data of the specified group id
3320 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3323 // error message if specified gid is not in database
3325 throw new BadRequestException('gid not available');
3327 // get data of the specified group id and group name
3328 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3332 // error message if specified gid is not in database
3333 if (count($rname) == 0)
3334 throw new BadRequestException('wrong group name');
3337 $ret = group_rmv($uid, $name);
3340 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3341 return api_apply_template("group_delete", $type, array('result' => $success));
3344 throw new BadRequestException('other API error');
3346 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3349 // create the specified group with the posted array of contacts
3350 function api_friendica_group_create(&$a, $type) {
3351 if (api_user()===false) throw new ForbiddenException();
3354 $user_info = api_get_user($a);
3355 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3356 $uid = $user_info['uid'];
3357 $json = json_decode($_POST['json'], true);
3358 $users = $json['user'];
3360 // error if no name specified
3362 throw new BadRequestException('group name not specified');
3364 // get data of the specified group name
3365 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3368 // error message if specified group name already exists
3369 if (count($rname) != 0)
3370 throw new BadRequestException('group name already exists');
3372 // check if specified group name is a deleted group
3373 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3376 // error message if specified group name already exists
3377 if (count($rname) != 0)
3378 $reactivate_group = true;
3381 $ret = group_add($uid, $name);
3383 $gid = group_byname($uid, $name);
3385 throw new BadRequestException('other API error');
3388 $erroraddinguser = false;
3389 $errorusers = array();
3390 foreach ($users as $user) {
3391 $cid = $user['cid'];
3392 // check if user really exists as contact
3393 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3396 if (count($contact))
3397 $result = group_add_member($uid, $name, $cid, $gid);
3399 $erroraddinguser = true;
3400 $errorusers[] = $cid;
3404 // return success message incl. missing users in array
3405 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3406 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3407 return api_apply_template("group_create", $type, array('result' => $success));
3409 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3412 // update the specified group with the posted array of contacts
3413 function api_friendica_group_update(&$a, $type) {
3414 if (api_user()===false) throw new ForbiddenException();
3417 $user_info = api_get_user($a);
3418 $uid = $user_info['uid'];
3419 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3420 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3421 $json = json_decode($_POST['json'], true);
3422 $users = $json['user'];
3424 // error if no name specified
3426 throw new BadRequestException('group name not specified');
3428 // error if no gid specified
3430 throw new BadRequestException('gid not specified');
3433 $members = group_get_members($gid);
3434 foreach ($members as $member) {
3435 $cid = $member['id'];
3436 foreach ($users as $user) {
3437 $found = ($user['cid'] == $cid ? true : false);
3440 $ret = group_rmv_member($uid, $name, $cid);
3445 $erroraddinguser = false;
3446 $errorusers = array();
3447 foreach ($users as $user) {
3448 $cid = $user['cid'];
3449 // check if user really exists as contact
3450 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3453 if (count($contact))
3454 $result = group_add_member($uid, $name, $cid, $gid);
3456 $erroraddinguser = true;
3457 $errorusers[] = $cid;
3461 // return success message incl. missing users in array
3462 $status = ($erroraddinguser ? "missing user" : "ok");
3463 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3464 return api_apply_template("group_update", $type, array('result' => $success));
3466 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3469 function api_friendica_activity(&$a, $type) {
3470 if (api_user()===false) throw new ForbiddenException();
3471 $verb = strtolower($a->argv[3]);
3472 $verb = preg_replace("|\..*$|", "", $verb);
3474 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3476 $res = do_like($id, $verb);
3483 return api_apply_template('test', $type, array('ok' => $ok));
3485 throw new BadRequestException('Error adding activity');
3489 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3490 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3491 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3492 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3493 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3494 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3495 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3496 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3497 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3498 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3501 * @brief Returns notifications
3504 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3507 function api_friendica_notification(&$a, $type) {
3508 if (api_user()===false) throw new ForbiddenException();
3509 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3510 $nm = new NotificationsManager();
3512 $notes = $nm->getAll(array(), "+seen -date", 50);
3514 if ($type == "xml") {
3515 $xmlnotes = array();
3516 foreach ($notes AS $note)
3517 $xmlnotes[] = array("@attributes" => $note);
3522 return api_apply_template("notes", $type, array('note' => $notes));
3526 * @brief Set notification as seen and returns associated item (if possible)
3528 * POST request with 'id' param as notification id
3531 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3534 function api_friendica_notification_seen(&$a, $type){
3535 if (api_user()===false) throw new ForbiddenException();
3536 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3538 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3540 $nm = new NotificationsManager();
3541 $note = $nm->getByID($id);
3542 if (is_null($note)) throw new BadRequestException("Invalid argument");
3544 $nm->setSeen($note);
3545 if ($note['otype']=='item') {
3546 // would be really better with an ItemsManager and $im->getByID() :-P
3547 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3548 intval($note['iid']),
3549 intval(local_user())
3552 // we found the item, return it to the user
3553 $user_info = api_get_user($a);
3554 $ret = api_format_items($r,$user_info);
3555 $data = array('statuses' => $ret);
3556 return api_apply_template("timeline", $type, $data);
3558 // the item can't be found, but we set the note as seen, so we count this as a success
3560 return api_apply_template('<auto>', $type, array('status' => "success"));
3563 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3564 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3569 [pagename] => api/1.1/statuses/lookup.json
3570 [id] => 605138389168451584
3571 [include_cards] => true
3572 [cards_platform] => Android-12
3573 [include_entities] => true
3574 [include_my_retweet] => 1
3576 [include_reply_count] => true
3577 [include_descendent_reply_count] => true
3581 Not implemented by now:
3582 statuses/retweets_of_me
3587 account/update_location
3588 account/update_profile_background_image
3589 account/update_profile_image
3593 Not implemented in status.net:
3594 statuses/retweeted_to_me
3595 statuses/retweeted_by_me
3596 direct_messages/destroy
3598 account/update_delivery_device
3599 notifications/follow