3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
27 require_once('include/plaintext.php');
30 define('API_METHOD_ANY','*');
31 define('API_METHOD_GET','GET');
32 define('API_METHOD_POST','POST,PUT');
33 define('API_METHOD_DELETE','POST,DELETE');
41 * @brief Auth API user
43 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
44 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
45 * into a page, and visitors will post something without noticing it).
48 if ($_SESSION['allow_api'])
55 * @brief Get source name from API client
57 * Clients can send 'source' parameter to be show in post metadata
58 * as "sent via <source>".
59 * Some clients doesn't send a source param, we support ones we know
63 * Client source name, default to "api" if unset/unknown
65 function api_source() {
66 if (requestdata('source'))
67 return (requestdata('source'));
69 // Support for known clients that doesn't send a source name
70 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
73 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
79 * @brief Format date for API
81 * @param string $str Source date, as UTC
82 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
84 function api_date($str){
85 //Wed May 23 06:01:13 +0000 2007
86 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
90 * @brief Register API endpoint
92 * Register a function to be the endpont for defined API path.
94 * @param string $path API URL path, relative to $a->get_baseurl()
95 * @param string $func Function name to call on path request
96 * @param bool $auth API need logged user
97 * @param string $method
98 * HTTP method reqiured to call this endpoint.
99 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
100 * Default to API_METHOD_ANY
102 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
110 // Workaround for hotot
111 $path = str_replace("api/", "api/1.1/", $path);
120 * @brief Login API user
122 * Log in user via OAuth1 or Simple HTTP Auth.
123 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
126 * @hook 'authenticate'
128 * 'username' => username from login form
129 * 'password' => password from login form
130 * 'authenticated' => return status,
131 * 'user_record' => return authenticated user record
133 * array $user logged user record
135 function api_login(&$a){
138 $oauth = new FKOAuth1();
139 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
140 if (!is_null($token)){
141 $oauth->loginUser($token->uid);
142 call_hooks('logged_in', $a->user);
145 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
146 }catch(Exception $e){
152 // workaround for HTTP-auth in CGI mode
153 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
154 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
155 if(strlen($userpass)) {
156 list($name, $password) = explode(':', $userpass);
157 $_SERVER['PHP_AUTH_USER'] = $name;
158 $_SERVER['PHP_AUTH_PW'] = $password;
162 if (!isset($_SERVER['PHP_AUTH_USER'])) {
163 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
164 header('WWW-Authenticate: Basic realm="Friendica"');
165 throw new UnauthorizedException("This API requires login");
168 $user = $_SERVER['PHP_AUTH_USER'];
169 $password = $_SERVER['PHP_AUTH_PW'];
170 $encrypted = hash('whirlpool',trim($password));
172 // allow "user@server" login (but ignore 'server' part)
173 $at=strstr($user, "@", true);
174 if ( $at ) $user=$at;
177 * next code from mod/auth.php. needs better solution
182 'username' => trim($user),
183 'password' => trim($password),
184 'authenticated' => 0,
185 'user_record' => null
190 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
191 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
192 * and later plugins should not interfere with an earlier one that succeeded.
196 call_hooks('authenticate', $addon_auth);
198 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
199 $record = $addon_auth['user_record'];
202 // process normal login request
204 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
205 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
214 if((! $record) || (! count($record))) {
215 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
216 header('WWW-Authenticate: Basic realm="Friendica"');
217 #header('HTTP/1.0 401 Unauthorized');
218 #die('This api requires login');
219 throw new UnauthorizedException("This API requires login");
222 authenticate_success($record); $_SESSION["allow_api"] = true;
224 call_hooks('logged_in', $a->user);
229 * @brief Check HTTP method of called API
231 * API endpoints can define which HTTP method to accept when called.
232 * This function check the current HTTP method agains endpoint
235 * @param string $method Required methods, uppercase, separated by comma
238 function api_check_method($method) {
239 if ($method=="*") return True;
240 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
244 * @brief Main API entry point
246 * Authenticate user, call registered API function, set HTTP headers
249 * @return string API call result
251 function api_call(&$a){
252 GLOBAL $API, $called_api;
255 if (strpos($a->query_string, ".xml")>0) $type="xml";
256 if (strpos($a->query_string, ".json")>0) $type="json";
257 if (strpos($a->query_string, ".rss")>0) $type="rss";
258 if (strpos($a->query_string, ".atom")>0) $type="atom";
259 if (strpos($a->query_string, ".as")>0) $type="as";
261 foreach ($API as $p=>$info){
262 if (strpos($a->query_string, $p)===0){
263 if (!api_check_method($info['method'])){
264 throw new MethodNotAllowedException();
267 $called_api= explode("/",$p);
268 //unset($_SERVER['PHP_AUTH_USER']);
269 if ($info['auth']===true && api_user()===false) {
273 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
274 logger('API parameters: ' . print_r($_REQUEST,true));
276 $stamp = microtime(true);
277 $r = call_user_func($info['func'], $a, $type);
278 $duration = (float)(microtime(true)-$stamp);
279 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
282 // api function returned false withour throw an
283 // exception. This should not happend, throw a 500
284 throw new InternalServerErrorException();
289 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
290 header ("Content-Type: text/xml");
291 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
294 header ("Content-Type: application/json");
296 $json = json_encode($rr);
297 if ($_GET['callback'])
298 $json = $_GET['callback']."(".$json.")";
302 header ("Content-Type: application/rss+xml");
303 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
306 header ("Content-Type: application/atom+xml");
307 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
310 //header ("Content-Type: application/json");
312 // return json_encode($rr);
313 return json_encode($r);
319 throw new NotImplementedException();
320 } catch (HTTPException $e) {
321 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
322 return api_error($a, $type, $e);
327 * @brief Format API error string
330 * @param string $type Return type (xml, json, rss, as)
331 * @param HTTPException $error Error object
332 * @return strin error message formatted as $type
334 function api_error(&$a, $type, $e) {
335 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
336 # TODO: https://dev.twitter.com/overview/api/response-codes
337 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
340 header ("Content-Type: text/xml");
341 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
344 header ("Content-Type: application/json");
345 return json_encode(array(
347 'request' => $a->query_string,
348 'code' => $e->httpcode." ".$e->httpdesc
352 header ("Content-Type: application/rss+xml");
353 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
356 header ("Content-Type: application/atom+xml");
357 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
363 * @brief Set values for RSS template
366 * @param array $arr Array to be passed to template
367 * @param array $user_info
370 function api_rss_extra(&$a, $arr, $user_info){
371 if (is_null($user_info)) $user_info = api_get_user($a);
372 $arr['$user'] = $user_info;
373 $arr['$rss'] = array(
374 'alternate' => $user_info['url'],
375 'self' => $a->get_baseurl(). "/". $a->query_string,
376 'base' => $a->get_baseurl(),
377 'updated' => api_date(null),
378 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
379 'language' => $user_info['language'],
380 'logo' => $a->get_baseurl()."/images/friendica-32.png",
388 * @brief Unique contact to contact url.
390 * @param int $id Contact id
391 * @return bool|string
392 * Contact url or False if contact id is unknown
394 function api_unique_id_to_url($id){
395 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
398 return ($r[0]["url"]);
404 * @brief Get user info array.
407 * @param int|string $contact_id Contact ID or URL
408 * @param string $type Return type (for errors)
410 function api_get_user(&$a, $contact_id = Null, $type = "json"){
417 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
419 // Searching for contact URL
420 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
421 $user = dbesc(normalise_link($contact_id));
423 $extra_query = "AND `contact`.`nurl` = '%s' ";
424 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
427 // Searching for unique contact id
428 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
429 $user = dbesc(api_unique_id_to_url($contact_id));
432 throw new BadRequestException("User not found.");
435 $extra_query = "AND `contact`.`nurl` = '%s' ";
436 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
439 if(is_null($user) && x($_GET, 'user_id')) {
440 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
443 throw new BadRequestException("User not found.");
446 $extra_query = "AND `contact`.`nurl` = '%s' ";
447 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
449 if(is_null($user) && x($_GET, 'screen_name')) {
450 $user = dbesc($_GET['screen_name']);
452 $extra_query = "AND `contact`.`nick` = '%s' ";
453 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
456 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
457 $argid = count($called_api);
458 list($user, $null) = explode(".",$a->argv[$argid]);
459 if(is_numeric($user)){
460 $user = dbesc(api_unique_id_to_url($user));
466 $extra_query = "AND `contact`.`nurl` = '%s' ";
467 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
469 $user = dbesc($user);
471 $extra_query = "AND `contact`.`nick` = '%s' ";
472 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
476 logger("api_get_user: user ".$user, LOGGER_DEBUG);
479 if (api_user()===false) {
483 $user = $_SESSION['uid'];
484 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
489 logger('api_user: ' . $extra_query . ', user: ' . $user);
491 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
497 // Selecting the id by priority, friendica first
498 api_best_nickname($uinfo);
500 // if the contact wasn't found, fetch it from the unique contacts
501 if (count($uinfo)==0) {
505 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
508 // If no nick where given, extract it from the address
509 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
510 $r[0]['nick'] = api_get_nick($r[0]["url"]);
514 'id_str' => (string) $r[0]["id"],
515 'name' => $r[0]["name"],
516 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
517 'location' => $r[0]["location"],
518 'description' => $r[0]["about"],
519 'url' => $r[0]["url"],
520 'protected' => false,
521 'followers_count' => 0,
522 'friends_count' => 0,
524 'created_at' => api_date($r[0]["created"]),
525 'favourites_count' => 0,
527 'time_zone' => 'UTC',
528 'geo_enabled' => false,
530 'statuses_count' => 0,
532 'contributors_enabled' => false,
533 'is_translator' => false,
534 'is_translation_enabled' => false,
535 'profile_image_url' => $r[0]["photo"],
536 'profile_image_url_https' => $r[0]["photo"],
537 'following' => false,
538 'follow_request_sent' => false,
539 'notifications' => false,
540 'statusnet_blocking' => false,
541 'notifications' => false,
542 'statusnet_profile_url' => $r[0]["url"],
546 'network' => $r[0]["network"],
551 throw new BadRequestException("User not found.");
555 if($uinfo[0]['self']) {
556 $usr = q("select * from user where uid = %d limit 1",
559 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
563 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
564 // count public wall messages
565 $r = q("SELECT count(*) as `count` FROM `item`
568 intval($uinfo[0]['uid'])
570 $countitms = $r[0]['count'];
573 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
574 $r = q("SELECT count(*) as `count` FROM `item`
575 WHERE `contact-id` = %d",
576 intval($uinfo[0]['id'])
578 $countitms = $r[0]['count'];
582 $r = q("SELECT count(*) as `count` FROM `contact`
583 WHERE `uid` = %d AND `rel` IN ( %d, %d )
584 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
585 intval($uinfo[0]['uid']),
586 intval(CONTACT_IS_SHARING),
587 intval(CONTACT_IS_FRIEND)
589 $countfriends = $r[0]['count'];
591 $r = q("SELECT count(*) as `count` FROM `contact`
592 WHERE `uid` = %d AND `rel` IN ( %d, %d )
593 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
594 intval($uinfo[0]['uid']),
595 intval(CONTACT_IS_FOLLOWER),
596 intval(CONTACT_IS_FRIEND)
598 $countfollowers = $r[0]['count'];
600 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
601 intval($uinfo[0]['uid'])
603 $starred = $r[0]['count'];
606 if(! $uinfo[0]['self']) {
612 // Add a nick if it isn't present there
613 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
614 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
617 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
619 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
620 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
623 'id' => intval($gcontact_id),
624 'id_str' => (string) intval($gcontact_id),
625 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
626 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
627 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
628 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
629 'profile_image_url' => $uinfo[0]['micro'],
630 'profile_image_url_https' => $uinfo[0]['micro'],
631 'url' => $uinfo[0]['url'],
632 'protected' => false,
633 'followers_count' => intval($countfollowers),
634 'friends_count' => intval($countfriends),
635 'created_at' => api_date($uinfo[0]['created']),
636 'favourites_count' => intval($starred),
638 'time_zone' => 'UTC',
639 'statuses_count' => intval($countitms),
640 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
642 'statusnet_blocking' => false,
643 'notifications' => false,
644 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
645 'statusnet_profile_url' => $uinfo[0]['url'],
646 'uid' => intval($uinfo[0]['uid']),
647 'cid' => intval($uinfo[0]['cid']),
648 'self' => $uinfo[0]['self'],
649 'network' => $uinfo[0]['network'],
656 function api_item_get_user(&$a, $item) {
658 // Make sure that there is an entry in the global contacts for author and owner
659 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
660 "photo" => $item['author-avatar'], "name" => $item['author-name']));
662 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
663 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
665 // Comments in threads may appear as wall-to-wall postings.
666 // So only take the owner at the top posting.
667 if ($item["id"] == $item["parent"])
668 $status_user = api_get_user($a,$item["owner-link"]);
670 $status_user = api_get_user($a,$item["author-link"]);
672 $status_user["protected"] = (($item["allow_cid"] != "") OR
673 ($item["allow_gid"] != "") OR
674 ($item["deny_cid"] != "") OR
675 ($item["deny_gid"] != "") OR
678 return ($status_user);
683 * @brief transform $data array in xml without a template
686 * @return string xml string
688 function api_array_to_xml($data, $ename="") {
691 if (count($data)==1 && !is_array($data[0])) {
692 $ename = array_keys($data)[0];
694 return "<$ename>$v</$ename>";
696 foreach($data as $k=>$v) {
699 $attrs .= sprintf('%s="%s" ', $k, $v);
701 if (is_numeric($k)) $k=trim($ename,'s');
702 $childs.=api_array_to_xml($v, $k);
706 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
711 * load api $templatename for $type and replace $data array
713 function api_apply_template($templatename, $type, $data){
721 $data = array_xmlify($data);
722 if ($templatename==="<auto>") {
723 $ret = api_array_to_xml($data);
725 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
727 header ("Content-Type: text/xml");
728 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
731 $ret = replace_macros($tpl, $data);
747 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
748 * returns a 401 status code and an error message if not.
749 * http://developer.twitter.com/doc/get/account/verify_credentials
751 function api_account_verify_credentials(&$a, $type){
752 if (api_user()===false) throw new ForbiddenException();
754 unset($_REQUEST["user_id"]);
755 unset($_GET["user_id"]);
757 unset($_REQUEST["screen_name"]);
758 unset($_GET["screen_name"]);
760 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
762 $user_info = api_get_user($a);
764 // "verified" isn't used here in the standard
765 unset($user_info["verified"]);
767 // - Adding last status
769 $user_info["status"] = api_status_show($a,"raw");
770 if (!count($user_info["status"]))
771 unset($user_info["status"]);
773 unset($user_info["status"]["user"]);
776 // "uid" and "self" are only needed for some internal stuff, so remove it from here
777 unset($user_info["uid"]);
778 unset($user_info["self"]);
780 return api_apply_template("user", $type, array('$user' => $user_info));
783 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
787 * get data from $_POST or $_GET
789 function requestdata($k){
790 if (isset($_POST[$k])){
793 if (isset($_GET[$k])){
799 /*Waitman Gobble Mod*/
800 function api_statuses_mediap(&$a, $type) {
801 if (api_user()===false) {
802 logger('api_statuses_update: no user');
803 throw new ForbiddenException();
805 $user_info = api_get_user($a);
807 $_REQUEST['type'] = 'wall';
808 $_REQUEST['profile_uid'] = api_user();
809 $_REQUEST['api_source'] = true;
810 $txt = requestdata('status');
811 //$txt = urldecode(requestdata('status'));
813 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
815 $txt = html2bb_video($txt);
816 $config = HTMLPurifier_Config::createDefault();
817 $config->set('Cache.DefinitionImpl', null);
818 $purifier = new HTMLPurifier($config);
819 $txt = $purifier->purify($txt);
821 $txt = html2bbcode($txt);
823 $a->argv[1]=$user_info['screen_name']; //should be set to username?
825 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
826 $bebop = wall_upload_post($a);
828 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
829 $_REQUEST['body']=$txt."\n\n".$bebop;
832 // this should output the last post (the one we just posted).
833 return api_status_show($a,$type);
835 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
836 /*Waitman Gobble Mod*/
839 function api_statuses_update(&$a, $type) {
840 if (api_user()===false) {
841 logger('api_statuses_update: no user');
842 throw new ForbiddenException();
845 $user_info = api_get_user($a);
847 // convert $_POST array items to the form we use for web posts.
849 // logger('api_post: ' . print_r($_POST,true));
851 if(requestdata('htmlstatus')) {
852 $txt = requestdata('htmlstatus');
853 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
854 $txt = html2bb_video($txt);
856 $config = HTMLPurifier_Config::createDefault();
857 $config->set('Cache.DefinitionImpl', null);
859 $purifier = new HTMLPurifier($config);
860 $txt = $purifier->purify($txt);
862 $_REQUEST['body'] = html2bbcode($txt);
866 $_REQUEST['body'] = requestdata('status');
868 $_REQUEST['title'] = requestdata('title');
870 $parent = requestdata('in_reply_to_status_id');
872 // Twidere sends "-1" if it is no reply ...
876 if(ctype_digit($parent))
877 $_REQUEST['parent'] = $parent;
879 $_REQUEST['parent_uri'] = $parent;
881 if(requestdata('lat') && requestdata('long'))
882 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
883 $_REQUEST['profile_uid'] = api_user();
886 $_REQUEST['type'] = 'net-comment';
888 // Check for throttling (maximum posts per day, week and month)
889 $throttle_day = get_config('system','throttle_limit_day');
890 if ($throttle_day > 0) {
891 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
893 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
894 AND `created` > '%s' AND `id` = `parent`",
895 intval(api_user()), dbesc($datefrom));
898 $posts_day = $r[0]["posts_day"];
902 if ($posts_day > $throttle_day) {
903 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
904 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
905 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
909 $throttle_week = get_config('system','throttle_limit_week');
910 if ($throttle_week > 0) {
911 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
913 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
914 AND `created` > '%s' AND `id` = `parent`",
915 intval(api_user()), dbesc($datefrom));
918 $posts_week = $r[0]["posts_week"];
922 if ($posts_week > $throttle_week) {
923 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
924 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
925 throw new TooManyRequestsException(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)));
946 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
950 $_REQUEST['type'] = 'wall';
953 if(x($_FILES,'media')) {
954 // upload the image if we have one
955 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
956 $media = wall_upload_post($a);
958 $_REQUEST['body'] .= "\n\n".$media;
961 // To-Do: Multiple IDs
962 if (requestdata('media_ids')) {
963 $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",
964 intval(requestdata('media_ids')), api_user());
966 $phototypes = Photo::supportedTypes();
967 $ext = $phototypes[$r[0]['type']];
968 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
969 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
973 // set this so that the item_post() function is quiet and doesn't redirect or emit json
975 $_REQUEST['api_source'] = true;
977 if (!x($_REQUEST, "source"))
978 $_REQUEST["source"] = api_source();
980 // call out normal post function
984 // this should output the last post (the one we just posted).
985 return api_status_show($a,$type);
987 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
988 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
991 function api_media_upload(&$a, $type) {
992 if (api_user()===false) {
994 throw new ForbiddenException();
997 $user_info = api_get_user($a);
999 if(!x($_FILES,'media')) {
1001 throw new BadRequestException("No media.");
1004 $media = wall_upload_post($a, false);
1007 throw new InternalServerErrorException();
1010 $returndata = array();
1011 $returndata["media_id"] = $media["id"];
1012 $returndata["media_id_string"] = (string)$media["id"];
1013 $returndata["size"] = $media["size"];
1014 $returndata["image"] = array("w" => $media["width"],
1015 "h" => $media["height"],
1016 "image_type" => $media["type"]);
1018 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1020 return array("media" => $returndata);
1022 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1024 function api_status_show(&$a, $type){
1025 $user_info = api_get_user($a);
1027 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1030 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1034 // get last public wall message
1035 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1036 FROM `item`, `item` as `i`
1037 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1038 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1039 AND `i`.`id` = `item`.`parent`
1040 AND `item`.`type`!='activity' $privacy_sql
1041 ORDER BY `item`.`created` DESC
1043 intval($user_info['cid']),
1045 dbesc($user_info['url']),
1046 dbesc(normalise_link($user_info['url'])),
1047 dbesc($user_info['url']),
1048 dbesc(normalise_link($user_info['url']))
1051 if (count($lastwall)>0){
1052 $lastwall = $lastwall[0];
1054 $in_reply_to_status_id = NULL;
1055 $in_reply_to_user_id = NULL;
1056 $in_reply_to_status_id_str = NULL;
1057 $in_reply_to_user_id_str = NULL;
1058 $in_reply_to_screen_name = NULL;
1059 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1060 $in_reply_to_status_id= intval($lastwall['parent']);
1061 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1063 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1065 if ($r[0]['nick'] == "")
1066 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1068 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1069 $in_reply_to_user_id = intval($r[0]['id']);
1070 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1074 // There seems to be situation, where both fields are identical:
1075 // https://github.com/friendica/friendica/issues/1010
1076 // This is a bugfix for that.
1077 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1078 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1079 $in_reply_to_status_id = NULL;
1080 $in_reply_to_user_id = NULL;
1081 $in_reply_to_status_id_str = NULL;
1082 $in_reply_to_user_id_str = NULL;
1083 $in_reply_to_screen_name = NULL;
1086 $converted = api_convert_item($lastwall);
1088 $status_info = array(
1089 'created_at' => api_date($lastwall['created']),
1090 'id' => intval($lastwall['id']),
1091 'id_str' => (string) $lastwall['id'],
1092 'text' => $converted["text"],
1093 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1094 'truncated' => false,
1095 'in_reply_to_status_id' => $in_reply_to_status_id,
1096 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1097 'in_reply_to_user_id' => $in_reply_to_user_id,
1098 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1099 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1100 'user' => $user_info,
1102 'coordinates' => "",
1104 'contributors' => "",
1105 'is_quote_status' => false,
1106 'retweet_count' => 0,
1107 'favorite_count' => 0,
1108 'favorited' => $lastwall['starred'] ? true : false,
1109 'retweeted' => false,
1110 'possibly_sensitive' => false,
1112 'statusnet_html' => $converted["html"],
1113 'statusnet_conversation_id' => $lastwall['parent'],
1116 if (count($converted["attachments"]) > 0)
1117 $status_info["attachments"] = $converted["attachments"];
1119 if (count($converted["entities"]) > 0)
1120 $status_info["entities"] = $converted["entities"];
1122 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1123 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1124 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1125 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1127 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1128 unset($status_info["user"]["uid"]);
1129 unset($status_info["user"]["self"]);
1132 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1135 return($status_info);
1137 return api_apply_template("status", $type, array('$status' => $status_info));
1146 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1147 * The author's most recent status will be returned inline.
1148 * http://developer.twitter.com/doc/get/users/show
1150 function api_users_show(&$a, $type){
1151 $user_info = api_get_user($a);
1153 $lastwall = q("SELECT `item`.*
1154 FROM `item`, `contact`
1155 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1156 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1157 AND `contact`.`id`=`item`.`contact-id`
1158 AND `type`!='activity'
1159 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1160 ORDER BY `created` DESC
1163 dbesc(ACTIVITY_POST),
1164 intval($user_info['cid']),
1165 dbesc($user_info['url']),
1166 dbesc(normalise_link($user_info['url'])),
1167 dbesc($user_info['url']),
1168 dbesc(normalise_link($user_info['url']))
1170 if (count($lastwall)>0){
1171 $lastwall = $lastwall[0];
1173 $in_reply_to_status_id = NULL;
1174 $in_reply_to_user_id = NULL;
1175 $in_reply_to_status_id_str = NULL;
1176 $in_reply_to_user_id_str = NULL;
1177 $in_reply_to_screen_name = NULL;
1178 if ($lastwall['parent']!=$lastwall['id']) {
1179 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1180 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1181 if (count($reply)>0) {
1182 $in_reply_to_status_id = intval($lastwall['parent']);
1183 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1185 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1187 if ($r[0]['nick'] == "")
1188 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1190 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1191 $in_reply_to_user_id = intval($r[0]['id']);
1192 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1197 $converted = api_convert_item($lastwall);
1199 $user_info['status'] = array(
1200 'text' => $converted["text"],
1201 'truncated' => false,
1202 'created_at' => api_date($lastwall['created']),
1203 'in_reply_to_status_id' => $in_reply_to_status_id,
1204 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1205 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1206 'id' => intval($lastwall['contact-id']),
1207 'id_str' => (string) $lastwall['contact-id'],
1208 'in_reply_to_user_id' => $in_reply_to_user_id,
1209 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1210 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1212 'favorited' => $lastwall['starred'] ? true : false,
1213 'statusnet_html' => $converted["html"],
1214 'statusnet_conversation_id' => $lastwall['parent'],
1217 if (count($converted["attachments"]) > 0)
1218 $user_info["status"]["attachments"] = $converted["attachments"];
1220 if (count($converted["entities"]) > 0)
1221 $user_info["status"]["entities"] = $converted["entities"];
1223 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1224 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1225 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1226 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1230 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1231 unset($user_info["uid"]);
1232 unset($user_info["self"]);
1234 return api_apply_template("user", $type, array('$user' => $user_info));
1237 api_register_func('api/users/show','api_users_show');
1240 function api_users_search(&$a, $type) {
1241 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1243 $userlist = array();
1245 if (isset($_GET["q"])) {
1246 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1248 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1251 foreach ($r AS $user) {
1252 $user_info = api_get_user($a, $user["id"]);
1253 //echo print_r($user_info, true)."\n";
1254 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1255 $userlist[] = $userdata["user"];
1257 $userlist = array("users" => $userlist);
1259 throw new BadRequestException("User not found.");
1262 throw new BadRequestException("User not found.");
1267 api_register_func('api/users/search','api_users_search');
1271 * http://developer.twitter.com/doc/get/statuses/home_timeline
1273 * TODO: Optional parameters
1274 * TODO: Add reply info
1276 function api_statuses_home_timeline(&$a, $type){
1277 if (api_user()===false) throw new ForbiddenException();
1279 unset($_REQUEST["user_id"]);
1280 unset($_GET["user_id"]);
1282 unset($_REQUEST["screen_name"]);
1283 unset($_GET["screen_name"]);
1285 $user_info = api_get_user($a);
1286 // get last newtork messages
1290 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1291 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1292 if ($page<0) $page=0;
1293 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1294 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1295 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1296 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1297 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1299 $start = $page*$count;
1303 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1304 if ($exclude_replies > 0)
1305 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1306 if ($conversation_id > 0)
1307 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1309 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1310 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1311 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1312 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1313 FROM `item`, `contact`
1314 WHERE `item`.`uid` = %d AND `verb` = '%s'
1315 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1316 AND `contact`.`id` = `item`.`contact-id`
1317 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1320 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1322 dbesc(ACTIVITY_POST),
1324 intval($start), intval($count)
1327 $ret = api_format_items($r,$user_info);
1329 // Set all posts from the query above to seen
1331 foreach ($r AS $item)
1332 $idarray[] = intval($item["id"]);
1334 $idlist = implode(",", $idarray);
1336 if ($idlist != "") {
1337 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1340 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1343 $data = array('$statuses' => $ret);
1347 $data = api_rss_extra($a, $data, $user_info);
1350 $as = api_format_as($a, $ret, $user_info);
1351 $as['title'] = $a->config['sitename']." Home Timeline";
1352 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1357 return api_apply_template("timeline", $type, $data);
1359 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1360 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1362 function api_statuses_public_timeline(&$a, $type){
1363 if (api_user()===false) throw new ForbiddenException();
1365 $user_info = api_get_user($a);
1366 // get last newtork messages
1370 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1371 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1372 if ($page<0) $page=0;
1373 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1374 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1375 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1376 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1377 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1379 $start = $page*$count;
1382 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1383 if ($exclude_replies > 0)
1384 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1385 if ($conversation_id > 0)
1386 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1388 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1389 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1390 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1391 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1392 `user`.`nickname`, `user`.`hidewall`
1393 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1394 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1395 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1396 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1397 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1398 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1399 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1402 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1403 dbesc(ACTIVITY_POST),
1408 $ret = api_format_items($r,$user_info);
1411 $data = array('$statuses' => $ret);
1415 $data = api_rss_extra($a, $data, $user_info);
1418 $as = api_format_as($a, $ret, $user_info);
1419 $as['title'] = $a->config['sitename']." Public Timeline";
1420 $as['link']['url'] = $a->get_baseurl()."/";
1425 return api_apply_template("timeline", $type, $data);
1427 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1432 function api_statuses_show(&$a, $type){
1433 if (api_user()===false) throw new ForbiddenException();
1435 $user_info = api_get_user($a);
1438 $id = intval($a->argv[3]);
1441 $id = intval($_REQUEST["id"]);
1445 $id = intval($a->argv[4]);
1447 logger('API: api_statuses_show: '.$id);
1449 $conversation = (x($_REQUEST,'conversation')?1:0);
1453 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1455 $sql_extra .= " AND `item`.`id` = %d";
1457 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1458 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1459 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1460 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1461 FROM `item`, `contact`
1462 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1463 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1464 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1467 dbesc(ACTIVITY_POST),
1472 throw new BadRequestException("There is no status with this id.");
1475 $ret = api_format_items($r,$user_info);
1477 if ($conversation) {
1478 $data = array('$statuses' => $ret);
1479 return api_apply_template("timeline", $type, $data);
1481 $data = array('$status' => $ret[0]);
1485 $data = api_rss_extra($a, $data, $user_info);
1487 return api_apply_template("status", $type, $data);
1490 api_register_func('api/statuses/show','api_statuses_show', true);
1496 function api_conversation_show(&$a, $type){
1497 if (api_user()===false) throw new ForbiddenException();
1499 $user_info = api_get_user($a);
1502 $id = intval($a->argv[3]);
1503 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1504 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1505 if ($page<0) $page=0;
1506 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1507 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1509 $start = $page*$count;
1512 $id = intval($_REQUEST["id"]);
1516 $id = intval($a->argv[4]);
1518 logger('API: api_conversation_show: '.$id);
1520 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1522 $id = $r[0]["parent"];
1527 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1529 // Not sure why this query was so complicated. We should keep it here for a while,
1530 // just to make sure that we really don't need it.
1531 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1532 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1534 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1535 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1536 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1537 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1539 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1540 WHERE `item`.`parent` = %d AND `item`.`visible`
1541 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1542 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1543 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1544 AND `item`.`id`>%d $sql_extra
1545 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1546 intval($id), intval(api_user()),
1547 dbesc(ACTIVITY_POST),
1549 intval($start), intval($count)
1553 throw new BadRequestException("There is no conversation with this id.");
1555 $ret = api_format_items($r,$user_info);
1557 $data = array('$statuses' => $ret);
1558 return api_apply_template("timeline", $type, $data);
1560 api_register_func('api/conversation/show','api_conversation_show', true);
1561 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1567 function api_statuses_repeat(&$a, $type){
1570 if (api_user()===false) throw new ForbiddenException();
1572 $user_info = api_get_user($a);
1575 $id = intval($a->argv[3]);
1578 $id = intval($_REQUEST["id"]);
1582 $id = intval($a->argv[4]);
1584 logger('API: api_statuses_repeat: '.$id);
1586 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1587 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1588 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1589 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1590 FROM `item`, `contact`
1591 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1592 AND `contact`.`id` = `item`.`contact-id`
1593 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1594 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1595 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1597 AND `item`.`id`=%d",
1601 if ($r[0]['body'] != "") {
1602 if (!intval(get_config('system','old_share'))) {
1603 if (strpos($r[0]['body'], "[/share]") !== false) {
1604 $pos = strpos($r[0]['body'], "[share");
1605 $post = substr($r[0]['body'], $pos);
1607 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1609 $post .= $r[0]['body'];
1610 $post .= "[/share]";
1612 $_REQUEST['body'] = $post;
1614 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1616 $_REQUEST['profile_uid'] = api_user();
1617 $_REQUEST['type'] = 'wall';
1618 $_REQUEST['api_source'] = true;
1620 if (!x($_REQUEST, "source"))
1621 $_REQUEST["source"] = api_source();
1625 throw new ForbiddenException();
1627 // this should output the last post (the one we just posted).
1629 return(api_status_show($a,$type));
1631 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1636 function api_statuses_destroy(&$a, $type){
1637 if (api_user()===false) throw new ForbiddenException();
1639 $user_info = api_get_user($a);
1642 $id = intval($a->argv[3]);
1645 $id = intval($_REQUEST["id"]);
1649 $id = intval($a->argv[4]);
1651 logger('API: api_statuses_destroy: '.$id);
1653 $ret = api_statuses_show($a, $type);
1655 drop_item($id, false);
1659 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1663 * http://developer.twitter.com/doc/get/statuses/mentions
1666 function api_statuses_mentions(&$a, $type){
1667 if (api_user()===false) throw new ForbiddenException();
1669 unset($_REQUEST["user_id"]);
1670 unset($_GET["user_id"]);
1672 unset($_REQUEST["screen_name"]);
1673 unset($_GET["screen_name"]);
1675 $user_info = api_get_user($a);
1676 // get last newtork messages
1680 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1681 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1682 if ($page<0) $page=0;
1683 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1684 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1685 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1687 $start = $page*$count;
1689 // Ugly code - should be changed
1690 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1691 $myurl = substr($myurl,strpos($myurl,'://')+3);
1692 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1693 $myurl = str_replace('www.','',$myurl);
1694 $diasp_url = str_replace('/profile/','/u/',$myurl);
1697 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1699 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1700 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1701 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1702 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1703 FROM `item` FORCE INDEX (`uid_id`), `contact`
1704 WHERE `item`.`uid` = %d AND `verb` = '%s'
1705 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1706 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1707 AND `contact`.`id` = `item`.`contact-id`
1708 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1709 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1712 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1714 dbesc(ACTIVITY_POST),
1715 dbesc(protect_sprintf($myurl)),
1716 dbesc(protect_sprintf($myurl)),
1719 intval($start), intval($count)
1722 $ret = api_format_items($r,$user_info);
1725 $data = array('$statuses' => $ret);
1729 $data = api_rss_extra($a, $data, $user_info);
1732 $as = api_format_as($a, $ret, $user_info);
1733 $as["title"] = $a->config['sitename']." Mentions";
1734 $as['link']['url'] = $a->get_baseurl()."/";
1739 return api_apply_template("timeline", $type, $data);
1741 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1742 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1745 function api_statuses_user_timeline(&$a, $type){
1746 if (api_user()===false) throw new ForbiddenException();
1748 $user_info = api_get_user($a);
1749 // get last network messages
1751 logger("api_statuses_user_timeline: api_user: ". api_user() .
1752 "\nuser_info: ".print_r($user_info, true) .
1753 "\n_REQUEST: ".print_r($_REQUEST, true),
1757 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1758 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1759 if ($page<0) $page=0;
1760 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1761 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1762 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1763 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1765 $start = $page*$count;
1768 if ($user_info['self']==1)
1769 $sql_extra .= " AND `item`.`wall` = 1 ";
1771 if ($exclude_replies > 0)
1772 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1773 if ($conversation_id > 0)
1774 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1776 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1777 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1778 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1779 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1780 FROM `item`, `contact`
1781 WHERE `item`.`uid` = %d AND `verb` = '%s'
1782 AND `item`.`contact-id` = %d
1783 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1784 AND `contact`.`id` = `item`.`contact-id`
1785 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1788 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1790 dbesc(ACTIVITY_POST),
1791 intval($user_info['cid']),
1793 intval($start), intval($count)
1796 $ret = api_format_items($r,$user_info, true);
1798 $data = array('$statuses' => $ret);
1802 $data = api_rss_extra($a, $data, $user_info);
1805 return api_apply_template("timeline", $type, $data);
1807 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1811 * Star/unstar an item
1812 * param: id : id of the item
1814 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1816 function api_favorites_create_destroy(&$a, $type){
1817 if (api_user()===false) throw new ForbiddenException();
1819 // for versioned api.
1820 /// @TODO We need a better global soluton
1822 if ($a->argv[1]=="1.1") $action_argv_id=3;
1824 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1825 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1826 if ($a->argc==$action_argv_id+2) {
1827 $itemid = intval($a->argv[$action_argv_id+1]);
1829 $itemid = intval($_REQUEST['id']);
1832 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1833 $itemid, api_user());
1835 if ($item===false || count($item)==0)
1836 throw new BadRequestException("Invalid item.");
1840 $item[0]['starred']=1;
1843 $item[0]['starred']=0;
1846 throw new BadRequestException("Invalid action ".$action);
1848 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1849 $item[0]['starred'], $itemid, api_user());
1851 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1852 $item[0]['starred'], $itemid, api_user());
1855 throw InternalServerErrorException("DB error");
1858 $user_info = api_get_user($a);
1859 $rets = api_format_items($item,$user_info);
1862 $data = array('$status' => $ret);
1866 $data = api_rss_extra($a, $data, $user_info);
1869 return api_apply_template("status", $type, $data);
1871 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1872 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1874 function api_favorites(&$a, $type){
1877 if (api_user()===false) throw new ForbiddenException();
1879 $called_api= array();
1881 $user_info = api_get_user($a);
1883 // in friendica starred item are private
1884 // return favorites only for self
1885 logger('api_favorites: self:' . $user_info['self']);
1887 if ($user_info['self']==0) {
1893 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1894 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1895 $count = (x($_GET,'count')?$_GET['count']:20);
1896 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1897 if ($page<0) $page=0;
1899 $start = $page*$count;
1902 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1904 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1905 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1906 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1907 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1908 FROM `item`, `contact`
1909 WHERE `item`.`uid` = %d
1910 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1911 AND `item`.`starred` = 1
1912 AND `contact`.`id` = `item`.`contact-id`
1913 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1916 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1919 intval($start), intval($count)
1922 $ret = api_format_items($r,$user_info);
1926 $data = array('$statuses' => $ret);
1930 $data = api_rss_extra($a, $data, $user_info);
1933 return api_apply_template("timeline", $type, $data);
1935 api_register_func('api/favorites','api_favorites', true);
1940 function api_format_as($a, $ret, $user_info) {
1942 $as['title'] = $a->config['sitename']." Public Timeline";
1944 foreach ($ret as $item) {
1945 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1946 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1947 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1948 $avatar[0]["rel"] = "avatar";
1949 $avatar[0]["type"] = "";
1950 $avatar[0]["width"] = 96;
1951 $avatar[0]["height"] = 96;
1952 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1953 $avatar[1]["rel"] = "avatar";
1954 $avatar[1]["type"] = "";
1955 $avatar[1]["width"] = 48;
1956 $avatar[1]["height"] = 48;
1957 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1958 $avatar[2]["rel"] = "avatar";
1959 $avatar[2]["type"] = "";
1960 $avatar[2]["width"] = 24;
1961 $avatar[2]["height"] = 24;
1962 $singleitem["actor"]["avatarLinks"] = $avatar;
1964 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1965 $singleitem["actor"]["image"]["rel"] = "avatar";
1966 $singleitem["actor"]["image"]["type"] = "";
1967 $singleitem["actor"]["image"]["width"] = 96;
1968 $singleitem["actor"]["image"]["height"] = 96;
1969 $singleitem["actor"]["type"] = "person";
1970 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1971 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1972 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1973 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1974 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1975 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1976 $singleitem["actor"]["contact"]["addresses"] = "";
1978 $singleitem["body"] = $item["text"];
1979 $singleitem["object"]["displayName"] = $item["text"];
1980 $singleitem["object"]["id"] = $item["url"];
1981 $singleitem["object"]["type"] = "note";
1982 $singleitem["object"]["url"] = $item["url"];
1983 //$singleitem["context"] =;
1984 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1985 $singleitem["provider"]["objectType"] = "service";
1986 $singleitem["provider"]["displayName"] = "Test";
1987 $singleitem["provider"]["url"] = "http://test.tld";
1988 $singleitem["title"] = $item["text"];
1989 $singleitem["verb"] = "post";
1990 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1991 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1992 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1993 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1994 //$singleitem["original"] = $item;
1995 $items[] = $singleitem;
1997 $as['items'] = $items;
1998 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1999 $as['link']['rel'] = "alternate";
2000 $as['link']['type'] = "text/html";
2004 function api_format_messages($item, $recipient, $sender) {
2005 // standard meta information
2007 'id' => $item['id'],
2008 'sender_id' => $sender['id'] ,
2010 'recipient_id' => $recipient['id'],
2011 'created_at' => api_date($item['created']),
2012 'sender_screen_name' => $sender['screen_name'],
2013 'recipient_screen_name' => $recipient['screen_name'],
2014 'sender' => $sender,
2015 'recipient' => $recipient,
2018 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2019 unset($ret["sender"]["uid"]);
2020 unset($ret["sender"]["self"]);
2021 unset($ret["recipient"]["uid"]);
2022 unset($ret["recipient"]["self"]);
2024 //don't send title to regular StatusNET requests to avoid confusing these apps
2025 if (x($_GET, 'getText')) {
2026 $ret['title'] = $item['title'] ;
2027 if ($_GET["getText"] == "html") {
2028 $ret['text'] = bbcode($item['body'], false, false);
2030 elseif ($_GET["getText"] == "plain") {
2031 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2032 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2036 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2038 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2039 unset($ret['sender']);
2040 unset($ret['recipient']);
2046 function api_convert_item($item) {
2048 $body = $item['body'];
2049 $attachments = api_get_attachments($body);
2051 // Workaround for ostatus messages where the title is identically to the body
2052 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2053 $statusbody = trim(html2plain($html, 0));
2055 // handle data: images
2056 $statusbody = api_format_items_embeded_images($item,$statusbody);
2058 $statustitle = trim($item['title']);
2060 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2061 $statustext = trim($statusbody);
2063 $statustext = trim($statustitle."\n\n".$statusbody);
2065 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2066 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2068 $statushtml = trim(bbcode($body, false, false));
2070 $search = array("<br>", "<blockquote>", "</blockquote>",
2071 "<h1>", "</h1>", "<h2>", "</h2>",
2072 "<h3>", "</h3>", "<h4>", "</h4>",
2073 "<h5>", "</h5>", "<h6>", "</h6>");
2074 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2075 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2076 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2077 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2078 $statushtml = str_replace($search, $replace, $statushtml);
2080 if ($item['title'] != "")
2081 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2083 $entities = api_get_entitities($statustext, $body);
2085 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2088 function api_get_attachments(&$body) {
2091 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2093 $URLSearchString = "^\[\]";
2094 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2099 $attachments = array();
2101 foreach ($images[1] AS $image) {
2102 $imagedata = get_photo_info($image);
2105 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2108 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2109 foreach ($images[0] AS $orig)
2110 $body = str_replace($orig, "", $body);
2112 return $attachments;
2115 function api_get_entitities(&$text, $bbcode) {
2118 * Links at the first character of the post
2123 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2125 if ($include_entities != "true") {
2127 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2129 foreach ($images[1] AS $image) {
2130 $replace = proxy_url($image);
2131 $text = str_replace($image, $replace, $text);
2136 $bbcode = bb_CleanPictureLinks($bbcode);
2138 // Change pure links in text to bbcode uris
2139 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2141 $entities = array();
2142 $entities["hashtags"] = array();
2143 $entities["symbols"] = array();
2144 $entities["urls"] = array();
2145 $entities["user_mentions"] = array();
2147 $URLSearchString = "^\[\]";
2149 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2151 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2152 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2153 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2155 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2156 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2157 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2159 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2160 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2161 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2163 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2165 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2166 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2168 $ordered_urls = array();
2169 foreach ($urls[1] AS $id=>$url) {
2170 //$start = strpos($text, $url, $offset);
2171 $start = iconv_strpos($text, $url, 0, "UTF-8");
2172 if (!($start === false))
2173 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2176 ksort($ordered_urls);
2179 //foreach ($urls[1] AS $id=>$url) {
2180 foreach ($ordered_urls AS $url) {
2181 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2182 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2183 $display_url = $url["title"];
2185 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2186 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2188 if (strlen($display_url) > 26)
2189 $display_url = substr($display_url, 0, 25)."…";
2192 //$start = strpos($text, $url, $offset);
2193 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2194 if (!($start === false)) {
2195 $entities["urls"][] = array("url" => $url["url"],
2196 "expanded_url" => $url["url"],
2197 "display_url" => $display_url,
2198 "indices" => array($start, $start+strlen($url["url"])));
2199 $offset = $start + 1;
2203 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2204 $ordered_images = array();
2205 foreach ($images[1] AS $image) {
2206 //$start = strpos($text, $url, $offset);
2207 $start = iconv_strpos($text, $image, 0, "UTF-8");
2208 if (!($start === false))
2209 $ordered_images[$start] = $image;
2211 //$entities["media"] = array();
2214 foreach ($ordered_images AS $url) {
2215 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2216 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2218 if (strlen($display_url) > 26)
2219 $display_url = substr($display_url, 0, 25)."…";
2221 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2222 if (!($start === false)) {
2223 $image = get_photo_info($url);
2225 // If image cache is activated, then use the following sizes:
2226 // thumb (150), small (340), medium (600) and large (1024)
2227 if (!get_config("system", "proxy_disabled")) {
2228 $media_url = proxy_url($url);
2231 $scale = scale_image($image[0], $image[1], 150);
2232 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2234 if (($image[0] > 150) OR ($image[1] > 150)) {
2235 $scale = scale_image($image[0], $image[1], 340);
2236 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2239 $scale = scale_image($image[0], $image[1], 600);
2240 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2242 if (($image[0] > 600) OR ($image[1] > 600)) {
2243 $scale = scale_image($image[0], $image[1], 1024);
2244 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2248 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2251 $entities["media"][] = array(
2253 "id_str" => (string)$start+1,
2254 "indices" => array($start, $start+strlen($url)),
2255 "media_url" => normalise_link($media_url),
2256 "media_url_https" => $media_url,
2258 "display_url" => $display_url,
2259 "expanded_url" => $url,
2263 $offset = $start + 1;
2269 function api_format_items_embeded_images(&$item, $text){
2271 $text = preg_replace_callback(
2272 "|data:image/([^;]+)[^=]+=*|m",
2273 function($match) use ($a, $item) {
2274 return $a->get_baseurl()."/display/".$item['guid'];
2281 * @brief return likes, dislikes and attend status for item
2283 * @param array $item
2285 * likes => int count
2286 * dislikes => int count
2288 function api_format_items_likes(&$item) {
2289 $activities = array(
2291 'dislike' => array(),
2292 'attendyes' => array(),
2293 'attendno' => array(),
2294 'attendmaybe' => array()
2296 $items = q('SELECT * FROM item
2297 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2298 intval($item['uid']),
2299 dbesc($item['uri']));
2300 foreach ($items as $i){
2301 builtin_activity_puller($i, $activities);
2305 $uri = $item['uri'];
2306 foreach($activities as $k => $v) {
2307 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2314 * @brief format items to be returned by api
2316 * @param array $r array of items
2317 * @param array $user_info
2318 * @param bool $filter_user filter items by $user_info
2320 function api_format_items($r,$user_info, $filter_user = false) {
2325 foreach($r as $item) {
2326 api_share_as_retweet($item);
2328 localize_item($item);
2329 $status_user = api_item_get_user($a,$item);
2331 // Look if the posts are matching if they should be filtered by user id
2332 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2335 if ($item['thr-parent'] != $item['uri']) {
2336 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2338 dbesc($item['thr-parent']));
2340 $in_reply_to_status_id = intval($r[0]['id']);
2342 $in_reply_to_status_id = intval($item['parent']);
2344 $in_reply_to_status_id_str = (string) intval($item['parent']);
2346 $in_reply_to_screen_name = NULL;
2347 $in_reply_to_user_id = NULL;
2348 $in_reply_to_user_id_str = NULL;
2350 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2352 intval($in_reply_to_status_id));
2354 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2357 if ($r[0]['nick'] == "")
2358 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2360 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2361 $in_reply_to_user_id = intval($r[0]['id']);
2362 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2366 $in_reply_to_screen_name = NULL;
2367 $in_reply_to_user_id = NULL;
2368 $in_reply_to_status_id = NULL;
2369 $in_reply_to_user_id_str = NULL;
2370 $in_reply_to_status_id_str = NULL;
2373 $converted = api_convert_item($item);
2376 'text' => $converted["text"],
2377 'truncated' => False,
2378 'created_at'=> api_date($item['created']),
2379 'in_reply_to_status_id' => $in_reply_to_status_id,
2380 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2381 'source' => (($item['app']) ? $item['app'] : 'web'),
2382 'id' => intval($item['id']),
2383 'id_str' => (string) intval($item['id']),
2384 'in_reply_to_user_id' => $in_reply_to_user_id,
2385 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2386 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2388 'favorited' => $item['starred'] ? true : false,
2389 'user' => $status_user ,
2390 //'entities' => NULL,
2391 'statusnet_html' => $converted["html"],
2392 'statusnet_conversation_id' => $item['parent'],
2393 'friendica_activities' => api_format_items_likes($item),
2396 if (count($converted["attachments"]) > 0)
2397 $status["attachments"] = $converted["attachments"];
2399 if (count($converted["entities"]) > 0)
2400 $status["entities"] = $converted["entities"];
2402 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2403 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2404 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2405 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2408 // Retweets are only valid for top postings
2409 // It doesn't work reliable with the link if its a feed
2410 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2412 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2414 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2415 $retweeted_status = $status;
2416 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2418 $status["retweeted_status"] = $retweeted_status;
2421 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2422 unset($status["user"]["uid"]);
2423 unset($status["user"]["self"]);
2425 if ($item["coord"] != "") {
2426 $coords = explode(' ',$item["coord"]);
2427 if (count($coords) == 2) {
2428 $status["geo"] = array('type' => 'Point',
2429 'coordinates' => array((float) $coords[0],
2430 (float) $coords[1]));
2440 function api_account_rate_limit_status(&$a,$type) {
2442 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2443 'remaining_hits' => (string) 150,
2444 'hourly_limit' => (string) 150,
2445 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2448 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2450 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2452 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2454 function api_help_test(&$a,$type) {
2460 return api_apply_template('test', $type, array("$ok" => $ok));
2462 api_register_func('api/help/test','api_help_test',false);
2464 function api_lists(&$a,$type) {
2468 api_register_func('api/lists','api_lists',true);
2470 function api_lists_list(&$a,$type) {
2474 api_register_func('api/lists/list','api_lists_list',true);
2477 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2478 * This function is deprecated by Twitter
2479 * returns: json, xml
2481 function api_statuses_f(&$a, $type, $qtype) {
2482 if (api_user()===false) throw new ForbiddenException();
2483 $user_info = api_get_user($a);
2485 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2486 /* this is to stop Hotot to load friends multiple times
2487 * I'm not sure if I'm missing return something or
2488 * is a bug in hotot. Workaround, meantime
2492 return array('$users' => $ret);*/
2496 if($qtype == 'friends')
2497 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2498 if($qtype == 'followers')
2499 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2501 // friends and followers only for self
2502 if ($user_info['self'] == 0)
2503 $sql_extra = " AND false ";
2505 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2510 foreach($r as $cid){
2511 $user = api_get_user($a, $cid['nurl']);
2512 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2513 unset($user["uid"]);
2514 unset($user["self"]);
2520 return array('$users' => $ret);
2523 function api_statuses_friends(&$a, $type){
2524 $data = api_statuses_f($a,$type,"friends");
2525 if ($data===false) return false;
2526 return api_apply_template("friends", $type, $data);
2528 function api_statuses_followers(&$a, $type){
2529 $data = api_statuses_f($a,$type,"followers");
2530 if ($data===false) return false;
2531 return api_apply_template("friends", $type, $data);
2533 api_register_func('api/statuses/friends','api_statuses_friends',true);
2534 api_register_func('api/statuses/followers','api_statuses_followers',true);
2541 function api_statusnet_config(&$a,$type) {
2542 $name = $a->config['sitename'];
2543 $server = $a->get_hostname();
2544 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2545 $email = $a->config['admin_email'];
2546 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2547 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2548 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2549 if($a->config['api_import_size'])
2550 $texlimit = string($a->config['api_import_size']);
2551 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2552 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2555 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2556 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2557 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2558 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2559 'shorturllength' => '30',
2560 'friendica' => array(
2561 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2562 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2563 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2564 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2569 return api_apply_template('config', $type, array('$config' => $config));
2572 api_register_func('api/statusnet/config','api_statusnet_config',false);
2574 function api_statusnet_version(&$a,$type) {
2576 $fake_statusnet_version = "0.9.7";
2578 if($type === 'xml') {
2579 header("Content-type: application/xml");
2580 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2583 elseif($type === 'json') {
2584 header("Content-type: application/json");
2585 echo '"'.$fake_statusnet_version.'"';
2589 api_register_func('api/statusnet/version','api_statusnet_version',false);
2592 * @todo use api_apply_template() to return data
2594 function api_ff_ids(&$a,$type,$qtype) {
2595 if(! api_user()) throw new ForbiddenException();
2597 $user_info = api_get_user($a);
2599 if($qtype == 'friends')
2600 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2601 if($qtype == 'followers')
2602 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2604 if (!$user_info["self"])
2605 $sql_extra = " AND false ";
2607 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2609 $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",
2615 if($type === 'xml') {
2616 header("Content-type: application/xml");
2617 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2619 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2620 echo '</ids>' . "\r\n";
2623 elseif($type === 'json') {
2625 header("Content-type: application/json");
2630 $ret[] = intval($rr['id']);
2632 echo json_encode($ret);
2638 function api_friends_ids(&$a,$type) {
2639 api_ff_ids($a,$type,'friends');
2641 function api_followers_ids(&$a,$type) {
2642 api_ff_ids($a,$type,'followers');
2644 api_register_func('api/friends/ids','api_friends_ids',true);
2645 api_register_func('api/followers/ids','api_followers_ids',true);
2648 function api_direct_messages_new(&$a, $type) {
2649 if (api_user()===false) throw new ForbiddenException();
2651 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2653 $sender = api_get_user($a);
2655 if ($_POST['screen_name']) {
2656 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2658 dbesc($_POST['screen_name']));
2660 // Selecting the id by priority, friendica first
2661 api_best_nickname($r);
2663 $recipient = api_get_user($a, $r[0]['nurl']);
2665 $recipient = api_get_user($a, $_POST['user_id']);
2669 if (x($_REQUEST,'replyto')) {
2670 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2672 intval($_REQUEST['replyto']));
2673 $replyto = $r[0]['parent-uri'];
2674 $sub = $r[0]['title'];
2677 if (x($_REQUEST,'title')) {
2678 $sub = $_REQUEST['title'];
2681 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2685 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2688 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2689 $ret = api_format_messages($r[0], $recipient, $sender);
2692 $ret = array("error"=>$id);
2695 $data = Array('$messages'=>$ret);
2700 $data = api_rss_extra($a, $data, $user_info);
2703 return api_apply_template("direct_messages", $type, $data);
2706 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2708 function api_direct_messages_box(&$a, $type, $box) {
2709 if (api_user()===false) throw new ForbiddenException();
2712 $count = (x($_GET,'count')?$_GET['count']:20);
2713 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2714 if ($page<0) $page=0;
2716 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2717 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2719 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2720 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2723 unset($_REQUEST["user_id"]);
2724 unset($_GET["user_id"]);
2726 unset($_REQUEST["screen_name"]);
2727 unset($_GET["screen_name"]);
2729 $user_info = api_get_user($a);
2730 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2731 $profile_url = $user_info["url"];
2735 $start = $page*$count;
2738 if ($box=="sentbox") {
2739 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2741 elseif ($box=="conversation") {
2742 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2744 elseif ($box=="all") {
2745 $sql_extra = "true";
2747 elseif ($box=="inbox") {
2748 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2752 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2754 if ($user_id !="") {
2755 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2757 elseif($screen_name !=""){
2758 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2761 $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",
2764 intval($start), intval($count)
2769 foreach($r as $item) {
2770 if ($box == "inbox" || $item['from-url'] != $profile_url){
2771 $recipient = $user_info;
2772 $sender = api_get_user($a,normalise_link($item['contact-url']));
2774 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2775 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2776 $sender = $user_info;
2779 $ret[]=api_format_messages($item, $recipient, $sender);
2783 $data = array('$messages' => $ret);
2787 $data = api_rss_extra($a, $data, $user_info);
2790 return api_apply_template("direct_messages", $type, $data);
2794 function api_direct_messages_sentbox(&$a, $type){
2795 return api_direct_messages_box($a, $type, "sentbox");
2797 function api_direct_messages_inbox(&$a, $type){
2798 return api_direct_messages_box($a, $type, "inbox");
2800 function api_direct_messages_all(&$a, $type){
2801 return api_direct_messages_box($a, $type, "all");
2803 function api_direct_messages_conversation(&$a, $type){
2804 return api_direct_messages_box($a, $type, "conversation");
2806 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2807 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2808 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2809 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2813 function api_oauth_request_token(&$a, $type){
2815 $oauth = new FKOAuth1();
2816 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2817 }catch(Exception $e){
2818 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2823 function api_oauth_access_token(&$a, $type){
2825 $oauth = new FKOAuth1();
2826 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2827 }catch(Exception $e){
2828 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2834 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2835 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2838 function api_fr_photos_list(&$a,$type) {
2839 if (api_user()===false) throw new ForbiddenException();
2840 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2841 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2842 intval(local_user())
2845 'image/jpeg' => 'jpg',
2846 'image/png' => 'png',
2847 'image/gif' => 'gif'
2849 $data = array('photos'=>array());
2851 foreach($r as $rr) {
2853 $photo['id'] = $rr['resource-id'];
2854 $photo['album'] = $rr['album'];
2855 $photo['filename'] = $rr['filename'];
2856 $photo['type'] = $rr['type'];
2857 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2858 $data['photos'][] = $photo;
2861 return api_apply_template("photos_list", $type, $data);
2864 function api_fr_photo_detail(&$a,$type) {
2865 if (api_user()===false) throw new ForbiddenException();
2866 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2868 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2869 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2870 $data_sql = ($scale === false ? "" : "data, ");
2872 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2873 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2874 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2876 intval(local_user()),
2877 dbesc($_REQUEST['photo_id']),
2882 'image/jpeg' => 'jpg',
2883 'image/png' => 'png',
2884 'image/gif' => 'gif'
2888 $data = array('photo' => $r[0]);
2889 if ($scale !== false) {
2890 $data['photo']['data'] = base64_encode($data['photo']['data']);
2892 unset($data['photo']['datasize']); //needed only with scale param
2894 $data['photo']['link'] = array();
2895 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2896 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2898 $data['photo']['id'] = $data['photo']['resource-id'];
2899 unset($data['photo']['resource-id']);
2900 unset($data['photo']['minscale']);
2901 unset($data['photo']['maxscale']);
2904 throw new NotFoundException();
2907 return api_apply_template("photo_detail", $type, $data);
2910 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2911 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2916 * similar as /mod/redir.php
2917 * redirect to 'url' after dfrn auth
2919 * why this when there is mod/redir.php already?
2920 * This use api_user() and api_login()
2923 * c_url: url of remote contact to auth to
2924 * url: string, url to redirect after auth
2926 function api_friendica_remoteauth(&$a) {
2927 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2928 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2930 if ($url === '' || $c_url === '')
2931 throw new BadRequestException("Wrong parameters.");
2933 $c_url = normalise_link($c_url);
2937 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2942 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2943 throw new BadRequestException("Unknown contact");
2947 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2949 if($r[0]['duplex'] && $r[0]['issued-id']) {
2950 $orig_id = $r[0]['issued-id'];
2951 $dfrn_id = '1:' . $orig_id;
2953 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2954 $orig_id = $r[0]['dfrn-id'];
2955 $dfrn_id = '0:' . $orig_id;
2958 $sec = random_string();
2960 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2961 VALUES( %d, %s, '%s', '%s', %d )",
2969 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2970 $dest = (($url) ? '&destination_url=' . $url : '');
2971 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2972 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2973 . '&type=profile&sec=' . $sec . $dest . $quiet );
2975 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2978 function api_share_as_retweet(&$item) {
2979 $body = trim($item["body"]);
2981 // Skip if it isn't a pure repeated messages
2982 // Does it start with a share?
2983 if (strpos($body, "[share") > 0)
2986 // Does it end with a share?
2987 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2990 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2991 // Skip if there is no shared message in there
2992 if ($body == $attributes)
2996 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2997 if ($matches[1] != "")
2998 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3000 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3001 if ($matches[1] != "")
3002 $author = $matches[1];
3005 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3006 if ($matches[1] != "")
3007 $profile = $matches[1];
3009 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3010 if ($matches[1] != "")
3011 $profile = $matches[1];
3014 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3015 if ($matches[1] != "")
3016 $avatar = $matches[1];
3018 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3019 if ($matches[1] != "")
3020 $avatar = $matches[1];
3023 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3024 if ($matches[1] != "")
3025 $link = $matches[1];
3027 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3028 if ($matches[1] != "")
3029 $link = $matches[1];
3031 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3033 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
3036 $item["body"] = $shared_body;
3037 $item["author-name"] = $author;
3038 $item["author-link"] = $profile;
3039 $item["author-avatar"] = $avatar;
3040 $item["plink"] = $link;
3046 function api_get_nick($profile) {
3048 - remove trailing junk from profile url
3049 - pump.io check has to check the website
3054 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3055 dbesc(normalise_link($profile)));
3057 $nick = $r[0]["nick"];
3060 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3061 dbesc(normalise_link($profile)));
3063 $nick = $r[0]["nick"];
3067 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3068 if ($friendica != $profile)
3073 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3074 if ($diaspora != $profile)
3079 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3080 if ($twitter != $profile)
3086 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3087 if ($StatusnetHost != $profile) {
3088 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3089 if ($StatusnetUser != $profile) {
3090 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3091 $user = json_decode($UserData);
3093 $nick = $user->screen_name;
3098 // To-Do: look at the page if its really a pumpio site
3099 //if (!$nick == "") {
3100 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3101 // if ($pumpio != $profile)
3103 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3113 function api_clean_plain_items($Text) {
3114 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3116 $Text = bb_CleanPictureLinks($Text);
3118 $URLSearchString = "^\[\]";
3120 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3122 if ($include_entities == "true") {
3123 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3126 // Simplify "attachment" element
3127 $Text = api_clean_attachments($Text);
3133 * @brief Removes most sharing information for API text export
3135 * @param string $body The original body
3137 * @return string Cleaned body
3139 function api_clean_attachments($body) {
3140 $data = get_attachment_data($body);
3147 if (isset($data["text"]))
3148 $body = $data["text"];
3150 if (($body == "") AND (isset($data["title"])))
3151 $body = $data["title"];
3153 if (isset($data["url"]))
3154 $body .= "\n".$data["url"];
3159 function api_best_nickname(&$contacts) {
3160 $best_contact = array();
3162 if (count($contact) == 0)
3165 foreach ($contacts AS $contact)
3166 if ($contact["network"] == "") {
3167 $contact["network"] = "dfrn";
3168 $best_contact = array($contact);
3171 if (sizeof($best_contact) == 0)
3172 foreach ($contacts AS $contact)
3173 if ($contact["network"] == "dfrn")
3174 $best_contact = array($contact);
3176 if (sizeof($best_contact) == 0)
3177 foreach ($contacts AS $contact)
3178 if ($contact["network"] == "dspr")
3179 $best_contact = array($contact);
3181 if (sizeof($best_contact) == 0)
3182 foreach ($contacts AS $contact)
3183 if ($contact["network"] == "stat")
3184 $best_contact = array($contact);
3186 if (sizeof($best_contact) == 0)
3187 foreach ($contacts AS $contact)
3188 if ($contact["network"] == "pump")
3189 $best_contact = array($contact);
3191 if (sizeof($best_contact) == 0)
3192 foreach ($contacts AS $contact)
3193 if ($contact["network"] == "twit")
3194 $best_contact = array($contact);
3196 if (sizeof($best_contact) == 1)
3197 $contacts = $best_contact;
3199 $contacts = array($contacts[0]);
3202 // return all or a specified group of the user with the containing contacts
3203 function api_friendica_group_show(&$a, $type) {
3204 if (api_user()===false) throw new ForbiddenException();
3207 $user_info = api_get_user($a);
3208 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3209 $uid = $user_info['uid'];
3211 // get data of the specified group id or all groups if not specified
3213 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3216 // error message if specified gid is not in database
3218 throw new BadRequestException("gid not available");
3221 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3224 // loop through all groups and retrieve all members for adding data in the user array
3225 foreach ($r as $rr) {
3226 $members = group_get_members($rr['id']);
3228 foreach ($members as $member) {
3229 $user = api_get_user($a, $member['nurl']);
3232 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3234 return api_apply_template("group_show", $type, array('$groups' => $grps));
3236 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3239 // delete the specified group of the user
3240 function api_friendica_group_delete(&$a, $type) {
3241 if (api_user()===false) throw new ForbiddenException();
3244 $user_info = api_get_user($a);
3245 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3246 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3247 $uid = $user_info['uid'];
3249 // error if no gid specified
3250 if ($gid == 0 || $name == "")
3251 throw new BadRequestException('gid or name not specified');
3253 // get data of the specified group id
3254 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3257 // error message if specified gid is not in database
3259 throw new BadRequestException('gid not available');
3261 // get data of the specified group id and group name
3262 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3266 // error message if specified gid is not in database
3267 if (count($rname) == 0)
3268 throw new BadRequestException('wrong group name');
3271 $ret = group_rmv($uid, $name);
3274 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3275 return api_apply_template("group_delete", $type, array('$result' => $success));
3278 throw new BadRequestException('other API error');
3280 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3283 // create the specified group with the posted array of contacts
3284 function api_friendica_group_create(&$a, $type) {
3285 if (api_user()===false) throw new ForbiddenException();
3288 $user_info = api_get_user($a);
3289 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3290 $uid = $user_info['uid'];
3291 $json = json_decode($_POST['json'], true);
3292 $users = $json['user'];
3294 // error if no name specified
3296 throw new BadRequestException('group name not specified');
3298 // get data of the specified group name
3299 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3302 // error message if specified group name already exists
3303 if (count($rname) != 0)
3304 throw new BadRequestException('group name already exists');
3306 // check if specified group name is a deleted group
3307 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3310 // error message if specified group name already exists
3311 if (count($rname) != 0)
3312 $reactivate_group = true;
3315 $ret = group_add($uid, $name);
3317 $gid = group_byname($uid, $name);
3319 throw new BadRequestException('other API error');
3322 $erroraddinguser = false;
3323 $errorusers = array();
3324 foreach ($users as $user) {
3325 $cid = $user['cid'];
3326 // check if user really exists as contact
3327 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3330 if (count($contact))
3331 $result = group_add_member($uid, $name, $cid, $gid);
3333 $erroraddinguser = true;
3334 $errorusers[] = $cid;
3338 // return success message incl. missing users in array
3339 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3340 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3341 return api_apply_template("group_create", $type, array('result' => $success));
3343 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3346 // update the specified group with the posted array of contacts
3347 function api_friendica_group_update(&$a, $type) {
3348 if (api_user()===false) throw new ForbiddenException();
3351 $user_info = api_get_user($a);
3352 $uid = $user_info['uid'];
3353 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3354 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3355 $json = json_decode($_POST['json'], true);
3356 $users = $json['user'];
3358 // error if no name specified
3360 throw new BadRequestException('group name not specified');
3362 // error if no gid specified
3364 throw new BadRequestException('gid not specified');
3367 $members = group_get_members($gid);
3368 foreach ($members as $member) {
3369 $cid = $member['id'];
3370 foreach ($users as $user) {
3371 $found = ($user['cid'] == $cid ? true : false);
3374 $ret = group_rmv_member($uid, $name, $cid);
3379 $erroraddinguser = false;
3380 $errorusers = array();
3381 foreach ($users as $user) {
3382 $cid = $user['cid'];
3383 // check if user really exists as contact
3384 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3387 if (count($contact))
3388 $result = group_add_member($uid, $name, $cid, $gid);
3390 $erroraddinguser = true;
3391 $errorusers[] = $cid;
3395 // return success message incl. missing users in array
3396 $status = ($erroraddinguser ? "missing user" : "ok");
3397 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3398 return api_apply_template("group_update", $type, array('result' => $success));
3400 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3403 function api_friendica_activity(&$a, $type) {
3404 if (api_user()===false) throw new ForbiddenException();
3405 $verb = strtolower($a->argv[3]);
3406 $verb = preg_replace("|\..*$|", "", $verb);
3408 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3410 $res = do_like($id, $verb);
3417 return api_apply_template('test', $type, array('ok' => $ok));
3419 throw new BadRequestException('Error adding activity');
3423 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3424 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3425 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3426 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3427 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3428 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3429 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3430 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3431 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3432 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3435 * @brief Returns notifications
3438 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3441 function api_friendica_notification(&$a, $type) {
3442 if (api_user()===false) throw new ForbiddenException();
3443 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3444 $nm = new NotificationsManager();
3446 $notes = $nm->getAll(array(), "+seen -date", 50);
3447 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3451 * @brief Set notification as seen and returns associated item (if possible)
3453 * POST request with 'id' param as notification id
3456 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3459 function api_friendica_notification_seen(&$a, $type){
3460 if (api_user()===false) throw new ForbiddenException();
3461 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3463 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3465 $nm = new NotificationsManager();
3466 $note = $nm->getByID($id);
3467 if (is_null($note)) throw new BadRequestException("Invalid argument");
3469 $nm->setSeen($note);
3470 if ($note['otype']=='item') {
3471 // would be really better with an ItemsManager and $im->getByID() :-P
3472 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3473 intval($note['iid']),
3474 intval(local_user())
3477 // we found the item, return it to the user
3478 $user_info = api_get_user($a);
3479 $ret = api_format_items($r,$user_info);
3480 $data = array('$statuses' => $ret);
3481 return api_apply_template("timeline", $type, $data);
3483 // the item can't be found, but we set the note as seen, so we count this as a success
3485 return api_apply_template('<auto>', $type, array('status' => "success"));
3488 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3489 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3494 [pagename] => api/1.1/statuses/lookup.json
3495 [id] => 605138389168451584
3496 [include_cards] => true
3497 [cards_platform] => Android-12
3498 [include_entities] => true
3499 [include_my_retweet] => 1
3501 [include_reply_count] => true
3502 [include_descendent_reply_count] => true
3506 Not implemented by now:
3507 statuses/retweets_of_me
3512 account/update_location
3513 account/update_profile_background_image
3514 account/update_profile_image
3518 Not implemented in status.net:
3519 statuses/retweeted_to_me
3520 statuses/retweeted_by_me
3521 direct_messages/destroy
3523 account/update_delivery_device
3524 notifications/follow