3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
29 define('API_METHOD_ANY','*');
30 define('API_METHOD_GET','GET');
31 define('API_METHOD_POST','POST,PUT');
32 define('API_METHOD_DELETE','POST,DELETE');
40 * @brief Auth API user
42 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
43 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
44 * into a page, and visitors will post something without noticing it).
47 if ($_SESSION['allow_api'])
54 * @brief Get source name from API client
56 * Clients can send 'source' parameter to be show in post metadata
57 * as "sent via <source>".
58 * Some clients doesn't send a source param, we support ones we know
62 * Client source name, default to "api" if unset/unknown
64 function api_source() {
65 if (requestdata('source'))
66 return (requestdata('source'));
68 // Support for known clients that doesn't send a source name
69 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
72 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
78 * @brief Format date for API
80 * @param string $str Source date, as UTC
81 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
83 function api_date($str){
84 //Wed May 23 06:01:13 +0000 2007
85 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
89 * @brief Register API endpoint
91 * Register a function to be the endpont for defined API path.
93 * @param string $path API URL path, relative to $a->get_baseurl()
94 * @param string $func Function name to call on path request
95 * @param bool $auth API need logged user
96 * @param string $method
97 * HTTP method reqiured to call this endpoint.
98 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
99 * Default to API_METHOD_ANY
101 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
109 // Workaround for hotot
110 $path = str_replace("api/", "api/1.1/", $path);
119 * @brief Login API user
121 * Log in user via OAuth1 or Simple HTTP Auth.
122 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
125 * @hook 'authenticate'
127 * 'username' => username from login form
128 * 'password' => password from login form
129 * 'authenticated' => return status,
130 * 'user_record' => return authenticated user record
132 * array $user logged user record
134 function api_login(&$a){
137 $oauth = new FKOAuth1();
138 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
139 if (!is_null($token)){
140 $oauth->loginUser($token->uid);
141 call_hooks('logged_in', $a->user);
144 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
145 }catch(Exception $e){
151 // workaround for HTTP-auth in CGI mode
152 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
153 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
154 if(strlen($userpass)) {
155 list($name, $password) = explode(':', $userpass);
156 $_SERVER['PHP_AUTH_USER'] = $name;
157 $_SERVER['PHP_AUTH_PW'] = $password;
161 if (!isset($_SERVER['PHP_AUTH_USER'])) {
162 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
163 header('WWW-Authenticate: Basic realm="Friendica"');
164 throw new UnauthorizedException("This API requires login");
167 $user = $_SERVER['PHP_AUTH_USER'];
168 $password = $_SERVER['PHP_AUTH_PW'];
169 $encrypted = hash('whirlpool',trim($password));
171 // allow "user@server" login (but ignore 'server' part)
172 $at=strstr($user, "@", true);
173 if ( $at ) $user=$at;
176 * next code from mod/auth.php. needs better solution
181 'username' => trim($user),
182 'password' => trim($password),
183 'authenticated' => 0,
184 'user_record' => null
189 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
190 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
191 * and later plugins should not interfere with an earlier one that succeeded.
195 call_hooks('authenticate', $addon_auth);
197 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
198 $record = $addon_auth['user_record'];
201 // process normal login request
203 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
204 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
213 if((! $record) || (! count($record))) {
214 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
215 header('WWW-Authenticate: Basic realm="Friendica"');
216 #header('HTTP/1.0 401 Unauthorized');
217 #die('This api requires login');
218 throw new UnauthorizedException("This API requires login");
221 authenticate_success($record); $_SESSION["allow_api"] = true;
223 call_hooks('logged_in', $a->user);
228 * @brief Check HTTP method of called API
230 * API endpoints can define which HTTP method to accept when called.
231 * This function check the current HTTP method agains endpoint
234 * @param string $method Required methods, uppercase, separated by comma
237 function api_check_method($method) {
238 if ($method=="*") return True;
239 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
243 * @brief Main API entry point
245 * Authenticate user, call registered API function, set HTTP headers
248 * @return string API call result
250 function api_call(&$a){
251 GLOBAL $API, $called_api;
254 if (strpos($a->query_string, ".xml")>0) $type="xml";
255 if (strpos($a->query_string, ".json")>0) $type="json";
256 if (strpos($a->query_string, ".rss")>0) $type="rss";
257 if (strpos($a->query_string, ".atom")>0) $type="atom";
258 if (strpos($a->query_string, ".as")>0) $type="as";
260 foreach ($API as $p=>$info){
261 if (strpos($a->query_string, $p)===0){
262 if (!api_check_method($info['method'])){
263 throw new MethodNotAllowedException();
266 $called_api= explode("/",$p);
267 //unset($_SERVER['PHP_AUTH_USER']);
268 if ($info['auth']===true && api_user()===false) {
272 load_contact_links(api_user());
274 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
275 logger('API parameters: ' . print_r($_REQUEST,true));
277 $stamp = microtime(true);
278 $r = call_user_func($info['func'], $a, $type);
279 $duration = (float)(microtime(true)-$stamp);
280 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
283 // api function returned false withour throw an
284 // exception. This should not happend, throw a 500
285 throw new InternalServerErrorException();
290 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
291 header ("Content-Type: text/xml");
292 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
295 header ("Content-Type: application/json");
297 $json = json_encode($rr);
298 if ($_GET['callback'])
299 $json = $_GET['callback']."(".$json.")";
303 header ("Content-Type: application/rss+xml");
304 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
307 header ("Content-Type: application/atom+xml");
308 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
311 //header ("Content-Type: application/json");
313 // return json_encode($rr);
314 return json_encode($r);
320 throw new NotImplementedException();
321 } catch (HTTPException $e) {
322 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
323 return api_error($a, $type, $e);
328 * @brief Format API error string
331 * @param string $type Return type (xml, json, rss, as)
332 * @param HTTPException $error Error object
333 * @return strin error message formatted as $type
335 function api_error(&$a, $type, $e) {
336 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
337 # TODO: https://dev.twitter.com/overview/api/response-codes
338 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
341 header ("Content-Type: text/xml");
342 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
345 header ("Content-Type: application/json");
346 return json_encode(array(
348 'request' => $a->query_string,
349 'code' => $e->httpcode." ".$e->httpdesc
353 header ("Content-Type: application/rss+xml");
354 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
357 header ("Content-Type: application/atom+xml");
358 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
364 * @brief Set values for RSS template
367 * @param array $arr Array to be passed to template
368 * @param array $user_info
371 function api_rss_extra(&$a, $arr, $user_info){
372 if (is_null($user_info)) $user_info = api_get_user($a);
373 $arr['$user'] = $user_info;
374 $arr['$rss'] = array(
375 'alternate' => $user_info['url'],
376 'self' => $a->get_baseurl(). "/". $a->query_string,
377 'base' => $a->get_baseurl(),
378 'updated' => api_date(null),
379 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
380 'language' => $user_info['language'],
381 'logo' => $a->get_baseurl()."/images/friendica-32.png",
389 * @brief Unique contact to contact url.
391 * @param int $id Contact id
392 * @return bool|string
393 * Contact url or False if contact id is unknown
395 function api_unique_id_to_url($id){
396 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
399 return ($r[0]["url"]);
405 * @brief Get user info array.
408 * @param int|string $contact_id Contact ID or URL
409 * @param string $type Return type (for errors)
411 function api_get_user(&$a, $contact_id = Null, $type = "json"){
418 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
420 // Searching for contact URL
421 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
422 $user = dbesc(normalise_link($contact_id));
424 $extra_query = "AND `contact`.`nurl` = '%s' ";
425 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
428 // Searching for unique contact id
429 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
430 $user = dbesc(api_unique_id_to_url($contact_id));
433 throw new BadRequestException("User not found.");
436 $extra_query = "AND `contact`.`nurl` = '%s' ";
437 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
440 if(is_null($user) && x($_GET, 'user_id')) {
441 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
444 throw new BadRequestException("User not found.");
447 $extra_query = "AND `contact`.`nurl` = '%s' ";
448 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
450 if(is_null($user) && x($_GET, 'screen_name')) {
451 $user = dbesc($_GET['screen_name']);
453 $extra_query = "AND `contact`.`nick` = '%s' ";
454 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
457 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
458 $argid = count($called_api);
459 list($user, $null) = explode(".",$a->argv[$argid]);
460 if(is_numeric($user)){
461 $user = dbesc(api_unique_id_to_url($user));
467 $extra_query = "AND `contact`.`nurl` = '%s' ";
468 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
470 $user = dbesc($user);
472 $extra_query = "AND `contact`.`nick` = '%s' ";
473 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
477 logger("api_get_user: user ".$user, LOGGER_DEBUG);
480 if (api_user()===false) {
484 $user = $_SESSION['uid'];
485 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
490 logger('api_user: ' . $extra_query . ', user: ' . $user);
492 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
498 // Selecting the id by priority, friendica first
499 api_best_nickname($uinfo);
501 // if the contact wasn't found, fetch it from the unique contacts
502 if (count($uinfo)==0) {
506 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
509 // If no nick where given, extract it from the address
510 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
511 $r[0]['nick'] = api_get_nick($r[0]["url"]);
515 'id_str' => (string) $r[0]["id"],
516 'name' => $r[0]["name"],
517 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
518 'location' => $r[0]["location"],
519 'description' => $r[0]["about"],
520 'url' => $r[0]["url"],
521 'protected' => false,
522 'followers_count' => 0,
523 'friends_count' => 0,
525 'created_at' => api_date($r[0]["created"]),
526 'favourites_count' => 0,
528 'time_zone' => 'UTC',
529 'geo_enabled' => false,
531 'statuses_count' => 0,
533 'contributors_enabled' => false,
534 'is_translator' => false,
535 'is_translation_enabled' => false,
536 'profile_image_url' => $r[0]["photo"],
537 'profile_image_url_https' => $r[0]["photo"],
538 'following' => false,
539 'follow_request_sent' => false,
540 'notifications' => false,
541 'statusnet_blocking' => false,
542 'notifications' => false,
543 'statusnet_profile_url' => $r[0]["url"],
547 'network' => $r[0]["network"],
552 throw new BadRequestException("User not found.");
556 if($uinfo[0]['self']) {
557 $usr = q("select * from user where uid = %d limit 1",
560 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
564 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
565 // count public wall messages
566 $r = q("SELECT count(*) as `count` FROM `item`
569 intval($uinfo[0]['uid'])
571 $countitms = $r[0]['count'];
574 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
575 $r = q("SELECT count(*) as `count` FROM `item`
576 WHERE `contact-id` = %d",
577 intval($uinfo[0]['id'])
579 $countitms = $r[0]['count'];
583 $r = q("SELECT count(*) as `count` FROM `contact`
584 WHERE `uid` = %d AND `rel` IN ( %d, %d )
585 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
586 intval($uinfo[0]['uid']),
587 intval(CONTACT_IS_SHARING),
588 intval(CONTACT_IS_FRIEND)
590 $countfriends = $r[0]['count'];
592 $r = q("SELECT count(*) as `count` FROM `contact`
593 WHERE `uid` = %d AND `rel` IN ( %d, %d )
594 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
595 intval($uinfo[0]['uid']),
596 intval(CONTACT_IS_FOLLOWER),
597 intval(CONTACT_IS_FRIEND)
599 $countfollowers = $r[0]['count'];
601 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
602 intval($uinfo[0]['uid'])
604 $starred = $r[0]['count'];
607 if(! $uinfo[0]['self']) {
613 // Add a nick if it isn't present there
614 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
615 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
618 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
620 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
621 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
624 'id' => intval($gcontact_id),
625 'id_str' => (string) intval($gcontact_id),
626 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
627 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
628 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
629 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
630 'profile_image_url' => $uinfo[0]['micro'],
631 'profile_image_url_https' => $uinfo[0]['micro'],
632 'url' => $uinfo[0]['url'],
633 'protected' => false,
634 'followers_count' => intval($countfollowers),
635 'friends_count' => intval($countfriends),
636 'created_at' => api_date($uinfo[0]['created']),
637 'favourites_count' => intval($starred),
639 'time_zone' => 'UTC',
640 'statuses_count' => intval($countitms),
641 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
643 'statusnet_blocking' => false,
644 'notifications' => false,
645 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
646 'statusnet_profile_url' => $uinfo[0]['url'],
647 'uid' => intval($uinfo[0]['uid']),
648 'cid' => intval($uinfo[0]['cid']),
649 'self' => $uinfo[0]['self'],
650 'network' => $uinfo[0]['network'],
657 function api_item_get_user(&$a, $item) {
659 // Make sure that there is an entry in the global contacts for author and owner
660 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
661 "photo" => $item['author-avatar'], "name" => $item['author-name']));
663 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
664 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
666 // Comments in threads may appear as wall-to-wall postings.
667 // So only take the owner at the top posting.
668 if ($item["id"] == $item["parent"])
669 $status_user = api_get_user($a,$item["owner-link"]);
671 $status_user = api_get_user($a,$item["author-link"]);
673 $status_user["protected"] = (($item["allow_cid"] != "") OR
674 ($item["allow_gid"] != "") OR
675 ($item["deny_cid"] != "") OR
676 ($item["deny_gid"] != "") OR
679 return ($status_user);
684 * @brief transform $data array in xml without a template
687 * @return string xml string
689 function api_array_to_xml($data, $ename="") {
692 if (count($data)==1 && !is_array($data[0])) {
693 $ename = array_keys($data)[0];
695 return "<$ename>$v</$ename>";
697 foreach($data as $k=>$v) {
700 $attrs .= sprintf('%s="%s" ', $k, $v);
702 if (is_numeric($k)) $k=trim($ename,'s');
703 $childs.=api_array_to_xml($v, $k);
707 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
712 * load api $templatename for $type and replace $data array
714 function api_apply_template($templatename, $type, $data){
722 $data = array_xmlify($data);
723 if ($templatename==="<auto>") {
724 $ret = api_array_to_xml($data);
726 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
728 header ("Content-Type: text/xml");
729 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
732 $ret = replace_macros($tpl, $data);
748 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
749 * returns a 401 status code and an error message if not.
750 * http://developer.twitter.com/doc/get/account/verify_credentials
752 function api_account_verify_credentials(&$a, $type){
753 if (api_user()===false) throw new ForbiddenException();
755 unset($_REQUEST["user_id"]);
756 unset($_GET["user_id"]);
758 unset($_REQUEST["screen_name"]);
759 unset($_GET["screen_name"]);
761 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
763 $user_info = api_get_user($a);
765 // "verified" isn't used here in the standard
766 unset($user_info["verified"]);
768 // - Adding last status
770 $user_info["status"] = api_status_show($a,"raw");
771 if (!count($user_info["status"]))
772 unset($user_info["status"]);
774 unset($user_info["status"]["user"]);
777 // "uid" and "self" are only needed for some internal stuff, so remove it from here
778 unset($user_info["uid"]);
779 unset($user_info["self"]);
781 return api_apply_template("user", $type, array('$user' => $user_info));
784 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
788 * get data from $_POST or $_GET
790 function requestdata($k){
791 if (isset($_POST[$k])){
794 if (isset($_GET[$k])){
800 /*Waitman Gobble Mod*/
801 function api_statuses_mediap(&$a, $type) {
802 if (api_user()===false) {
803 logger('api_statuses_update: no user');
804 throw new ForbiddenException();
806 $user_info = api_get_user($a);
808 $_REQUEST['type'] = 'wall';
809 $_REQUEST['profile_uid'] = api_user();
810 $_REQUEST['api_source'] = true;
811 $txt = requestdata('status');
812 //$txt = urldecode(requestdata('status'));
814 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
816 $txt = html2bb_video($txt);
817 $config = HTMLPurifier_Config::createDefault();
818 $config->set('Cache.DefinitionImpl', null);
819 $purifier = new HTMLPurifier($config);
820 $txt = $purifier->purify($txt);
822 $txt = html2bbcode($txt);
824 $a->argv[1]=$user_info['screen_name']; //should be set to username?
826 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
827 $bebop = wall_upload_post($a);
829 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
830 $_REQUEST['body']=$txt."\n\n".$bebop;
833 // this should output the last post (the one we just posted).
834 return api_status_show($a,$type);
836 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
837 /*Waitman Gobble Mod*/
840 function api_statuses_update(&$a, $type) {
841 if (api_user()===false) {
842 logger('api_statuses_update: no user');
843 throw new ForbiddenException();
846 $user_info = api_get_user($a);
848 // convert $_POST array items to the form we use for web posts.
850 // logger('api_post: ' . print_r($_POST,true));
852 if(requestdata('htmlstatus')) {
853 $txt = requestdata('htmlstatus');
854 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
855 $txt = html2bb_video($txt);
857 $config = HTMLPurifier_Config::createDefault();
858 $config->set('Cache.DefinitionImpl', null);
860 $purifier = new HTMLPurifier($config);
861 $txt = $purifier->purify($txt);
863 $_REQUEST['body'] = html2bbcode($txt);
867 $_REQUEST['body'] = requestdata('status');
869 $_REQUEST['title'] = requestdata('title');
871 $parent = requestdata('in_reply_to_status_id');
873 // Twidere sends "-1" if it is no reply ...
877 if(ctype_digit($parent))
878 $_REQUEST['parent'] = $parent;
880 $_REQUEST['parent_uri'] = $parent;
882 if(requestdata('lat') && requestdata('long'))
883 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
884 $_REQUEST['profile_uid'] = api_user();
887 $_REQUEST['type'] = 'net-comment';
889 // Check for throttling (maximum posts per day, week and month)
890 $throttle_day = get_config('system','throttle_limit_day');
891 if ($throttle_day > 0) {
892 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
894 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
895 AND `created` > '%s' AND `id` = `parent`",
896 intval(api_user()), dbesc($datefrom));
899 $posts_day = $r[0]["posts_day"];
903 if ($posts_day > $throttle_day) {
904 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
905 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
906 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
910 $throttle_week = get_config('system','throttle_limit_week');
911 if ($throttle_week > 0) {
912 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
914 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
915 AND `created` > '%s' AND `id` = `parent`",
916 intval(api_user()), dbesc($datefrom));
919 $posts_week = $r[0]["posts_week"];
923 if ($posts_week > $throttle_week) {
924 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
925 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
926 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
931 $throttle_month = get_config('system','throttle_limit_month');
932 if ($throttle_month > 0) {
933 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
935 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
936 AND `created` > '%s' AND `id` = `parent`",
937 intval(api_user()), dbesc($datefrom));
940 $posts_month = $r[0]["posts_month"];
944 if ($posts_month > $throttle_month) {
945 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
946 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
947 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
951 $_REQUEST['type'] = 'wall';
954 if(x($_FILES,'media')) {
955 // upload the image if we have one
956 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
957 $media = wall_upload_post($a);
959 $_REQUEST['body'] .= "\n\n".$media;
962 // To-Do: Multiple IDs
963 if (requestdata('media_ids')) {
964 $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",
965 intval(requestdata('media_ids')), api_user());
967 $phototypes = Photo::supportedTypes();
968 $ext = $phototypes[$r[0]['type']];
969 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
970 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
974 // set this so that the item_post() function is quiet and doesn't redirect or emit json
976 $_REQUEST['api_source'] = true;
978 if (!x($_REQUEST, "source"))
979 $_REQUEST["source"] = api_source();
981 // call out normal post function
985 // this should output the last post (the one we just posted).
986 return api_status_show($a,$type);
988 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
989 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
992 function api_media_upload(&$a, $type) {
993 if (api_user()===false) {
995 throw new ForbiddenException();
998 $user_info = api_get_user($a);
1000 if(!x($_FILES,'media')) {
1002 throw new BadRequestException("No media.");
1005 $media = wall_upload_post($a, false);
1008 throw new InternalServerErrorException();
1011 $returndata = array();
1012 $returndata["media_id"] = $media["id"];
1013 $returndata["media_id_string"] = (string)$media["id"];
1014 $returndata["size"] = $media["size"];
1015 $returndata["image"] = array("w" => $media["width"],
1016 "h" => $media["height"],
1017 "image_type" => $media["type"]);
1019 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1021 return array("media" => $returndata);
1023 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1025 function api_status_show(&$a, $type){
1026 $user_info = api_get_user($a);
1028 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1031 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1035 // get last public wall message
1036 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1037 FROM `item`, `item` as `i`
1038 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1039 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1040 AND `i`.`id` = `item`.`parent`
1041 AND `item`.`type`!='activity' $privacy_sql
1042 ORDER BY `item`.`created` DESC
1044 intval($user_info['cid']),
1046 dbesc($user_info['url']),
1047 dbesc(normalise_link($user_info['url'])),
1048 dbesc($user_info['url']),
1049 dbesc(normalise_link($user_info['url']))
1052 if (count($lastwall)>0){
1053 $lastwall = $lastwall[0];
1055 $in_reply_to_status_id = NULL;
1056 $in_reply_to_user_id = NULL;
1057 $in_reply_to_status_id_str = NULL;
1058 $in_reply_to_user_id_str = NULL;
1059 $in_reply_to_screen_name = NULL;
1060 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1061 $in_reply_to_status_id= intval($lastwall['parent']);
1062 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1064 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1066 if ($r[0]['nick'] == "")
1067 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1069 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1070 $in_reply_to_user_id = intval($r[0]['id']);
1071 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1075 // There seems to be situation, where both fields are identical:
1076 // https://github.com/friendica/friendica/issues/1010
1077 // This is a bugfix for that.
1078 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1079 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1080 $in_reply_to_status_id = NULL;
1081 $in_reply_to_user_id = NULL;
1082 $in_reply_to_status_id_str = NULL;
1083 $in_reply_to_user_id_str = NULL;
1084 $in_reply_to_screen_name = NULL;
1087 $converted = api_convert_item($lastwall);
1089 $status_info = array(
1090 'created_at' => api_date($lastwall['created']),
1091 'id' => intval($lastwall['id']),
1092 'id_str' => (string) $lastwall['id'],
1093 'text' => $converted["text"],
1094 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1095 'truncated' => false,
1096 'in_reply_to_status_id' => $in_reply_to_status_id,
1097 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1098 'in_reply_to_user_id' => $in_reply_to_user_id,
1099 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1100 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1101 'user' => $user_info,
1103 'coordinates' => "",
1105 'contributors' => "",
1106 'is_quote_status' => false,
1107 'retweet_count' => 0,
1108 'favorite_count' => 0,
1109 'favorited' => $lastwall['starred'] ? true : false,
1110 'retweeted' => false,
1111 'possibly_sensitive' => false,
1113 'statusnet_html' => $converted["html"],
1114 'statusnet_conversation_id' => $lastwall['parent'],
1117 if (count($converted["attachments"]) > 0)
1118 $status_info["attachments"] = $converted["attachments"];
1120 if (count($converted["entities"]) > 0)
1121 $status_info["entities"] = $converted["entities"];
1123 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1124 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1125 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1126 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1128 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1129 unset($status_info["user"]["uid"]);
1130 unset($status_info["user"]["self"]);
1133 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1136 return($status_info);
1138 return api_apply_template("status", $type, array('$status' => $status_info));
1147 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1148 * The author's most recent status will be returned inline.
1149 * http://developer.twitter.com/doc/get/users/show
1151 function api_users_show(&$a, $type){
1152 $user_info = api_get_user($a);
1154 $lastwall = q("SELECT `item`.*
1155 FROM `item`, `contact`
1156 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1157 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1158 AND `contact`.`id`=`item`.`contact-id`
1159 AND `type`!='activity'
1160 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1161 ORDER BY `created` DESC
1164 dbesc(ACTIVITY_POST),
1165 intval($user_info['cid']),
1166 dbesc($user_info['url']),
1167 dbesc(normalise_link($user_info['url'])),
1168 dbesc($user_info['url']),
1169 dbesc(normalise_link($user_info['url']))
1171 if (count($lastwall)>0){
1172 $lastwall = $lastwall[0];
1174 $in_reply_to_status_id = NULL;
1175 $in_reply_to_user_id = NULL;
1176 $in_reply_to_status_id_str = NULL;
1177 $in_reply_to_user_id_str = NULL;
1178 $in_reply_to_screen_name = NULL;
1179 if ($lastwall['parent']!=$lastwall['id']) {
1180 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1181 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1182 if (count($reply)>0) {
1183 $in_reply_to_status_id = intval($lastwall['parent']);
1184 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1186 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1188 if ($r[0]['nick'] == "")
1189 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1191 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1192 $in_reply_to_user_id = intval($r[0]['id']);
1193 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1198 $converted = api_convert_item($lastwall);
1200 $user_info['status'] = array(
1201 'text' => $converted["text"],
1202 'truncated' => false,
1203 'created_at' => api_date($lastwall['created']),
1204 'in_reply_to_status_id' => $in_reply_to_status_id,
1205 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1206 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1207 'id' => intval($lastwall['contact-id']),
1208 'id_str' => (string) $lastwall['contact-id'],
1209 'in_reply_to_user_id' => $in_reply_to_user_id,
1210 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1211 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1213 'favorited' => $lastwall['starred'] ? true : false,
1214 'statusnet_html' => $converted["html"],
1215 'statusnet_conversation_id' => $lastwall['parent'],
1218 if (count($converted["attachments"]) > 0)
1219 $user_info["status"]["attachments"] = $converted["attachments"];
1221 if (count($converted["entities"]) > 0)
1222 $user_info["status"]["entities"] = $converted["entities"];
1224 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1225 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1226 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1227 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1231 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1232 unset($user_info["uid"]);
1233 unset($user_info["self"]);
1235 return api_apply_template("user", $type, array('$user' => $user_info));
1238 api_register_func('api/users/show','api_users_show');
1241 function api_users_search(&$a, $type) {
1242 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1244 $userlist = array();
1246 if (isset($_GET["q"])) {
1247 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1249 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1252 foreach ($r AS $user) {
1253 $user_info = api_get_user($a, $user["id"]);
1254 //echo print_r($user_info, true)."\n";
1255 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1256 $userlist[] = $userdata["user"];
1258 $userlist = array("users" => $userlist);
1260 throw new BadRequestException("User not found.");
1263 throw new BadRequestException("User not found.");
1268 api_register_func('api/users/search','api_users_search');
1272 * http://developer.twitter.com/doc/get/statuses/home_timeline
1274 * TODO: Optional parameters
1275 * TODO: Add reply info
1277 function api_statuses_home_timeline(&$a, $type){
1278 if (api_user()===false) throw new ForbiddenException();
1280 unset($_REQUEST["user_id"]);
1281 unset($_GET["user_id"]);
1283 unset($_REQUEST["screen_name"]);
1284 unset($_GET["screen_name"]);
1286 $user_info = api_get_user($a);
1287 // get last newtork messages
1291 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1292 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1293 if ($page<0) $page=0;
1294 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1295 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1296 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1297 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1298 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1300 $start = $page*$count;
1304 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1305 if ($exclude_replies > 0)
1306 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1307 if ($conversation_id > 0)
1308 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1310 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1311 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1312 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1313 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1314 FROM `item`, `contact`
1315 WHERE `item`.`uid` = %d AND `verb` = '%s'
1316 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1317 AND `contact`.`id` = `item`.`contact-id`
1318 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1321 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1323 dbesc(ACTIVITY_POST),
1325 intval($start), intval($count)
1328 $ret = api_format_items($r,$user_info);
1330 // Set all posts from the query above to seen
1332 foreach ($r AS $item)
1333 $idarray[] = intval($item["id"]);
1335 $idlist = implode(",", $idarray);
1338 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1341 $data = array('$statuses' => $ret);
1345 $data = api_rss_extra($a, $data, $user_info);
1348 $as = api_format_as($a, $ret, $user_info);
1349 $as['title'] = $a->config['sitename']." Home Timeline";
1350 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1355 return api_apply_template("timeline", $type, $data);
1357 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1358 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1360 function api_statuses_public_timeline(&$a, $type){
1361 if (api_user()===false) throw new ForbiddenException();
1363 $user_info = api_get_user($a);
1364 // get last newtork messages
1368 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1369 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1370 if ($page<0) $page=0;
1371 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1372 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1373 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1374 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1375 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1377 $start = $page*$count;
1380 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1381 if ($exclude_replies > 0)
1382 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1383 if ($conversation_id > 0)
1384 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1386 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1387 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1388 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1389 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1390 `user`.`nickname`, `user`.`hidewall`
1391 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1392 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1393 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1394 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1395 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1396 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1397 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1400 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1401 dbesc(ACTIVITY_POST),
1406 $ret = api_format_items($r,$user_info);
1409 $data = array('$statuses' => $ret);
1413 $data = api_rss_extra($a, $data, $user_info);
1416 $as = api_format_as($a, $ret, $user_info);
1417 $as['title'] = $a->config['sitename']." Public Timeline";
1418 $as['link']['url'] = $a->get_baseurl()."/";
1423 return api_apply_template("timeline", $type, $data);
1425 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1430 function api_statuses_show(&$a, $type){
1431 if (api_user()===false) throw new ForbiddenException();
1433 $user_info = api_get_user($a);
1436 $id = intval($a->argv[3]);
1439 $id = intval($_REQUEST["id"]);
1443 $id = intval($a->argv[4]);
1445 logger('API: api_statuses_show: '.$id);
1447 $conversation = (x($_REQUEST,'conversation')?1:0);
1451 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1453 $sql_extra .= " AND `item`.`id` = %d";
1455 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1456 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1457 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1458 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1459 FROM `item`, `contact`
1460 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1461 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1462 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1465 dbesc(ACTIVITY_POST),
1470 throw new BadRequestException("There is no status with this id.");
1473 $ret = api_format_items($r,$user_info);
1475 if ($conversation) {
1476 $data = array('$statuses' => $ret);
1477 return api_apply_template("timeline", $type, $data);
1479 $data = array('$status' => $ret[0]);
1483 $data = api_rss_extra($a, $data, $user_info);
1485 return api_apply_template("status", $type, $data);
1488 api_register_func('api/statuses/show','api_statuses_show', true);
1494 function api_conversation_show(&$a, $type){
1495 if (api_user()===false) throw new ForbiddenException();
1497 $user_info = api_get_user($a);
1500 $id = intval($a->argv[3]);
1501 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1502 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1503 if ($page<0) $page=0;
1504 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1505 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1507 $start = $page*$count;
1510 $id = intval($_REQUEST["id"]);
1514 $id = intval($a->argv[4]);
1516 logger('API: api_conversation_show: '.$id);
1518 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1520 $id = $r[0]["parent"];
1525 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1527 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1528 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1529 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1530 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
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`), `contact`
1533 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1534 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1535 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1536 AND `item`.`id`>%d $sql_extra
1537 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1538 intval($id), intval(api_user()),
1539 dbesc(ACTIVITY_POST),
1541 intval($start), intval($count)
1545 throw new BadRequestException("There is no conversation with this id.");
1547 $ret = api_format_items($r,$user_info);
1549 $data = array('$statuses' => $ret);
1550 return api_apply_template("timeline", $type, $data);
1552 api_register_func('api/conversation/show','api_conversation_show', true);
1558 function api_statuses_repeat(&$a, $type){
1561 if (api_user()===false) throw new ForbiddenException();
1563 $user_info = api_get_user($a);
1566 $id = intval($a->argv[3]);
1569 $id = intval($_REQUEST["id"]);
1573 $id = intval($a->argv[4]);
1575 logger('API: api_statuses_repeat: '.$id);
1577 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1578 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1579 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1580 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1581 FROM `item`, `contact`
1582 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1583 AND `contact`.`id` = `item`.`contact-id`
1584 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1585 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1586 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1588 AND `item`.`id`=%d",
1592 if ($r[0]['body'] != "") {
1593 if (!intval(get_config('system','old_share'))) {
1594 if (strpos($r[0]['body'], "[/share]") !== false) {
1595 $pos = strpos($r[0]['body'], "[share");
1596 $post = substr($r[0]['body'], $pos);
1598 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1600 $post .= $r[0]['body'];
1601 $post .= "[/share]";
1603 $_REQUEST['body'] = $post;
1605 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1607 $_REQUEST['profile_uid'] = api_user();
1608 $_REQUEST['type'] = 'wall';
1609 $_REQUEST['api_source'] = true;
1611 if (!x($_REQUEST, "source"))
1612 $_REQUEST["source"] = api_source();
1616 throw new ForbiddenException();
1618 // this should output the last post (the one we just posted).
1620 return(api_status_show($a,$type));
1622 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1627 function api_statuses_destroy(&$a, $type){
1628 if (api_user()===false) throw new ForbiddenException();
1630 $user_info = api_get_user($a);
1633 $id = intval($a->argv[3]);
1636 $id = intval($_REQUEST["id"]);
1640 $id = intval($a->argv[4]);
1642 logger('API: api_statuses_destroy: '.$id);
1644 $ret = api_statuses_show($a, $type);
1646 drop_item($id, false);
1650 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1654 * http://developer.twitter.com/doc/get/statuses/mentions
1657 function api_statuses_mentions(&$a, $type){
1658 if (api_user()===false) throw new ForbiddenException();
1660 unset($_REQUEST["user_id"]);
1661 unset($_GET["user_id"]);
1663 unset($_REQUEST["screen_name"]);
1664 unset($_GET["screen_name"]);
1666 $user_info = api_get_user($a);
1667 // get last newtork messages
1671 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1672 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1673 if ($page<0) $page=0;
1674 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1675 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1676 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1678 $start = $page*$count;
1680 // Ugly code - should be changed
1681 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1682 $myurl = substr($myurl,strpos($myurl,'://')+3);
1683 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1684 $myurl = str_replace('www.','',$myurl);
1685 $diasp_url = str_replace('/profile/','/u/',$myurl);
1688 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1690 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1691 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1692 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1693 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1694 FROM `item` FORCE INDEX (`uid_id`), `contact`
1695 WHERE `item`.`uid` = %d AND `verb` = '%s'
1696 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1697 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1698 AND `contact`.`id` = `item`.`contact-id`
1699 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1700 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1703 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1705 dbesc(ACTIVITY_POST),
1706 dbesc(protect_sprintf($myurl)),
1707 dbesc(protect_sprintf($myurl)),
1710 intval($start), intval($count)
1713 $ret = api_format_items($r,$user_info);
1716 $data = array('$statuses' => $ret);
1720 $data = api_rss_extra($a, $data, $user_info);
1723 $as = api_format_as($a, $ret, $user_info);
1724 $as["title"] = $a->config['sitename']." Mentions";
1725 $as['link']['url'] = $a->get_baseurl()."/";
1730 return api_apply_template("timeline", $type, $data);
1732 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1733 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1736 function api_statuses_user_timeline(&$a, $type){
1737 if (api_user()===false) throw new ForbiddenException();
1739 $user_info = api_get_user($a);
1740 // get last network messages
1742 logger("api_statuses_user_timeline: api_user: ". api_user() .
1743 "\nuser_info: ".print_r($user_info, true) .
1744 "\n_REQUEST: ".print_r($_REQUEST, true),
1748 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1749 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1750 if ($page<0) $page=0;
1751 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1752 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1753 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1754 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1756 $start = $page*$count;
1759 if ($user_info['self']==1)
1760 $sql_extra .= " AND `item`.`wall` = 1 ";
1762 if ($exclude_replies > 0)
1763 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1764 if ($conversation_id > 0)
1765 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1767 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1768 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1769 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1770 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1771 FROM `item`, `contact`
1772 WHERE `item`.`uid` = %d AND `verb` = '%s'
1773 AND `item`.`contact-id` = %d
1774 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1775 AND `contact`.`id` = `item`.`contact-id`
1776 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1779 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1781 dbesc(ACTIVITY_POST),
1782 intval($user_info['cid']),
1784 intval($start), intval($count)
1787 $ret = api_format_items($r,$user_info, true);
1789 $data = array('$statuses' => $ret);
1793 $data = api_rss_extra($a, $data, $user_info);
1796 return api_apply_template("timeline", $type, $data);
1798 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1802 * Star/unstar an item
1803 * param: id : id of the item
1805 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1807 function api_favorites_create_destroy(&$a, $type){
1808 if (api_user()===false) throw new ForbiddenException();
1810 // for versioned api.
1811 /// @TODO We need a better global soluton
1813 if ($a->argv[1]=="1.1") $action_argv_id=3;
1815 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1816 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1817 if ($a->argc==$action_argv_id+2) {
1818 $itemid = intval($a->argv[$action_argv_id+1]);
1820 $itemid = intval($_REQUEST['id']);
1823 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1824 $itemid, api_user());
1826 if ($item===false || count($item)==0)
1827 throw new BadRequestException("Invalid item.");
1831 $item[0]['starred']=1;
1834 $item[0]['starred']=0;
1837 throw new BadRequestException("Invalid action ".$action);
1839 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1840 $item[0]['starred'], $itemid, api_user());
1842 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1843 $item[0]['starred'], $itemid, api_user());
1846 throw InternalServerErrorException("DB error");
1849 $user_info = api_get_user($a);
1850 $rets = api_format_items($item,$user_info);
1853 $data = array('$status' => $ret);
1857 $data = api_rss_extra($a, $data, $user_info);
1860 return api_apply_template("status", $type, $data);
1862 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1863 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1865 function api_favorites(&$a, $type){
1868 if (api_user()===false) throw new ForbiddenException();
1870 $called_api= array();
1872 $user_info = api_get_user($a);
1874 // in friendica starred item are private
1875 // return favorites only for self
1876 logger('api_favorites: self:' . $user_info['self']);
1878 if ($user_info['self']==0) {
1884 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1885 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1886 $count = (x($_GET,'count')?$_GET['count']:20);
1887 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1888 if ($page<0) $page=0;
1890 $start = $page*$count;
1893 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1895 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1896 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1897 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1898 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1899 FROM `item`, `contact`
1900 WHERE `item`.`uid` = %d
1901 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1902 AND `item`.`starred` = 1
1903 AND `contact`.`id` = `item`.`contact-id`
1904 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1907 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1910 intval($start), intval($count)
1913 $ret = api_format_items($r,$user_info);
1917 $data = array('$statuses' => $ret);
1921 $data = api_rss_extra($a, $data, $user_info);
1924 return api_apply_template("timeline", $type, $data);
1926 api_register_func('api/favorites','api_favorites', true);
1931 function api_format_as($a, $ret, $user_info) {
1933 $as['title'] = $a->config['sitename']." Public Timeline";
1935 foreach ($ret as $item) {
1936 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1937 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1938 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1939 $avatar[0]["rel"] = "avatar";
1940 $avatar[0]["type"] = "";
1941 $avatar[0]["width"] = 96;
1942 $avatar[0]["height"] = 96;
1943 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1944 $avatar[1]["rel"] = "avatar";
1945 $avatar[1]["type"] = "";
1946 $avatar[1]["width"] = 48;
1947 $avatar[1]["height"] = 48;
1948 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1949 $avatar[2]["rel"] = "avatar";
1950 $avatar[2]["type"] = "";
1951 $avatar[2]["width"] = 24;
1952 $avatar[2]["height"] = 24;
1953 $singleitem["actor"]["avatarLinks"] = $avatar;
1955 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1956 $singleitem["actor"]["image"]["rel"] = "avatar";
1957 $singleitem["actor"]["image"]["type"] = "";
1958 $singleitem["actor"]["image"]["width"] = 96;
1959 $singleitem["actor"]["image"]["height"] = 96;
1960 $singleitem["actor"]["type"] = "person";
1961 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1962 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1963 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1964 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1965 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1966 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1967 $singleitem["actor"]["contact"]["addresses"] = "";
1969 $singleitem["body"] = $item["text"];
1970 $singleitem["object"]["displayName"] = $item["text"];
1971 $singleitem["object"]["id"] = $item["url"];
1972 $singleitem["object"]["type"] = "note";
1973 $singleitem["object"]["url"] = $item["url"];
1974 //$singleitem["context"] =;
1975 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1976 $singleitem["provider"]["objectType"] = "service";
1977 $singleitem["provider"]["displayName"] = "Test";
1978 $singleitem["provider"]["url"] = "http://test.tld";
1979 $singleitem["title"] = $item["text"];
1980 $singleitem["verb"] = "post";
1981 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1982 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1983 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1984 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1985 //$singleitem["original"] = $item;
1986 $items[] = $singleitem;
1988 $as['items'] = $items;
1989 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1990 $as['link']['rel'] = "alternate";
1991 $as['link']['type'] = "text/html";
1995 function api_format_messages($item, $recipient, $sender) {
1996 // standard meta information
1998 'id' => $item['id'],
1999 'sender_id' => $sender['id'] ,
2001 'recipient_id' => $recipient['id'],
2002 'created_at' => api_date($item['created']),
2003 'sender_screen_name' => $sender['screen_name'],
2004 'recipient_screen_name' => $recipient['screen_name'],
2005 'sender' => $sender,
2006 'recipient' => $recipient,
2009 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2010 unset($ret["sender"]["uid"]);
2011 unset($ret["sender"]["self"]);
2012 unset($ret["recipient"]["uid"]);
2013 unset($ret["recipient"]["self"]);
2015 //don't send title to regular StatusNET requests to avoid confusing these apps
2016 if (x($_GET, 'getText')) {
2017 $ret['title'] = $item['title'] ;
2018 if ($_GET["getText"] == "html") {
2019 $ret['text'] = bbcode($item['body'], false, false);
2021 elseif ($_GET["getText"] == "plain") {
2022 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2023 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2027 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2029 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2030 unset($ret['sender']);
2031 unset($ret['recipient']);
2037 function api_convert_item($item) {
2039 $body = $item['body'];
2040 $attachments = api_get_attachments($body);
2042 // Workaround for ostatus messages where the title is identically to the body
2043 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2044 $statusbody = trim(html2plain($html, 0));
2046 // handle data: images
2047 $statusbody = api_format_items_embeded_images($item,$statusbody);
2049 $statustitle = trim($item['title']);
2051 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2052 $statustext = trim($statusbody);
2054 $statustext = trim($statustitle."\n\n".$statusbody);
2056 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2057 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2059 $statushtml = trim(bbcode($body, false, false));
2061 if ($item['title'] != "")
2062 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2064 $entities = api_get_entitities($statustext, $body);
2066 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2069 function api_get_attachments(&$body) {
2072 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2074 $URLSearchString = "^\[\]";
2075 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2080 $attachments = array();
2082 foreach ($images[1] AS $image) {
2083 $imagedata = get_photo_info($image);
2086 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2089 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2090 foreach ($images[0] AS $orig)
2091 $body = str_replace($orig, "", $body);
2093 return $attachments;
2096 function api_get_entitities(&$text, $bbcode) {
2099 * Links at the first character of the post
2104 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2106 if ($include_entities != "true") {
2108 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2110 foreach ($images[1] AS $image) {
2111 $replace = proxy_url($image);
2112 $text = str_replace($image, $replace, $text);
2117 $bbcode = bb_CleanPictureLinks($bbcode);
2119 // Change pure links in text to bbcode uris
2120 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2122 $entities = array();
2123 $entities["hashtags"] = array();
2124 $entities["symbols"] = array();
2125 $entities["urls"] = array();
2126 $entities["user_mentions"] = array();
2128 $URLSearchString = "^\[\]";
2130 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2132 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2133 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2134 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2136 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2137 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2138 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2140 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2141 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2142 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2144 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2146 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2147 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2149 $ordered_urls = array();
2150 foreach ($urls[1] AS $id=>$url) {
2151 //$start = strpos($text, $url, $offset);
2152 $start = iconv_strpos($text, $url, 0, "UTF-8");
2153 if (!($start === false))
2154 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2157 ksort($ordered_urls);
2160 //foreach ($urls[1] AS $id=>$url) {
2161 foreach ($ordered_urls AS $url) {
2162 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2163 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2164 $display_url = $url["title"];
2166 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2167 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2169 if (strlen($display_url) > 26)
2170 $display_url = substr($display_url, 0, 25)."…";
2173 //$start = strpos($text, $url, $offset);
2174 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2175 if (!($start === false)) {
2176 $entities["urls"][] = array("url" => $url["url"],
2177 "expanded_url" => $url["url"],
2178 "display_url" => $display_url,
2179 "indices" => array($start, $start+strlen($url["url"])));
2180 $offset = $start + 1;
2184 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2185 $ordered_images = array();
2186 foreach ($images[1] AS $image) {
2187 //$start = strpos($text, $url, $offset);
2188 $start = iconv_strpos($text, $image, 0, "UTF-8");
2189 if (!($start === false))
2190 $ordered_images[$start] = $image;
2192 //$entities["media"] = array();
2195 foreach ($ordered_images AS $url) {
2196 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2197 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2199 if (strlen($display_url) > 26)
2200 $display_url = substr($display_url, 0, 25)."…";
2202 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2203 if (!($start === false)) {
2204 $image = get_photo_info($url);
2206 // If image cache is activated, then use the following sizes:
2207 // thumb (150), small (340), medium (600) and large (1024)
2208 if (!get_config("system", "proxy_disabled")) {
2209 $media_url = proxy_url($url);
2212 $scale = scale_image($image[0], $image[1], 150);
2213 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2215 if (($image[0] > 150) OR ($image[1] > 150)) {
2216 $scale = scale_image($image[0], $image[1], 340);
2217 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2220 $scale = scale_image($image[0], $image[1], 600);
2221 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2223 if (($image[0] > 600) OR ($image[1] > 600)) {
2224 $scale = scale_image($image[0], $image[1], 1024);
2225 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2229 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2232 $entities["media"][] = array(
2234 "id_str" => (string)$start+1,
2235 "indices" => array($start, $start+strlen($url)),
2236 "media_url" => normalise_link($media_url),
2237 "media_url_https" => $media_url,
2239 "display_url" => $display_url,
2240 "expanded_url" => $url,
2244 $offset = $start + 1;
2250 function api_format_items_embeded_images(&$item, $text){
2252 $text = preg_replace_callback(
2253 "|data:image/([^;]+)[^=]+=*|m",
2254 function($match) use ($a, $item) {
2255 return $a->get_baseurl()."/display/".$item['guid'];
2262 * @brief return likes, dislikes and attend status for item
2264 * @param array $item
2266 * likes => int count
2267 * dislikes => int count
2269 function api_format_items_likes(&$item) {
2270 $activities = array(
2272 'dislike' => array(),
2273 'attendyes' => array(),
2274 'attendno' => array(),
2275 'attendmaybe' => array()
2277 $items = q('SELECT * FROM item
2278 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2279 intval($item['uid']),
2280 dbesc($item['uri']));
2281 foreach ($items as $i){
2282 builtin_activity_puller($i, $activities);
2286 $uri = $item['uri'];
2287 foreach($activities as $k => $v) {
2288 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2295 * @brief format items to be returned by api
2297 * @param array $r array of items
2298 * @param array $user_info
2299 * @param bool $filter_user filter items by $user_info
2301 function api_format_items($r,$user_info, $filter_user = false) {
2306 foreach($r as $item) {
2307 api_share_as_retweet($item);
2309 localize_item($item);
2310 $status_user = api_item_get_user($a,$item);
2312 // Look if the posts are matching if they should be filtered by user id
2313 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2316 if ($item['thr-parent'] != $item['uri']) {
2317 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2319 dbesc($item['thr-parent']));
2321 $in_reply_to_status_id = intval($r[0]['id']);
2323 $in_reply_to_status_id = intval($item['parent']);
2325 $in_reply_to_status_id_str = (string) intval($item['parent']);
2327 $in_reply_to_screen_name = NULL;
2328 $in_reply_to_user_id = NULL;
2329 $in_reply_to_user_id_str = NULL;
2331 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2333 intval($in_reply_to_status_id));
2335 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2338 if ($r[0]['nick'] == "")
2339 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2341 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2342 $in_reply_to_user_id = intval($r[0]['id']);
2343 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2347 $in_reply_to_screen_name = NULL;
2348 $in_reply_to_user_id = NULL;
2349 $in_reply_to_status_id = NULL;
2350 $in_reply_to_user_id_str = NULL;
2351 $in_reply_to_status_id_str = NULL;
2354 $converted = api_convert_item($item);
2357 'text' => $converted["text"],
2358 'truncated' => False,
2359 'created_at'=> api_date($item['created']),
2360 'in_reply_to_status_id' => $in_reply_to_status_id,
2361 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2362 'source' => (($item['app']) ? $item['app'] : 'web'),
2363 'id' => intval($item['id']),
2364 'id_str' => (string) intval($item['id']),
2365 'in_reply_to_user_id' => $in_reply_to_user_id,
2366 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2367 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2369 'favorited' => $item['starred'] ? true : false,
2370 'user' => $status_user ,
2371 //'entities' => NULL,
2372 'statusnet_html' => $converted["html"],
2373 'statusnet_conversation_id' => $item['parent'],
2374 'friendica_activities' => api_format_items_likes($item),
2377 if (count($converted["attachments"]) > 0)
2378 $status["attachments"] = $converted["attachments"];
2380 if (count($converted["entities"]) > 0)
2381 $status["entities"] = $converted["entities"];
2383 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2384 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2385 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2386 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2389 // Retweets are only valid for top postings
2390 // It doesn't work reliable with the link if its a feed
2391 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2393 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2395 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2396 $retweeted_status = $status;
2397 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2399 $status["retweeted_status"] = $retweeted_status;
2402 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2403 unset($status["user"]["uid"]);
2404 unset($status["user"]["self"]);
2406 if ($item["coord"] != "") {
2407 $coords = explode(' ',$item["coord"]);
2408 if (count($coords) == 2) {
2409 $status["geo"] = array('type' => 'Point',
2410 'coordinates' => array((float) $coords[0],
2411 (float) $coords[1]));
2421 function api_account_rate_limit_status(&$a,$type) {
2423 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2424 'remaining_hits' => (string) 150,
2425 'hourly_limit' => (string) 150,
2426 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2429 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2431 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2433 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2435 function api_help_test(&$a,$type) {
2441 return api_apply_template('test', $type, array("$ok" => $ok));
2443 api_register_func('api/help/test','api_help_test',false);
2445 function api_lists(&$a,$type) {
2449 api_register_func('api/lists','api_lists',true);
2451 function api_lists_list(&$a,$type) {
2455 api_register_func('api/lists/list','api_lists_list',true);
2458 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2459 * This function is deprecated by Twitter
2460 * returns: json, xml
2462 function api_statuses_f(&$a, $type, $qtype) {
2463 if (api_user()===false) throw new ForbiddenException();
2464 $user_info = api_get_user($a);
2466 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2467 /* this is to stop Hotot to load friends multiple times
2468 * I'm not sure if I'm missing return something or
2469 * is a bug in hotot. Workaround, meantime
2473 return array('$users' => $ret);*/
2477 if($qtype == 'friends')
2478 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2479 if($qtype == 'followers')
2480 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2482 // friends and followers only for self
2483 if ($user_info['self'] == 0)
2484 $sql_extra = " AND false ";
2486 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2491 foreach($r as $cid){
2492 $user = api_get_user($a, $cid['nurl']);
2493 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2494 unset($user["uid"]);
2495 unset($user["self"]);
2501 return array('$users' => $ret);
2504 function api_statuses_friends(&$a, $type){
2505 $data = api_statuses_f($a,$type,"friends");
2506 if ($data===false) return false;
2507 return api_apply_template("friends", $type, $data);
2509 function api_statuses_followers(&$a, $type){
2510 $data = api_statuses_f($a,$type,"followers");
2511 if ($data===false) return false;
2512 return api_apply_template("friends", $type, $data);
2514 api_register_func('api/statuses/friends','api_statuses_friends',true);
2515 api_register_func('api/statuses/followers','api_statuses_followers',true);
2522 function api_statusnet_config(&$a,$type) {
2523 $name = $a->config['sitename'];
2524 $server = $a->get_hostname();
2525 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2526 $email = $a->config['admin_email'];
2527 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2528 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2529 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2530 if($a->config['api_import_size'])
2531 $texlimit = string($a->config['api_import_size']);
2532 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2533 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2536 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2537 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2538 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2539 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2540 'shorturllength' => '30',
2541 'friendica' => array(
2542 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2543 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2544 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2545 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2550 return api_apply_template('config', $type, array('$config' => $config));
2553 api_register_func('api/statusnet/config','api_statusnet_config',false);
2555 function api_statusnet_version(&$a,$type) {
2557 $fake_statusnet_version = "0.9.7";
2559 if($type === 'xml') {
2560 header("Content-type: application/xml");
2561 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2564 elseif($type === 'json') {
2565 header("Content-type: application/json");
2566 echo '"'.$fake_statusnet_version.'"';
2570 api_register_func('api/statusnet/version','api_statusnet_version',false);
2573 * @todo use api_apply_template() to return data
2575 function api_ff_ids(&$a,$type,$qtype) {
2576 if(! api_user()) throw new ForbiddenException();
2578 $user_info = api_get_user($a);
2580 if($qtype == 'friends')
2581 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2582 if($qtype == 'followers')
2583 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2585 if (!$user_info["self"])
2586 $sql_extra = " AND false ";
2588 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2590 $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",
2596 if($type === 'xml') {
2597 header("Content-type: application/xml");
2598 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2600 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2601 echo '</ids>' . "\r\n";
2604 elseif($type === 'json') {
2606 header("Content-type: application/json");
2611 $ret[] = intval($rr['id']);
2613 echo json_encode($ret);
2619 function api_friends_ids(&$a,$type) {
2620 api_ff_ids($a,$type,'friends');
2622 function api_followers_ids(&$a,$type) {
2623 api_ff_ids($a,$type,'followers');
2625 api_register_func('api/friends/ids','api_friends_ids',true);
2626 api_register_func('api/followers/ids','api_followers_ids',true);
2629 function api_direct_messages_new(&$a, $type) {
2630 if (api_user()===false) throw new ForbiddenException();
2632 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2634 $sender = api_get_user($a);
2636 if ($_POST['screen_name']) {
2637 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2639 dbesc($_POST['screen_name']));
2641 // Selecting the id by priority, friendica first
2642 api_best_nickname($r);
2644 $recipient = api_get_user($a, $r[0]['nurl']);
2646 $recipient = api_get_user($a, $_POST['user_id']);
2650 if (x($_REQUEST,'replyto')) {
2651 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2653 intval($_REQUEST['replyto']));
2654 $replyto = $r[0]['parent-uri'];
2655 $sub = $r[0]['title'];
2658 if (x($_REQUEST,'title')) {
2659 $sub = $_REQUEST['title'];
2662 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2666 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2669 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2670 $ret = api_format_messages($r[0], $recipient, $sender);
2673 $ret = array("error"=>$id);
2676 $data = Array('$messages'=>$ret);
2681 $data = api_rss_extra($a, $data, $user_info);
2684 return api_apply_template("direct_messages", $type, $data);
2687 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2689 function api_direct_messages_box(&$a, $type, $box) {
2690 if (api_user()===false) throw new ForbiddenException();
2693 $count = (x($_GET,'count')?$_GET['count']:20);
2694 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2695 if ($page<0) $page=0;
2697 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2698 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2700 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2701 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2704 unset($_REQUEST["user_id"]);
2705 unset($_GET["user_id"]);
2707 unset($_REQUEST["screen_name"]);
2708 unset($_GET["screen_name"]);
2710 $user_info = api_get_user($a);
2711 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2712 $profile_url = $user_info["url"];
2716 $start = $page*$count;
2719 if ($box=="sentbox") {
2720 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2722 elseif ($box=="conversation") {
2723 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2725 elseif ($box=="all") {
2726 $sql_extra = "true";
2728 elseif ($box=="inbox") {
2729 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2733 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2735 if ($user_id !="") {
2736 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2738 elseif($screen_name !=""){
2739 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2742 $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",
2745 intval($start), intval($count)
2750 foreach($r as $item) {
2751 if ($box == "inbox" || $item['from-url'] != $profile_url){
2752 $recipient = $user_info;
2753 $sender = api_get_user($a,normalise_link($item['contact-url']));
2755 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2756 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2757 $sender = $user_info;
2760 $ret[]=api_format_messages($item, $recipient, $sender);
2764 $data = array('$messages' => $ret);
2768 $data = api_rss_extra($a, $data, $user_info);
2771 return api_apply_template("direct_messages", $type, $data);
2775 function api_direct_messages_sentbox(&$a, $type){
2776 return api_direct_messages_box($a, $type, "sentbox");
2778 function api_direct_messages_inbox(&$a, $type){
2779 return api_direct_messages_box($a, $type, "inbox");
2781 function api_direct_messages_all(&$a, $type){
2782 return api_direct_messages_box($a, $type, "all");
2784 function api_direct_messages_conversation(&$a, $type){
2785 return api_direct_messages_box($a, $type, "conversation");
2787 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2788 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2789 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2790 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2794 function api_oauth_request_token(&$a, $type){
2796 $oauth = new FKOAuth1();
2797 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2798 }catch(Exception $e){
2799 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2804 function api_oauth_access_token(&$a, $type){
2806 $oauth = new FKOAuth1();
2807 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2808 }catch(Exception $e){
2809 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2815 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2816 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2819 function api_fr_photos_list(&$a,$type) {
2820 if (api_user()===false) throw new ForbiddenException();
2821 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2822 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2823 intval(local_user())
2826 'image/jpeg' => 'jpg',
2827 'image/png' => 'png',
2828 'image/gif' => 'gif'
2830 $data = array('photos'=>array());
2832 foreach($r as $rr) {
2834 $photo['id'] = $rr['resource-id'];
2835 $photo['album'] = $rr['album'];
2836 $photo['filename'] = $rr['filename'];
2837 $photo['type'] = $rr['type'];
2838 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2839 $data['photos'][] = $photo;
2842 return api_apply_template("photos_list", $type, $data);
2845 function api_fr_photo_detail(&$a,$type) {
2846 if (api_user()===false) throw new ForbiddenException();
2847 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2849 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2850 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2851 $data_sql = ($scale === false ? "" : "data, ");
2853 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2854 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2855 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2857 intval(local_user()),
2858 dbesc($_REQUEST['photo_id']),
2863 'image/jpeg' => 'jpg',
2864 'image/png' => 'png',
2865 'image/gif' => 'gif'
2869 $data = array('photo' => $r[0]);
2870 if ($scale !== false) {
2871 $data['photo']['data'] = base64_encode($data['photo']['data']);
2873 unset($data['photo']['datasize']); //needed only with scale param
2875 $data['photo']['link'] = array();
2876 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2877 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2879 $data['photo']['id'] = $data['photo']['resource-id'];
2880 unset($data['photo']['resource-id']);
2881 unset($data['photo']['minscale']);
2882 unset($data['photo']['maxscale']);
2885 throw new NotFoundException();
2888 return api_apply_template("photo_detail", $type, $data);
2891 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2892 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2897 * similar as /mod/redir.php
2898 * redirect to 'url' after dfrn auth
2900 * why this when there is mod/redir.php already?
2901 * This use api_user() and api_login()
2904 * c_url: url of remote contact to auth to
2905 * url: string, url to redirect after auth
2907 function api_friendica_remoteauth(&$a) {
2908 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2909 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2911 if ($url === '' || $c_url === '')
2912 throw new BadRequestException("Wrong parameters.");
2914 $c_url = normalise_link($c_url);
2918 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2923 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2924 throw new BadRequestException("Unknown contact");
2928 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2930 if($r[0]['duplex'] && $r[0]['issued-id']) {
2931 $orig_id = $r[0]['issued-id'];
2932 $dfrn_id = '1:' . $orig_id;
2934 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2935 $orig_id = $r[0]['dfrn-id'];
2936 $dfrn_id = '0:' . $orig_id;
2939 $sec = random_string();
2941 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2942 VALUES( %d, %s, '%s', '%s', %d )",
2950 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2951 $dest = (($url) ? '&destination_url=' . $url : '');
2952 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2953 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2954 . '&type=profile&sec=' . $sec . $dest . $quiet );
2956 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2959 function api_share_as_retweet(&$item) {
2960 $body = trim($item["body"]);
2962 // Skip if it isn't a pure repeated messages
2963 // Does it start with a share?
2964 if (strpos($body, "[share") > 0)
2967 // Does it end with a share?
2968 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2971 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2972 // Skip if there is no shared message in there
2973 if ($body == $attributes)
2977 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2978 if ($matches[1] != "")
2979 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2981 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2982 if ($matches[1] != "")
2983 $author = $matches[1];
2986 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2987 if ($matches[1] != "")
2988 $profile = $matches[1];
2990 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2991 if ($matches[1] != "")
2992 $profile = $matches[1];
2995 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2996 if ($matches[1] != "")
2997 $avatar = $matches[1];
2999 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3000 if ($matches[1] != "")
3001 $avatar = $matches[1];
3004 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3005 if ($matches[1] != "")
3006 $link = $matches[1];
3008 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3009 if ($matches[1] != "")
3010 $link = $matches[1];
3012 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3014 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
3017 $item["body"] = $shared_body;
3018 $item["author-name"] = $author;
3019 $item["author-link"] = $profile;
3020 $item["author-avatar"] = $avatar;
3021 $item["plink"] = $link;
3027 function api_get_nick($profile) {
3029 - remove trailing junk from profile url
3030 - pump.io check has to check the website
3035 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3036 dbesc(normalise_link($profile)));
3038 $nick = $r[0]["nick"];
3041 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3042 dbesc(normalise_link($profile)));
3044 $nick = $r[0]["nick"];
3048 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3049 if ($friendica != $profile)
3054 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3055 if ($diaspora != $profile)
3060 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3061 if ($twitter != $profile)
3067 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3068 if ($StatusnetHost != $profile) {
3069 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3070 if ($StatusnetUser != $profile) {
3071 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3072 $user = json_decode($UserData);
3074 $nick = $user->screen_name;
3079 // To-Do: look at the page if its really a pumpio site
3080 //if (!$nick == "") {
3081 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3082 // if ($pumpio != $profile)
3084 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3094 function api_clean_plain_items($Text) {
3095 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3097 $Text = bb_CleanPictureLinks($Text);
3099 $URLSearchString = "^\[\]";
3101 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3103 if ($include_entities == "true") {
3104 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3107 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
3111 function api_cleanup_share($shared) {
3112 if ($shared[2] != "type-link")
3115 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
3121 if (isset($bookmark[2][0]))
3122 $title = $bookmark[2][0];
3124 if (isset($bookmark[1][0]))
3125 $link = $bookmark[1][0];
3127 if (strpos($shared[1],$title) !== false)
3130 if (strpos($shared[1],$link) !== false)
3133 $text = trim($shared[1]);
3135 //if (strlen($text) < strlen($title))
3136 if (($text == "") AND ($title != ""))
3137 $text .= "\n\n".trim($title);
3140 $text .= "\n".trim($link);
3142 return(trim($text));
3145 function api_best_nickname(&$contacts) {
3146 $best_contact = array();
3148 if (count($contact) == 0)
3151 foreach ($contacts AS $contact)
3152 if ($contact["network"] == "") {
3153 $contact["network"] = "dfrn";
3154 $best_contact = array($contact);
3157 if (sizeof($best_contact) == 0)
3158 foreach ($contacts AS $contact)
3159 if ($contact["network"] == "dfrn")
3160 $best_contact = array($contact);
3162 if (sizeof($best_contact) == 0)
3163 foreach ($contacts AS $contact)
3164 if ($contact["network"] == "dspr")
3165 $best_contact = array($contact);
3167 if (sizeof($best_contact) == 0)
3168 foreach ($contacts AS $contact)
3169 if ($contact["network"] == "stat")
3170 $best_contact = array($contact);
3172 if (sizeof($best_contact) == 0)
3173 foreach ($contacts AS $contact)
3174 if ($contact["network"] == "pump")
3175 $best_contact = array($contact);
3177 if (sizeof($best_contact) == 0)
3178 foreach ($contacts AS $contact)
3179 if ($contact["network"] == "twit")
3180 $best_contact = array($contact);
3182 if (sizeof($best_contact) == 1)
3183 $contacts = $best_contact;
3185 $contacts = array($contacts[0]);
3188 // return all or a specified group of the user with the containing contacts
3189 function api_friendica_group_show(&$a, $type) {
3190 if (api_user()===false) throw new ForbiddenException();
3193 $user_info = api_get_user($a);
3194 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3195 $uid = $user_info['uid'];
3197 // get data of the specified group id or all groups if not specified
3199 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3202 // error message if specified gid is not in database
3204 throw new BadRequestException("gid not available");
3207 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3210 // loop through all groups and retrieve all members for adding data in the user array
3211 foreach ($r as $rr) {
3212 $members = group_get_members($rr['id']);
3214 foreach ($members as $member) {
3215 $user = api_get_user($a, $member['nurl']);
3218 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3220 return api_apply_template("group_show", $type, array('$groups' => $grps));
3222 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3225 // delete the specified group of the user
3226 function api_friendica_group_delete(&$a, $type) {
3227 if (api_user()===false) throw new ForbiddenException();
3230 $user_info = api_get_user($a);
3231 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3232 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3233 $uid = $user_info['uid'];
3235 // error if no gid specified
3236 if ($gid == 0 || $name == "")
3237 throw new BadRequestException('gid or name not specified');
3239 // get data of the specified group id
3240 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3243 // error message if specified gid is not in database
3245 throw new BadRequestException('gid not available');
3247 // get data of the specified group id and group name
3248 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3252 // error message if specified gid is not in database
3253 if (count($rname) == 0)
3254 throw new BadRequestException('wrong group name');
3257 $ret = group_rmv($uid, $name);
3260 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3261 return api_apply_template("group_delete", $type, array('$result' => $success));
3264 throw new BadRequestException('other API error');
3266 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3269 // create the specified group with the posted array of contacts
3270 function api_friendica_group_create(&$a, $type) {
3271 if (api_user()===false) throw new ForbiddenException();
3274 $user_info = api_get_user($a);
3275 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3276 $uid = $user_info['uid'];
3277 $json = json_decode($_POST['json'], true);
3278 $users = $json['user'];
3280 // error if no name specified
3282 throw new BadRequestException('group name not specified');
3284 // get data of the specified group name
3285 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3288 // error message if specified group name already exists
3289 if (count($rname) != 0)
3290 throw new BadRequestException('group name already exists');
3292 // check if specified group name is a deleted group
3293 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3296 // error message if specified group name already exists
3297 if (count($rname) != 0)
3298 $reactivate_group = true;
3301 $ret = group_add($uid, $name);
3303 $gid = group_byname($uid, $name);
3305 throw new BadRequestException('other API error');
3308 $erroraddinguser = false;
3309 $errorusers = array();
3310 foreach ($users as $user) {
3311 $cid = $user['cid'];
3312 // check if user really exists as contact
3313 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3316 if (count($contact))
3317 $result = group_add_member($uid, $name, $cid, $gid);
3319 $erroraddinguser = true;
3320 $errorusers[] = $cid;
3324 // return success message incl. missing users in array
3325 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3326 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3327 return api_apply_template("group_create", $type, array('result' => $success));
3329 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3332 // update the specified group with the posted array of contacts
3333 function api_friendica_group_update(&$a, $type) {
3334 if (api_user()===false) throw new ForbiddenException();
3337 $user_info = api_get_user($a);
3338 $uid = $user_info['uid'];
3339 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3340 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3341 $json = json_decode($_POST['json'], true);
3342 $users = $json['user'];
3344 // error if no name specified
3346 throw new BadRequestException('group name not specified');
3348 // error if no gid specified
3350 throw new BadRequestException('gid not specified');
3353 $members = group_get_members($gid);
3354 foreach ($members as $member) {
3355 $cid = $member['id'];
3356 foreach ($users as $user) {
3357 $found = ($user['cid'] == $cid ? true : false);
3360 $ret = group_rmv_member($uid, $name, $cid);
3365 $erroraddinguser = false;
3366 $errorusers = array();
3367 foreach ($users as $user) {
3368 $cid = $user['cid'];
3369 // check if user really exists as contact
3370 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3373 if (count($contact))
3374 $result = group_add_member($uid, $name, $cid, $gid);
3376 $erroraddinguser = true;
3377 $errorusers[] = $cid;
3381 // return success message incl. missing users in array
3382 $status = ($erroraddinguser ? "missing user" : "ok");
3383 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3384 return api_apply_template("group_update", $type, array('result' => $success));
3386 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3389 function api_friendica_activity(&$a, $type) {
3390 if (api_user()===false) throw new ForbiddenException();
3391 $verb = strtolower($a->argv[3]);
3392 $verb = preg_replace("|\..*$|", "", $verb);
3394 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3396 $res = do_like($id, $verb);
3403 return api_apply_template('test', $type, array('ok' => $ok));
3405 throw new BadRequestException('Error adding activity');
3409 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3410 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3411 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3412 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3413 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3414 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3415 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3416 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3417 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3418 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3421 * @brief Returns notifications
3424 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3427 function api_friendica_notification(&$a, $type) {
3428 if (api_user()===false) throw new ForbiddenException();
3429 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3430 $nm = new NotificationsManager();
3432 $notes = $nm->getAll(array(), "+seen -date", 50);
3433 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3437 * @brief Set notification as seen and returns associated item (if possible)
3439 * POST request with 'id' param as notification id
3442 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3445 function api_friendica_notification_seen(&$a, $type){
3446 if (api_user()===false) throw new ForbiddenException();
3447 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3449 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3451 $nm = new NotificationsManager();
3452 $note = $nm->getByID($id);
3453 if (is_null($note)) throw new BadRequestException("Invalid argument");
3455 $nm->setSeen($note);
3456 if ($note['otype']=='item') {
3457 // would be really better with an ItemsManager and $im->getByID() :-P
3458 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3459 intval($note['iid']),
3460 intval(local_user())
3463 // we found the item, return it to the user
3464 $user_info = api_get_user($a);
3465 $ret = api_format_items($r,$user_info);
3466 $data = array('$statuses' => $ret);
3467 return api_apply_template("timeline", $type, $data);
3469 // the item can't be found, but we set the note as seen, so we count this as a success
3471 return api_apply_template('<auto>', $type, array('status' => "success"));
3474 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3475 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3480 [pagename] => api/1.1/statuses/lookup.json
3481 [id] => 605138389168451584
3482 [include_cards] => true
3483 [cards_platform] => Android-12
3484 [include_entities] => true
3485 [include_my_retweet] => 1
3487 [include_reply_count] => true
3488 [include_descendent_reply_count] => true
3492 Not implemented by now:
3493 statuses/retweets_of_me
3498 account/update_location
3499 account/update_profile_background_image
3500 account/update_profile_image
3504 Not implemented in status.net:
3505 statuses/retweeted_to_me
3506 statuses/retweeted_by_me
3507 direct_messages/destroy
3509 account/update_delivery_device
3510 notifications/follow