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');
28 define('API_METHOD_ANY','*');
29 define('API_METHOD_GET','GET');
30 define('API_METHOD_POST','POST,PUT');
31 define('API_METHOD_DELETE','POST,DELETE');
39 * @brief Auth API user
41 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
42 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
43 * into a page, and visitors will post something without noticing it).
46 if ($_SESSION['allow_api'])
53 * @brief Get source name from API client
55 * Clients can send 'source' parameter to be show in post metadata
56 * as "sent via <source>".
57 * Some clients doesn't send a source param, we support ones we know
61 * Client source name, default to "api" if unset/unknown
63 function api_source() {
64 if (requestdata('source'))
65 return (requestdata('source'));
67 // Support for known clients that doesn't send a source name
68 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
71 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
77 * @brief Format date for API
79 * @param string $str Source date, as UTC
80 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
82 function api_date($str){
83 //Wed May 23 06:01:13 +0000 2007
84 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
88 * @brief Register API endpoint
90 * Register a function to be the endpont for defined API path.
92 * @param string $path API URL path, relative to $a->get_baseurl()
93 * @param string $func Function name to call on path request
94 * @param bool $auth API need logged user
95 * @param string $method
96 * HTTP method reqiured to call this endpoint.
97 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
98 * Default to API_METHOD_ANY
100 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
108 // Workaround for hotot
109 $path = str_replace("api/", "api/1.1/", $path);
118 * @brief Login API user
120 * Log in user via OAuth1 or Simple HTTP Auth.
121 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
124 * @hook 'authenticate'
126 * 'username' => username from login form
127 * 'password' => password from login form
128 * 'authenticated' => return status,
129 * 'user_record' => return authenticated user record
131 * array $user logged user record
133 function api_login(&$a){
136 $oauth = new FKOAuth1();
137 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
138 if (!is_null($token)){
139 $oauth->loginUser($token->uid);
140 call_hooks('logged_in', $a->user);
143 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
144 }catch(Exception $e){
150 // workaround for HTTP-auth in CGI mode
151 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
152 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
153 if(strlen($userpass)) {
154 list($name, $password) = explode(':', $userpass);
155 $_SERVER['PHP_AUTH_USER'] = $name;
156 $_SERVER['PHP_AUTH_PW'] = $password;
160 if (!isset($_SERVER['PHP_AUTH_USER'])) {
161 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
162 header('WWW-Authenticate: Basic realm="Friendica"');
163 header('HTTP/1.0 401 Unauthorized');
164 die((api_error($a, 'json', "This api requires login")));
166 //die('This api requires login');
169 $user = $_SERVER['PHP_AUTH_USER'];
170 $password = $_SERVER['PHP_AUTH_PW'];
171 $encrypted = hash('whirlpool',trim($password));
173 // allow "user@server" login (but ignore 'server' part)
174 $at=strstr($user, "@", true);
175 if ( $at ) $user=$at;
178 * next code from mod/auth.php. needs better solution
183 'username' => trim($user),
184 'password' => trim($password),
185 'authenticated' => 0,
186 'user_record' => null
191 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
192 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
193 * and later plugins should not interfere with an earlier one that succeeded.
197 call_hooks('authenticate', $addon_auth);
199 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
200 $record = $addon_auth['user_record'];
203 // process normal login request
205 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
206 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
215 if((! $record) || (! count($record))) {
216 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
217 header('WWW-Authenticate: Basic realm="Friendica"');
218 header('HTTP/1.0 401 Unauthorized');
219 die('This api requires login');
222 authenticate_success($record); $_SESSION["allow_api"] = true;
224 call_hooks('logged_in', $a->user);
229 * @brief Check HTTP method of called API
231 * API endpoints can define which HTTP method to accept when called.
232 * This function check the current HTTP method agains endpoint
235 * @param string $method Required methods, uppercase, separated by comma
238 function api_check_method($method) {
239 if ($method=="*") return True;
240 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
244 * @brief Main API entry point
246 * Authenticate user, call registered API function, set HTTP headers
249 * @return string API call result
251 function api_call(&$a){
252 GLOBAL $API, $called_api;
255 if (strpos($a->query_string, ".xml")>0) $type="xml";
256 if (strpos($a->query_string, ".json")>0) $type="json";
257 if (strpos($a->query_string, ".rss")>0) $type="rss";
258 if (strpos($a->query_string, ".atom")>0) $type="atom";
259 if (strpos($a->query_string, ".as")>0) $type="as";
261 foreach ($API as $p=>$info){
262 if (strpos($a->query_string, $p)===0){
263 if (!api_check_method($info['method'])){
264 throw new MethodNotAllowedException();
267 $called_api= explode("/",$p);
268 //unset($_SERVER['PHP_AUTH_USER']);
269 if ($info['auth']===true && api_user()===false) {
273 load_contact_links(api_user());
275 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
276 logger('API parameters: ' . print_r($_REQUEST,true));
278 $stamp = microtime(true);
279 $r = call_user_func($info['func'], $a, $type);
280 $duration = (float)(microtime(true)-$stamp);
281 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
284 // api function returned false withour throw an
285 // exception. This should not happend, throw a 500
286 throw new InternalServerErrorException();
291 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
292 header ("Content-Type: text/xml");
293 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
296 header ("Content-Type: application/json");
298 $json = json_encode($rr);
299 if ($_GET['callback'])
300 $json = $_GET['callback']."(".$json.")";
304 header ("Content-Type: application/rss+xml");
305 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
308 header ("Content-Type: application/atom+xml");
309 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
312 //header ("Content-Type: application/json");
314 // return json_encode($rr);
315 return json_encode($r);
321 throw new NotImplementedException();
322 } catch (HTTPException $e) {
323 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
324 return api_error($a, $type, $e);
329 * @brief Format API error string
332 * @param string $type Return type (xml, json, rss, as)
333 * @param string $error Error message
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 * load api $templatename for $type and replace $data array
686 function api_apply_template($templatename, $type, $data){
694 $data = array_xmlify($data);
695 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
697 header ("Content-Type: text/xml");
698 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
701 $ret = replace_macros($tpl, $data);
716 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
717 * returns a 401 status code and an error message if not.
718 * http://developer.twitter.com/doc/get/account/verify_credentials
720 function api_account_verify_credentials(&$a, $type){
721 if (api_user()===false) throw new ForbiddenException();
723 unset($_REQUEST["user_id"]);
724 unset($_GET["user_id"]);
726 unset($_REQUEST["screen_name"]);
727 unset($_GET["screen_name"]);
729 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
731 $user_info = api_get_user($a);
733 // "verified" isn't used here in the standard
734 unset($user_info["verified"]);
736 // - Adding last status
738 $user_info["status"] = api_status_show($a,"raw");
739 if (!count($user_info["status"]))
740 unset($user_info["status"]);
742 unset($user_info["status"]["user"]);
745 // "uid" and "self" are only needed for some internal stuff, so remove it from here
746 unset($user_info["uid"]);
747 unset($user_info["self"]);
749 return api_apply_template("user", $type, array('$user' => $user_info));
752 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
756 * get data from $_POST or $_GET
758 function requestdata($k){
759 if (isset($_POST[$k])){
762 if (isset($_GET[$k])){
768 /*Waitman Gobble Mod*/
769 function api_statuses_mediap(&$a, $type) {
770 if (api_user()===false) {
771 logger('api_statuses_update: no user');
772 throw new ForbiddenException();
774 $user_info = api_get_user($a);
776 $_REQUEST['type'] = 'wall';
777 $_REQUEST['profile_uid'] = api_user();
778 $_REQUEST['api_source'] = true;
779 $txt = requestdata('status');
780 //$txt = urldecode(requestdata('status'));
782 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
784 $txt = html2bb_video($txt);
785 $config = HTMLPurifier_Config::createDefault();
786 $config->set('Cache.DefinitionImpl', null);
787 $purifier = new HTMLPurifier($config);
788 $txt = $purifier->purify($txt);
790 $txt = html2bbcode($txt);
792 $a->argv[1]=$user_info['screen_name']; //should be set to username?
794 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
795 $bebop = wall_upload_post($a);
797 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
798 $_REQUEST['body']=$txt."\n\n".$bebop;
801 // this should output the last post (the one we just posted).
802 return api_status_show($a,$type);
804 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
805 /*Waitman Gobble Mod*/
808 function api_statuses_update(&$a, $type) {
809 if (api_user()===false) {
810 logger('api_statuses_update: no user');
811 throw new ForbiddenException();
814 $user_info = api_get_user($a);
816 // convert $_POST array items to the form we use for web posts.
818 // logger('api_post: ' . print_r($_POST,true));
820 if(requestdata('htmlstatus')) {
821 $txt = requestdata('htmlstatus');
822 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
823 $txt = html2bb_video($txt);
825 $config = HTMLPurifier_Config::createDefault();
826 $config->set('Cache.DefinitionImpl', null);
828 $purifier = new HTMLPurifier($config);
829 $txt = $purifier->purify($txt);
831 $_REQUEST['body'] = html2bbcode($txt);
835 $_REQUEST['body'] = requestdata('status');
837 $_REQUEST['title'] = requestdata('title');
839 $parent = requestdata('in_reply_to_status_id');
841 // Twidere sends "-1" if it is no reply ...
845 if(ctype_digit($parent))
846 $_REQUEST['parent'] = $parent;
848 $_REQUEST['parent_uri'] = $parent;
850 if(requestdata('lat') && requestdata('long'))
851 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
852 $_REQUEST['profile_uid'] = api_user();
855 $_REQUEST['type'] = 'net-comment';
857 // Check for throttling (maximum posts per day, week and month)
858 $throttle_day = get_config('system','throttle_limit_day');
859 if ($throttle_day > 0) {
860 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
862 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
863 AND `created` > '%s' AND `id` = `parent`",
864 intval(api_user()), dbesc($datefrom));
867 $posts_day = $r[0]["posts_day"];
871 if ($posts_day > $throttle_day) {
872 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
873 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
877 $throttle_week = get_config('system','throttle_limit_week');
878 if ($throttle_week > 0) {
879 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
881 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
882 AND `created` > '%s' AND `id` = `parent`",
883 intval(api_user()), dbesc($datefrom));
886 $posts_week = $r[0]["posts_week"];
890 if ($posts_week > $throttle_week) {
891 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
892 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
896 $throttle_month = get_config('system','throttle_limit_month');
897 if ($throttle_month > 0) {
898 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
900 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
901 AND `created` > '%s' AND `id` = `parent`",
902 intval(api_user()), dbesc($datefrom));
905 $posts_month = $r[0]["posts_month"];
909 if ($posts_month > $throttle_month) {
910 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
911 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
915 $_REQUEST['type'] = 'wall';
918 if(x($_FILES,'media')) {
919 // upload the image if we have one
920 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
921 $media = wall_upload_post($a);
923 $_REQUEST['body'] .= "\n\n".$media;
926 // To-Do: Multiple IDs
927 if (requestdata('media_ids')) {
928 $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",
929 intval(requestdata('media_ids')), api_user());
931 $phototypes = Photo::supportedTypes();
932 $ext = $phototypes[$r[0]['type']];
933 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
934 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
938 // set this so that the item_post() function is quiet and doesn't redirect or emit json
940 $_REQUEST['api_source'] = true;
942 if (!x($_REQUEST, "source"))
943 $_REQUEST["source"] = api_source();
945 // call out normal post function
949 // this should output the last post (the one we just posted).
950 return api_status_show($a,$type);
952 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
953 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
956 function api_media_upload(&$a, $type) {
957 if (api_user()===false) {
959 throw new ForbiddenException();
962 $user_info = api_get_user($a);
964 if(!x($_FILES,'media')) {
966 throw new BadRequestException("No media.");
969 $media = wall_upload_post($a, false);
972 throw new InternalServerErrorException();
975 $returndata = array();
976 $returndata["media_id"] = $media["id"];
977 $returndata["media_id_string"] = (string)$media["id"];
978 $returndata["size"] = $media["size"];
979 $returndata["image"] = array("w" => $media["width"],
980 "h" => $media["height"],
981 "image_type" => $media["type"]);
983 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
985 return array("media" => $returndata);
987 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
989 function api_status_show(&$a, $type){
990 $user_info = api_get_user($a);
992 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
995 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
999 // get last public wall message
1000 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1001 FROM `item`, `item` as `i`
1002 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1003 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1004 AND `i`.`id` = `item`.`parent`
1005 AND `item`.`type`!='activity' $privacy_sql
1006 ORDER BY `item`.`created` DESC
1008 intval($user_info['cid']),
1010 dbesc($user_info['url']),
1011 dbesc(normalise_link($user_info['url'])),
1012 dbesc($user_info['url']),
1013 dbesc(normalise_link($user_info['url']))
1016 if (count($lastwall)>0){
1017 $lastwall = $lastwall[0];
1019 $in_reply_to_status_id = NULL;
1020 $in_reply_to_user_id = NULL;
1021 $in_reply_to_status_id_str = NULL;
1022 $in_reply_to_user_id_str = NULL;
1023 $in_reply_to_screen_name = NULL;
1024 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1025 $in_reply_to_status_id= intval($lastwall['parent']);
1026 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1028 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1030 if ($r[0]['nick'] == "")
1031 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1033 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1034 $in_reply_to_user_id = intval($r[0]['id']);
1035 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1039 // There seems to be situation, where both fields are identical:
1040 // https://github.com/friendica/friendica/issues/1010
1041 // This is a bugfix for that.
1042 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1043 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1044 $in_reply_to_status_id = NULL;
1045 $in_reply_to_user_id = NULL;
1046 $in_reply_to_status_id_str = NULL;
1047 $in_reply_to_user_id_str = NULL;
1048 $in_reply_to_screen_name = NULL;
1051 $converted = api_convert_item($lastwall);
1053 $status_info = array(
1054 'created_at' => api_date($lastwall['created']),
1055 'id' => intval($lastwall['id']),
1056 'id_str' => (string) $lastwall['id'],
1057 'text' => $converted["text"],
1058 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1059 'truncated' => false,
1060 'in_reply_to_status_id' => $in_reply_to_status_id,
1061 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1062 'in_reply_to_user_id' => $in_reply_to_user_id,
1063 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1064 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1065 'user' => $user_info,
1067 'coordinates' => "",
1069 'contributors' => "",
1070 'is_quote_status' => false,
1071 'retweet_count' => 0,
1072 'favorite_count' => 0,
1073 'favorited' => $lastwall['starred'] ? true : false,
1074 'retweeted' => false,
1075 'possibly_sensitive' => false,
1077 'statusnet_html' => $converted["html"],
1078 'statusnet_conversation_id' => $lastwall['parent'],
1081 if (count($converted["attachments"]) > 0)
1082 $status_info["attachments"] = $converted["attachments"];
1084 if (count($converted["entities"]) > 0)
1085 $status_info["entities"] = $converted["entities"];
1087 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1088 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1089 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1090 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1092 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1093 unset($status_info["user"]["uid"]);
1094 unset($status_info["user"]["self"]);
1097 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1100 return($status_info);
1102 return api_apply_template("status", $type, array('$status' => $status_info));
1111 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1112 * The author's most recent status will be returned inline.
1113 * http://developer.twitter.com/doc/get/users/show
1115 function api_users_show(&$a, $type){
1116 $user_info = api_get_user($a);
1118 $lastwall = q("SELECT `item`.*
1119 FROM `item`, `contact`
1120 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1121 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1122 AND `contact`.`id`=`item`.`contact-id`
1123 AND `type`!='activity'
1124 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1125 ORDER BY `created` DESC
1128 dbesc(ACTIVITY_POST),
1129 intval($user_info['cid']),
1130 dbesc($user_info['url']),
1131 dbesc(normalise_link($user_info['url'])),
1132 dbesc($user_info['url']),
1133 dbesc(normalise_link($user_info['url']))
1135 if (count($lastwall)>0){
1136 $lastwall = $lastwall[0];
1138 $in_reply_to_status_id = NULL;
1139 $in_reply_to_user_id = NULL;
1140 $in_reply_to_status_id_str = NULL;
1141 $in_reply_to_user_id_str = NULL;
1142 $in_reply_to_screen_name = NULL;
1143 if ($lastwall['parent']!=$lastwall['id']) {
1144 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1145 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1146 if (count($reply)>0) {
1147 $in_reply_to_status_id = intval($lastwall['parent']);
1148 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1150 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1152 if ($r[0]['nick'] == "")
1153 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1155 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1156 $in_reply_to_user_id = intval($r[0]['id']);
1157 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1162 $converted = api_convert_item($lastwall);
1164 $user_info['status'] = array(
1165 'text' => $converted["text"],
1166 'truncated' => false,
1167 'created_at' => api_date($lastwall['created']),
1168 'in_reply_to_status_id' => $in_reply_to_status_id,
1169 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1170 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1171 'id' => intval($lastwall['contact-id']),
1172 'id_str' => (string) $lastwall['contact-id'],
1173 'in_reply_to_user_id' => $in_reply_to_user_id,
1174 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1175 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1177 'favorited' => $lastwall['starred'] ? true : false,
1178 'statusnet_html' => $converted["html"],
1179 'statusnet_conversation_id' => $lastwall['parent'],
1182 if (count($converted["attachments"]) > 0)
1183 $user_info["status"]["attachments"] = $converted["attachments"];
1185 if (count($converted["entities"]) > 0)
1186 $user_info["status"]["entities"] = $converted["entities"];
1188 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1189 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1190 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1191 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1195 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1196 unset($user_info["uid"]);
1197 unset($user_info["self"]);
1199 return api_apply_template("user", $type, array('$user' => $user_info));
1202 api_register_func('api/users/show','api_users_show');
1205 function api_users_search(&$a, $type) {
1206 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1208 $userlist = array();
1210 if (isset($_GET["q"])) {
1211 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1213 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1216 foreach ($r AS $user) {
1217 $user_info = api_get_user($a, $user["id"]);
1218 //echo print_r($user_info, true)."\n";
1219 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1220 $userlist[] = $userdata["user"];
1222 $userlist = array("users" => $userlist);
1224 throw new BadRequestException("User not found.");
1227 throw new BadRequestException("User not found.");
1232 api_register_func('api/users/search','api_users_search');
1236 * http://developer.twitter.com/doc/get/statuses/home_timeline
1238 * TODO: Optional parameters
1239 * TODO: Add reply info
1241 function api_statuses_home_timeline(&$a, $type){
1242 if (api_user()===false) throw new ForbiddenException();
1244 unset($_REQUEST["user_id"]);
1245 unset($_GET["user_id"]);
1247 unset($_REQUEST["screen_name"]);
1248 unset($_GET["screen_name"]);
1250 $user_info = api_get_user($a);
1251 // get last newtork messages
1255 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1256 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1257 if ($page<0) $page=0;
1258 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1259 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1260 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1261 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1262 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1264 $start = $page*$count;
1268 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1269 if ($exclude_replies > 0)
1270 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1271 if ($conversation_id > 0)
1272 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1274 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1275 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1276 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1277 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1278 FROM `item`, `contact`
1279 WHERE `item`.`uid` = %d AND `verb` = '%s'
1280 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1281 AND `contact`.`id` = `item`.`contact-id`
1282 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1285 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1287 dbesc(ACTIVITY_POST),
1289 intval($start), intval($count)
1292 $ret = api_format_items($r,$user_info);
1294 // Set all posts from the query above to seen
1296 foreach ($r AS $item)
1297 $idarray[] = intval($item["id"]);
1299 $idlist = implode(",", $idarray);
1302 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1305 $data = array('$statuses' => $ret);
1309 $data = api_rss_extra($a, $data, $user_info);
1312 $as = api_format_as($a, $ret, $user_info);
1313 $as['title'] = $a->config['sitename']." Home Timeline";
1314 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1319 return api_apply_template("timeline", $type, $data);
1321 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1322 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1324 function api_statuses_public_timeline(&$a, $type){
1325 if (api_user()===false) throw new ForbiddenException();
1327 $user_info = api_get_user($a);
1328 // get last newtork messages
1332 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1333 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1334 if ($page<0) $page=0;
1335 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1336 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1337 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1338 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1339 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1341 $start = $page*$count;
1344 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1345 if ($exclude_replies > 0)
1346 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1347 if ($conversation_id > 0)
1348 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1350 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1351 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1352 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1353 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1354 `user`.`nickname`, `user`.`hidewall`
1355 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1356 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1357 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1358 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1359 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1360 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1361 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1364 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1365 dbesc(ACTIVITY_POST),
1370 $ret = api_format_items($r,$user_info);
1373 $data = array('$statuses' => $ret);
1377 $data = api_rss_extra($a, $data, $user_info);
1380 $as = api_format_as($a, $ret, $user_info);
1381 $as['title'] = $a->config['sitename']." Public Timeline";
1382 $as['link']['url'] = $a->get_baseurl()."/";
1387 return api_apply_template("timeline", $type, $data);
1389 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1394 function api_statuses_show(&$a, $type){
1395 if (api_user()===false) throw new ForbiddenException();
1397 $user_info = api_get_user($a);
1400 $id = intval($a->argv[3]);
1403 $id = intval($_REQUEST["id"]);
1407 $id = intval($a->argv[4]);
1409 logger('API: api_statuses_show: '.$id);
1411 $conversation = (x($_REQUEST,'conversation')?1:0);
1415 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1417 $sql_extra .= " AND `item`.`id` = %d";
1419 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1420 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1421 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1422 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1423 FROM `item`, `contact`
1424 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1425 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1426 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1429 dbesc(ACTIVITY_POST),
1434 throw new BadRequestException("There is no status with this id.");
1437 $ret = api_format_items($r,$user_info);
1439 if ($conversation) {
1440 $data = array('$statuses' => $ret);
1441 return api_apply_template("timeline", $type, $data);
1443 $data = array('$status' => $ret[0]);
1447 $data = api_rss_extra($a, $data, $user_info);
1449 return api_apply_template("status", $type, $data);
1452 api_register_func('api/statuses/show','api_statuses_show', true);
1458 function api_conversation_show(&$a, $type){
1459 if (api_user()===false) throw new ForbiddenException();
1461 $user_info = api_get_user($a);
1464 $id = intval($a->argv[3]);
1465 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1466 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1467 if ($page<0) $page=0;
1468 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1469 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1471 $start = $page*$count;
1474 $id = intval($_REQUEST["id"]);
1478 $id = intval($a->argv[4]);
1480 logger('API: api_conversation_show: '.$id);
1482 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1484 $id = $r[0]["parent"];
1489 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1491 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1492 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1493 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1494 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1495 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1496 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1497 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1498 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1499 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1500 AND `item`.`id`>%d $sql_extra
1501 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1502 intval($id), intval(api_user()),
1503 dbesc(ACTIVITY_POST),
1505 intval($start), intval($count)
1509 throw new BadRequestException("There is no conversation with this id.");
1511 $ret = api_format_items($r,$user_info);
1513 $data = array('$statuses' => $ret);
1514 return api_apply_template("timeline", $type, $data);
1516 api_register_func('api/conversation/show','api_conversation_show', true);
1522 function api_statuses_repeat(&$a, $type){
1525 if (api_user()===false) throw new ForbiddenException();
1527 $user_info = api_get_user($a);
1530 $id = intval($a->argv[3]);
1533 $id = intval($_REQUEST["id"]);
1537 $id = intval($a->argv[4]);
1539 logger('API: api_statuses_repeat: '.$id);
1541 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1542 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1543 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1544 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1545 FROM `item`, `contact`
1546 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1547 AND `contact`.`id` = `item`.`contact-id`
1548 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1549 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1550 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1552 AND `item`.`id`=%d",
1556 if ($r[0]['body'] != "") {
1557 if (!intval(get_config('system','old_share'))) {
1558 if (strpos($r[0]['body'], "[/share]") !== false) {
1559 $pos = strpos($r[0]['body'], "[share");
1560 $post = substr($r[0]['body'], $pos);
1562 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1564 $post .= $r[0]['body'];
1565 $post .= "[/share]";
1567 $_REQUEST['body'] = $post;
1569 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1571 $_REQUEST['profile_uid'] = api_user();
1572 $_REQUEST['type'] = 'wall';
1573 $_REQUEST['api_source'] = true;
1575 if (!x($_REQUEST, "source"))
1576 $_REQUEST["source"] = api_source();
1580 throw new ForbiddenException();
1582 // this should output the last post (the one we just posted).
1584 return(api_status_show($a,$type));
1586 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1591 function api_statuses_destroy(&$a, $type){
1592 if (api_user()===false) throw new ForbiddenException();
1594 $user_info = api_get_user($a);
1597 $id = intval($a->argv[3]);
1600 $id = intval($_REQUEST["id"]);
1604 $id = intval($a->argv[4]);
1606 logger('API: api_statuses_destroy: '.$id);
1608 $ret = api_statuses_show($a, $type);
1610 drop_item($id, false);
1614 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1618 * http://developer.twitter.com/doc/get/statuses/mentions
1621 function api_statuses_mentions(&$a, $type){
1622 if (api_user()===false) throw new ForbiddenException();
1624 unset($_REQUEST["user_id"]);
1625 unset($_GET["user_id"]);
1627 unset($_REQUEST["screen_name"]);
1628 unset($_GET["screen_name"]);
1630 $user_info = api_get_user($a);
1631 // get last newtork messages
1635 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1636 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1637 if ($page<0) $page=0;
1638 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1639 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1640 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1642 $start = $page*$count;
1644 // Ugly code - should be changed
1645 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1646 $myurl = substr($myurl,strpos($myurl,'://')+3);
1647 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1648 $myurl = str_replace('www.','',$myurl);
1649 $diasp_url = str_replace('/profile/','/u/',$myurl);
1652 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1654 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1655 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1656 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1657 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1658 FROM `item`, `contact`
1659 WHERE `item`.`uid` = %d AND `verb` = '%s'
1660 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1661 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1662 AND `contact`.`id` = `item`.`contact-id`
1663 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1664 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1667 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1669 dbesc(ACTIVITY_POST),
1670 dbesc(protect_sprintf($myurl)),
1671 dbesc(protect_sprintf($myurl)),
1674 intval($start), intval($count)
1677 $ret = api_format_items($r,$user_info);
1680 $data = array('$statuses' => $ret);
1684 $data = api_rss_extra($a, $data, $user_info);
1687 $as = api_format_as($a, $ret, $user_info);
1688 $as["title"] = $a->config['sitename']." Mentions";
1689 $as['link']['url'] = $a->get_baseurl()."/";
1694 return api_apply_template("timeline", $type, $data);
1696 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1697 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1700 function api_statuses_user_timeline(&$a, $type){
1701 if (api_user()===false) throw new ForbiddenException();
1703 $user_info = api_get_user($a);
1704 // get last network messages
1706 logger("api_statuses_user_timeline: api_user: ". api_user() .
1707 "\nuser_info: ".print_r($user_info, true) .
1708 "\n_REQUEST: ".print_r($_REQUEST, true),
1712 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1713 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1714 if ($page<0) $page=0;
1715 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1716 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1717 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1718 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1720 $start = $page*$count;
1723 if ($user_info['self']==1)
1724 $sql_extra .= " AND `item`.`wall` = 1 ";
1726 if ($exclude_replies > 0)
1727 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1728 if ($conversation_id > 0)
1729 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1731 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1732 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1733 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1734 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1735 FROM `item`, `contact`
1736 WHERE `item`.`uid` = %d AND `verb` = '%s'
1737 AND `item`.`contact-id` = %d
1738 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1739 AND `contact`.`id` = `item`.`contact-id`
1740 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1743 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1745 dbesc(ACTIVITY_POST),
1746 intval($user_info['cid']),
1748 intval($start), intval($count)
1751 $ret = api_format_items($r,$user_info, true);
1753 $data = array('$statuses' => $ret);
1757 $data = api_rss_extra($a, $data, $user_info);
1760 return api_apply_template("timeline", $type, $data);
1762 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1766 * Star/unstar an item
1767 * param: id : id of the item
1769 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1771 function api_favorites_create_destroy(&$a, $type){
1772 if (api_user()===false) throw new ForbiddenException();
1774 // for versioned api.
1775 /// @TODO We need a better global soluton
1777 if ($a->argv[1]=="1.1") $action_argv_id=3;
1779 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1780 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1781 if ($a->argc==$action_argv_id+2) {
1782 $itemid = intval($a->argv[$action_argv_id+1]);
1784 $itemid = intval($_REQUEST['id']);
1787 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1788 $itemid, api_user());
1790 if ($item===false || count($item)==0)
1791 throw new BadRequestException("Invalid item.");
1795 $item[0]['starred']=1;
1798 $item[0]['starred']=0;
1801 throw new BadRequestException("Invalid action ".$action);
1803 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1804 $item[0]['starred'], $itemid, api_user());
1806 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1807 $item[0]['starred'], $itemid, api_user());
1810 throw InternalServerErrorException("DB error");
1813 $user_info = api_get_user($a);
1814 $rets = api_format_items($item,$user_info);
1817 $data = array('$status' => $ret);
1821 $data = api_rss_extra($a, $data, $user_info);
1824 return api_apply_template("status", $type, $data);
1826 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1827 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1829 function api_favorites(&$a, $type){
1832 if (api_user()===false) throw new ForbiddenException();
1834 $called_api= array();
1836 $user_info = api_get_user($a);
1838 // in friendica starred item are private
1839 // return favorites only for self
1840 logger('api_favorites: self:' . $user_info['self']);
1842 if ($user_info['self']==0) {
1848 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1849 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1850 $count = (x($_GET,'count')?$_GET['count']:20);
1851 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1852 if ($page<0) $page=0;
1854 $start = $page*$count;
1857 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1859 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1860 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1861 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1862 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1863 FROM `item`, `contact`
1864 WHERE `item`.`uid` = %d
1865 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1866 AND `item`.`starred` = 1
1867 AND `contact`.`id` = `item`.`contact-id`
1868 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1871 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1874 intval($start), intval($count)
1877 $ret = api_format_items($r,$user_info);
1881 $data = array('$statuses' => $ret);
1885 $data = api_rss_extra($a, $data, $user_info);
1888 return api_apply_template("timeline", $type, $data);
1890 api_register_func('api/favorites','api_favorites', true);
1895 function api_format_as($a, $ret, $user_info) {
1897 $as['title'] = $a->config['sitename']." Public Timeline";
1899 foreach ($ret as $item) {
1900 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1901 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1902 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1903 $avatar[0]["rel"] = "avatar";
1904 $avatar[0]["type"] = "";
1905 $avatar[0]["width"] = 96;
1906 $avatar[0]["height"] = 96;
1907 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1908 $avatar[1]["rel"] = "avatar";
1909 $avatar[1]["type"] = "";
1910 $avatar[1]["width"] = 48;
1911 $avatar[1]["height"] = 48;
1912 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1913 $avatar[2]["rel"] = "avatar";
1914 $avatar[2]["type"] = "";
1915 $avatar[2]["width"] = 24;
1916 $avatar[2]["height"] = 24;
1917 $singleitem["actor"]["avatarLinks"] = $avatar;
1919 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1920 $singleitem["actor"]["image"]["rel"] = "avatar";
1921 $singleitem["actor"]["image"]["type"] = "";
1922 $singleitem["actor"]["image"]["width"] = 96;
1923 $singleitem["actor"]["image"]["height"] = 96;
1924 $singleitem["actor"]["type"] = "person";
1925 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1926 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1927 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1928 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1929 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1930 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1931 $singleitem["actor"]["contact"]["addresses"] = "";
1933 $singleitem["body"] = $item["text"];
1934 $singleitem["object"]["displayName"] = $item["text"];
1935 $singleitem["object"]["id"] = $item["url"];
1936 $singleitem["object"]["type"] = "note";
1937 $singleitem["object"]["url"] = $item["url"];
1938 //$singleitem["context"] =;
1939 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1940 $singleitem["provider"]["objectType"] = "service";
1941 $singleitem["provider"]["displayName"] = "Test";
1942 $singleitem["provider"]["url"] = "http://test.tld";
1943 $singleitem["title"] = $item["text"];
1944 $singleitem["verb"] = "post";
1945 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1946 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1947 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1948 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1949 //$singleitem["original"] = $item;
1950 $items[] = $singleitem;
1952 $as['items'] = $items;
1953 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1954 $as['link']['rel'] = "alternate";
1955 $as['link']['type'] = "text/html";
1959 function api_format_messages($item, $recipient, $sender) {
1960 // standard meta information
1962 'id' => $item['id'],
1963 'sender_id' => $sender['id'] ,
1965 'recipient_id' => $recipient['id'],
1966 'created_at' => api_date($item['created']),
1967 'sender_screen_name' => $sender['screen_name'],
1968 'recipient_screen_name' => $recipient['screen_name'],
1969 'sender' => $sender,
1970 'recipient' => $recipient,
1973 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1974 unset($ret["sender"]["uid"]);
1975 unset($ret["sender"]["self"]);
1976 unset($ret["recipient"]["uid"]);
1977 unset($ret["recipient"]["self"]);
1979 //don't send title to regular StatusNET requests to avoid confusing these apps
1980 if (x($_GET, 'getText')) {
1981 $ret['title'] = $item['title'] ;
1982 if ($_GET["getText"] == "html") {
1983 $ret['text'] = bbcode($item['body'], false, false);
1985 elseif ($_GET["getText"] == "plain") {
1986 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1987 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1991 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1993 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1994 unset($ret['sender']);
1995 unset($ret['recipient']);
2001 function api_convert_item($item) {
2003 $body = $item['body'];
2004 $attachments = api_get_attachments($body);
2006 // Workaround for ostatus messages where the title is identically to the body
2007 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2008 $statusbody = trim(html2plain($html, 0));
2010 // handle data: images
2011 $statusbody = api_format_items_embeded_images($item,$statusbody);
2013 $statustitle = trim($item['title']);
2015 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2016 $statustext = trim($statusbody);
2018 $statustext = trim($statustitle."\n\n".$statusbody);
2020 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2021 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2023 $statushtml = trim(bbcode($body, false, false));
2025 if ($item['title'] != "")
2026 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2028 $entities = api_get_entitities($statustext, $body);
2030 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2033 function api_get_attachments(&$body) {
2036 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2038 $URLSearchString = "^\[\]";
2039 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2044 $attachments = array();
2046 foreach ($images[1] AS $image) {
2047 $imagedata = get_photo_info($image);
2050 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2053 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2054 foreach ($images[0] AS $orig)
2055 $body = str_replace($orig, "", $body);
2057 return $attachments;
2060 function api_get_entitities(&$text, $bbcode) {
2063 * Links at the first character of the post
2068 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2070 if ($include_entities != "true") {
2072 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2074 foreach ($images[1] AS $image) {
2075 $replace = proxy_url($image);
2076 $text = str_replace($image, $replace, $text);
2081 $bbcode = bb_CleanPictureLinks($bbcode);
2083 // Change pure links in text to bbcode uris
2084 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2086 $entities = array();
2087 $entities["hashtags"] = array();
2088 $entities["symbols"] = array();
2089 $entities["urls"] = array();
2090 $entities["user_mentions"] = array();
2092 $URLSearchString = "^\[\]";
2094 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2096 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2097 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2098 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2100 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2101 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2102 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2104 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2105 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2106 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2108 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2110 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2111 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2113 $ordered_urls = array();
2114 foreach ($urls[1] AS $id=>$url) {
2115 //$start = strpos($text, $url, $offset);
2116 $start = iconv_strpos($text, $url, 0, "UTF-8");
2117 if (!($start === false))
2118 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2121 ksort($ordered_urls);
2124 //foreach ($urls[1] AS $id=>$url) {
2125 foreach ($ordered_urls AS $url) {
2126 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2127 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2128 $display_url = $url["title"];
2130 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2131 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2133 if (strlen($display_url) > 26)
2134 $display_url = substr($display_url, 0, 25)."…";
2137 //$start = strpos($text, $url, $offset);
2138 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2139 if (!($start === false)) {
2140 $entities["urls"][] = array("url" => $url["url"],
2141 "expanded_url" => $url["url"],
2142 "display_url" => $display_url,
2143 "indices" => array($start, $start+strlen($url["url"])));
2144 $offset = $start + 1;
2148 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2149 $ordered_images = array();
2150 foreach ($images[1] AS $image) {
2151 //$start = strpos($text, $url, $offset);
2152 $start = iconv_strpos($text, $image, 0, "UTF-8");
2153 if (!($start === false))
2154 $ordered_images[$start] = $image;
2156 //$entities["media"] = array();
2159 foreach ($ordered_images AS $url) {
2160 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2161 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2163 if (strlen($display_url) > 26)
2164 $display_url = substr($display_url, 0, 25)."…";
2166 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2167 if (!($start === false)) {
2168 $image = get_photo_info($url);
2170 // If image cache is activated, then use the following sizes:
2171 // thumb (150), small (340), medium (600) and large (1024)
2172 if (!get_config("system", "proxy_disabled")) {
2173 $media_url = proxy_url($url);
2176 $scale = scale_image($image[0], $image[1], 150);
2177 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2179 if (($image[0] > 150) OR ($image[1] > 150)) {
2180 $scale = scale_image($image[0], $image[1], 340);
2181 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2184 $scale = scale_image($image[0], $image[1], 600);
2185 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2187 if (($image[0] > 600) OR ($image[1] > 600)) {
2188 $scale = scale_image($image[0], $image[1], 1024);
2189 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2193 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2196 $entities["media"][] = array(
2198 "id_str" => (string)$start+1,
2199 "indices" => array($start, $start+strlen($url)),
2200 "media_url" => normalise_link($media_url),
2201 "media_url_https" => $media_url,
2203 "display_url" => $display_url,
2204 "expanded_url" => $url,
2208 $offset = $start + 1;
2214 function api_format_items_embeded_images(&$item, $text){
2216 $text = preg_replace_callback(
2217 "|data:image/([^;]+)[^=]+=*|m",
2218 function($match) use ($a, $item) {
2219 return $a->get_baseurl()."/display/".$item['guid'];
2226 * @brief return likes, dislikes and attend status for item
2228 * @param array $item
2230 * likes => int count
2231 * dislikes => int count
2233 function api_format_items_likes(&$item) {
2234 $activities = array(
2236 'dislike' => array(),
2237 'attendyes' => array(),
2238 'attendno' => array(),
2239 'attendmaybe' => array()
2241 $items = q('SELECT * FROM item
2242 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2243 intval($item['uid']),
2244 dbesc($item['uri']));
2245 foreach ($items as $i){
2246 builtin_activity_puller($i, $activities);
2250 $uri = $item['uri'];
2251 foreach($activities as $k => $v) {
2252 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2259 * @brief format items to be returned by api
2261 * @param array $r array of items
2262 * @param array $user_info
2263 * @param bool $filter_user filter items by $user_info
2265 function api_format_items($r,$user_info, $filter_user = false) {
2270 foreach($r as $item) {
2271 api_share_as_retweet($item);
2273 localize_item($item);
2274 $status_user = api_item_get_user($a,$item);
2276 // Look if the posts are matching if they should be filtered by user id
2277 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2280 if ($item['thr-parent'] != $item['uri']) {
2281 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2283 dbesc($item['thr-parent']));
2285 $in_reply_to_status_id = intval($r[0]['id']);
2287 $in_reply_to_status_id = intval($item['parent']);
2289 $in_reply_to_status_id_str = (string) intval($item['parent']);
2291 $in_reply_to_screen_name = NULL;
2292 $in_reply_to_user_id = NULL;
2293 $in_reply_to_user_id_str = NULL;
2295 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2297 intval($in_reply_to_status_id));
2299 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2302 if ($r[0]['nick'] == "")
2303 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2305 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2306 $in_reply_to_user_id = intval($r[0]['id']);
2307 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2311 $in_reply_to_screen_name = NULL;
2312 $in_reply_to_user_id = NULL;
2313 $in_reply_to_status_id = NULL;
2314 $in_reply_to_user_id_str = NULL;
2315 $in_reply_to_status_id_str = NULL;
2318 $converted = api_convert_item($item);
2321 'text' => $converted["text"],
2322 'truncated' => False,
2323 'created_at'=> api_date($item['created']),
2324 'in_reply_to_status_id' => $in_reply_to_status_id,
2325 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2326 'source' => (($item['app']) ? $item['app'] : 'web'),
2327 'id' => intval($item['id']),
2328 'id_str' => (string) intval($item['id']),
2329 'in_reply_to_user_id' => $in_reply_to_user_id,
2330 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2331 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2333 'favorited' => $item['starred'] ? true : false,
2334 'user' => $status_user ,
2335 //'entities' => NULL,
2336 'statusnet_html' => $converted["html"],
2337 'statusnet_conversation_id' => $item['parent'],
2338 'friendica_activities' => api_format_items_likes($item),
2341 if (count($converted["attachments"]) > 0)
2342 $status["attachments"] = $converted["attachments"];
2344 if (count($converted["entities"]) > 0)
2345 $status["entities"] = $converted["entities"];
2347 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2348 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2349 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2350 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2353 // Retweets are only valid for top postings
2354 // It doesn't work reliable with the link if its a feed
2355 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2357 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2359 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2360 $retweeted_status = $status;
2361 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2363 $status["retweeted_status"] = $retweeted_status;
2366 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2367 unset($status["user"]["uid"]);
2368 unset($status["user"]["self"]);
2370 if ($item["coord"] != "") {
2371 $coords = explode(' ',$item["coord"]);
2372 if (count($coords) == 2) {
2373 $status["geo"] = array('type' => 'Point',
2374 'coordinates' => array((float) $coords[0],
2375 (float) $coords[1]));
2385 function api_account_rate_limit_status(&$a,$type) {
2387 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2388 'remaining_hits' => (string) 150,
2389 'hourly_limit' => (string) 150,
2390 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2393 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2395 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2397 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2399 function api_help_test(&$a,$type) {
2405 return api_apply_template('test', $type, array("$ok" => $ok));
2407 api_register_func('api/help/test','api_help_test',false);
2409 function api_lists(&$a,$type) {
2413 api_register_func('api/lists','api_lists',true);
2415 function api_lists_list(&$a,$type) {
2419 api_register_func('api/lists/list','api_lists_list',true);
2422 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2423 * This function is deprecated by Twitter
2424 * returns: json, xml
2426 function api_statuses_f(&$a, $type, $qtype) {
2427 if (api_user()===false) throw new ForbiddenException();
2428 $user_info = api_get_user($a);
2430 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2431 /* this is to stop Hotot to load friends multiple times
2432 * I'm not sure if I'm missing return something or
2433 * is a bug in hotot. Workaround, meantime
2437 return array('$users' => $ret);*/
2441 if($qtype == 'friends')
2442 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2443 if($qtype == 'followers')
2444 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2446 // friends and followers only for self
2447 if ($user_info['self'] == 0)
2448 $sql_extra = " AND false ";
2450 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2455 foreach($r as $cid){
2456 $user = api_get_user($a, $cid['nurl']);
2457 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2458 unset($user["uid"]);
2459 unset($user["self"]);
2465 return array('$users' => $ret);
2468 function api_statuses_friends(&$a, $type){
2469 $data = api_statuses_f($a,$type,"friends");
2470 if ($data===false) return false;
2471 return api_apply_template("friends", $type, $data);
2473 function api_statuses_followers(&$a, $type){
2474 $data = api_statuses_f($a,$type,"followers");
2475 if ($data===false) return false;
2476 return api_apply_template("friends", $type, $data);
2478 api_register_func('api/statuses/friends','api_statuses_friends',true);
2479 api_register_func('api/statuses/followers','api_statuses_followers',true);
2486 function api_statusnet_config(&$a,$type) {
2487 $name = $a->config['sitename'];
2488 $server = $a->get_hostname();
2489 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2490 $email = $a->config['admin_email'];
2491 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2492 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2493 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2494 if($a->config['api_import_size'])
2495 $texlimit = string($a->config['api_import_size']);
2496 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2497 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2500 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2501 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2502 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2503 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2504 'shorturllength' => '30',
2505 'friendica' => array(
2506 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2507 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2508 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2509 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2514 return api_apply_template('config', $type, array('$config' => $config));
2517 api_register_func('api/statusnet/config','api_statusnet_config',false);
2519 function api_statusnet_version(&$a,$type) {
2521 $fake_statusnet_version = "0.9.7";
2523 if($type === 'xml') {
2524 header("Content-type: application/xml");
2525 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2528 elseif($type === 'json') {
2529 header("Content-type: application/json");
2530 echo '"'.$fake_statusnet_version.'"';
2534 api_register_func('api/statusnet/version','api_statusnet_version',false);
2537 * @todo use api_apply_template() to return data
2539 function api_ff_ids(&$a,$type,$qtype) {
2540 if(! api_user()) throw new ForbiddenException();
2542 $user_info = api_get_user($a);
2544 if($qtype == 'friends')
2545 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2546 if($qtype == 'followers')
2547 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2549 if (!$user_info["self"])
2550 $sql_extra = " AND false ";
2552 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2554 $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",
2560 if($type === 'xml') {
2561 header("Content-type: application/xml");
2562 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2564 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2565 echo '</ids>' . "\r\n";
2568 elseif($type === 'json') {
2570 header("Content-type: application/json");
2575 $ret[] = intval($rr['id']);
2577 echo json_encode($ret);
2583 function api_friends_ids(&$a,$type) {
2584 api_ff_ids($a,$type,'friends');
2586 function api_followers_ids(&$a,$type) {
2587 api_ff_ids($a,$type,'followers');
2589 api_register_func('api/friends/ids','api_friends_ids',true);
2590 api_register_func('api/followers/ids','api_followers_ids',true);
2593 function api_direct_messages_new(&$a, $type) {
2594 if (api_user()===false) throw new ForbiddenException();
2596 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2598 $sender = api_get_user($a);
2600 if ($_POST['screen_name']) {
2601 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2603 dbesc($_POST['screen_name']));
2605 // Selecting the id by priority, friendica first
2606 api_best_nickname($r);
2608 $recipient = api_get_user($a, $r[0]['nurl']);
2610 $recipient = api_get_user($a, $_POST['user_id']);
2614 if (x($_REQUEST,'replyto')) {
2615 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2617 intval($_REQUEST['replyto']));
2618 $replyto = $r[0]['parent-uri'];
2619 $sub = $r[0]['title'];
2622 if (x($_REQUEST,'title')) {
2623 $sub = $_REQUEST['title'];
2626 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2630 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2633 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2634 $ret = api_format_messages($r[0], $recipient, $sender);
2637 $ret = array("error"=>$id);
2640 $data = Array('$messages'=>$ret);
2645 $data = api_rss_extra($a, $data, $user_info);
2648 return api_apply_template("direct_messages", $type, $data);
2651 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2653 function api_direct_messages_box(&$a, $type, $box) {
2654 if (api_user()===false) throw new ForbiddenException();
2657 $count = (x($_GET,'count')?$_GET['count']:20);
2658 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2659 if ($page<0) $page=0;
2661 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2662 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2664 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2665 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2668 unset($_REQUEST["user_id"]);
2669 unset($_GET["user_id"]);
2671 unset($_REQUEST["screen_name"]);
2672 unset($_GET["screen_name"]);
2674 $user_info = api_get_user($a);
2675 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2676 $profile_url = $user_info["url"];
2680 $start = $page*$count;
2683 if ($box=="sentbox") {
2684 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2686 elseif ($box=="conversation") {
2687 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2689 elseif ($box=="all") {
2690 $sql_extra = "true";
2692 elseif ($box=="inbox") {
2693 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2697 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2699 if ($user_id !="") {
2700 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2702 elseif($screen_name !=""){
2703 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2706 $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",
2709 intval($start), intval($count)
2714 foreach($r as $item) {
2715 if ($box == "inbox" || $item['from-url'] != $profile_url){
2716 $recipient = $user_info;
2717 $sender = api_get_user($a,normalise_link($item['contact-url']));
2719 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2720 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2721 $sender = $user_info;
2724 $ret[]=api_format_messages($item, $recipient, $sender);
2728 $data = array('$messages' => $ret);
2732 $data = api_rss_extra($a, $data, $user_info);
2735 return api_apply_template("direct_messages", $type, $data);
2739 function api_direct_messages_sentbox(&$a, $type){
2740 return api_direct_messages_box($a, $type, "sentbox");
2742 function api_direct_messages_inbox(&$a, $type){
2743 return api_direct_messages_box($a, $type, "inbox");
2745 function api_direct_messages_all(&$a, $type){
2746 return api_direct_messages_box($a, $type, "all");
2748 function api_direct_messages_conversation(&$a, $type){
2749 return api_direct_messages_box($a, $type, "conversation");
2751 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2752 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2753 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2754 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2758 function api_oauth_request_token(&$a, $type){
2760 $oauth = new FKOAuth1();
2761 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2762 }catch(Exception $e){
2763 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2768 function api_oauth_access_token(&$a, $type){
2770 $oauth = new FKOAuth1();
2771 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2772 }catch(Exception $e){
2773 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2779 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2780 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2783 function api_fr_photos_list(&$a,$type) {
2784 if (api_user()===false) throw new ForbiddenException();
2785 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2786 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2787 intval(local_user())
2790 'image/jpeg' => 'jpg',
2791 'image/png' => 'png',
2792 'image/gif' => 'gif'
2794 $data = array('photos'=>array());
2796 foreach($r as $rr) {
2798 $photo['id'] = $rr['resource-id'];
2799 $photo['album'] = $rr['album'];
2800 $photo['filename'] = $rr['filename'];
2801 $photo['type'] = $rr['type'];
2802 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2803 $data['photos'][] = $photo;
2806 return api_apply_template("photos_list", $type, $data);
2809 function api_fr_photo_detail(&$a,$type) {
2810 if (api_user()===false) throw new ForbiddenException();
2811 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2813 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2814 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2815 $data_sql = ($scale === false ? "" : "data, ");
2817 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2818 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2819 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2821 intval(local_user()),
2822 dbesc($_REQUEST['photo_id']),
2827 'image/jpeg' => 'jpg',
2828 'image/png' => 'png',
2829 'image/gif' => 'gif'
2833 $data = array('photo' => $r[0]);
2834 if ($scale !== false) {
2835 $data['photo']['data'] = base64_encode($data['photo']['data']);
2837 unset($data['photo']['datasize']); //needed only with scale param
2839 $data['photo']['link'] = array();
2840 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2841 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2843 $data['photo']['id'] = $data['photo']['resource-id'];
2844 unset($data['photo']['resource-id']);
2845 unset($data['photo']['minscale']);
2846 unset($data['photo']['maxscale']);
2849 throw new NotFoundException();
2852 return api_apply_template("photo_detail", $type, $data);
2855 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2856 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2861 * similar as /mod/redir.php
2862 * redirect to 'url' after dfrn auth
2864 * why this when there is mod/redir.php already?
2865 * This use api_user() and api_login()
2868 * c_url: url of remote contact to auth to
2869 * url: string, url to redirect after auth
2871 function api_friendica_remoteauth(&$a) {
2872 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2873 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2875 if ($url === '' || $c_url === '')
2876 throw new BadRequestException("Wrong parameters.");
2878 $c_url = normalise_link($c_url);
2882 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2887 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2888 throw new BadRequestException("Unknown contact");
2892 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2894 if($r[0]['duplex'] && $r[0]['issued-id']) {
2895 $orig_id = $r[0]['issued-id'];
2896 $dfrn_id = '1:' . $orig_id;
2898 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2899 $orig_id = $r[0]['dfrn-id'];
2900 $dfrn_id = '0:' . $orig_id;
2903 $sec = random_string();
2905 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2906 VALUES( %d, %s, '%s', '%s', %d )",
2914 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2915 $dest = (($url) ? '&destination_url=' . $url : '');
2916 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2917 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2918 . '&type=profile&sec=' . $sec . $dest . $quiet );
2920 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2923 function api_share_as_retweet(&$item) {
2924 $body = trim($item["body"]);
2926 // Skip if it isn't a pure repeated messages
2927 // Does it start with a share?
2928 if (strpos($body, "[share") > 0)
2931 // Does it end with a share?
2932 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2935 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2936 // Skip if there is no shared message in there
2937 if ($body == $attributes)
2941 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2942 if ($matches[1] != "")
2943 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2945 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2946 if ($matches[1] != "")
2947 $author = $matches[1];
2950 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2951 if ($matches[1] != "")
2952 $profile = $matches[1];
2954 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2955 if ($matches[1] != "")
2956 $profile = $matches[1];
2959 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2960 if ($matches[1] != "")
2961 $avatar = $matches[1];
2963 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2964 if ($matches[1] != "")
2965 $avatar = $matches[1];
2968 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2969 if ($matches[1] != "")
2970 $link = $matches[1];
2972 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2973 if ($matches[1] != "")
2974 $link = $matches[1];
2976 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2978 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2981 $item["body"] = $shared_body;
2982 $item["author-name"] = $author;
2983 $item["author-link"] = $profile;
2984 $item["author-avatar"] = $avatar;
2985 $item["plink"] = $link;
2991 function api_get_nick($profile) {
2993 - remove trailing junk from profile url
2994 - pump.io check has to check the website
2999 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3000 dbesc(normalise_link($profile)));
3002 $nick = $r[0]["nick"];
3005 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3006 dbesc(normalise_link($profile)));
3008 $nick = $r[0]["nick"];
3012 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3013 if ($friendica != $profile)
3018 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3019 if ($diaspora != $profile)
3024 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3025 if ($twitter != $profile)
3031 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3032 if ($StatusnetHost != $profile) {
3033 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3034 if ($StatusnetUser != $profile) {
3035 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3036 $user = json_decode($UserData);
3038 $nick = $user->screen_name;
3043 // To-Do: look at the page if its really a pumpio site
3044 //if (!$nick == "") {
3045 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3046 // if ($pumpio != $profile)
3048 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3058 function api_clean_plain_items($Text) {
3059 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3061 $Text = bb_CleanPictureLinks($Text);
3063 $URLSearchString = "^\[\]";
3065 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3067 if ($include_entities == "true") {
3068 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3071 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
3075 function api_cleanup_share($shared) {
3076 if ($shared[2] != "type-link")
3079 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
3085 if (isset($bookmark[2][0]))
3086 $title = $bookmark[2][0];
3088 if (isset($bookmark[1][0]))
3089 $link = $bookmark[1][0];
3091 if (strpos($shared[1],$title) !== false)
3094 if (strpos($shared[1],$link) !== false)
3097 $text = trim($shared[1]);
3099 //if (strlen($text) < strlen($title))
3100 if (($text == "") AND ($title != ""))
3101 $text .= "\n\n".trim($title);
3104 $text .= "\n".trim($link);
3106 return(trim($text));
3109 function api_best_nickname(&$contacts) {
3110 $best_contact = array();
3112 if (count($contact) == 0)
3115 foreach ($contacts AS $contact)
3116 if ($contact["network"] == "") {
3117 $contact["network"] = "dfrn";
3118 $best_contact = array($contact);
3121 if (sizeof($best_contact) == 0)
3122 foreach ($contacts AS $contact)
3123 if ($contact["network"] == "dfrn")
3124 $best_contact = array($contact);
3126 if (sizeof($best_contact) == 0)
3127 foreach ($contacts AS $contact)
3128 if ($contact["network"] == "dspr")
3129 $best_contact = array($contact);
3131 if (sizeof($best_contact) == 0)
3132 foreach ($contacts AS $contact)
3133 if ($contact["network"] == "stat")
3134 $best_contact = array($contact);
3136 if (sizeof($best_contact) == 0)
3137 foreach ($contacts AS $contact)
3138 if ($contact["network"] == "pump")
3139 $best_contact = array($contact);
3141 if (sizeof($best_contact) == 0)
3142 foreach ($contacts AS $contact)
3143 if ($contact["network"] == "twit")
3144 $best_contact = array($contact);
3146 if (sizeof($best_contact) == 1)
3147 $contacts = $best_contact;
3149 $contacts = array($contacts[0]);
3152 // return all or a specified group of the user with the containing contacts
3153 function api_friendica_group_show(&$a, $type) {
3154 if (api_user()===false) throw new ForbiddenException();
3157 $user_info = api_get_user($a);
3158 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3159 $uid = $user_info['uid'];
3161 // get data of the specified group id or all groups if not specified
3163 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3166 // error message if specified gid is not in database
3168 throw new BadRequestException("gid not available");
3171 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3174 // loop through all groups and retrieve all members for adding data in the user array
3175 foreach ($r as $rr) {
3176 $members = group_get_members($rr['id']);
3178 foreach ($members as $member) {
3179 $user = api_get_user($a, $member['nurl']);
3182 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3184 return api_apply_template("group_show", $type, array('$groups' => $grps));
3186 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3189 // delete the specified group of the user
3190 function api_friendica_group_delete(&$a, $type) {
3191 if (api_user()===false) throw new ForbiddenException();
3194 $user_info = api_get_user($a);
3195 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3196 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3197 $uid = $user_info['uid'];
3199 // error if no gid specified
3200 if ($gid == 0 || $name == "")
3201 throw new BadRequestException('gid or name not specified');
3203 // get data of the specified group id
3204 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3207 // error message if specified gid is not in database
3209 throw new BadRequestException('gid not available');
3211 // get data of the specified group id and group name
3212 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3216 // error message if specified gid is not in database
3217 if (count($rname) == 0)
3218 throw new BadRequestException('wrong group name');
3221 $ret = group_rmv($uid, $name);
3224 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3225 return api_apply_template("group_delete", $type, array('$result' => $success));
3228 throw new BadRequestException('other API error');
3230 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3233 // create the specified group with the posted array of contacts
3234 function api_friendica_group_create(&$a, $type) {
3235 if (api_user()===false) throw new ForbiddenException();
3238 $user_info = api_get_user($a);
3239 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3240 $uid = $user_info['uid'];
3241 $json = json_decode($_POST['json'], true);
3242 $users = $json['user'];
3244 // error if no name specified
3246 throw new BadRequestException('group name not specified');
3248 // get data of the specified group name
3249 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3252 // error message if specified group name already exists
3253 if (count($rname) != 0)
3254 throw new BadRequestException('group name already exists');
3256 // check if specified group name is a deleted group
3257 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3260 // error message if specified group name already exists
3261 if (count($rname) != 0)
3262 $reactivate_group = true;
3265 $ret = group_add($uid, $name);
3267 $gid = group_byname($uid, $name);
3269 throw new BadRequestException('other API error');
3272 $erroraddinguser = false;
3273 $errorusers = array();
3274 foreach ($users as $user) {
3275 $cid = $user['cid'];
3276 // check if user really exists as contact
3277 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3280 if (count($contact))
3281 $result = group_add_member($uid, $name, $cid, $gid);
3283 $erroraddinguser = true;
3284 $errorusers[] = $cid;
3288 // return success message incl. missing users in array
3289 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3290 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3291 return api_apply_template("group_create", $type, array('result' => $success));
3293 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3296 // update the specified group with the posted array of contacts
3297 function api_friendica_group_update(&$a, $type) {
3298 if (api_user()===false) throw new ForbiddenException();
3301 $user_info = api_get_user($a);
3302 $uid = $user_info['uid'];
3303 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3304 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3305 $json = json_decode($_POST['json'], true);
3306 $users = $json['user'];
3308 // error if no name specified
3310 throw new BadRequestException('group name not specified');
3312 // error if no gid specified
3314 throw new BadRequestException('gid not specified');
3317 $members = group_get_members($gid);
3318 foreach ($members as $member) {
3319 $cid = $member['id'];
3320 foreach ($users as $user) {
3321 $found = ($user['cid'] == $cid ? true : false);
3324 $ret = group_rmv_member($uid, $name, $cid);
3329 $erroraddinguser = false;
3330 $errorusers = array();
3331 foreach ($users as $user) {
3332 $cid = $user['cid'];
3333 // check if user really exists as contact
3334 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3337 if (count($contact))
3338 $result = group_add_member($uid, $name, $cid, $gid);
3340 $erroraddinguser = true;
3341 $errorusers[] = $cid;
3345 // return success message incl. missing users in array
3346 $status = ($erroraddinguser ? "missing user" : "ok");
3347 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3348 return api_apply_template("group_update", $type, array('result' => $success));
3350 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3353 function api_friendica_activity(&$a, $type) {
3354 if (api_user()===false) throw new ForbiddenException();
3355 $verb = strtolower($a->argv[3]);
3356 $verb = preg_replace("|\..*$|", "", $verb);
3358 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3360 $res = do_like($id, $verb);
3367 return api_apply_template('test', $type, array('ok' => $ok));
3369 throw new BadRequestException('Error adding activity');
3373 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3374 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3375 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3376 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3377 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3378 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3379 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3380 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3381 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3382 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3386 [pagename] => api/1.1/statuses/lookup.json
3387 [id] => 605138389168451584
3388 [include_cards] => true
3389 [cards_platform] => Android-12
3390 [include_entities] => true
3391 [include_my_retweet] => 1
3393 [include_reply_count] => true
3394 [include_descendent_reply_count] => true
3398 Not implemented by now:
3399 statuses/retweets_of_me
3404 account/update_location
3405 account/update_profile_background_image
3406 account/update_profile_image
3410 Not implemented in status.net:
3411 statuses/retweeted_to_me
3412 statuses/retweeted_by_me
3413 direct_messages/destroy
3415 account/update_delivery_device
3416 notifications/follow