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');
29 define('API_METHOD_ANY','*');
30 define('API_METHOD_GET','GET');
31 define('API_METHOD_POST','POST,PUT');
32 define('API_METHOD_DELETE','POST,DELETE');
40 * @brief Auth API user
42 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
43 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
44 * into a page, and visitors will post something without noticing it).
47 if ($_SESSION['allow_api'])
54 * @brief Get source name from API client
56 * Clients can send 'source' parameter to be show in post metadata
57 * as "sent via <source>".
58 * Some clients doesn't send a source param, we support ones we know
62 * Client source name, default to "api" if unset/unknown
64 function api_source() {
65 if (requestdata('source'))
66 return (requestdata('source'));
68 // Support for known clients that doesn't send a source name
69 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
72 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
78 * @brief Format date for API
80 * @param string $str Source date, as UTC
81 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
83 function api_date($str){
84 //Wed May 23 06:01:13 +0000 2007
85 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
89 * @brief Register API endpoint
91 * Register a function to be the endpont for defined API path.
93 * @param string $path API URL path, relative to $a->get_baseurl()
94 * @param string $func Function name to call on path request
95 * @param bool $auth API need logged user
96 * @param string $method
97 * HTTP method reqiured to call this endpoint.
98 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
99 * Default to API_METHOD_ANY
101 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
109 // Workaround for hotot
110 $path = str_replace("api/", "api/1.1/", $path);
119 * @brief Login API user
121 * Log in user via OAuth1 or Simple HTTP Auth.
122 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
125 * @hook 'authenticate'
127 * 'username' => username from login form
128 * 'password' => password from login form
129 * 'authenticated' => return status,
130 * 'user_record' => return authenticated user record
132 * array $user logged user record
134 function api_login(&$a){
137 $oauth = new FKOAuth1();
138 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
139 if (!is_null($token)){
140 $oauth->loginUser($token->uid);
141 call_hooks('logged_in', $a->user);
144 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
145 }catch(Exception $e){
151 // workaround for HTTP-auth in CGI mode
152 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
153 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
154 if(strlen($userpass)) {
155 list($name, $password) = explode(':', $userpass);
156 $_SERVER['PHP_AUTH_USER'] = $name;
157 $_SERVER['PHP_AUTH_PW'] = $password;
161 if (!isset($_SERVER['PHP_AUTH_USER'])) {
162 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
163 header('WWW-Authenticate: Basic realm="Friendica"');
164 header('HTTP/1.0 401 Unauthorized');
165 die((api_error($a, 'json', "This api requires login")));
167 //die('This api requires login');
170 $user = $_SERVER['PHP_AUTH_USER'];
171 $password = $_SERVER['PHP_AUTH_PW'];
172 $encrypted = hash('whirlpool',trim($password));
174 // allow "user@server" login (but ignore 'server' part)
175 $at=strstr($user, "@", true);
176 if ( $at ) $user=$at;
179 * next code from mod/auth.php. needs better solution
184 'username' => trim($user),
185 'password' => trim($password),
186 'authenticated' => 0,
187 'user_record' => null
192 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
193 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
194 * and later plugins should not interfere with an earlier one that succeeded.
198 call_hooks('authenticate', $addon_auth);
200 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
201 $record = $addon_auth['user_record'];
204 // process normal login request
206 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
207 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
216 if((! $record) || (! count($record))) {
217 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
218 header('WWW-Authenticate: Basic realm="Friendica"');
219 header('HTTP/1.0 401 Unauthorized');
220 die('This api requires login');
223 authenticate_success($record); $_SESSION["allow_api"] = true;
225 call_hooks('logged_in', $a->user);
230 * @brief Check HTTP method of called API
232 * API endpoints can define which HTTP method to accept when called.
233 * This function check the current HTTP method agains endpoint
236 * @param string $method Required methods, uppercase, separated by comma
239 function api_check_method($method) {
240 if ($method=="*") return True;
241 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
245 * @brief Main API entry point
247 * Authenticate user, call registered API function, set HTTP headers
250 * @return string API call result
252 function api_call(&$a){
253 GLOBAL $API, $called_api;
256 if (strpos($a->query_string, ".xml")>0) $type="xml";
257 if (strpos($a->query_string, ".json")>0) $type="json";
258 if (strpos($a->query_string, ".rss")>0) $type="rss";
259 if (strpos($a->query_string, ".atom")>0) $type="atom";
260 if (strpos($a->query_string, ".as")>0) $type="as";
262 foreach ($API as $p=>$info){
263 if (strpos($a->query_string, $p)===0){
264 if (!api_check_method($info['method'])){
265 throw new MethodNotAllowedException();
268 $called_api= explode("/",$p);
269 //unset($_SERVER['PHP_AUTH_USER']);
270 if ($info['auth']===true && api_user()===false) {
274 load_contact_links(api_user());
276 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
277 logger('API parameters: ' . print_r($_REQUEST,true));
279 $stamp = microtime(true);
280 $r = call_user_func($info['func'], $a, $type);
281 $duration = (float)(microtime(true)-$stamp);
282 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
285 // api function returned false withour throw an
286 // exception. This should not happend, throw a 500
287 throw new InternalServerErrorException();
292 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
293 header ("Content-Type: text/xml");
294 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
297 header ("Content-Type: application/json");
299 $json = json_encode($rr);
300 if ($_GET['callback'])
301 $json = $_GET['callback']."(".$json.")";
305 header ("Content-Type: application/rss+xml");
306 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
309 header ("Content-Type: application/atom+xml");
310 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
313 //header ("Content-Type: application/json");
315 // return json_encode($rr);
316 return json_encode($r);
322 logger('API call not implemented: '.$a->query_string);
323 throw new NotImplementedException();
324 } catch (HTTPException $e) {
325 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
326 return api_error($a, $type, $e);
331 * @brief Format API error string
334 * @param string $type Return type (xml, json, rss, as)
335 * @param string $error Error message
337 function api_error(&$a, $type, $e) {
338 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
339 # TODO: https://dev.twitter.com/overview/api/response-codes
340 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
343 header ("Content-Type: text/xml");
344 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
347 header ("Content-Type: application/json");
348 return json_encode(array(
350 'request' => $a->query_string,
351 'code' => $e->httpcode." ".$e->httpdesc
355 header ("Content-Type: application/rss+xml");
356 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
359 header ("Content-Type: application/atom+xml");
360 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
366 * @brief Set values for RSS template
369 * @param array $arr Array to be passed to template
370 * @param array $user_info
373 function api_rss_extra(&$a, $arr, $user_info){
374 if (is_null($user_info)) $user_info = api_get_user($a);
375 $arr['$user'] = $user_info;
376 $arr['$rss'] = array(
377 'alternate' => $user_info['url'],
378 'self' => $a->get_baseurl(). "/". $a->query_string,
379 'base' => $a->get_baseurl(),
380 'updated' => api_date(null),
381 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
382 'language' => $user_info['language'],
383 'logo' => $a->get_baseurl()."/images/friendica-32.png",
391 * @brief Unique contact to contact url.
393 * @param int $id Contact id
394 * @return bool|string
395 * Contact url or False if contact id is unknown
397 function api_unique_id_to_url($id){
398 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
401 return ($r[0]["url"]);
407 * @brief Get user info array.
410 * @param int|string $contact_id Contact ID or URL
411 * @param string $type Return type (for errors)
413 function api_get_user(&$a, $contact_id = Null, $type = "json"){
420 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
422 // Searching for contact URL
423 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
424 $user = dbesc(normalise_link($contact_id));
426 $extra_query = "AND `contact`.`nurl` = '%s' ";
427 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
430 // Searching for unique contact id
431 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
432 $user = dbesc(api_unique_id_to_url($contact_id));
435 throw new BadRequestException("User not found.");
438 $extra_query = "AND `contact`.`nurl` = '%s' ";
439 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
442 if(is_null($user) && x($_GET, 'user_id')) {
443 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
446 throw new BadRequestException("User not found.");
449 $extra_query = "AND `contact`.`nurl` = '%s' ";
450 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
452 if(is_null($user) && x($_GET, 'screen_name')) {
453 $user = dbesc($_GET['screen_name']);
455 $extra_query = "AND `contact`.`nick` = '%s' ";
456 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
459 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
460 $argid = count($called_api);
461 list($user, $null) = explode(".",$a->argv[$argid]);
462 if(is_numeric($user)){
463 $user = dbesc(api_unique_id_to_url($user));
469 $extra_query = "AND `contact`.`nurl` = '%s' ";
470 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
472 $user = dbesc($user);
474 $extra_query = "AND `contact`.`nick` = '%s' ";
475 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
479 logger("api_get_user: user ".$user, LOGGER_DEBUG);
482 if (api_user()===false) {
486 $user = $_SESSION['uid'];
487 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
492 logger('api_user: ' . $extra_query . ', user: ' . $user);
494 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
500 // Selecting the id by priority, friendica first
501 api_best_nickname($uinfo);
503 // if the contact wasn't found, fetch it from the unique contacts
504 if (count($uinfo)==0) {
508 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
511 // If no nick where given, extract it from the address
512 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
513 $r[0]['nick'] = api_get_nick($r[0]["url"]);
517 'id_str' => (string) $r[0]["id"],
518 'name' => $r[0]["name"],
519 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
520 'location' => $r[0]["location"],
521 'description' => $r[0]["about"],
522 'url' => $r[0]["url"],
523 'protected' => false,
524 'followers_count' => 0,
525 'friends_count' => 0,
527 'created_at' => api_date($r[0]["created"]),
528 'favourites_count' => 0,
530 'time_zone' => 'UTC',
531 'geo_enabled' => false,
533 'statuses_count' => 0,
535 'contributors_enabled' => false,
536 'is_translator' => false,
537 'is_translation_enabled' => false,
538 'profile_image_url' => $r[0]["photo"],
539 'profile_image_url_https' => $r[0]["photo"],
540 'following' => false,
541 'follow_request_sent' => false,
542 'notifications' => false,
543 'statusnet_blocking' => false,
544 'notifications' => false,
545 'statusnet_profile_url' => $r[0]["url"],
549 'network' => $r[0]["network"],
554 throw new BadRequestException("User not found.");
558 if($uinfo[0]['self']) {
559 $usr = q("select * from user where uid = %d limit 1",
562 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
566 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
567 // count public wall messages
568 $r = q("SELECT count(*) as `count` FROM `item`
571 intval($uinfo[0]['uid'])
573 $countitms = $r[0]['count'];
576 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
577 $r = q("SELECT count(*) as `count` FROM `item`
578 WHERE `contact-id` = %d",
579 intval($uinfo[0]['id'])
581 $countitms = $r[0]['count'];
585 $r = q("SELECT count(*) as `count` FROM `contact`
586 WHERE `uid` = %d AND `rel` IN ( %d, %d )
587 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
588 intval($uinfo[0]['uid']),
589 intval(CONTACT_IS_SHARING),
590 intval(CONTACT_IS_FRIEND)
592 $countfriends = $r[0]['count'];
594 $r = q("SELECT count(*) as `count` FROM `contact`
595 WHERE `uid` = %d AND `rel` IN ( %d, %d )
596 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
597 intval($uinfo[0]['uid']),
598 intval(CONTACT_IS_FOLLOWER),
599 intval(CONTACT_IS_FRIEND)
601 $countfollowers = $r[0]['count'];
603 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
604 intval($uinfo[0]['uid'])
606 $starred = $r[0]['count'];
609 if(! $uinfo[0]['self']) {
615 // Add a nick if it isn't present there
616 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
617 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
620 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
622 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
623 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
626 'id' => intval($gcontact_id),
627 'id_str' => (string) intval($gcontact_id),
628 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
629 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
630 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
631 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
632 'profile_image_url' => $uinfo[0]['micro'],
633 'profile_image_url_https' => $uinfo[0]['micro'],
634 'url' => $uinfo[0]['url'],
635 'protected' => false,
636 'followers_count' => intval($countfollowers),
637 'friends_count' => intval($countfriends),
638 'created_at' => api_date($uinfo[0]['created']),
639 'favourites_count' => intval($starred),
641 'time_zone' => 'UTC',
642 'statuses_count' => intval($countitms),
643 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
645 'statusnet_blocking' => false,
646 'notifications' => false,
647 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
648 'statusnet_profile_url' => $uinfo[0]['url'],
649 'uid' => intval($uinfo[0]['uid']),
650 'cid' => intval($uinfo[0]['cid']),
651 'self' => $uinfo[0]['self'],
652 'network' => $uinfo[0]['network'],
659 function api_item_get_user(&$a, $item) {
661 // Make sure that there is an entry in the global contacts for author and owner
662 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
663 "photo" => $item['author-avatar'], "name" => $item['author-name']));
665 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
666 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
668 // Comments in threads may appear as wall-to-wall postings.
669 // So only take the owner at the top posting.
670 if ($item["id"] == $item["parent"])
671 $status_user = api_get_user($a,$item["owner-link"]);
673 $status_user = api_get_user($a,$item["author-link"]);
675 $status_user["protected"] = (($item["allow_cid"] != "") OR
676 ($item["allow_gid"] != "") OR
677 ($item["deny_cid"] != "") OR
678 ($item["deny_gid"] != "") OR
681 return ($status_user);
686 * @brief transform $data array in xml without a template
689 * @return string xml string
691 function api_array_to_xml($data, $ename="") {
694 if (count($data)==1 && !is_array($data[0])) {
695 $ename = array_keys($data)[0];
697 return "<$ename>$v</$ename>";
699 foreach($data as $k=>$v) {
702 $attrs .= sprintf('%s="%s" ', $k, $v);
704 if (is_numeric($k)) $k=trim($ename,'s');
705 $childs.=api_array_to_xml($v, $k);
709 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
714 * load api $templatename for $type and replace $data array
716 function api_apply_template($templatename, $type, $data){
724 $data = array_xmlify($data);
725 if ($templatename==="<auto>") {
726 $ret = api_array_to_xml($data);
728 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
730 header ("Content-Type: text/xml");
731 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
734 $ret = replace_macros($tpl, $data);
750 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
751 * returns a 401 status code and an error message if not.
752 * http://developer.twitter.com/doc/get/account/verify_credentials
754 function api_account_verify_credentials(&$a, $type){
755 if (api_user()===false) throw new ForbiddenException();
757 unset($_REQUEST["user_id"]);
758 unset($_GET["user_id"]);
760 unset($_REQUEST["screen_name"]);
761 unset($_GET["screen_name"]);
763 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
765 $user_info = api_get_user($a);
767 // "verified" isn't used here in the standard
768 unset($user_info["verified"]);
770 // - Adding last status
772 $user_info["status"] = api_status_show($a,"raw");
773 if (!count($user_info["status"]))
774 unset($user_info["status"]);
776 unset($user_info["status"]["user"]);
779 // "uid" and "self" are only needed for some internal stuff, so remove it from here
780 unset($user_info["uid"]);
781 unset($user_info["self"]);
783 return api_apply_template("user", $type, array('$user' => $user_info));
786 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
790 * get data from $_POST or $_GET
792 function requestdata($k){
793 if (isset($_POST[$k])){
796 if (isset($_GET[$k])){
802 /*Waitman Gobble Mod*/
803 function api_statuses_mediap(&$a, $type) {
804 if (api_user()===false) {
805 logger('api_statuses_update: no user');
806 throw new ForbiddenException();
808 $user_info = api_get_user($a);
810 $_REQUEST['type'] = 'wall';
811 $_REQUEST['profile_uid'] = api_user();
812 $_REQUEST['api_source'] = true;
813 $txt = requestdata('status');
814 //$txt = urldecode(requestdata('status'));
816 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
818 $txt = html2bb_video($txt);
819 $config = HTMLPurifier_Config::createDefault();
820 $config->set('Cache.DefinitionImpl', null);
821 $purifier = new HTMLPurifier($config);
822 $txt = $purifier->purify($txt);
824 $txt = html2bbcode($txt);
826 $a->argv[1]=$user_info['screen_name']; //should be set to username?
828 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
829 $bebop = wall_upload_post($a);
831 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
832 $_REQUEST['body']=$txt."\n\n".$bebop;
835 // this should output the last post (the one we just posted).
836 return api_status_show($a,$type);
838 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
839 /*Waitman Gobble Mod*/
842 function api_statuses_update(&$a, $type) {
843 if (api_user()===false) {
844 logger('api_statuses_update: no user');
845 throw new ForbiddenException();
848 $user_info = api_get_user($a);
850 // convert $_POST array items to the form we use for web posts.
852 // logger('api_post: ' . print_r($_POST,true));
854 if(requestdata('htmlstatus')) {
855 $txt = requestdata('htmlstatus');
856 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
857 $txt = html2bb_video($txt);
859 $config = HTMLPurifier_Config::createDefault();
860 $config->set('Cache.DefinitionImpl', null);
862 $purifier = new HTMLPurifier($config);
863 $txt = $purifier->purify($txt);
865 $_REQUEST['body'] = html2bbcode($txt);
869 $_REQUEST['body'] = requestdata('status');
871 $_REQUEST['title'] = requestdata('title');
873 $parent = requestdata('in_reply_to_status_id');
875 // Twidere sends "-1" if it is no reply ...
879 if(ctype_digit($parent))
880 $_REQUEST['parent'] = $parent;
882 $_REQUEST['parent_uri'] = $parent;
884 if(requestdata('lat') && requestdata('long'))
885 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
886 $_REQUEST['profile_uid'] = api_user();
889 $_REQUEST['type'] = 'net-comment';
891 // Check for throttling (maximum posts per day, week and month)
892 $throttle_day = get_config('system','throttle_limit_day');
893 if ($throttle_day > 0) {
894 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
896 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
897 AND `created` > '%s' AND `id` = `parent`",
898 intval(api_user()), dbesc($datefrom));
901 $posts_day = $r[0]["posts_day"];
905 if ($posts_day > $throttle_day) {
906 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
907 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
911 $throttle_week = get_config('system','throttle_limit_week');
912 if ($throttle_week > 0) {
913 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
915 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
916 AND `created` > '%s' AND `id` = `parent`",
917 intval(api_user()), dbesc($datefrom));
920 $posts_week = $r[0]["posts_week"];
924 if ($posts_week > $throttle_week) {
925 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
926 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
930 $throttle_month = get_config('system','throttle_limit_month');
931 if ($throttle_month > 0) {
932 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
934 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
935 AND `created` > '%s' AND `id` = `parent`",
936 intval(api_user()), dbesc($datefrom));
939 $posts_month = $r[0]["posts_month"];
943 if ($posts_month > $throttle_month) {
944 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
945 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
949 $_REQUEST['type'] = 'wall';
952 if(x($_FILES,'media')) {
953 // upload the image if we have one
954 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
955 $media = wall_upload_post($a);
957 $_REQUEST['body'] .= "\n\n".$media;
960 // To-Do: Multiple IDs
961 if (requestdata('media_ids')) {
962 $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",
963 intval(requestdata('media_ids')), api_user());
965 $phototypes = Photo::supportedTypes();
966 $ext = $phototypes[$r[0]['type']];
967 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
968 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
972 // set this so that the item_post() function is quiet and doesn't redirect or emit json
974 $_REQUEST['api_source'] = true;
976 if (!x($_REQUEST, "source"))
977 $_REQUEST["source"] = api_source();
979 // call out normal post function
983 // this should output the last post (the one we just posted).
984 return api_status_show($a,$type);
986 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
987 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
990 function api_media_upload(&$a, $type) {
991 if (api_user()===false) {
993 throw new ForbiddenException();
996 $user_info = api_get_user($a);
998 if(!x($_FILES,'media')) {
1000 throw new BadRequestException("No media.");
1003 $media = wall_upload_post($a, false);
1006 throw new InternalServerErrorException();
1009 $returndata = array();
1010 $returndata["media_id"] = $media["id"];
1011 $returndata["media_id_string"] = (string)$media["id"];
1012 $returndata["size"] = $media["size"];
1013 $returndata["image"] = array("w" => $media["width"],
1014 "h" => $media["height"],
1015 "image_type" => $media["type"]);
1017 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1019 return array("media" => $returndata);
1021 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1023 function api_status_show(&$a, $type){
1024 $user_info = api_get_user($a);
1026 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1029 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1033 // get last public wall message
1034 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1035 FROM `item`, `item` as `i`
1036 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1037 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1038 AND `i`.`id` = `item`.`parent`
1039 AND `item`.`type`!='activity' $privacy_sql
1040 ORDER BY `item`.`created` DESC
1042 intval($user_info['cid']),
1044 dbesc($user_info['url']),
1045 dbesc(normalise_link($user_info['url'])),
1046 dbesc($user_info['url']),
1047 dbesc(normalise_link($user_info['url']))
1050 if (count($lastwall)>0){
1051 $lastwall = $lastwall[0];
1053 $in_reply_to_status_id = NULL;
1054 $in_reply_to_user_id = NULL;
1055 $in_reply_to_status_id_str = NULL;
1056 $in_reply_to_user_id_str = NULL;
1057 $in_reply_to_screen_name = NULL;
1058 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1059 $in_reply_to_status_id= intval($lastwall['parent']);
1060 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1062 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1064 if ($r[0]['nick'] == "")
1065 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1067 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1068 $in_reply_to_user_id = intval($r[0]['id']);
1069 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1073 // There seems to be situation, where both fields are identical:
1074 // https://github.com/friendica/friendica/issues/1010
1075 // This is a bugfix for that.
1076 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1077 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1078 $in_reply_to_status_id = NULL;
1079 $in_reply_to_user_id = NULL;
1080 $in_reply_to_status_id_str = NULL;
1081 $in_reply_to_user_id_str = NULL;
1082 $in_reply_to_screen_name = NULL;
1085 $converted = api_convert_item($lastwall);
1087 $status_info = array(
1088 'created_at' => api_date($lastwall['created']),
1089 'id' => intval($lastwall['id']),
1090 'id_str' => (string) $lastwall['id'],
1091 'text' => $converted["text"],
1092 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1093 'truncated' => false,
1094 'in_reply_to_status_id' => $in_reply_to_status_id,
1095 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1096 'in_reply_to_user_id' => $in_reply_to_user_id,
1097 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1098 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1099 'user' => $user_info,
1101 'coordinates' => "",
1103 'contributors' => "",
1104 'is_quote_status' => false,
1105 'retweet_count' => 0,
1106 'favorite_count' => 0,
1107 'favorited' => $lastwall['starred'] ? true : false,
1108 'retweeted' => false,
1109 'possibly_sensitive' => false,
1111 'statusnet_html' => $converted["html"],
1112 'statusnet_conversation_id' => $lastwall['parent'],
1115 if (count($converted["attachments"]) > 0)
1116 $status_info["attachments"] = $converted["attachments"];
1118 if (count($converted["entities"]) > 0)
1119 $status_info["entities"] = $converted["entities"];
1121 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1122 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1123 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1124 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1126 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1127 unset($status_info["user"]["uid"]);
1128 unset($status_info["user"]["self"]);
1131 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1134 return($status_info);
1136 return api_apply_template("status", $type, array('$status' => $status_info));
1145 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1146 * The author's most recent status will be returned inline.
1147 * http://developer.twitter.com/doc/get/users/show
1149 function api_users_show(&$a, $type){
1150 $user_info = api_get_user($a);
1152 $lastwall = q("SELECT `item`.*
1153 FROM `item`, `contact`
1154 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1155 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1156 AND `contact`.`id`=`item`.`contact-id`
1157 AND `type`!='activity'
1158 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1159 ORDER BY `created` DESC
1162 dbesc(ACTIVITY_POST),
1163 intval($user_info['cid']),
1164 dbesc($user_info['url']),
1165 dbesc(normalise_link($user_info['url'])),
1166 dbesc($user_info['url']),
1167 dbesc(normalise_link($user_info['url']))
1169 if (count($lastwall)>0){
1170 $lastwall = $lastwall[0];
1172 $in_reply_to_status_id = NULL;
1173 $in_reply_to_user_id = NULL;
1174 $in_reply_to_status_id_str = NULL;
1175 $in_reply_to_user_id_str = NULL;
1176 $in_reply_to_screen_name = NULL;
1177 if ($lastwall['parent']!=$lastwall['id']) {
1178 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1179 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1180 if (count($reply)>0) {
1181 $in_reply_to_status_id = intval($lastwall['parent']);
1182 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1184 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1186 if ($r[0]['nick'] == "")
1187 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1189 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1190 $in_reply_to_user_id = intval($r[0]['id']);
1191 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1196 $converted = api_convert_item($lastwall);
1198 $user_info['status'] = array(
1199 'text' => $converted["text"],
1200 'truncated' => false,
1201 'created_at' => api_date($lastwall['created']),
1202 'in_reply_to_status_id' => $in_reply_to_status_id,
1203 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1204 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1205 'id' => intval($lastwall['contact-id']),
1206 'id_str' => (string) $lastwall['contact-id'],
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,
1211 'favorited' => $lastwall['starred'] ? true : false,
1212 'statusnet_html' => $converted["html"],
1213 'statusnet_conversation_id' => $lastwall['parent'],
1216 if (count($converted["attachments"]) > 0)
1217 $user_info["status"]["attachments"] = $converted["attachments"];
1219 if (count($converted["entities"]) > 0)
1220 $user_info["status"]["entities"] = $converted["entities"];
1222 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1223 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1224 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1225 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1229 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1230 unset($user_info["uid"]);
1231 unset($user_info["self"]);
1233 return api_apply_template("user", $type, array('$user' => $user_info));
1236 api_register_func('api/users/show','api_users_show');
1239 function api_users_search(&$a, $type) {
1240 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1242 $userlist = array();
1244 if (isset($_GET["q"])) {
1245 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1247 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1250 foreach ($r AS $user) {
1251 $user_info = api_get_user($a, $user["id"]);
1252 //echo print_r($user_info, true)."\n";
1253 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1254 $userlist[] = $userdata["user"];
1256 $userlist = array("users" => $userlist);
1258 throw new BadRequestException("User not found.");
1261 throw new BadRequestException("User not found.");
1266 api_register_func('api/users/search','api_users_search');
1270 * http://developer.twitter.com/doc/get/statuses/home_timeline
1272 * TODO: Optional parameters
1273 * TODO: Add reply info
1275 function api_statuses_home_timeline(&$a, $type){
1276 if (api_user()===false) throw new ForbiddenException();
1278 unset($_REQUEST["user_id"]);
1279 unset($_GET["user_id"]);
1281 unset($_REQUEST["screen_name"]);
1282 unset($_GET["screen_name"]);
1284 $user_info = api_get_user($a);
1285 // get last newtork messages
1289 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1290 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1291 if ($page<0) $page=0;
1292 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1293 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1294 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1295 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1296 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1298 $start = $page*$count;
1302 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1303 if ($exclude_replies > 0)
1304 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1305 if ($conversation_id > 0)
1306 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1308 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1309 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1310 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1311 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1312 FROM `item`, `contact`
1313 WHERE `item`.`uid` = %d AND `verb` = '%s'
1314 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1315 AND `contact`.`id` = `item`.`contact-id`
1316 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1319 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1321 dbesc(ACTIVITY_POST),
1323 intval($start), intval($count)
1326 $ret = api_format_items($r,$user_info);
1328 // Set all posts from the query above to seen
1330 foreach ($r AS $item)
1331 $idarray[] = intval($item["id"]);
1333 $idlist = implode(",", $idarray);
1336 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1339 $data = array('$statuses' => $ret);
1343 $data = api_rss_extra($a, $data, $user_info);
1346 $as = api_format_as($a, $ret, $user_info);
1347 $as['title'] = $a->config['sitename']." Home Timeline";
1348 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1353 return api_apply_template("timeline", $type, $data);
1355 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1356 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1358 function api_statuses_public_timeline(&$a, $type){
1359 if (api_user()===false) throw new ForbiddenException();
1361 $user_info = api_get_user($a);
1362 // get last newtork messages
1366 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1367 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1368 if ($page<0) $page=0;
1369 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1370 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1371 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1372 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1373 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1375 $start = $page*$count;
1378 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1379 if ($exclude_replies > 0)
1380 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1381 if ($conversation_id > 0)
1382 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1384 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1385 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1386 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1387 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1388 `user`.`nickname`, `user`.`hidewall`
1389 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1390 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1391 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1392 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1393 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1394 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1395 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1398 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1399 dbesc(ACTIVITY_POST),
1404 $ret = api_format_items($r,$user_info);
1407 $data = array('$statuses' => $ret);
1411 $data = api_rss_extra($a, $data, $user_info);
1414 $as = api_format_as($a, $ret, $user_info);
1415 $as['title'] = $a->config['sitename']." Public Timeline";
1416 $as['link']['url'] = $a->get_baseurl()."/";
1421 return api_apply_template("timeline", $type, $data);
1423 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1428 function api_statuses_show(&$a, $type){
1429 if (api_user()===false) throw new ForbiddenException();
1431 $user_info = api_get_user($a);
1434 $id = intval($a->argv[3]);
1437 $id = intval($_REQUEST["id"]);
1441 $id = intval($a->argv[4]);
1443 logger('API: api_statuses_show: '.$id);
1445 $conversation = (x($_REQUEST,'conversation')?1:0);
1449 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1451 $sql_extra .= " AND `item`.`id` = %d";
1453 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1454 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1455 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1456 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1457 FROM `item`, `contact`
1458 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1459 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1460 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1463 dbesc(ACTIVITY_POST),
1468 throw new BadRequestException("There is no status with this id.");
1471 $ret = api_format_items($r,$user_info);
1473 if ($conversation) {
1474 $data = array('$statuses' => $ret);
1475 return api_apply_template("timeline", $type, $data);
1477 $data = array('$status' => $ret[0]);
1481 $data = api_rss_extra($a, $data, $user_info);
1483 return api_apply_template("status", $type, $data);
1486 api_register_func('api/statuses/show','api_statuses_show', true);
1492 function api_conversation_show(&$a, $type){
1493 if (api_user()===false) throw new ForbiddenException();
1495 $user_info = api_get_user($a);
1498 $id = intval($a->argv[3]);
1499 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1500 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1501 if ($page<0) $page=0;
1502 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1503 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1505 $start = $page*$count;
1508 $id = intval($_REQUEST["id"]);
1512 $id = intval($a->argv[4]);
1514 logger('API: api_conversation_show: '.$id);
1516 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1518 $id = $r[0]["parent"];
1523 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1525 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1526 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1527 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1528 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1529 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1530 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1531 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1532 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1533 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1534 AND `item`.`id`>%d $sql_extra
1535 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1536 intval($id), intval(api_user()),
1537 dbesc(ACTIVITY_POST),
1539 intval($start), intval($count)
1543 throw new BadRequestException("There is no conversation with this id.");
1545 $ret = api_format_items($r,$user_info);
1547 $data = array('$statuses' => $ret);
1548 return api_apply_template("timeline", $type, $data);
1550 api_register_func('api/conversation/show','api_conversation_show', true);
1556 function api_statuses_repeat(&$a, $type){
1559 if (api_user()===false) throw new ForbiddenException();
1561 $user_info = api_get_user($a);
1564 $id = intval($a->argv[3]);
1567 $id = intval($_REQUEST["id"]);
1571 $id = intval($a->argv[4]);
1573 logger('API: api_statuses_repeat: '.$id);
1575 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1576 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1577 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1578 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1579 FROM `item`, `contact`
1580 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1581 AND `contact`.`id` = `item`.`contact-id`
1582 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1583 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1584 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1586 AND `item`.`id`=%d",
1590 if ($r[0]['body'] != "") {
1591 if (!intval(get_config('system','old_share'))) {
1592 if (strpos($r[0]['body'], "[/share]") !== false) {
1593 $pos = strpos($r[0]['body'], "[share");
1594 $post = substr($r[0]['body'], $pos);
1596 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1598 $post .= $r[0]['body'];
1599 $post .= "[/share]";
1601 $_REQUEST['body'] = $post;
1603 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1605 $_REQUEST['profile_uid'] = api_user();
1606 $_REQUEST['type'] = 'wall';
1607 $_REQUEST['api_source'] = true;
1609 if (!x($_REQUEST, "source"))
1610 $_REQUEST["source"] = api_source();
1614 throw new ForbiddenException();
1616 // this should output the last post (the one we just posted).
1618 return(api_status_show($a,$type));
1620 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1625 function api_statuses_destroy(&$a, $type){
1626 if (api_user()===false) throw new ForbiddenException();
1628 $user_info = api_get_user($a);
1631 $id = intval($a->argv[3]);
1634 $id = intval($_REQUEST["id"]);
1638 $id = intval($a->argv[4]);
1640 logger('API: api_statuses_destroy: '.$id);
1642 $ret = api_statuses_show($a, $type);
1644 drop_item($id, false);
1648 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1652 * http://developer.twitter.com/doc/get/statuses/mentions
1655 function api_statuses_mentions(&$a, $type){
1656 if (api_user()===false) throw new ForbiddenException();
1658 unset($_REQUEST["user_id"]);
1659 unset($_GET["user_id"]);
1661 unset($_REQUEST["screen_name"]);
1662 unset($_GET["screen_name"]);
1664 $user_info = api_get_user($a);
1665 // get last newtork messages
1669 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1670 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1671 if ($page<0) $page=0;
1672 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1673 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1674 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1676 $start = $page*$count;
1678 // Ugly code - should be changed
1679 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1680 $myurl = substr($myurl,strpos($myurl,'://')+3);
1681 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1682 $myurl = str_replace('www.','',$myurl);
1683 $diasp_url = str_replace('/profile/','/u/',$myurl);
1686 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1688 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1689 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1690 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1691 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1692 FROM `item`, `contact`
1693 WHERE `item`.`uid` = %d AND `verb` = '%s'
1694 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1695 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1696 AND `contact`.`id` = `item`.`contact-id`
1697 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1698 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1701 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1703 dbesc(ACTIVITY_POST),
1704 dbesc(protect_sprintf($myurl)),
1705 dbesc(protect_sprintf($myurl)),
1708 intval($start), intval($count)
1711 $ret = api_format_items($r,$user_info);
1714 $data = array('$statuses' => $ret);
1718 $data = api_rss_extra($a, $data, $user_info);
1721 $as = api_format_as($a, $ret, $user_info);
1722 $as["title"] = $a->config['sitename']." Mentions";
1723 $as['link']['url'] = $a->get_baseurl()."/";
1728 return api_apply_template("timeline", $type, $data);
1730 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1731 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1734 function api_statuses_user_timeline(&$a, $type){
1735 if (api_user()===false) throw new ForbiddenException();
1737 $user_info = api_get_user($a);
1738 // get last network messages
1740 logger("api_statuses_user_timeline: api_user: ". api_user() .
1741 "\nuser_info: ".print_r($user_info, true) .
1742 "\n_REQUEST: ".print_r($_REQUEST, true),
1746 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1747 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1748 if ($page<0) $page=0;
1749 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1750 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1751 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1752 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1754 $start = $page*$count;
1757 if ($user_info['self']==1)
1758 $sql_extra .= " AND `item`.`wall` = 1 ";
1760 if ($exclude_replies > 0)
1761 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1762 if ($conversation_id > 0)
1763 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1765 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1766 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1767 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1768 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1769 FROM `item`, `contact`
1770 WHERE `item`.`uid` = %d AND `verb` = '%s'
1771 AND `item`.`contact-id` = %d
1772 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1773 AND `contact`.`id` = `item`.`contact-id`
1774 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1777 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1779 dbesc(ACTIVITY_POST),
1780 intval($user_info['cid']),
1782 intval($start), intval($count)
1785 $ret = api_format_items($r,$user_info, true);
1787 $data = array('$statuses' => $ret);
1791 $data = api_rss_extra($a, $data, $user_info);
1794 return api_apply_template("timeline", $type, $data);
1796 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1800 * Star/unstar an item
1801 * param: id : id of the item
1803 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1805 function api_favorites_create_destroy(&$a, $type){
1806 if (api_user()===false) throw new ForbiddenException();
1808 // for versioned api.
1809 /// @TODO We need a better global soluton
1811 if ($a->argv[1]=="1.1") $action_argv_id=3;
1813 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1814 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1815 if ($a->argc==$action_argv_id+2) {
1816 $itemid = intval($a->argv[$action_argv_id+1]);
1818 $itemid = intval($_REQUEST['id']);
1821 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1822 $itemid, api_user());
1824 if ($item===false || count($item)==0)
1825 throw new BadRequestException("Invalid item.");
1829 $item[0]['starred']=1;
1832 $item[0]['starred']=0;
1835 throw new BadRequestException("Invalid action ".$action);
1837 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1838 $item[0]['starred'], $itemid, api_user());
1840 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1841 $item[0]['starred'], $itemid, api_user());
1844 throw InternalServerErrorException("DB error");
1847 $user_info = api_get_user($a);
1848 $rets = api_format_items($item,$user_info);
1851 $data = array('$status' => $ret);
1855 $data = api_rss_extra($a, $data, $user_info);
1858 return api_apply_template("status", $type, $data);
1860 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1861 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1863 function api_favorites(&$a, $type){
1866 if (api_user()===false) throw new ForbiddenException();
1868 $called_api= array();
1870 $user_info = api_get_user($a);
1872 // in friendica starred item are private
1873 // return favorites only for self
1874 logger('api_favorites: self:' . $user_info['self']);
1876 if ($user_info['self']==0) {
1882 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1883 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1884 $count = (x($_GET,'count')?$_GET['count']:20);
1885 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1886 if ($page<0) $page=0;
1888 $start = $page*$count;
1891 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1893 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1894 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1895 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1896 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1897 FROM `item`, `contact`
1898 WHERE `item`.`uid` = %d
1899 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1900 AND `item`.`starred` = 1
1901 AND `contact`.`id` = `item`.`contact-id`
1902 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1905 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1908 intval($start), intval($count)
1911 $ret = api_format_items($r,$user_info);
1915 $data = array('$statuses' => $ret);
1919 $data = api_rss_extra($a, $data, $user_info);
1922 return api_apply_template("timeline", $type, $data);
1924 api_register_func('api/favorites','api_favorites', true);
1929 function api_format_as($a, $ret, $user_info) {
1931 $as['title'] = $a->config['sitename']." Public Timeline";
1933 foreach ($ret as $item) {
1934 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1935 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1936 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1937 $avatar[0]["rel"] = "avatar";
1938 $avatar[0]["type"] = "";
1939 $avatar[0]["width"] = 96;
1940 $avatar[0]["height"] = 96;
1941 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1942 $avatar[1]["rel"] = "avatar";
1943 $avatar[1]["type"] = "";
1944 $avatar[1]["width"] = 48;
1945 $avatar[1]["height"] = 48;
1946 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1947 $avatar[2]["rel"] = "avatar";
1948 $avatar[2]["type"] = "";
1949 $avatar[2]["width"] = 24;
1950 $avatar[2]["height"] = 24;
1951 $singleitem["actor"]["avatarLinks"] = $avatar;
1953 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1954 $singleitem["actor"]["image"]["rel"] = "avatar";
1955 $singleitem["actor"]["image"]["type"] = "";
1956 $singleitem["actor"]["image"]["width"] = 96;
1957 $singleitem["actor"]["image"]["height"] = 96;
1958 $singleitem["actor"]["type"] = "person";
1959 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1960 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1961 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1962 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1963 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1964 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1965 $singleitem["actor"]["contact"]["addresses"] = "";
1967 $singleitem["body"] = $item["text"];
1968 $singleitem["object"]["displayName"] = $item["text"];
1969 $singleitem["object"]["id"] = $item["url"];
1970 $singleitem["object"]["type"] = "note";
1971 $singleitem["object"]["url"] = $item["url"];
1972 //$singleitem["context"] =;
1973 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1974 $singleitem["provider"]["objectType"] = "service";
1975 $singleitem["provider"]["displayName"] = "Test";
1976 $singleitem["provider"]["url"] = "http://test.tld";
1977 $singleitem["title"] = $item["text"];
1978 $singleitem["verb"] = "post";
1979 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1980 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1981 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1982 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1983 //$singleitem["original"] = $item;
1984 $items[] = $singleitem;
1986 $as['items'] = $items;
1987 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1988 $as['link']['rel'] = "alternate";
1989 $as['link']['type'] = "text/html";
1993 function api_format_messages($item, $recipient, $sender) {
1994 // standard meta information
1996 'id' => $item['id'],
1997 'sender_id' => $sender['id'] ,
1999 'recipient_id' => $recipient['id'],
2000 'created_at' => api_date($item['created']),
2001 'sender_screen_name' => $sender['screen_name'],
2002 'recipient_screen_name' => $recipient['screen_name'],
2003 'sender' => $sender,
2004 'recipient' => $recipient,
2007 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2008 unset($ret["sender"]["uid"]);
2009 unset($ret["sender"]["self"]);
2010 unset($ret["recipient"]["uid"]);
2011 unset($ret["recipient"]["self"]);
2013 //don't send title to regular StatusNET requests to avoid confusing these apps
2014 if (x($_GET, 'getText')) {
2015 $ret['title'] = $item['title'] ;
2016 if ($_GET["getText"] == "html") {
2017 $ret['text'] = bbcode($item['body'], false, false);
2019 elseif ($_GET["getText"] == "plain") {
2020 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2021 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2025 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2027 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2028 unset($ret['sender']);
2029 unset($ret['recipient']);
2035 function api_convert_item($item) {
2037 $body = $item['body'];
2038 $attachments = api_get_attachments($body);
2040 // Workaround for ostatus messages where the title is identically to the body
2041 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2042 $statusbody = trim(html2plain($html, 0));
2044 // handle data: images
2045 $statusbody = api_format_items_embeded_images($item,$statusbody);
2047 $statustitle = trim($item['title']);
2049 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2050 $statustext = trim($statusbody);
2052 $statustext = trim($statustitle."\n\n".$statusbody);
2054 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2055 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2057 $statushtml = trim(bbcode($body, false, false));
2059 if ($item['title'] != "")
2060 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2062 $entities = api_get_entitities($statustext, $body);
2064 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2067 function api_get_attachments(&$body) {
2070 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2072 $URLSearchString = "^\[\]";
2073 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2078 $attachments = array();
2080 foreach ($images[1] AS $image) {
2081 $imagedata = get_photo_info($image);
2084 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2087 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2088 foreach ($images[0] AS $orig)
2089 $body = str_replace($orig, "", $body);
2091 return $attachments;
2094 function api_get_entitities(&$text, $bbcode) {
2097 * Links at the first character of the post
2102 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2104 if ($include_entities != "true") {
2106 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2108 foreach ($images[1] AS $image) {
2109 $replace = proxy_url($image);
2110 $text = str_replace($image, $replace, $text);
2115 $bbcode = bb_CleanPictureLinks($bbcode);
2117 // Change pure links in text to bbcode uris
2118 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2120 $entities = array();
2121 $entities["hashtags"] = array();
2122 $entities["symbols"] = array();
2123 $entities["urls"] = array();
2124 $entities["user_mentions"] = array();
2126 $URLSearchString = "^\[\]";
2128 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2130 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2131 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2132 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2134 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2135 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2136 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2138 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2139 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2140 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2142 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2144 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2145 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2147 $ordered_urls = array();
2148 foreach ($urls[1] AS $id=>$url) {
2149 //$start = strpos($text, $url, $offset);
2150 $start = iconv_strpos($text, $url, 0, "UTF-8");
2151 if (!($start === false))
2152 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2155 ksort($ordered_urls);
2158 //foreach ($urls[1] AS $id=>$url) {
2159 foreach ($ordered_urls AS $url) {
2160 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2161 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2162 $display_url = $url["title"];
2164 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2165 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2167 if (strlen($display_url) > 26)
2168 $display_url = substr($display_url, 0, 25)."…";
2171 //$start = strpos($text, $url, $offset);
2172 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2173 if (!($start === false)) {
2174 $entities["urls"][] = array("url" => $url["url"],
2175 "expanded_url" => $url["url"],
2176 "display_url" => $display_url,
2177 "indices" => array($start, $start+strlen($url["url"])));
2178 $offset = $start + 1;
2182 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2183 $ordered_images = array();
2184 foreach ($images[1] AS $image) {
2185 //$start = strpos($text, $url, $offset);
2186 $start = iconv_strpos($text, $image, 0, "UTF-8");
2187 if (!($start === false))
2188 $ordered_images[$start] = $image;
2190 //$entities["media"] = array();
2193 foreach ($ordered_images AS $url) {
2194 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2195 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2197 if (strlen($display_url) > 26)
2198 $display_url = substr($display_url, 0, 25)."…";
2200 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2201 if (!($start === false)) {
2202 $image = get_photo_info($url);
2204 // If image cache is activated, then use the following sizes:
2205 // thumb (150), small (340), medium (600) and large (1024)
2206 if (!get_config("system", "proxy_disabled")) {
2207 $media_url = proxy_url($url);
2210 $scale = scale_image($image[0], $image[1], 150);
2211 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2213 if (($image[0] > 150) OR ($image[1] > 150)) {
2214 $scale = scale_image($image[0], $image[1], 340);
2215 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2218 $scale = scale_image($image[0], $image[1], 600);
2219 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2221 if (($image[0] > 600) OR ($image[1] > 600)) {
2222 $scale = scale_image($image[0], $image[1], 1024);
2223 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2227 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2230 $entities["media"][] = array(
2232 "id_str" => (string)$start+1,
2233 "indices" => array($start, $start+strlen($url)),
2234 "media_url" => normalise_link($media_url),
2235 "media_url_https" => $media_url,
2237 "display_url" => $display_url,
2238 "expanded_url" => $url,
2242 $offset = $start + 1;
2248 function api_format_items_embeded_images(&$item, $text){
2250 $text = preg_replace_callback(
2251 "|data:image/([^;]+)[^=]+=*|m",
2252 function($match) use ($a, $item) {
2253 return $a->get_baseurl()."/display/".$item['guid'];
2260 * @brief return likes, dislikes and attend status for item
2262 * @param array $item
2264 * likes => int count
2265 * dislikes => int count
2267 function api_format_items_likes(&$item) {
2268 $activities = array(
2270 'dislike' => array(),
2271 'attendyes' => array(),
2272 'attendno' => array(),
2273 'attendmaybe' => array()
2275 $items = q('SELECT * FROM item
2276 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2277 intval($item['uid']),
2278 dbesc($item['uri']));
2279 foreach ($items as $i){
2280 builtin_activity_puller($i, $activities);
2284 $uri = $item['uri'];
2285 foreach($activities as $k => $v) {
2286 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2293 * @brief format items to be returned by api
2295 * @param array $r array of items
2296 * @param array $user_info
2297 * @param bool $filter_user filter items by $user_info
2299 function api_format_items($r,$user_info, $filter_user = false) {
2304 foreach($r as $item) {
2305 api_share_as_retweet($item);
2307 localize_item($item);
2308 $status_user = api_item_get_user($a,$item);
2310 // Look if the posts are matching if they should be filtered by user id
2311 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2314 if ($item['thr-parent'] != $item['uri']) {
2315 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2317 dbesc($item['thr-parent']));
2319 $in_reply_to_status_id = intval($r[0]['id']);
2321 $in_reply_to_status_id = intval($item['parent']);
2323 $in_reply_to_status_id_str = (string) intval($item['parent']);
2325 $in_reply_to_screen_name = NULL;
2326 $in_reply_to_user_id = NULL;
2327 $in_reply_to_user_id_str = NULL;
2329 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2331 intval($in_reply_to_status_id));
2333 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2336 if ($r[0]['nick'] == "")
2337 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2339 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2340 $in_reply_to_user_id = intval($r[0]['id']);
2341 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2345 $in_reply_to_screen_name = NULL;
2346 $in_reply_to_user_id = NULL;
2347 $in_reply_to_status_id = NULL;
2348 $in_reply_to_user_id_str = NULL;
2349 $in_reply_to_status_id_str = NULL;
2352 $converted = api_convert_item($item);
2355 'text' => $converted["text"],
2356 'truncated' => False,
2357 'created_at'=> api_date($item['created']),
2358 'in_reply_to_status_id' => $in_reply_to_status_id,
2359 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2360 'source' => (($item['app']) ? $item['app'] : 'web'),
2361 'id' => intval($item['id']),
2362 'id_str' => (string) intval($item['id']),
2363 'in_reply_to_user_id' => $in_reply_to_user_id,
2364 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2365 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2367 'favorited' => $item['starred'] ? true : false,
2368 'user' => $status_user ,
2369 //'entities' => NULL,
2370 'statusnet_html' => $converted["html"],
2371 'statusnet_conversation_id' => $item['parent'],
2372 'friendica_activities' => api_format_items_likes($item),
2375 if (count($converted["attachments"]) > 0)
2376 $status["attachments"] = $converted["attachments"];
2378 if (count($converted["entities"]) > 0)
2379 $status["entities"] = $converted["entities"];
2381 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2382 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2383 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2384 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2387 // Retweets are only valid for top postings
2388 // It doesn't work reliable with the link if its a feed
2389 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2391 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2393 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2394 $retweeted_status = $status;
2395 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2397 $status["retweeted_status"] = $retweeted_status;
2400 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2401 unset($status["user"]["uid"]);
2402 unset($status["user"]["self"]);
2404 if ($item["coord"] != "") {
2405 $coords = explode(' ',$item["coord"]);
2406 if (count($coords) == 2) {
2407 $status["geo"] = array('type' => 'Point',
2408 'coordinates' => array((float) $coords[0],
2409 (float) $coords[1]));
2419 function api_account_rate_limit_status(&$a,$type) {
2421 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2422 'remaining_hits' => (string) 150,
2423 'hourly_limit' => (string) 150,
2424 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2427 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2429 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2431 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2433 function api_help_test(&$a,$type) {
2439 return api_apply_template('test', $type, array("$ok" => $ok));
2441 api_register_func('api/help/test','api_help_test',false);
2443 function api_lists(&$a,$type) {
2447 api_register_func('api/lists','api_lists',true);
2449 function api_lists_list(&$a,$type) {
2453 api_register_func('api/lists/list','api_lists_list',true);
2456 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2457 * This function is deprecated by Twitter
2458 * returns: json, xml
2460 function api_statuses_f(&$a, $type, $qtype) {
2461 if (api_user()===false) throw new ForbiddenException();
2462 $user_info = api_get_user($a);
2464 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2465 /* this is to stop Hotot to load friends multiple times
2466 * I'm not sure if I'm missing return something or
2467 * is a bug in hotot. Workaround, meantime
2471 return array('$users' => $ret);*/
2475 if($qtype == 'friends')
2476 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2477 if($qtype == 'followers')
2478 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2480 // friends and followers only for self
2481 if ($user_info['self'] == 0)
2482 $sql_extra = " AND false ";
2484 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2489 foreach($r as $cid){
2490 $user = api_get_user($a, $cid['nurl']);
2491 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2492 unset($user["uid"]);
2493 unset($user["self"]);
2499 return array('$users' => $ret);
2502 function api_statuses_friends(&$a, $type){
2503 $data = api_statuses_f($a,$type,"friends");
2504 if ($data===false) return false;
2505 return api_apply_template("friends", $type, $data);
2507 function api_statuses_followers(&$a, $type){
2508 $data = api_statuses_f($a,$type,"followers");
2509 if ($data===false) return false;
2510 return api_apply_template("friends", $type, $data);
2512 api_register_func('api/statuses/friends','api_statuses_friends',true);
2513 api_register_func('api/statuses/followers','api_statuses_followers',true);
2520 function api_statusnet_config(&$a,$type) {
2521 $name = $a->config['sitename'];
2522 $server = $a->get_hostname();
2523 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2524 $email = $a->config['admin_email'];
2525 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2526 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2527 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2528 if($a->config['api_import_size'])
2529 $texlimit = string($a->config['api_import_size']);
2530 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2531 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2534 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2535 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2536 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2537 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2538 'shorturllength' => '30',
2539 'friendica' => array(
2540 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2541 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2542 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2543 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2548 return api_apply_template('config', $type, array('$config' => $config));
2551 api_register_func('api/statusnet/config','api_statusnet_config',false);
2553 function api_statusnet_version(&$a,$type) {
2555 $fake_statusnet_version = "0.9.7";
2557 if($type === 'xml') {
2558 header("Content-type: application/xml");
2559 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2562 elseif($type === 'json') {
2563 header("Content-type: application/json");
2564 echo '"'.$fake_statusnet_version.'"';
2568 api_register_func('api/gnusocial/version','api_statusnet_version',false);
2569 api_register_func('api/statusnet/version','api_statusnet_version',false);
2572 * @todo use api_apply_template() to return data
2574 function api_ff_ids(&$a,$type,$qtype) {
2575 if(! api_user()) throw new ForbiddenException();
2577 $user_info = api_get_user($a);
2579 if($qtype == 'friends')
2580 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2581 if($qtype == 'followers')
2582 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2584 if (!$user_info["self"])
2585 $sql_extra = " AND false ";
2587 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2589 $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",
2595 if($type === 'xml') {
2596 header("Content-type: application/xml");
2597 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2599 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2600 echo '</ids>' . "\r\n";
2603 elseif($type === 'json') {
2605 header("Content-type: application/json");
2610 $ret[] = intval($rr['id']);
2612 echo json_encode($ret);
2618 function api_friends_ids(&$a,$type) {
2619 api_ff_ids($a,$type,'friends');
2621 function api_followers_ids(&$a,$type) {
2622 api_ff_ids($a,$type,'followers');
2624 api_register_func('api/friends/ids','api_friends_ids',true);
2625 api_register_func('api/followers/ids','api_followers_ids',true);
2628 function api_direct_messages_new(&$a, $type) {
2629 if (api_user()===false) throw new ForbiddenException();
2631 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2633 $sender = api_get_user($a);
2635 if ($_POST['screen_name']) {
2636 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2638 dbesc($_POST['screen_name']));
2640 // Selecting the id by priority, friendica first
2641 api_best_nickname($r);
2643 $recipient = api_get_user($a, $r[0]['nurl']);
2645 $recipient = api_get_user($a, $_POST['user_id']);
2649 if (x($_REQUEST,'replyto')) {
2650 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2652 intval($_REQUEST['replyto']));
2653 $replyto = $r[0]['parent-uri'];
2654 $sub = $r[0]['title'];
2657 if (x($_REQUEST,'title')) {
2658 $sub = $_REQUEST['title'];
2661 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2665 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2668 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2669 $ret = api_format_messages($r[0], $recipient, $sender);
2672 $ret = array("error"=>$id);
2675 $data = Array('$messages'=>$ret);
2680 $data = api_rss_extra($a, $data, $user_info);
2683 return api_apply_template("direct_messages", $type, $data);
2686 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2688 function api_direct_messages_box(&$a, $type, $box) {
2689 if (api_user()===false) throw new ForbiddenException();
2692 $count = (x($_GET,'count')?$_GET['count']:20);
2693 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2694 if ($page<0) $page=0;
2696 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2697 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2699 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2700 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2703 unset($_REQUEST["user_id"]);
2704 unset($_GET["user_id"]);
2706 unset($_REQUEST["screen_name"]);
2707 unset($_GET["screen_name"]);
2709 $user_info = api_get_user($a);
2710 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2711 $profile_url = $user_info["url"];
2715 $start = $page*$count;
2718 if ($box=="sentbox") {
2719 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2721 elseif ($box=="conversation") {
2722 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2724 elseif ($box=="all") {
2725 $sql_extra = "true";
2727 elseif ($box=="inbox") {
2728 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2732 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2734 if ($user_id !="") {
2735 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2737 elseif($screen_name !=""){
2738 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2741 $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",
2744 intval($start), intval($count)
2749 foreach($r as $item) {
2750 if ($box == "inbox" || $item['from-url'] != $profile_url){
2751 $recipient = $user_info;
2752 $sender = api_get_user($a,normalise_link($item['contact-url']));
2754 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2755 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2756 $sender = $user_info;
2759 $ret[]=api_format_messages($item, $recipient, $sender);
2763 $data = array('$messages' => $ret);
2767 $data = api_rss_extra($a, $data, $user_info);
2770 return api_apply_template("direct_messages", $type, $data);
2774 function api_direct_messages_sentbox(&$a, $type){
2775 return api_direct_messages_box($a, $type, "sentbox");
2777 function api_direct_messages_inbox(&$a, $type){
2778 return api_direct_messages_box($a, $type, "inbox");
2780 function api_direct_messages_all(&$a, $type){
2781 return api_direct_messages_box($a, $type, "all");
2783 function api_direct_messages_conversation(&$a, $type){
2784 return api_direct_messages_box($a, $type, "conversation");
2786 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2787 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2788 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2789 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2793 function api_oauth_request_token(&$a, $type){
2795 $oauth = new FKOAuth1();
2796 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2797 }catch(Exception $e){
2798 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2803 function api_oauth_access_token(&$a, $type){
2805 $oauth = new FKOAuth1();
2806 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2807 }catch(Exception $e){
2808 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2814 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2815 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2818 function api_fr_photos_list(&$a,$type) {
2819 if (api_user()===false) throw new ForbiddenException();
2820 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2821 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2822 intval(local_user())
2825 'image/jpeg' => 'jpg',
2826 'image/png' => 'png',
2827 'image/gif' => 'gif'
2829 $data = array('photos'=>array());
2831 foreach($r as $rr) {
2833 $photo['id'] = $rr['resource-id'];
2834 $photo['album'] = $rr['album'];
2835 $photo['filename'] = $rr['filename'];
2836 $photo['type'] = $rr['type'];
2837 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2838 $data['photos'][] = $photo;
2841 return api_apply_template("photos_list", $type, $data);
2844 function api_fr_photo_detail(&$a,$type) {
2845 if (api_user()===false) throw new ForbiddenException();
2846 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2848 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2849 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2850 $data_sql = ($scale === false ? "" : "data, ");
2852 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2853 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2854 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2856 intval(local_user()),
2857 dbesc($_REQUEST['photo_id']),
2862 'image/jpeg' => 'jpg',
2863 'image/png' => 'png',
2864 'image/gif' => 'gif'
2868 $data = array('photo' => $r[0]);
2869 if ($scale !== false) {
2870 $data['photo']['data'] = base64_encode($data['photo']['data']);
2872 unset($data['photo']['datasize']); //needed only with scale param
2874 $data['photo']['link'] = array();
2875 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2876 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2878 $data['photo']['id'] = $data['photo']['resource-id'];
2879 unset($data['photo']['resource-id']);
2880 unset($data['photo']['minscale']);
2881 unset($data['photo']['maxscale']);
2884 throw new NotFoundException();
2887 return api_apply_template("photo_detail", $type, $data);
2890 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2891 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2896 * similar as /mod/redir.php
2897 * redirect to 'url' after dfrn auth
2899 * why this when there is mod/redir.php already?
2900 * This use api_user() and api_login()
2903 * c_url: url of remote contact to auth to
2904 * url: string, url to redirect after auth
2906 function api_friendica_remoteauth(&$a) {
2907 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2908 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2910 if ($url === '' || $c_url === '')
2911 throw new BadRequestException("Wrong parameters.");
2913 $c_url = normalise_link($c_url);
2917 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2922 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2923 throw new BadRequestException("Unknown contact");
2927 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2929 if($r[0]['duplex'] && $r[0]['issued-id']) {
2930 $orig_id = $r[0]['issued-id'];
2931 $dfrn_id = '1:' . $orig_id;
2933 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2934 $orig_id = $r[0]['dfrn-id'];
2935 $dfrn_id = '0:' . $orig_id;
2938 $sec = random_string();
2940 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2941 VALUES( %d, %s, '%s', '%s', %d )",
2949 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2950 $dest = (($url) ? '&destination_url=' . $url : '');
2951 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2952 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2953 . '&type=profile&sec=' . $sec . $dest . $quiet );
2955 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2958 function api_share_as_retweet(&$item) {
2959 $body = trim($item["body"]);
2961 // Skip if it isn't a pure repeated messages
2962 // Does it start with a share?
2963 if (strpos($body, "[share") > 0)
2966 // Does it end with a share?
2967 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2970 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2971 // Skip if there is no shared message in there
2972 if ($body == $attributes)
2976 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2977 if ($matches[1] != "")
2978 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2980 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2981 if ($matches[1] != "")
2982 $author = $matches[1];
2985 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2986 if ($matches[1] != "")
2987 $profile = $matches[1];
2989 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2990 if ($matches[1] != "")
2991 $profile = $matches[1];
2994 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2995 if ($matches[1] != "")
2996 $avatar = $matches[1];
2998 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2999 if ($matches[1] != "")
3000 $avatar = $matches[1];
3003 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3004 if ($matches[1] != "")
3005 $link = $matches[1];
3007 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3008 if ($matches[1] != "")
3009 $link = $matches[1];
3011 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3013 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
3016 $item["body"] = $shared_body;
3017 $item["author-name"] = $author;
3018 $item["author-link"] = $profile;
3019 $item["author-avatar"] = $avatar;
3020 $item["plink"] = $link;
3026 function api_get_nick($profile) {
3028 - remove trailing junk from profile url
3029 - pump.io check has to check the website
3034 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3035 dbesc(normalise_link($profile)));
3037 $nick = $r[0]["nick"];
3040 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3041 dbesc(normalise_link($profile)));
3043 $nick = $r[0]["nick"];
3047 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3048 if ($friendica != $profile)
3053 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3054 if ($diaspora != $profile)
3059 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3060 if ($twitter != $profile)
3066 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3067 if ($StatusnetHost != $profile) {
3068 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3069 if ($StatusnetUser != $profile) {
3070 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3071 $user = json_decode($UserData);
3073 $nick = $user->screen_name;
3078 // To-Do: look at the page if its really a pumpio site
3079 //if (!$nick == "") {
3080 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3081 // if ($pumpio != $profile)
3083 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3093 function api_clean_plain_items($Text) {
3094 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3096 $Text = bb_CleanPictureLinks($Text);
3098 $URLSearchString = "^\[\]";
3100 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3102 if ($include_entities == "true") {
3103 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3106 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
3110 function api_cleanup_share($shared) {
3111 if ($shared[2] != "type-link")
3114 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
3120 if (isset($bookmark[2][0]))
3121 $title = $bookmark[2][0];
3123 if (isset($bookmark[1][0]))
3124 $link = $bookmark[1][0];
3126 if (strpos($shared[1],$title) !== false)
3129 if (strpos($shared[1],$link) !== false)
3132 $text = trim($shared[1]);
3134 //if (strlen($text) < strlen($title))
3135 if (($text == "") AND ($title != ""))
3136 $text .= "\n\n".trim($title);
3139 $text .= "\n".trim($link);
3141 return(trim($text));
3144 function api_best_nickname(&$contacts) {
3145 $best_contact = array();
3147 if (count($contact) == 0)
3150 foreach ($contacts AS $contact)
3151 if ($contact["network"] == "") {
3152 $contact["network"] = "dfrn";
3153 $best_contact = array($contact);
3156 if (sizeof($best_contact) == 0)
3157 foreach ($contacts AS $contact)
3158 if ($contact["network"] == "dfrn")
3159 $best_contact = array($contact);
3161 if (sizeof($best_contact) == 0)
3162 foreach ($contacts AS $contact)
3163 if ($contact["network"] == "dspr")
3164 $best_contact = array($contact);
3166 if (sizeof($best_contact) == 0)
3167 foreach ($contacts AS $contact)
3168 if ($contact["network"] == "stat")
3169 $best_contact = array($contact);
3171 if (sizeof($best_contact) == 0)
3172 foreach ($contacts AS $contact)
3173 if ($contact["network"] == "pump")
3174 $best_contact = array($contact);
3176 if (sizeof($best_contact) == 0)
3177 foreach ($contacts AS $contact)
3178 if ($contact["network"] == "twit")
3179 $best_contact = array($contact);
3181 if (sizeof($best_contact) == 1)
3182 $contacts = $best_contact;
3184 $contacts = array($contacts[0]);
3187 // return all or a specified group of the user with the containing contacts
3188 function api_friendica_group_show(&$a, $type) {
3189 if (api_user()===false) throw new ForbiddenException();
3192 $user_info = api_get_user($a);
3193 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3194 $uid = $user_info['uid'];
3196 // get data of the specified group id or all groups if not specified
3198 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3201 // error message if specified gid is not in database
3203 throw new BadRequestException("gid not available");
3206 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3209 // loop through all groups and retrieve all members for adding data in the user array
3210 foreach ($r as $rr) {
3211 $members = group_get_members($rr['id']);
3213 foreach ($members as $member) {
3214 $user = api_get_user($a, $member['nurl']);
3217 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3219 return api_apply_template("group_show", $type, array('$groups' => $grps));
3221 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3224 // delete the specified group of the user
3225 function api_friendica_group_delete(&$a, $type) {
3226 if (api_user()===false) throw new ForbiddenException();
3229 $user_info = api_get_user($a);
3230 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3231 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3232 $uid = $user_info['uid'];
3234 // error if no gid specified
3235 if ($gid == 0 || $name == "")
3236 throw new BadRequestException('gid or name not specified');
3238 // get data of the specified group id
3239 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3242 // error message if specified gid is not in database
3244 throw new BadRequestException('gid not available');
3246 // get data of the specified group id and group name
3247 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3251 // error message if specified gid is not in database
3252 if (count($rname) == 0)
3253 throw new BadRequestException('wrong group name');
3256 $ret = group_rmv($uid, $name);
3259 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3260 return api_apply_template("group_delete", $type, array('$result' => $success));
3263 throw new BadRequestException('other API error');
3265 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3268 // create the specified group with the posted array of contacts
3269 function api_friendica_group_create(&$a, $type) {
3270 if (api_user()===false) throw new ForbiddenException();
3273 $user_info = api_get_user($a);
3274 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3275 $uid = $user_info['uid'];
3276 $json = json_decode($_POST['json'], true);
3277 $users = $json['user'];
3279 // error if no name specified
3281 throw new BadRequestException('group name not specified');
3283 // get data of the specified group name
3284 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3287 // error message if specified group name already exists
3288 if (count($rname) != 0)
3289 throw new BadRequestException('group name already exists');
3291 // check if specified group name is a deleted group
3292 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3295 // error message if specified group name already exists
3296 if (count($rname) != 0)
3297 $reactivate_group = true;
3300 $ret = group_add($uid, $name);
3302 $gid = group_byname($uid, $name);
3304 throw new BadRequestException('other API error');
3307 $erroraddinguser = false;
3308 $errorusers = array();
3309 foreach ($users as $user) {
3310 $cid = $user['cid'];
3311 // check if user really exists as contact
3312 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3315 if (count($contact))
3316 $result = group_add_member($uid, $name, $cid, $gid);
3318 $erroraddinguser = true;
3319 $errorusers[] = $cid;
3323 // return success message incl. missing users in array
3324 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3325 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3326 return api_apply_template("group_create", $type, array('result' => $success));
3328 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3331 // update the specified group with the posted array of contacts
3332 function api_friendica_group_update(&$a, $type) {
3333 if (api_user()===false) throw new ForbiddenException();
3336 $user_info = api_get_user($a);
3337 $uid = $user_info['uid'];
3338 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3339 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3340 $json = json_decode($_POST['json'], true);
3341 $users = $json['user'];
3343 // error if no name specified
3345 throw new BadRequestException('group name not specified');
3347 // error if no gid specified
3349 throw new BadRequestException('gid not specified');
3352 $members = group_get_members($gid);
3353 foreach ($members as $member) {
3354 $cid = $member['id'];
3355 foreach ($users as $user) {
3356 $found = ($user['cid'] == $cid ? true : false);
3359 $ret = group_rmv_member($uid, $name, $cid);
3364 $erroraddinguser = false;
3365 $errorusers = array();
3366 foreach ($users as $user) {
3367 $cid = $user['cid'];
3368 // check if user really exists as contact
3369 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3372 if (count($contact))
3373 $result = group_add_member($uid, $name, $cid, $gid);
3375 $erroraddinguser = true;
3376 $errorusers[] = $cid;
3380 // return success message incl. missing users in array
3381 $status = ($erroraddinguser ? "missing user" : "ok");
3382 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3383 return api_apply_template("group_update", $type, array('result' => $success));
3385 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3388 function api_friendica_activity(&$a, $type) {
3389 if (api_user()===false) throw new ForbiddenException();
3390 $verb = strtolower($a->argv[3]);
3391 $verb = preg_replace("|\..*$|", "", $verb);
3393 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3395 $res = do_like($id, $verb);
3402 return api_apply_template('test', $type, array('ok' => $ok));
3404 throw new BadRequestException('Error adding activity');
3408 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3409 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3410 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3411 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3412 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3413 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3414 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3415 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3416 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3417 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3420 * @brief Returns notifications
3423 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3426 function api_friendica_notification(&$a, $type) {
3427 if (api_user()===false) throw new ForbiddenException();
3428 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3429 $nm = new NotificationsManager();
3431 $notes = $nm->getAll(array(), "+seen -date", 50);
3432 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3436 * @brief Set notification as seen and returns associated item (if possible)
3438 * POST request with 'id' param as notification id
3441 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3444 function api_friendica_notification_seen(&$a, $type){
3445 if (api_user()===false) throw new ForbiddenException();
3446 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3448 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3450 $nm = new NotificationsManager();
3451 $note = $nm->getByID($id);
3452 if (is_null($note)) throw new BadRequestException("Invalid argument");
3454 $nm->setSeen($note);
3455 if ($note['otype']=='item') {
3456 // would be really better with an ItemsManager and $im->getByID() :-P
3457 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3458 intval($note['iid']),
3459 intval(local_user())
3462 // we found the item, return it to the user
3463 $user_info = api_get_user($a);
3464 $ret = api_format_items($r,$user_info);
3465 $data = array('$statuses' => $ret);
3466 return api_apply_template("timeline", $type, $data);
3468 // the item can't be found, but we set the note as seen, so we count this as a success
3470 return api_apply_template('<auto>', $type, array('status' => "success"));
3473 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3474 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3479 [pagename] => api/1.1/statuses/lookup.json
3480 [id] => 605138389168451584
3481 [include_cards] => true
3482 [cards_platform] => Android-12
3483 [include_entities] => true
3484 [include_my_retweet] => 1
3486 [include_reply_count] => true
3487 [include_descendent_reply_count] => true
3491 Not implemented by now:
3492 statuses/retweets_of_me
3497 account/update_location
3498 account/update_profile_background_image
3499 account/update_profile_image
3503 Not implemented in status.net:
3504 statuses/retweeted_to_me
3505 statuses/retweeted_by_me
3506 direct_messages/destroy
3508 account/update_delivery_device
3509 notifications/follow