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, $templatename) {
771 $data2 = array_pop($data);
774 $namespaces = array("statusnet" => "http://status.net/schema/api/1/",
775 "friendica" => "http://friendi.ca/schema/api/1/");
777 if ($templatename == "test") {
778 $namespaces = array();
779 $templatename = "ok";
782 if ($templatename == "ratelimit") {
783 $namespaces = array();
784 $templatename = "hash";
787 if (is_array($data2))
788 api_walk_recursive($data2, "api_reformat_xml");
794 if ($templatename == "friends") {
796 $parentname = "users";
797 } elseif ($templatename == "direct_messages") {
798 $childname = "direct_message";
799 $parentname = "direct-messages";
801 $childname = "status";
802 $parentname = "statuses";
805 foreach ($data2 AS $item)
806 $data4[$i++.":".$childname] = $item;
808 $data3 = array($parentname => $data4);
810 $data3 = array($templatename => $data2);
812 $ret = xml::from_array($data3, $xml, false, $namespaces);
818 * load api $templatename for $type and replace $data array
820 function api_apply_template($templatename, $type, $data){
828 $ret = api_create_xml($data, $templatename);
831 $data = array_xmlify($data);
832 if ($templatename==="<auto>") {
833 $ret = api_array_to_xml($data);
835 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
837 header ("Content-Type: text/xml");
838 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
841 $ret = replace_macros($tpl, $data);
857 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
858 * returns a 401 status code and an error message if not.
859 * http://developer.twitter.com/doc/get/account/verify_credentials
861 function api_account_verify_credentials(&$a, $type){
862 if (api_user()===false) throw new ForbiddenException();
864 unset($_REQUEST["user_id"]);
865 unset($_GET["user_id"]);
867 unset($_REQUEST["screen_name"]);
868 unset($_GET["screen_name"]);
870 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
872 $user_info = api_get_user($a);
874 // "verified" isn't used here in the standard
875 unset($user_info["verified"]);
877 // - Adding last status
879 $user_info["status"] = api_status_show($a,"raw");
880 if (!count($user_info["status"]))
881 unset($user_info["status"]);
883 unset($user_info["status"]["user"]);
886 // "uid" and "self" are only needed for some internal stuff, so remove it from here
887 unset($user_info["uid"]);
888 unset($user_info["self"]);
890 return api_apply_template("user", $type, array('$user' => $user_info));
893 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
897 * get data from $_POST or $_GET
899 function requestdata($k){
900 if (isset($_POST[$k])){
903 if (isset($_GET[$k])){
909 /*Waitman Gobble Mod*/
910 function api_statuses_mediap(&$a, $type) {
911 if (api_user()===false) {
912 logger('api_statuses_update: no user');
913 throw new ForbiddenException();
915 $user_info = api_get_user($a);
917 $_REQUEST['type'] = 'wall';
918 $_REQUEST['profile_uid'] = api_user();
919 $_REQUEST['api_source'] = true;
920 $txt = requestdata('status');
921 //$txt = urldecode(requestdata('status'));
923 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
925 $txt = html2bb_video($txt);
926 $config = HTMLPurifier_Config::createDefault();
927 $config->set('Cache.DefinitionImpl', null);
928 $purifier = new HTMLPurifier($config);
929 $txt = $purifier->purify($txt);
931 $txt = html2bbcode($txt);
933 $a->argv[1]=$user_info['screen_name']; //should be set to username?
935 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
936 $bebop = wall_upload_post($a);
938 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
939 $_REQUEST['body']=$txt."\n\n".$bebop;
942 // this should output the last post (the one we just posted).
943 return api_status_show($a,$type);
945 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
946 /*Waitman Gobble Mod*/
949 function api_statuses_update(&$a, $type) {
950 if (api_user()===false) {
951 logger('api_statuses_update: no user');
952 throw new ForbiddenException();
955 $user_info = api_get_user($a);
957 // convert $_POST array items to the form we use for web posts.
959 // logger('api_post: ' . print_r($_POST,true));
961 if(requestdata('htmlstatus')) {
962 $txt = requestdata('htmlstatus');
963 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
964 $txt = html2bb_video($txt);
966 $config = HTMLPurifier_Config::createDefault();
967 $config->set('Cache.DefinitionImpl', null);
969 $purifier = new HTMLPurifier($config);
970 $txt = $purifier->purify($txt);
972 $_REQUEST['body'] = html2bbcode($txt);
976 $_REQUEST['body'] = requestdata('status');
978 $_REQUEST['title'] = requestdata('title');
980 $parent = requestdata('in_reply_to_status_id');
982 // Twidere sends "-1" if it is no reply ...
986 if(ctype_digit($parent))
987 $_REQUEST['parent'] = $parent;
989 $_REQUEST['parent_uri'] = $parent;
991 if(requestdata('lat') && requestdata('long'))
992 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
993 $_REQUEST['profile_uid'] = api_user();
996 $_REQUEST['type'] = 'net-comment';
998 // Check for throttling (maximum posts per day, week and month)
999 $throttle_day = get_config('system','throttle_limit_day');
1000 if ($throttle_day > 0) {
1001 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1003 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1004 AND `created` > '%s' AND `id` = `parent`",
1005 intval(api_user()), dbesc($datefrom));
1008 $posts_day = $r[0]["posts_day"];
1012 if ($posts_day > $throttle_day) {
1013 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1014 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1015 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1019 $throttle_week = get_config('system','throttle_limit_week');
1020 if ($throttle_week > 0) {
1021 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1023 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1024 AND `created` > '%s' AND `id` = `parent`",
1025 intval(api_user()), dbesc($datefrom));
1028 $posts_week = $r[0]["posts_week"];
1032 if ($posts_week > $throttle_week) {
1033 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1034 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1035 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1040 $throttle_month = get_config('system','throttle_limit_month');
1041 if ($throttle_month > 0) {
1042 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1044 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1045 AND `created` > '%s' AND `id` = `parent`",
1046 intval(api_user()), dbesc($datefrom));
1049 $posts_month = $r[0]["posts_month"];
1053 if ($posts_month > $throttle_month) {
1054 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1055 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1056 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1060 $_REQUEST['type'] = 'wall';
1063 if(x($_FILES,'media')) {
1064 // upload the image if we have one
1065 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1066 $media = wall_upload_post($a);
1067 if(strlen($media)>0)
1068 $_REQUEST['body'] .= "\n\n".$media;
1071 // To-Do: Multiple IDs
1072 if (requestdata('media_ids')) {
1073 $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",
1074 intval(requestdata('media_ids')), api_user());
1076 $phototypes = Photo::supportedTypes();
1077 $ext = $phototypes[$r[0]['type']];
1078 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1079 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1083 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1085 $_REQUEST['api_source'] = true;
1087 if (!x($_REQUEST, "source"))
1088 $_REQUEST["source"] = api_source();
1090 // call out normal post function
1094 // this should output the last post (the one we just posted).
1095 return api_status_show($a,$type);
1097 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1098 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1101 function api_media_upload(&$a, $type) {
1102 if (api_user()===false) {
1104 throw new ForbiddenException();
1107 $user_info = api_get_user($a);
1109 if(!x($_FILES,'media')) {
1111 throw new BadRequestException("No media.");
1114 $media = wall_upload_post($a, false);
1117 throw new InternalServerErrorException();
1120 $returndata = array();
1121 $returndata["media_id"] = $media["id"];
1122 $returndata["media_id_string"] = (string)$media["id"];
1123 $returndata["size"] = $media["size"];
1124 $returndata["image"] = array("w" => $media["width"],
1125 "h" => $media["height"],
1126 "image_type" => $media["type"]);
1128 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1130 return array("media" => $returndata);
1132 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1134 function api_status_show(&$a, $type){
1135 $user_info = api_get_user($a);
1137 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1140 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1144 // get last public wall message
1145 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1146 FROM `item`, `item` as `i`
1147 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1148 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1149 AND `i`.`id` = `item`.`parent`
1150 AND `item`.`type`!='activity' $privacy_sql
1151 ORDER BY `item`.`created` DESC
1153 intval($user_info['cid']),
1155 dbesc($user_info['url']),
1156 dbesc(normalise_link($user_info['url'])),
1157 dbesc($user_info['url']),
1158 dbesc(normalise_link($user_info['url']))
1161 if (count($lastwall)>0){
1162 $lastwall = $lastwall[0];
1164 $in_reply_to_status_id = NULL;
1165 $in_reply_to_user_id = NULL;
1166 $in_reply_to_status_id_str = NULL;
1167 $in_reply_to_user_id_str = NULL;
1168 $in_reply_to_screen_name = NULL;
1169 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1170 $in_reply_to_status_id= intval($lastwall['parent']);
1171 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1173 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1175 if ($r[0]['nick'] == "")
1176 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1178 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1179 $in_reply_to_user_id = intval($r[0]['id']);
1180 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1184 // There seems to be situation, where both fields are identical:
1185 // https://github.com/friendica/friendica/issues/1010
1186 // This is a bugfix for that.
1187 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1188 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1189 $in_reply_to_status_id = NULL;
1190 $in_reply_to_user_id = NULL;
1191 $in_reply_to_status_id_str = NULL;
1192 $in_reply_to_user_id_str = NULL;
1193 $in_reply_to_screen_name = NULL;
1196 $converted = api_convert_item($lastwall);
1198 $status_info = array(
1199 'created_at' => api_date($lastwall['created']),
1200 'id' => intval($lastwall['id']),
1201 'id_str' => (string) $lastwall['id'],
1202 'text' => $converted["text"],
1203 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1204 'truncated' => false,
1205 'in_reply_to_status_id' => $in_reply_to_status_id,
1206 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1207 'in_reply_to_user_id' => $in_reply_to_user_id,
1208 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1209 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1210 'user' => $user_info,
1212 'coordinates' => "",
1214 'contributors' => "",
1215 'is_quote_status' => false,
1216 'retweet_count' => 0,
1217 'favorite_count' => 0,
1218 'favorited' => $lastwall['starred'] ? true : false,
1219 'retweeted' => false,
1220 'possibly_sensitive' => false,
1222 'statusnet_html' => $converted["html"],
1223 'statusnet_conversation_id' => $lastwall['parent'],
1226 if (count($converted["attachments"]) > 0)
1227 $status_info["attachments"] = $converted["attachments"];
1229 if (count($converted["entities"]) > 0)
1230 $status_info["entities"] = $converted["entities"];
1232 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1233 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1234 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1235 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1237 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1238 unset($status_info["user"]["uid"]);
1239 unset($status_info["user"]["self"]);
1242 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1245 return($status_info);
1247 return api_apply_template("status", $type, array('$status' => $status_info));
1256 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1257 * The author's most recent status will be returned inline.
1258 * http://developer.twitter.com/doc/get/users/show
1260 function api_users_show(&$a, $type){
1261 $user_info = api_get_user($a);
1263 $lastwall = q("SELECT `item`.*
1264 FROM `item`, `contact`
1265 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1266 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1267 AND `contact`.`id`=`item`.`contact-id`
1268 AND `type`!='activity'
1269 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1270 ORDER BY `created` DESC
1273 dbesc(ACTIVITY_POST),
1274 intval($user_info['cid']),
1275 dbesc($user_info['url']),
1276 dbesc(normalise_link($user_info['url'])),
1277 dbesc($user_info['url']),
1278 dbesc(normalise_link($user_info['url']))
1280 if (count($lastwall)>0){
1281 $lastwall = $lastwall[0];
1283 $in_reply_to_status_id = NULL;
1284 $in_reply_to_user_id = NULL;
1285 $in_reply_to_status_id_str = NULL;
1286 $in_reply_to_user_id_str = NULL;
1287 $in_reply_to_screen_name = NULL;
1288 if ($lastwall['parent']!=$lastwall['id']) {
1289 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1290 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1291 if (count($reply)>0) {
1292 $in_reply_to_status_id = intval($lastwall['parent']);
1293 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1295 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1297 if ($r[0]['nick'] == "")
1298 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1300 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1301 $in_reply_to_user_id = intval($r[0]['id']);
1302 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1307 $converted = api_convert_item($lastwall);
1309 $user_info['status'] = array(
1310 'text' => $converted["text"],
1311 'truncated' => false,
1312 'created_at' => api_date($lastwall['created']),
1313 'in_reply_to_status_id' => $in_reply_to_status_id,
1314 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1315 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1316 'id' => intval($lastwall['contact-id']),
1317 'id_str' => (string) $lastwall['contact-id'],
1318 'in_reply_to_user_id' => $in_reply_to_user_id,
1319 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1320 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1322 'favorited' => $lastwall['starred'] ? true : false,
1323 'statusnet_html' => $converted["html"],
1324 'statusnet_conversation_id' => $lastwall['parent'],
1327 if (count($converted["attachments"]) > 0)
1328 $user_info["status"]["attachments"] = $converted["attachments"];
1330 if (count($converted["entities"]) > 0)
1331 $user_info["status"]["entities"] = $converted["entities"];
1333 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1334 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1335 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1336 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1340 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1341 unset($user_info["uid"]);
1342 unset($user_info["self"]);
1344 return api_apply_template("user", $type, array('$user' => $user_info));
1347 api_register_func('api/users/show','api_users_show');
1350 function api_users_search(&$a, $type) {
1351 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1353 $userlist = array();
1355 if (isset($_GET["q"])) {
1356 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1358 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1361 foreach ($r AS $user) {
1362 $user_info = api_get_user($a, $user["id"]);
1363 //echo print_r($user_info, true)."\n";
1364 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1365 $userlist[] = $userdata["user"];
1367 $userlist = array("users" => $userlist);
1369 throw new BadRequestException("User not found.");
1372 throw new BadRequestException("User not found.");
1377 api_register_func('api/users/search','api_users_search');
1381 * http://developer.twitter.com/doc/get/statuses/home_timeline
1383 * TODO: Optional parameters
1384 * TODO: Add reply info
1386 function api_statuses_home_timeline(&$a, $type){
1387 if (api_user()===false) throw new ForbiddenException();
1389 unset($_REQUEST["user_id"]);
1390 unset($_GET["user_id"]);
1392 unset($_REQUEST["screen_name"]);
1393 unset($_GET["screen_name"]);
1395 $user_info = api_get_user($a);
1396 // get last newtork messages
1400 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1401 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1402 if ($page<0) $page=0;
1403 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1404 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1405 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1406 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1407 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1409 $start = $page*$count;
1413 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1414 if ($exclude_replies > 0)
1415 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1416 if ($conversation_id > 0)
1417 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1419 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1420 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1421 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1422 `contact`.`id` AS `cid`
1423 FROM `item`, `contact`
1424 WHERE `item`.`uid` = %d AND `verb` = '%s'
1425 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1426 AND `contact`.`id` = `item`.`contact-id`
1427 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1430 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1432 dbesc(ACTIVITY_POST),
1434 intval($start), intval($count)
1437 $ret = api_format_items($r,$user_info);
1439 // Set all posts from the query above to seen
1441 foreach ($r AS $item)
1442 $idarray[] = intval($item["id"]);
1444 $idlist = implode(",", $idarray);
1446 if ($idlist != "") {
1447 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1450 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1453 $data = array('$statuses' => $ret);
1457 $data = api_rss_extra($a, $data, $user_info);
1461 return api_apply_template("timeline", $type, $data);
1463 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1464 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1466 function api_statuses_public_timeline(&$a, $type){
1467 if (api_user()===false) throw new ForbiddenException();
1469 $user_info = api_get_user($a);
1470 // get last newtork messages
1474 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1475 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1476 if ($page<0) $page=0;
1477 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1478 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1479 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1480 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1481 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1483 $start = $page*$count;
1486 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1487 if ($exclude_replies > 0)
1488 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1489 if ($conversation_id > 0)
1490 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1492 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1493 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1494 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1495 `contact`.`id` AS `cid`,
1496 `user`.`nickname`, `user`.`hidewall`
1497 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1498 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1499 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1500 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1501 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1502 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1503 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1506 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1507 dbesc(ACTIVITY_POST),
1512 $ret = api_format_items($r,$user_info);
1515 $data = array('$statuses' => $ret);
1519 $data = api_rss_extra($a, $data, $user_info);
1523 return api_apply_template("timeline", $type, $data);
1525 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1530 function api_statuses_show(&$a, $type){
1531 if (api_user()===false) throw new ForbiddenException();
1533 $user_info = api_get_user($a);
1536 $id = intval($a->argv[3]);
1539 $id = intval($_REQUEST["id"]);
1543 $id = intval($a->argv[4]);
1545 logger('API: api_statuses_show: '.$id);
1547 $conversation = (x($_REQUEST,'conversation')?1:0);
1551 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1553 $sql_extra .= " AND `item`.`id` = %d";
1555 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1556 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1557 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1558 `contact`.`id` AS `cid`
1559 FROM `item`, `contact`
1560 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1561 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1562 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1565 dbesc(ACTIVITY_POST),
1570 throw new BadRequestException("There is no status with this id.");
1573 $ret = api_format_items($r,$user_info);
1575 if ($conversation) {
1576 $data = array('$statuses' => $ret);
1577 return api_apply_template("timeline", $type, $data);
1579 $data = array('$status' => $ret[0]);
1583 $data = api_rss_extra($a, $data, $user_info);
1585 return api_apply_template("status", $type, $data);
1588 api_register_func('api/statuses/show','api_statuses_show', true);
1594 function api_conversation_show(&$a, $type){
1595 if (api_user()===false) throw new ForbiddenException();
1597 $user_info = api_get_user($a);
1600 $id = intval($a->argv[3]);
1601 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1602 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1603 if ($page<0) $page=0;
1604 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1605 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1607 $start = $page*$count;
1610 $id = intval($_REQUEST["id"]);
1614 $id = intval($a->argv[4]);
1616 logger('API: api_conversation_show: '.$id);
1618 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1620 $id = $r[0]["parent"];
1625 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1627 // Not sure why this query was so complicated. We should keep it here for a while,
1628 // just to make sure that we really don't need it.
1629 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1630 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1632 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1633 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1634 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1635 `contact`.`id` AS `cid`
1637 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1638 WHERE `item`.`parent` = %d AND `item`.`visible`
1639 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1640 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1641 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1642 AND `item`.`id`>%d $sql_extra
1643 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1644 intval($id), intval(api_user()),
1645 dbesc(ACTIVITY_POST),
1647 intval($start), intval($count)
1651 throw new BadRequestException("There is no conversation with this id.");
1653 $ret = api_format_items($r,$user_info);
1655 $data = array('$statuses' => $ret);
1656 return api_apply_template("timeline", $type, $data);
1658 api_register_func('api/conversation/show','api_conversation_show', true);
1659 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1665 function api_statuses_repeat(&$a, $type){
1668 if (api_user()===false) throw new ForbiddenException();
1670 $user_info = api_get_user($a);
1673 $id = intval($a->argv[3]);
1676 $id = intval($_REQUEST["id"]);
1680 $id = intval($a->argv[4]);
1682 logger('API: api_statuses_repeat: '.$id);
1684 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1685 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1686 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1687 `contact`.`id` AS `cid`
1688 FROM `item`, `contact`
1689 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1690 AND `contact`.`id` = `item`.`contact-id`
1691 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1692 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1693 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1695 AND `item`.`id`=%d",
1699 if ($r[0]['body'] != "") {
1700 if (!intval(get_config('system','old_share'))) {
1701 if (strpos($r[0]['body'], "[/share]") !== false) {
1702 $pos = strpos($r[0]['body'], "[share");
1703 $post = substr($r[0]['body'], $pos);
1705 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1707 $post .= $r[0]['body'];
1708 $post .= "[/share]";
1710 $_REQUEST['body'] = $post;
1712 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1714 $_REQUEST['profile_uid'] = api_user();
1715 $_REQUEST['type'] = 'wall';
1716 $_REQUEST['api_source'] = true;
1718 if (!x($_REQUEST, "source"))
1719 $_REQUEST["source"] = api_source();
1723 throw new ForbiddenException();
1725 // this should output the last post (the one we just posted).
1727 return(api_status_show($a,$type));
1729 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1734 function api_statuses_destroy(&$a, $type){
1735 if (api_user()===false) throw new ForbiddenException();
1737 $user_info = api_get_user($a);
1740 $id = intval($a->argv[3]);
1743 $id = intval($_REQUEST["id"]);
1747 $id = intval($a->argv[4]);
1749 logger('API: api_statuses_destroy: '.$id);
1751 $ret = api_statuses_show($a, $type);
1753 drop_item($id, false);
1757 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1761 * http://developer.twitter.com/doc/get/statuses/mentions
1764 function api_statuses_mentions(&$a, $type){
1765 if (api_user()===false) throw new ForbiddenException();
1767 unset($_REQUEST["user_id"]);
1768 unset($_GET["user_id"]);
1770 unset($_REQUEST["screen_name"]);
1771 unset($_GET["screen_name"]);
1773 $user_info = api_get_user($a);
1774 // get last newtork messages
1778 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1779 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1780 if ($page<0) $page=0;
1781 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1782 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1783 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1785 $start = $page*$count;
1787 // Ugly code - should be changed
1788 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1789 $myurl = substr($myurl,strpos($myurl,'://')+3);
1790 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1791 $myurl = str_replace('www.','',$myurl);
1792 $diasp_url = str_replace('/profile/','/u/',$myurl);
1795 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1797 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1798 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1799 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1800 `contact`.`id` AS `cid`
1801 FROM `item` FORCE INDEX (`uid_id`), `contact`
1802 WHERE `item`.`uid` = %d AND `verb` = '%s'
1803 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1804 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1805 AND `contact`.`id` = `item`.`contact-id`
1806 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1807 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1810 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1812 dbesc(ACTIVITY_POST),
1813 dbesc(protect_sprintf($myurl)),
1814 dbesc(protect_sprintf($myurl)),
1817 intval($start), intval($count)
1820 $ret = api_format_items($r,$user_info);
1823 $data = array('$statuses' => $ret);
1827 $data = api_rss_extra($a, $data, $user_info);
1831 return api_apply_template("timeline", $type, $data);
1833 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1834 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1837 function api_statuses_user_timeline(&$a, $type){
1838 if (api_user()===false) throw new ForbiddenException();
1840 $user_info = api_get_user($a);
1841 // get last network messages
1843 logger("api_statuses_user_timeline: api_user: ". api_user() .
1844 "\nuser_info: ".print_r($user_info, true) .
1845 "\n_REQUEST: ".print_r($_REQUEST, true),
1849 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1850 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1851 if ($page<0) $page=0;
1852 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1853 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1854 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1855 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1857 $start = $page*$count;
1860 if ($user_info['self']==1)
1861 $sql_extra .= " AND `item`.`wall` = 1 ";
1863 if ($exclude_replies > 0)
1864 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1865 if ($conversation_id > 0)
1866 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1868 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1869 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1870 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1871 `contact`.`id` AS `cid`
1873 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1874 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1875 WHERE `item`.`uid` = %d AND `verb` = '%s'
1876 AND `item`.`contact-id` = %d
1877 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1880 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1882 dbesc(ACTIVITY_POST),
1883 intval($user_info['cid']),
1885 intval($start), intval($count)
1888 $ret = api_format_items($r,$user_info, true);
1890 $data = array('$statuses' => $ret);
1894 $data = api_rss_extra($a, $data, $user_info);
1897 return api_apply_template("timeline", $type, $data);
1899 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1903 * Star/unstar an item
1904 * param: id : id of the item
1906 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1908 function api_favorites_create_destroy(&$a, $type){
1909 if (api_user()===false) throw new ForbiddenException();
1911 // for versioned api.
1912 /// @TODO We need a better global soluton
1914 if ($a->argv[1]=="1.1") $action_argv_id=3;
1916 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1917 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1918 if ($a->argc==$action_argv_id+2) {
1919 $itemid = intval($a->argv[$action_argv_id+1]);
1921 $itemid = intval($_REQUEST['id']);
1924 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1925 $itemid, api_user());
1927 if ($item===false || count($item)==0)
1928 throw new BadRequestException("Invalid item.");
1932 $item[0]['starred']=1;
1935 $item[0]['starred']=0;
1938 throw new BadRequestException("Invalid action ".$action);
1940 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1941 $item[0]['starred'], $itemid, api_user());
1943 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1944 $item[0]['starred'], $itemid, api_user());
1947 throw InternalServerErrorException("DB error");
1950 $user_info = api_get_user($a);
1951 $rets = api_format_items($item,$user_info);
1954 $data = array('$status' => $ret);
1958 $data = api_rss_extra($a, $data, $user_info);
1961 return api_apply_template("status", $type, $data);
1963 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1964 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1966 function api_favorites(&$a, $type){
1969 if (api_user()===false) throw new ForbiddenException();
1971 $called_api= array();
1973 $user_info = api_get_user($a);
1975 // in friendica starred item are private
1976 // return favorites only for self
1977 logger('api_favorites: self:' . $user_info['self']);
1979 if ($user_info['self']==0) {
1985 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1986 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1987 $count = (x($_GET,'count')?$_GET['count']:20);
1988 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1989 if ($page<0) $page=0;
1991 $start = $page*$count;
1994 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1996 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1997 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1998 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1999 `contact`.`id` AS `cid`
2000 FROM `item`, `contact`
2001 WHERE `item`.`uid` = %d
2002 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2003 AND `item`.`starred` = 1
2004 AND `contact`.`id` = `item`.`contact-id`
2005 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
2008 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2011 intval($start), intval($count)
2014 $ret = api_format_items($r,$user_info);
2018 $data = array('$statuses' => $ret);
2022 $data = api_rss_extra($a, $data, $user_info);
2025 return api_apply_template("timeline", $type, $data);
2027 api_register_func('api/favorites','api_favorites', true);
2029 function api_format_messages($item, $recipient, $sender) {
2030 // standard meta information
2032 'id' => $item['id'],
2033 'sender_id' => $sender['id'] ,
2035 'recipient_id' => $recipient['id'],
2036 'created_at' => api_date($item['created']),
2037 'sender_screen_name' => $sender['screen_name'],
2038 'recipient_screen_name' => $recipient['screen_name'],
2039 'sender' => $sender,
2040 'recipient' => $recipient,
2043 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2044 unset($ret["sender"]["uid"]);
2045 unset($ret["sender"]["self"]);
2046 unset($ret["recipient"]["uid"]);
2047 unset($ret["recipient"]["self"]);
2049 //don't send title to regular StatusNET requests to avoid confusing these apps
2050 if (x($_GET, 'getText')) {
2051 $ret['title'] = $item['title'] ;
2052 if ($_GET["getText"] == "html") {
2053 $ret['text'] = bbcode($item['body'], false, false);
2055 elseif ($_GET["getText"] == "plain") {
2056 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2057 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2061 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2063 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2064 unset($ret['sender']);
2065 unset($ret['recipient']);
2071 function api_convert_item($item) {
2072 $body = $item['body'];
2073 $attachments = api_get_attachments($body);
2075 // Workaround for ostatus messages where the title is identically to the body
2076 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2077 $statusbody = trim(html2plain($html, 0));
2079 // handle data: images
2080 $statusbody = api_format_items_embeded_images($item,$statusbody);
2082 $statustitle = trim($item['title']);
2084 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2085 $statustext = trim($statusbody);
2087 $statustext = trim($statustitle."\n\n".$statusbody);
2089 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2090 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2092 $statushtml = trim(bbcode($body, false, false));
2094 $search = array("<br>", "<blockquote>", "</blockquote>",
2095 "<h1>", "</h1>", "<h2>", "</h2>",
2096 "<h3>", "</h3>", "<h4>", "</h4>",
2097 "<h5>", "</h5>", "<h6>", "</h6>");
2098 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2099 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2100 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2101 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2102 $statushtml = str_replace($search, $replace, $statushtml);
2104 if ($item['title'] != "")
2105 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2107 $entities = api_get_entitities($statustext, $body);
2110 "text" => $statustext,
2111 "html" => $statushtml,
2112 "attachments" => $attachments,
2113 "entities" => $entities
2117 function api_get_attachments(&$body) {
2120 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2122 $URLSearchString = "^\[\]";
2123 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2128 $attachments = array();
2130 foreach ($images[1] AS $image) {
2131 $imagedata = get_photo_info($image);
2134 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2137 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2138 foreach ($images[0] AS $orig)
2139 $body = str_replace($orig, "", $body);
2141 return $attachments;
2144 function api_get_entitities(&$text, $bbcode) {
2147 * Links at the first character of the post
2152 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2154 if ($include_entities != "true") {
2156 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2158 foreach ($images[1] AS $image) {
2159 $replace = proxy_url($image);
2160 $text = str_replace($image, $replace, $text);
2165 $bbcode = bb_CleanPictureLinks($bbcode);
2167 // Change pure links in text to bbcode uris
2168 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2170 $entities = array();
2171 $entities["hashtags"] = array();
2172 $entities["symbols"] = array();
2173 $entities["urls"] = array();
2174 $entities["user_mentions"] = array();
2176 $URLSearchString = "^\[\]";
2178 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2180 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2181 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2182 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2184 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2185 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2186 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2188 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2189 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2190 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2192 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2194 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2195 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2197 $ordered_urls = array();
2198 foreach ($urls[1] AS $id=>$url) {
2199 //$start = strpos($text, $url, $offset);
2200 $start = iconv_strpos($text, $url, 0, "UTF-8");
2201 if (!($start === false))
2202 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2205 ksort($ordered_urls);
2208 //foreach ($urls[1] AS $id=>$url) {
2209 foreach ($ordered_urls AS $url) {
2210 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2211 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2212 $display_url = $url["title"];
2214 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2215 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2217 if (strlen($display_url) > 26)
2218 $display_url = substr($display_url, 0, 25)."…";
2221 //$start = strpos($text, $url, $offset);
2222 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2223 if (!($start === false)) {
2224 $entities["urls"][] = array("url" => $url["url"],
2225 "expanded_url" => $url["url"],
2226 "display_url" => $display_url,
2227 "indices" => array($start, $start+strlen($url["url"])));
2228 $offset = $start + 1;
2232 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2233 $ordered_images = array();
2234 foreach ($images[1] AS $image) {
2235 //$start = strpos($text, $url, $offset);
2236 $start = iconv_strpos($text, $image, 0, "UTF-8");
2237 if (!($start === false))
2238 $ordered_images[$start] = $image;
2240 //$entities["media"] = array();
2243 foreach ($ordered_images AS $url) {
2244 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2245 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2247 if (strlen($display_url) > 26)
2248 $display_url = substr($display_url, 0, 25)."…";
2250 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2251 if (!($start === false)) {
2252 $image = get_photo_info($url);
2254 // If image cache is activated, then use the following sizes:
2255 // thumb (150), small (340), medium (600) and large (1024)
2256 if (!get_config("system", "proxy_disabled")) {
2257 $media_url = proxy_url($url);
2260 $scale = scale_image($image[0], $image[1], 150);
2261 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2263 if (($image[0] > 150) OR ($image[1] > 150)) {
2264 $scale = scale_image($image[0], $image[1], 340);
2265 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2268 $scale = scale_image($image[0], $image[1], 600);
2269 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2271 if (($image[0] > 600) OR ($image[1] > 600)) {
2272 $scale = scale_image($image[0], $image[1], 1024);
2273 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2277 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2280 $entities["media"][] = array(
2282 "id_str" => (string)$start+1,
2283 "indices" => array($start, $start+strlen($url)),
2284 "media_url" => normalise_link($media_url),
2285 "media_url_https" => $media_url,
2287 "display_url" => $display_url,
2288 "expanded_url" => $url,
2292 $offset = $start + 1;
2298 function api_format_items_embeded_images(&$item, $text){
2300 $text = preg_replace_callback(
2301 "|data:image/([^;]+)[^=]+=*|m",
2302 function($match) use ($a, $item) {
2303 return $a->get_baseurl()."/display/".$item['guid'];
2311 * @brief return <a href='url'>name</a> as array
2313 * @param string $txt
2318 function api_contactlink_to_array($txt) {
2320 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2321 if ($r && count($match)==3) {
2323 'name' => $match[2],
2337 * @brief return likes, dislikes and attend status for item
2339 * @param array $item
2341 * likes => int count
2342 * dislikes => int count
2344 function api_format_items_activities(&$item) {
2345 $activities = array(
2347 'dislike' => array(),
2348 'attendyes' => array(),
2349 'attendno' => array(),
2350 'attendmaybe' => array()
2352 $items = q('SELECT * FROM item
2353 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2354 intval($item['uid']),
2355 dbesc($item['uri']));
2356 foreach ($items as $i){
2357 builtin_activity_puller($i, $activities);
2361 $uri = $item['uri']."-l";
2362 foreach($activities as $k => $v) {
2363 $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2370 * @brief format items to be returned by api
2372 * @param array $r array of items
2373 * @param array $user_info
2374 * @param bool $filter_user filter items by $user_info
2376 function api_format_items($r,$user_info, $filter_user = false) {
2381 foreach($r as $item) {
2383 localize_item($item);
2384 list($status_user, $owner_user) = api_item_get_user($a,$item);
2386 // Look if the posts are matching if they should be filtered by user id
2387 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2390 if ($item['thr-parent'] != $item['uri']) {
2391 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2393 dbesc($item['thr-parent']));
2395 $in_reply_to_status_id = intval($r[0]['id']);
2397 $in_reply_to_status_id = intval($item['parent']);
2399 $in_reply_to_status_id_str = (string) intval($item['parent']);
2401 $in_reply_to_screen_name = NULL;
2402 $in_reply_to_user_id = NULL;
2403 $in_reply_to_user_id_str = NULL;
2405 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2407 intval($in_reply_to_status_id));
2409 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2412 if ($r[0]['nick'] == "")
2413 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2415 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2416 $in_reply_to_user_id = intval($r[0]['id']);
2417 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2421 $in_reply_to_screen_name = NULL;
2422 $in_reply_to_user_id = NULL;
2423 $in_reply_to_status_id = NULL;
2424 $in_reply_to_user_id_str = NULL;
2425 $in_reply_to_status_id_str = NULL;
2428 $converted = api_convert_item($item);
2431 'text' => $converted["text"],
2432 'truncated' => False,
2433 'created_at'=> api_date($item['created']),
2434 'in_reply_to_status_id' => $in_reply_to_status_id,
2435 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2436 'source' => (($item['app']) ? $item['app'] : 'web'),
2437 'id' => intval($item['id']),
2438 'id_str' => (string) intval($item['id']),
2439 'in_reply_to_user_id' => $in_reply_to_user_id,
2440 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2441 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2443 'favorited' => $item['starred'] ? true : false,
2444 'user' => $status_user ,
2445 'friendica_owner' => $owner_user,
2446 //'entities' => NULL,
2447 'statusnet_html' => $converted["html"],
2448 'statusnet_conversation_id' => $item['parent'],
2449 'friendica_activities' => api_format_items_activities($item),
2452 if (count($converted["attachments"]) > 0)
2453 $status["attachments"] = $converted["attachments"];
2455 if (count($converted["entities"]) > 0)
2456 $status["entities"] = $converted["entities"];
2458 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2459 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2460 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2461 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2464 // Retweets are only valid for top postings
2465 // It doesn't work reliable with the link if its a feed
2466 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2468 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2471 if ($item["id"] == $item["parent"]) {
2472 $retweeted_item = api_share_as_retweet($item);
2473 if ($retweeted_item !== false) {
2474 $retweeted_status = $status;
2476 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2477 } catch( BadRequestException $e ) {
2478 // user not found. should be found?
2479 /// @todo check if the user should be always found
2480 $retweeted_status["user"] = array();
2483 $rt_converted = api_convert_item($retweeted_item);
2485 $retweeted_status['text'] = $rt_converted["text"];
2486 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2487 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item);
2488 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2489 $status['retweeted_status'] = $retweeted_status;
2493 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2494 unset($status["user"]["uid"]);
2495 unset($status["user"]["self"]);
2497 if ($item["coord"] != "") {
2498 $coords = explode(' ',$item["coord"]);
2499 if (count($coords) == 2) {
2500 $status["geo"] = array('type' => 'Point',
2501 'coordinates' => array((float) $coords[0],
2502 (float) $coords[1]));
2512 function api_account_rate_limit_status(&$a,$type) {
2514 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2515 'remaining_hits' => (string) 150,
2516 'hourly_limit' => (string) 150,
2517 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2520 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2522 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2524 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2526 function api_help_test(&$a,$type) {
2532 return api_apply_template('test', $type, array("$ok" => $ok));
2534 api_register_func('api/help/test','api_help_test',false);
2536 function api_lists(&$a,$type) {
2540 api_register_func('api/lists','api_lists',true);
2542 function api_lists_list(&$a,$type) {
2546 api_register_func('api/lists/list','api_lists_list',true);
2549 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2550 * This function is deprecated by Twitter
2551 * returns: json, xml
2553 function api_statuses_f(&$a, $type, $qtype) {
2554 if (api_user()===false) throw new ForbiddenException();
2555 $user_info = api_get_user($a);
2557 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2558 /* this is to stop Hotot to load friends multiple times
2559 * I'm not sure if I'm missing return something or
2560 * is a bug in hotot. Workaround, meantime
2564 return array('$users' => $ret);*/
2568 if($qtype == 'friends')
2569 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2570 if($qtype == 'followers')
2571 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2573 // friends and followers only for self
2574 if ($user_info['self'] == 0)
2575 $sql_extra = " AND false ";
2577 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2582 foreach($r as $cid){
2583 $user = api_get_user($a, $cid['nurl']);
2584 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2585 unset($user["uid"]);
2586 unset($user["self"]);
2592 return array('$users' => $ret);
2595 function api_statuses_friends(&$a, $type){
2596 $data = api_statuses_f($a,$type,"friends");
2597 if ($data===false) return false;
2598 return api_apply_template("friends", $type, $data);
2600 function api_statuses_followers(&$a, $type){
2601 $data = api_statuses_f($a,$type,"followers");
2602 if ($data===false) return false;
2603 return api_apply_template("friends", $type, $data);
2605 api_register_func('api/statuses/friends','api_statuses_friends',true);
2606 api_register_func('api/statuses/followers','api_statuses_followers',true);
2613 function api_statusnet_config(&$a,$type) {
2614 $name = $a->config['sitename'];
2615 $server = $a->get_hostname();
2616 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2617 $email = $a->config['admin_email'];
2618 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2619 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2620 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2621 if($a->config['api_import_size'])
2622 $texlimit = string($a->config['api_import_size']);
2623 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2624 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2627 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2628 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2629 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2630 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2631 'shorturllength' => '30',
2632 'friendica' => array(
2633 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2634 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2635 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2636 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2641 return api_apply_template('config', $type, array('$config' => $config));
2644 api_register_func('api/statusnet/config','api_statusnet_config',false);
2646 function api_statusnet_version(&$a,$type) {
2648 $fake_statusnet_version = "0.9.7";
2650 if($type === 'xml') {
2651 header("Content-type: application/xml");
2652 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2655 elseif($type === 'json') {
2656 header("Content-type: application/json");
2657 echo '"'.$fake_statusnet_version.'"';
2661 api_register_func('api/statusnet/version','api_statusnet_version',false);
2664 * @todo use api_apply_template() to return data
2666 function api_ff_ids(&$a,$type,$qtype) {
2667 if(! api_user()) throw new ForbiddenException();
2669 $user_info = api_get_user($a);
2671 if($qtype == 'friends')
2672 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2673 if($qtype == 'followers')
2674 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2676 if (!$user_info["self"])
2677 $sql_extra = " AND false ";
2679 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2681 $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",
2687 if($type === 'xml') {
2688 header("Content-type: application/xml");
2689 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2691 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2692 echo '</ids>' . "\r\n";
2695 elseif($type === 'json') {
2697 header("Content-type: application/json");
2702 $ret[] = intval($rr['id']);
2704 echo json_encode($ret);
2710 function api_friends_ids(&$a,$type) {
2711 api_ff_ids($a,$type,'friends');
2713 function api_followers_ids(&$a,$type) {
2714 api_ff_ids($a,$type,'followers');
2716 api_register_func('api/friends/ids','api_friends_ids',true);
2717 api_register_func('api/followers/ids','api_followers_ids',true);
2720 function api_direct_messages_new(&$a, $type) {
2721 if (api_user()===false) throw new ForbiddenException();
2723 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2725 $sender = api_get_user($a);
2727 if ($_POST['screen_name']) {
2728 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2730 dbesc($_POST['screen_name']));
2732 // Selecting the id by priority, friendica first
2733 api_best_nickname($r);
2735 $recipient = api_get_user($a, $r[0]['nurl']);
2737 $recipient = api_get_user($a, $_POST['user_id']);
2741 if (x($_REQUEST,'replyto')) {
2742 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2744 intval($_REQUEST['replyto']));
2745 $replyto = $r[0]['parent-uri'];
2746 $sub = $r[0]['title'];
2749 if (x($_REQUEST,'title')) {
2750 $sub = $_REQUEST['title'];
2753 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2757 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2760 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2761 $ret = api_format_messages($r[0], $recipient, $sender);
2764 $ret = array("error"=>$id);
2767 $data = Array('$messages'=>$ret);
2772 $data = api_rss_extra($a, $data, $user_info);
2775 return api_apply_template("direct_messages", $type, $data);
2778 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2780 function api_direct_messages_box(&$a, $type, $box) {
2781 if (api_user()===false) throw new ForbiddenException();
2784 $count = (x($_GET,'count')?$_GET['count']:20);
2785 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2786 if ($page<0) $page=0;
2788 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2789 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2791 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2792 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2795 unset($_REQUEST["user_id"]);
2796 unset($_GET["user_id"]);
2798 unset($_REQUEST["screen_name"]);
2799 unset($_GET["screen_name"]);
2801 $user_info = api_get_user($a);
2802 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2803 $profile_url = $user_info["url"];
2807 $start = $page*$count;
2810 if ($box=="sentbox") {
2811 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2813 elseif ($box=="conversation") {
2814 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2816 elseif ($box=="all") {
2817 $sql_extra = "true";
2819 elseif ($box=="inbox") {
2820 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2824 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2826 if ($user_id !="") {
2827 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2829 elseif($screen_name !=""){
2830 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2833 $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",
2836 intval($start), intval($count)
2841 foreach($r as $item) {
2842 if ($box == "inbox" || $item['from-url'] != $profile_url){
2843 $recipient = $user_info;
2844 $sender = api_get_user($a,normalise_link($item['contact-url']));
2846 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2847 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2848 $sender = $user_info;
2851 $ret[]=api_format_messages($item, $recipient, $sender);
2855 $data = array('$messages' => $ret);
2859 $data = api_rss_extra($a, $data, $user_info);
2862 return api_apply_template("direct_messages", $type, $data);
2866 function api_direct_messages_sentbox(&$a, $type){
2867 return api_direct_messages_box($a, $type, "sentbox");
2869 function api_direct_messages_inbox(&$a, $type){
2870 return api_direct_messages_box($a, $type, "inbox");
2872 function api_direct_messages_all(&$a, $type){
2873 return api_direct_messages_box($a, $type, "all");
2875 function api_direct_messages_conversation(&$a, $type){
2876 return api_direct_messages_box($a, $type, "conversation");
2878 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2879 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2880 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2881 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2885 function api_oauth_request_token(&$a, $type){
2887 $oauth = new FKOAuth1();
2888 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2889 }catch(Exception $e){
2890 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2895 function api_oauth_access_token(&$a, $type){
2897 $oauth = new FKOAuth1();
2898 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2899 }catch(Exception $e){
2900 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2906 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2907 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2910 function api_fr_photos_list(&$a,$type) {
2911 if (api_user()===false) throw new ForbiddenException();
2912 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2913 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2914 intval(local_user())
2917 'image/jpeg' => 'jpg',
2918 'image/png' => 'png',
2919 'image/gif' => 'gif'
2921 $data = array('photos'=>array());
2923 foreach($r as $rr) {
2925 $photo['id'] = $rr['resource-id'];
2926 $photo['album'] = $rr['album'];
2927 $photo['filename'] = $rr['filename'];
2928 $photo['type'] = $rr['type'];
2929 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2930 $data['photos'][] = $photo;
2933 return api_apply_template("photos_list", $type, $data);
2936 function api_fr_photo_detail(&$a,$type) {
2937 if (api_user()===false) throw new ForbiddenException();
2938 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2940 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2941 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2942 $data_sql = ($scale === false ? "" : "data, ");
2944 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2945 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2946 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2948 intval(local_user()),
2949 dbesc($_REQUEST['photo_id']),
2954 'image/jpeg' => 'jpg',
2955 'image/png' => 'png',
2956 'image/gif' => 'gif'
2960 $data = array('photo' => $r[0]);
2961 if ($scale !== false) {
2962 $data['photo']['data'] = base64_encode($data['photo']['data']);
2964 unset($data['photo']['datasize']); //needed only with scale param
2966 $data['photo']['link'] = array();
2967 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2968 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2970 $data['photo']['id'] = $data['photo']['resource-id'];
2971 unset($data['photo']['resource-id']);
2972 unset($data['photo']['minscale']);
2973 unset($data['photo']['maxscale']);
2976 throw new NotFoundException();
2979 return api_apply_template("photo_detail", $type, $data);
2982 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2983 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2988 * similar as /mod/redir.php
2989 * redirect to 'url' after dfrn auth
2991 * why this when there is mod/redir.php already?
2992 * This use api_user() and api_login()
2995 * c_url: url of remote contact to auth to
2996 * url: string, url to redirect after auth
2998 function api_friendica_remoteauth(&$a) {
2999 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
3000 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
3002 if ($url === '' || $c_url === '')
3003 throw new BadRequestException("Wrong parameters.");
3005 $c_url = normalise_link($c_url);
3009 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3014 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
3015 throw new BadRequestException("Unknown contact");
3019 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3021 if($r[0]['duplex'] && $r[0]['issued-id']) {
3022 $orig_id = $r[0]['issued-id'];
3023 $dfrn_id = '1:' . $orig_id;
3025 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3026 $orig_id = $r[0]['dfrn-id'];
3027 $dfrn_id = '0:' . $orig_id;
3030 $sec = random_string();
3032 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3033 VALUES( %d, %s, '%s', '%s', %d )",
3041 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3042 $dest = (($url) ? '&destination_url=' . $url : '');
3043 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3044 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3045 . '&type=profile&sec=' . $sec . $dest . $quiet );
3047 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3050 * @brief Return the item shared, if the item contains only the [share] tag
3052 * @param array $item Sharer item
3053 * @return array Shared item or false if not a reshare
3055 function api_share_as_retweet(&$item) {
3056 $body = trim($item["body"]);
3058 if (diaspora::is_reshare($body, false)===false) {
3062 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3063 // Skip if there is no shared message in there
3064 // we already checked this in diaspora::is_reshare()
3065 // but better one more than one less...
3066 if ($body == $attributes)
3070 // build the fake reshared item
3071 $reshared_item = $item;
3074 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3075 if ($matches[1] != "")
3076 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3078 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3079 if ($matches[1] != "")
3080 $author = $matches[1];
3083 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3084 if ($matches[1] != "")
3085 $profile = $matches[1];
3087 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3088 if ($matches[1] != "")
3089 $profile = $matches[1];
3092 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3093 if ($matches[1] != "")
3094 $avatar = $matches[1];
3096 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3097 if ($matches[1] != "")
3098 $avatar = $matches[1];
3101 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3102 if ($matches[1] != "")
3103 $link = $matches[1];
3105 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3106 if ($matches[1] != "")
3107 $link = $matches[1];
3110 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3111 if ($matches[1] != "")
3112 $posted= $matches[1];
3114 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3115 if ($matches[1] != "")
3116 $posted = $matches[1];
3118 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3120 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3125 $reshared_item["body"] = $shared_body;
3126 $reshared_item["author-name"] = $author;
3127 $reshared_item["author-link"] = $profile;
3128 $reshared_item["author-avatar"] = $avatar;
3129 $reshared_item["plink"] = $link;
3130 $reshared_item["created"] = $posted;
3131 $reshared_item["edited"] = $posted;
3133 return $reshared_item;
3137 function api_get_nick($profile) {
3139 - remove trailing junk from profile url
3140 - pump.io check has to check the website
3145 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3146 dbesc(normalise_link($profile)));
3148 $nick = $r[0]["nick"];
3151 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3152 dbesc(normalise_link($profile)));
3154 $nick = $r[0]["nick"];
3158 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3159 if ($friendica != $profile)
3164 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3165 if ($diaspora != $profile)
3170 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3171 if ($twitter != $profile)
3177 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3178 if ($StatusnetHost != $profile) {
3179 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3180 if ($StatusnetUser != $profile) {
3181 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3182 $user = json_decode($UserData);
3184 $nick = $user->screen_name;
3189 // To-Do: look at the page if its really a pumpio site
3190 //if (!$nick == "") {
3191 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3192 // if ($pumpio != $profile)
3194 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3204 function api_clean_plain_items($Text) {
3205 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3207 $Text = bb_CleanPictureLinks($Text);
3208 $URLSearchString = "^\[\]";
3210 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3212 if ($include_entities == "true") {
3213 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3216 // Simplify "attachment" element
3217 $Text = api_clean_attachments($Text);
3223 * @brief Removes most sharing information for API text export
3225 * @param string $body The original body
3227 * @return string Cleaned body
3229 function api_clean_attachments($body) {
3230 $data = get_attachment_data($body);
3237 if (isset($data["text"]))
3238 $body = $data["text"];
3240 if (($body == "") AND (isset($data["title"])))
3241 $body = $data["title"];
3243 if (isset($data["url"]))
3244 $body .= "\n".$data["url"];
3246 $body .= $data["after"];
3251 function api_best_nickname(&$contacts) {
3252 $best_contact = array();
3254 if (count($contact) == 0)
3257 foreach ($contacts AS $contact)
3258 if ($contact["network"] == "") {
3259 $contact["network"] = "dfrn";
3260 $best_contact = array($contact);
3263 if (sizeof($best_contact) == 0)
3264 foreach ($contacts AS $contact)
3265 if ($contact["network"] == "dfrn")
3266 $best_contact = array($contact);
3268 if (sizeof($best_contact) == 0)
3269 foreach ($contacts AS $contact)
3270 if ($contact["network"] == "dspr")
3271 $best_contact = array($contact);
3273 if (sizeof($best_contact) == 0)
3274 foreach ($contacts AS $contact)
3275 if ($contact["network"] == "stat")
3276 $best_contact = array($contact);
3278 if (sizeof($best_contact) == 0)
3279 foreach ($contacts AS $contact)
3280 if ($contact["network"] == "pump")
3281 $best_contact = array($contact);
3283 if (sizeof($best_contact) == 0)
3284 foreach ($contacts AS $contact)
3285 if ($contact["network"] == "twit")
3286 $best_contact = array($contact);
3288 if (sizeof($best_contact) == 1)
3289 $contacts = $best_contact;
3291 $contacts = array($contacts[0]);
3294 // return all or a specified group of the user with the containing contacts
3295 function api_friendica_group_show(&$a, $type) {
3296 if (api_user()===false) throw new ForbiddenException();
3299 $user_info = api_get_user($a);
3300 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3301 $uid = $user_info['uid'];
3303 // get data of the specified group id or all groups if not specified
3305 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3308 // error message if specified gid is not in database
3310 throw new BadRequestException("gid not available");
3313 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3316 // loop through all groups and retrieve all members for adding data in the user array
3317 foreach ($r as $rr) {
3318 $members = group_get_members($rr['id']);
3320 foreach ($members as $member) {
3321 $user = api_get_user($a, $member['nurl']);
3324 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3326 return api_apply_template("group_show", $type, array('$groups' => $grps));
3328 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3331 // delete the specified group of the user
3332 function api_friendica_group_delete(&$a, $type) {
3333 if (api_user()===false) throw new ForbiddenException();
3336 $user_info = api_get_user($a);
3337 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3338 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3339 $uid = $user_info['uid'];
3341 // error if no gid specified
3342 if ($gid == 0 || $name == "")
3343 throw new BadRequestException('gid or name not specified');
3345 // get data of the specified group id
3346 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3349 // error message if specified gid is not in database
3351 throw new BadRequestException('gid not available');
3353 // get data of the specified group id and group name
3354 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3358 // error message if specified gid is not in database
3359 if (count($rname) == 0)
3360 throw new BadRequestException('wrong group name');
3363 $ret = group_rmv($uid, $name);
3366 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3367 return api_apply_template("group_delete", $type, array('$result' => $success));
3370 throw new BadRequestException('other API error');
3372 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3375 // create the specified group with the posted array of contacts
3376 function api_friendica_group_create(&$a, $type) {
3377 if (api_user()===false) throw new ForbiddenException();
3380 $user_info = api_get_user($a);
3381 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3382 $uid = $user_info['uid'];
3383 $json = json_decode($_POST['json'], true);
3384 $users = $json['user'];
3386 // error if no name specified
3388 throw new BadRequestException('group name not specified');
3390 // get data of the specified group name
3391 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3394 // error message if specified group name already exists
3395 if (count($rname) != 0)
3396 throw new BadRequestException('group name already exists');
3398 // check if specified group name is a deleted group
3399 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3402 // error message if specified group name already exists
3403 if (count($rname) != 0)
3404 $reactivate_group = true;
3407 $ret = group_add($uid, $name);
3409 $gid = group_byname($uid, $name);
3411 throw new BadRequestException('other API error');
3414 $erroraddinguser = false;
3415 $errorusers = array();
3416 foreach ($users as $user) {
3417 $cid = $user['cid'];
3418 // check if user really exists as contact
3419 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3422 if (count($contact))
3423 $result = group_add_member($uid, $name, $cid, $gid);
3425 $erroraddinguser = true;
3426 $errorusers[] = $cid;
3430 // return success message incl. missing users in array
3431 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3432 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3433 return api_apply_template("group_create", $type, array('result' => $success));
3435 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3438 // update the specified group with the posted array of contacts
3439 function api_friendica_group_update(&$a, $type) {
3440 if (api_user()===false) throw new ForbiddenException();
3443 $user_info = api_get_user($a);
3444 $uid = $user_info['uid'];
3445 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3446 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3447 $json = json_decode($_POST['json'], true);
3448 $users = $json['user'];
3450 // error if no name specified
3452 throw new BadRequestException('group name not specified');
3454 // error if no gid specified
3456 throw new BadRequestException('gid not specified');
3459 $members = group_get_members($gid);
3460 foreach ($members as $member) {
3461 $cid = $member['id'];
3462 foreach ($users as $user) {
3463 $found = ($user['cid'] == $cid ? true : false);
3466 $ret = group_rmv_member($uid, $name, $cid);
3471 $erroraddinguser = false;
3472 $errorusers = array();
3473 foreach ($users as $user) {
3474 $cid = $user['cid'];
3475 // check if user really exists as contact
3476 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3479 if (count($contact))
3480 $result = group_add_member($uid, $name, $cid, $gid);
3482 $erroraddinguser = true;
3483 $errorusers[] = $cid;
3487 // return success message incl. missing users in array
3488 $status = ($erroraddinguser ? "missing user" : "ok");
3489 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3490 return api_apply_template("group_update", $type, array('result' => $success));
3492 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3495 function api_friendica_activity(&$a, $type) {
3496 if (api_user()===false) throw new ForbiddenException();
3497 $verb = strtolower($a->argv[3]);
3498 $verb = preg_replace("|\..*$|", "", $verb);
3500 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3502 $res = do_like($id, $verb);
3509 return api_apply_template('test', $type, array('ok' => $ok));
3511 throw new BadRequestException('Error adding activity');
3515 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3516 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3517 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3518 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3519 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3520 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3521 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3522 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3523 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3524 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3527 * @brief Returns notifications
3530 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3533 function api_friendica_notification(&$a, $type) {
3534 if (api_user()===false) throw new ForbiddenException();
3535 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3536 $nm = new NotificationsManager();
3538 $notes = $nm->getAll(array(), "+seen -date", 50);
3539 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3543 * @brief Set notification as seen and returns associated item (if possible)
3545 * POST request with 'id' param as notification id
3548 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3551 function api_friendica_notification_seen(&$a, $type){
3552 if (api_user()===false) throw new ForbiddenException();
3553 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3555 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3557 $nm = new NotificationsManager();
3558 $note = $nm->getByID($id);
3559 if (is_null($note)) throw new BadRequestException("Invalid argument");
3561 $nm->setSeen($note);
3562 if ($note['otype']=='item') {
3563 // would be really better with an ItemsManager and $im->getByID() :-P
3564 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3565 intval($note['iid']),
3566 intval(local_user())
3569 // we found the item, return it to the user
3570 $user_info = api_get_user($a);
3571 $ret = api_format_items($r,$user_info);
3572 $data = array('$statuses' => $ret);
3573 return api_apply_template("timeline", $type, $data);
3575 // the item can't be found, but we set the note as seen, so we count this as a success
3577 return api_apply_template('<auto>', $type, array('status' => "success"));
3580 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3581 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3586 [pagename] => api/1.1/statuses/lookup.json
3587 [id] => 605138389168451584
3588 [include_cards] => true
3589 [cards_platform] => Android-12
3590 [include_entities] => true
3591 [include_my_retweet] => 1
3593 [include_reply_count] => true
3594 [include_descendent_reply_count] => true
3598 Not implemented by now:
3599 statuses/retweets_of_me
3604 account/update_location
3605 account/update_profile_background_image
3606 account/update_profile_image
3610 Not implemented in status.net:
3611 statuses/retweeted_to_me
3612 statuses/retweeted_by_me
3613 direct_messages/destroy
3615 account/update_delivery_device
3616 notifications/follow