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 require_once('library/HTMLPurifier.auto.php');
786 $txt = html2bb_video($txt);
787 $config = HTMLPurifier_Config::createDefault();
788 $config->set('Cache.DefinitionImpl', null);
789 $purifier = new HTMLPurifier($config);
790 $txt = $purifier->purify($txt);
792 $txt = html2bbcode($txt);
794 $a->argv[1]=$user_info['screen_name']; //should be set to username?
796 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
797 $bebop = wall_upload_post($a);
799 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
800 $_REQUEST['body']=$txt."\n\n".$bebop;
803 // this should output the last post (the one we just posted).
804 return api_status_show($a,$type);
806 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
807 /*Waitman Gobble Mod*/
810 function api_statuses_update(&$a, $type) {
811 if (api_user()===false) {
812 logger('api_statuses_update: no user');
813 throw new ForbiddenException();
816 $user_info = api_get_user($a);
818 // convert $_POST array items to the form we use for web posts.
820 // logger('api_post: ' . print_r($_POST,true));
822 if(requestdata('htmlstatus')) {
823 $txt = requestdata('htmlstatus');
824 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
826 require_once('library/HTMLPurifier.auto.php');
828 $txt = html2bb_video($txt);
830 $config = HTMLPurifier_Config::createDefault();
831 $config->set('Cache.DefinitionImpl', null);
833 $purifier = new HTMLPurifier($config);
834 $txt = $purifier->purify($txt);
836 $_REQUEST['body'] = html2bbcode($txt);
840 $_REQUEST['body'] = requestdata('status');
842 $_REQUEST['title'] = requestdata('title');
844 $parent = requestdata('in_reply_to_status_id');
846 // Twidere sends "-1" if it is no reply ...
850 if(ctype_digit($parent))
851 $_REQUEST['parent'] = $parent;
853 $_REQUEST['parent_uri'] = $parent;
855 if(requestdata('lat') && requestdata('long'))
856 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
857 $_REQUEST['profile_uid'] = api_user();
860 $_REQUEST['type'] = 'net-comment';
862 // Check for throttling (maximum posts per day, week and month)
863 $throttle_day = get_config('system','throttle_limit_day');
864 if ($throttle_day > 0) {
865 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
867 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
868 AND `created` > '%s' AND `id` = `parent`",
869 intval(api_user()), dbesc($datefrom));
872 $posts_day = $r[0]["posts_day"];
876 if ($posts_day > $throttle_day) {
877 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
878 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
882 $throttle_week = get_config('system','throttle_limit_week');
883 if ($throttle_week > 0) {
884 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
886 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
887 AND `created` > '%s' AND `id` = `parent`",
888 intval(api_user()), dbesc($datefrom));
891 $posts_week = $r[0]["posts_week"];
895 if ($posts_week > $throttle_week) {
896 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
897 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
901 $throttle_month = get_config('system','throttle_limit_month');
902 if ($throttle_month > 0) {
903 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
905 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
906 AND `created` > '%s' AND `id` = `parent`",
907 intval(api_user()), dbesc($datefrom));
910 $posts_month = $r[0]["posts_month"];
914 if ($posts_month > $throttle_month) {
915 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
916 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
920 $_REQUEST['type'] = 'wall';
923 if(x($_FILES,'media')) {
924 // upload the image if we have one
925 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
926 $media = wall_upload_post($a);
928 $_REQUEST['body'] .= "\n\n".$media;
931 // To-Do: Multiple IDs
932 if (requestdata('media_ids')) {
933 $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",
934 intval(requestdata('media_ids')), api_user());
936 $phototypes = Photo::supportedTypes();
937 $ext = $phototypes[$r[0]['type']];
938 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
939 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
943 // set this so that the item_post() function is quiet and doesn't redirect or emit json
945 $_REQUEST['api_source'] = true;
947 if (!x($_REQUEST, "source"))
948 $_REQUEST["source"] = api_source();
950 // call out normal post function
954 // this should output the last post (the one we just posted).
955 return api_status_show($a,$type);
957 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
958 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
961 function api_media_upload(&$a, $type) {
962 if (api_user()===false) {
964 throw new ForbiddenException();
967 $user_info = api_get_user($a);
969 if(!x($_FILES,'media')) {
971 throw new BadRequestException("No media.");
974 $media = wall_upload_post($a, false);
977 throw new InternalServerErrorException();
980 $returndata = array();
981 $returndata["media_id"] = $media["id"];
982 $returndata["media_id_string"] = (string)$media["id"];
983 $returndata["size"] = $media["size"];
984 $returndata["image"] = array("w" => $media["width"],
985 "h" => $media["height"],
986 "image_type" => $media["type"]);
988 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
990 return array("media" => $returndata);
992 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
994 function api_status_show(&$a, $type){
995 $user_info = api_get_user($a);
997 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1000 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1004 // get last public wall message
1005 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1006 FROM `item`, `item` as `i`
1007 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1008 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1009 AND `i`.`id` = `item`.`parent`
1010 AND `item`.`type`!='activity' $privacy_sql
1011 ORDER BY `item`.`created` DESC
1013 intval($user_info['cid']),
1015 dbesc($user_info['url']),
1016 dbesc(normalise_link($user_info['url'])),
1017 dbesc($user_info['url']),
1018 dbesc(normalise_link($user_info['url']))
1021 if (count($lastwall)>0){
1022 $lastwall = $lastwall[0];
1024 $in_reply_to_status_id = NULL;
1025 $in_reply_to_user_id = NULL;
1026 $in_reply_to_status_id_str = NULL;
1027 $in_reply_to_user_id_str = NULL;
1028 $in_reply_to_screen_name = NULL;
1029 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1030 $in_reply_to_status_id= intval($lastwall['parent']);
1031 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1033 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1035 if ($r[0]['nick'] == "")
1036 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1038 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1039 $in_reply_to_user_id = intval($r[0]['id']);
1040 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1044 // There seems to be situation, where both fields are identical:
1045 // https://github.com/friendica/friendica/issues/1010
1046 // This is a bugfix for that.
1047 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1048 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1049 $in_reply_to_status_id = NULL;
1050 $in_reply_to_user_id = NULL;
1051 $in_reply_to_status_id_str = NULL;
1052 $in_reply_to_user_id_str = NULL;
1053 $in_reply_to_screen_name = NULL;
1056 $converted = api_convert_item($lastwall);
1058 $status_info = array(
1059 'created_at' => api_date($lastwall['created']),
1060 'id' => intval($lastwall['id']),
1061 'id_str' => (string) $lastwall['id'],
1062 'text' => $converted["text"],
1063 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1064 'truncated' => false,
1065 'in_reply_to_status_id' => $in_reply_to_status_id,
1066 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1067 'in_reply_to_user_id' => $in_reply_to_user_id,
1068 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1069 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1070 'user' => $user_info,
1072 'coordinates' => "",
1074 'contributors' => "",
1075 'is_quote_status' => false,
1076 'retweet_count' => 0,
1077 'favorite_count' => 0,
1078 'favorited' => $lastwall['starred'] ? true : false,
1079 'retweeted' => false,
1080 'possibly_sensitive' => false,
1082 'statusnet_html' => $converted["html"],
1083 'statusnet_conversation_id' => $lastwall['parent'],
1086 if (count($converted["attachments"]) > 0)
1087 $status_info["attachments"] = $converted["attachments"];
1089 if (count($converted["entities"]) > 0)
1090 $status_info["entities"] = $converted["entities"];
1092 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1093 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1094 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1095 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1097 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1098 unset($status_info["user"]["uid"]);
1099 unset($status_info["user"]["self"]);
1102 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1105 return($status_info);
1107 return api_apply_template("status", $type, array('$status' => $status_info));
1116 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1117 * The author's most recent status will be returned inline.
1118 * http://developer.twitter.com/doc/get/users/show
1120 function api_users_show(&$a, $type){
1121 $user_info = api_get_user($a);
1123 $lastwall = q("SELECT `item`.*
1124 FROM `item`, `contact`
1125 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1126 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1127 AND `contact`.`id`=`item`.`contact-id`
1128 AND `type`!='activity'
1129 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1130 ORDER BY `created` DESC
1133 dbesc(ACTIVITY_POST),
1134 intval($user_info['cid']),
1135 dbesc($user_info['url']),
1136 dbesc(normalise_link($user_info['url'])),
1137 dbesc($user_info['url']),
1138 dbesc(normalise_link($user_info['url']))
1140 if (count($lastwall)>0){
1141 $lastwall = $lastwall[0];
1143 $in_reply_to_status_id = NULL;
1144 $in_reply_to_user_id = NULL;
1145 $in_reply_to_status_id_str = NULL;
1146 $in_reply_to_user_id_str = NULL;
1147 $in_reply_to_screen_name = NULL;
1148 if ($lastwall['parent']!=$lastwall['id']) {
1149 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1150 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1151 if (count($reply)>0) {
1152 $in_reply_to_status_id = intval($lastwall['parent']);
1153 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1155 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1157 if ($r[0]['nick'] == "")
1158 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1160 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1161 $in_reply_to_user_id = intval($r[0]['id']);
1162 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1167 $converted = api_convert_item($lastwall);
1169 $user_info['status'] = array(
1170 'text' => $converted["text"],
1171 'truncated' => false,
1172 'created_at' => api_date($lastwall['created']),
1173 'in_reply_to_status_id' => $in_reply_to_status_id,
1174 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1175 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1176 'id' => intval($lastwall['contact-id']),
1177 'id_str' => (string) $lastwall['contact-id'],
1178 'in_reply_to_user_id' => $in_reply_to_user_id,
1179 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1180 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1182 'favorited' => $lastwall['starred'] ? true : false,
1183 'statusnet_html' => $converted["html"],
1184 'statusnet_conversation_id' => $lastwall['parent'],
1187 if (count($converted["attachments"]) > 0)
1188 $user_info["status"]["attachments"] = $converted["attachments"];
1190 if (count($converted["entities"]) > 0)
1191 $user_info["status"]["entities"] = $converted["entities"];
1193 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1194 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1195 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1196 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1200 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1201 unset($user_info["uid"]);
1202 unset($user_info["self"]);
1204 return api_apply_template("user", $type, array('$user' => $user_info));
1207 api_register_func('api/users/show','api_users_show');
1210 function api_users_search(&$a, $type) {
1211 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1213 $userlist = array();
1215 if (isset($_GET["q"])) {
1216 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1218 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1221 foreach ($r AS $user) {
1222 $user_info = api_get_user($a, $user["id"]);
1223 //echo print_r($user_info, true)."\n";
1224 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1225 $userlist[] = $userdata["user"];
1227 $userlist = array("users" => $userlist);
1229 throw new BadRequestException("User not found.");
1232 throw new BadRequestException("User not found.");
1237 api_register_func('api/users/search','api_users_search');
1241 * http://developer.twitter.com/doc/get/statuses/home_timeline
1243 * TODO: Optional parameters
1244 * TODO: Add reply info
1246 function api_statuses_home_timeline(&$a, $type){
1247 if (api_user()===false) throw new ForbiddenException();
1249 unset($_REQUEST["user_id"]);
1250 unset($_GET["user_id"]);
1252 unset($_REQUEST["screen_name"]);
1253 unset($_GET["screen_name"]);
1255 $user_info = api_get_user($a);
1256 // get last newtork messages
1260 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1261 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1262 if ($page<0) $page=0;
1263 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1264 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1265 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1266 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1267 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1269 $start = $page*$count;
1273 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1274 if ($exclude_replies > 0)
1275 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1276 if ($conversation_id > 0)
1277 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1279 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1280 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1281 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1282 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1283 FROM `item`, `contact`
1284 WHERE `item`.`uid` = %d AND `verb` = '%s'
1285 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1286 AND `contact`.`id` = `item`.`contact-id`
1287 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1290 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1292 dbesc(ACTIVITY_POST),
1294 intval($start), intval($count)
1297 $ret = api_format_items($r,$user_info);
1299 // Set all posts from the query above to seen
1301 foreach ($r AS $item)
1302 $idarray[] = intval($item["id"]);
1304 $idlist = implode(",", $idarray);
1307 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1310 $data = array('$statuses' => $ret);
1314 $data = api_rss_extra($a, $data, $user_info);
1317 $as = api_format_as($a, $ret, $user_info);
1318 $as['title'] = $a->config['sitename']." Home Timeline";
1319 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1324 return api_apply_template("timeline", $type, $data);
1326 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1327 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1329 function api_statuses_public_timeline(&$a, $type){
1330 if (api_user()===false) throw new ForbiddenException();
1332 $user_info = api_get_user($a);
1333 // get last newtork messages
1337 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1338 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1339 if ($page<0) $page=0;
1340 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1341 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1342 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1343 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1344 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1346 $start = $page*$count;
1349 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1350 if ($exclude_replies > 0)
1351 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1352 if ($conversation_id > 0)
1353 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1355 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1356 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1357 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1358 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1359 `user`.`nickname`, `user`.`hidewall`
1360 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1361 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1362 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1363 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1364 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1365 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1366 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1369 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1370 dbesc(ACTIVITY_POST),
1375 $ret = api_format_items($r,$user_info);
1378 $data = array('$statuses' => $ret);
1382 $data = api_rss_extra($a, $data, $user_info);
1385 $as = api_format_as($a, $ret, $user_info);
1386 $as['title'] = $a->config['sitename']." Public Timeline";
1387 $as['link']['url'] = $a->get_baseurl()."/";
1392 return api_apply_template("timeline", $type, $data);
1394 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1399 function api_statuses_show(&$a, $type){
1400 if (api_user()===false) throw new ForbiddenException();
1402 $user_info = api_get_user($a);
1405 $id = intval($a->argv[3]);
1408 $id = intval($_REQUEST["id"]);
1412 $id = intval($a->argv[4]);
1414 logger('API: api_statuses_show: '.$id);
1416 $conversation = (x($_REQUEST,'conversation')?1:0);
1420 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1422 $sql_extra .= " AND `item`.`id` = %d";
1424 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1425 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1426 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1427 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1428 FROM `item`, `contact`
1429 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1430 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1431 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1434 dbesc(ACTIVITY_POST),
1439 throw new BadRequestException("There is no status with this id.");
1442 $ret = api_format_items($r,$user_info);
1444 if ($conversation) {
1445 $data = array('$statuses' => $ret);
1446 return api_apply_template("timeline", $type, $data);
1448 $data = array('$status' => $ret[0]);
1452 $data = api_rss_extra($a, $data, $user_info);
1454 return api_apply_template("status", $type, $data);
1457 api_register_func('api/statuses/show','api_statuses_show', true);
1463 function api_conversation_show(&$a, $type){
1464 if (api_user()===false) throw new ForbiddenException();
1466 $user_info = api_get_user($a);
1469 $id = intval($a->argv[3]);
1470 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1471 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1472 if ($page<0) $page=0;
1473 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1474 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1476 $start = $page*$count;
1479 $id = intval($_REQUEST["id"]);
1483 $id = intval($a->argv[4]);
1485 logger('API: api_conversation_show: '.$id);
1487 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1489 $id = $r[0]["parent"];
1494 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1496 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1497 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1498 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1499 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1500 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1501 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1502 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1503 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1504 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1505 AND `item`.`id`>%d $sql_extra
1506 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1507 intval($id), intval(api_user()),
1508 dbesc(ACTIVITY_POST),
1510 intval($start), intval($count)
1514 throw new BadRequestException("There is no conversation with this id.");
1516 $ret = api_format_items($r,$user_info);
1518 $data = array('$statuses' => $ret);
1519 return api_apply_template("timeline", $type, $data);
1521 api_register_func('api/conversation/show','api_conversation_show', true);
1527 function api_statuses_repeat(&$a, $type){
1530 if (api_user()===false) throw new ForbiddenException();
1532 $user_info = api_get_user($a);
1535 $id = intval($a->argv[3]);
1538 $id = intval($_REQUEST["id"]);
1542 $id = intval($a->argv[4]);
1544 logger('API: api_statuses_repeat: '.$id);
1546 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1547 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1548 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1549 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1550 FROM `item`, `contact`
1551 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1552 AND `contact`.`id` = `item`.`contact-id`
1553 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1554 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1555 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1557 AND `item`.`id`=%d",
1561 if ($r[0]['body'] != "") {
1562 if (!intval(get_config('system','old_share'))) {
1563 if (strpos($r[0]['body'], "[/share]") !== false) {
1564 $pos = strpos($r[0]['body'], "[share");
1565 $post = substr($r[0]['body'], $pos);
1567 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1569 $post .= $r[0]['body'];
1570 $post .= "[/share]";
1572 $_REQUEST['body'] = $post;
1574 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1576 $_REQUEST['profile_uid'] = api_user();
1577 $_REQUEST['type'] = 'wall';
1578 $_REQUEST['api_source'] = true;
1580 if (!x($_REQUEST, "source"))
1581 $_REQUEST["source"] = api_source();
1585 throw new ForbiddenException();
1587 // this should output the last post (the one we just posted).
1589 return(api_status_show($a,$type));
1591 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1596 function api_statuses_destroy(&$a, $type){
1597 if (api_user()===false) throw new ForbiddenException();
1599 $user_info = api_get_user($a);
1602 $id = intval($a->argv[3]);
1605 $id = intval($_REQUEST["id"]);
1609 $id = intval($a->argv[4]);
1611 logger('API: api_statuses_destroy: '.$id);
1613 $ret = api_statuses_show($a, $type);
1615 drop_item($id, false);
1619 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1623 * http://developer.twitter.com/doc/get/statuses/mentions
1626 function api_statuses_mentions(&$a, $type){
1627 if (api_user()===false) throw new ForbiddenException();
1629 unset($_REQUEST["user_id"]);
1630 unset($_GET["user_id"]);
1632 unset($_REQUEST["screen_name"]);
1633 unset($_GET["screen_name"]);
1635 $user_info = api_get_user($a);
1636 // get last newtork messages
1640 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1641 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1642 if ($page<0) $page=0;
1643 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1644 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1645 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1647 $start = $page*$count;
1649 // Ugly code - should be changed
1650 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1651 $myurl = substr($myurl,strpos($myurl,'://')+3);
1652 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1653 $myurl = str_replace('www.','',$myurl);
1654 $diasp_url = str_replace('/profile/','/u/',$myurl);
1657 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1659 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1660 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1661 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1662 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1663 FROM `item`, `contact`
1664 WHERE `item`.`uid` = %d AND `verb` = '%s'
1665 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1666 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1667 AND `contact`.`id` = `item`.`contact-id`
1668 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1669 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1672 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1674 dbesc(ACTIVITY_POST),
1675 dbesc(protect_sprintf($myurl)),
1676 dbesc(protect_sprintf($myurl)),
1679 intval($start), intval($count)
1682 $ret = api_format_items($r,$user_info);
1685 $data = array('$statuses' => $ret);
1689 $data = api_rss_extra($a, $data, $user_info);
1692 $as = api_format_as($a, $ret, $user_info);
1693 $as["title"] = $a->config['sitename']." Mentions";
1694 $as['link']['url'] = $a->get_baseurl()."/";
1699 return api_apply_template("timeline", $type, $data);
1701 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1702 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1705 function api_statuses_user_timeline(&$a, $type){
1706 if (api_user()===false) throw new ForbiddenException();
1708 $user_info = api_get_user($a);
1709 // get last network messages
1711 logger("api_statuses_user_timeline: api_user: ". api_user() .
1712 "\nuser_info: ".print_r($user_info, true) .
1713 "\n_REQUEST: ".print_r($_REQUEST, true),
1717 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1718 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1719 if ($page<0) $page=0;
1720 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1721 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1722 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1723 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1725 $start = $page*$count;
1728 if ($user_info['self']==1)
1729 $sql_extra .= " AND `item`.`wall` = 1 ";
1731 if ($exclude_replies > 0)
1732 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1733 if ($conversation_id > 0)
1734 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1736 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1737 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1738 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1739 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1740 FROM `item`, `contact`
1741 WHERE `item`.`uid` = %d AND `verb` = '%s'
1742 AND `item`.`contact-id` = %d
1743 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1744 AND `contact`.`id` = `item`.`contact-id`
1745 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1748 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1750 dbesc(ACTIVITY_POST),
1751 intval($user_info['cid']),
1753 intval($start), intval($count)
1756 $ret = api_format_items($r,$user_info, true);
1758 $data = array('$statuses' => $ret);
1762 $data = api_rss_extra($a, $data, $user_info);
1765 return api_apply_template("timeline", $type, $data);
1767 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1771 * Star/unstar an item
1772 * param: id : id of the item
1774 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1776 function api_favorites_create_destroy(&$a, $type){
1777 if (api_user()===false) throw new ForbiddenException();
1779 // for versioned api.
1780 /// @TODO We need a better global soluton
1782 if ($a->argv[1]=="1.1") $action_argv_id=3;
1784 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1785 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1786 if ($a->argc==$action_argv_id+2) {
1787 $itemid = intval($a->argv[$action_argv_id+1]);
1789 $itemid = intval($_REQUEST['id']);
1792 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1793 $itemid, api_user());
1795 if ($item===false || count($item)==0)
1796 throw new BadRequestException("Invalid item.");
1800 $item[0]['starred']=1;
1803 $item[0]['starred']=0;
1806 throw new BadRequestException("Invalid action ".$action);
1808 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1809 $item[0]['starred'], $itemid, api_user());
1811 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1812 $item[0]['starred'], $itemid, api_user());
1815 throw InternalServerErrorException("DB error");
1818 $user_info = api_get_user($a);
1819 $rets = api_format_items($item,$user_info);
1822 $data = array('$status' => $ret);
1826 $data = api_rss_extra($a, $data, $user_info);
1829 return api_apply_template("status", $type, $data);
1831 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1832 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1834 function api_favorites(&$a, $type){
1837 if (api_user()===false) throw new ForbiddenException();
1839 $called_api= array();
1841 $user_info = api_get_user($a);
1843 // in friendica starred item are private
1844 // return favorites only for self
1845 logger('api_favorites: self:' . $user_info['self']);
1847 if ($user_info['self']==0) {
1853 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1854 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1855 $count = (x($_GET,'count')?$_GET['count']:20);
1856 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1857 if ($page<0) $page=0;
1859 $start = $page*$count;
1862 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1864 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1865 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1866 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1867 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1868 FROM `item`, `contact`
1869 WHERE `item`.`uid` = %d
1870 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1871 AND `item`.`starred` = 1
1872 AND `contact`.`id` = `item`.`contact-id`
1873 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1876 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1879 intval($start), intval($count)
1882 $ret = api_format_items($r,$user_info);
1886 $data = array('$statuses' => $ret);
1890 $data = api_rss_extra($a, $data, $user_info);
1893 return api_apply_template("timeline", $type, $data);
1895 api_register_func('api/favorites','api_favorites', true);
1900 function api_format_as($a, $ret, $user_info) {
1902 $as['title'] = $a->config['sitename']." Public Timeline";
1904 foreach ($ret as $item) {
1905 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1906 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1907 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1908 $avatar[0]["rel"] = "avatar";
1909 $avatar[0]["type"] = "";
1910 $avatar[0]["width"] = 96;
1911 $avatar[0]["height"] = 96;
1912 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1913 $avatar[1]["rel"] = "avatar";
1914 $avatar[1]["type"] = "";
1915 $avatar[1]["width"] = 48;
1916 $avatar[1]["height"] = 48;
1917 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1918 $avatar[2]["rel"] = "avatar";
1919 $avatar[2]["type"] = "";
1920 $avatar[2]["width"] = 24;
1921 $avatar[2]["height"] = 24;
1922 $singleitem["actor"]["avatarLinks"] = $avatar;
1924 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1925 $singleitem["actor"]["image"]["rel"] = "avatar";
1926 $singleitem["actor"]["image"]["type"] = "";
1927 $singleitem["actor"]["image"]["width"] = 96;
1928 $singleitem["actor"]["image"]["height"] = 96;
1929 $singleitem["actor"]["type"] = "person";
1930 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1931 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1932 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1933 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1934 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1935 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1936 $singleitem["actor"]["contact"]["addresses"] = "";
1938 $singleitem["body"] = $item["text"];
1939 $singleitem["object"]["displayName"] = $item["text"];
1940 $singleitem["object"]["id"] = $item["url"];
1941 $singleitem["object"]["type"] = "note";
1942 $singleitem["object"]["url"] = $item["url"];
1943 //$singleitem["context"] =;
1944 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1945 $singleitem["provider"]["objectType"] = "service";
1946 $singleitem["provider"]["displayName"] = "Test";
1947 $singleitem["provider"]["url"] = "http://test.tld";
1948 $singleitem["title"] = $item["text"];
1949 $singleitem["verb"] = "post";
1950 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1951 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1952 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1953 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1954 //$singleitem["original"] = $item;
1955 $items[] = $singleitem;
1957 $as['items'] = $items;
1958 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1959 $as['link']['rel'] = "alternate";
1960 $as['link']['type'] = "text/html";
1964 function api_format_messages($item, $recipient, $sender) {
1965 // standard meta information
1967 'id' => $item['id'],
1968 'sender_id' => $sender['id'] ,
1970 'recipient_id' => $recipient['id'],
1971 'created_at' => api_date($item['created']),
1972 'sender_screen_name' => $sender['screen_name'],
1973 'recipient_screen_name' => $recipient['screen_name'],
1974 'sender' => $sender,
1975 'recipient' => $recipient,
1978 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1979 unset($ret["sender"]["uid"]);
1980 unset($ret["sender"]["self"]);
1981 unset($ret["recipient"]["uid"]);
1982 unset($ret["recipient"]["self"]);
1984 //don't send title to regular StatusNET requests to avoid confusing these apps
1985 if (x($_GET, 'getText')) {
1986 $ret['title'] = $item['title'] ;
1987 if ($_GET["getText"] == "html") {
1988 $ret['text'] = bbcode($item['body'], false, false);
1990 elseif ($_GET["getText"] == "plain") {
1991 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1992 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1996 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1998 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1999 unset($ret['sender']);
2000 unset($ret['recipient']);
2006 function api_convert_item($item) {
2008 $body = $item['body'];
2009 $attachments = api_get_attachments($body);
2011 // Workaround for ostatus messages where the title is identically to the body
2012 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2013 $statusbody = trim(html2plain($html, 0));
2015 // handle data: images
2016 $statusbody = api_format_items_embeded_images($item,$statusbody);
2018 $statustitle = trim($item['title']);
2020 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2021 $statustext = trim($statusbody);
2023 $statustext = trim($statustitle."\n\n".$statusbody);
2025 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2026 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2028 $statushtml = trim(bbcode($body, false, false));
2030 if ($item['title'] != "")
2031 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2033 $entities = api_get_entitities($statustext, $body);
2035 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2038 function api_get_attachments(&$body) {
2041 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2043 $URLSearchString = "^\[\]";
2044 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2049 $attachments = array();
2051 foreach ($images[1] AS $image) {
2052 $imagedata = get_photo_info($image);
2055 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2058 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2059 foreach ($images[0] AS $orig)
2060 $body = str_replace($orig, "", $body);
2062 return $attachments;
2065 function api_get_entitities(&$text, $bbcode) {
2068 * Links at the first character of the post
2073 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2075 if ($include_entities != "true") {
2077 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2079 foreach ($images[1] AS $image) {
2080 $replace = proxy_url($image);
2081 $text = str_replace($image, $replace, $text);
2086 $bbcode = bb_CleanPictureLinks($bbcode);
2088 // Change pure links in text to bbcode uris
2089 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2091 $entities = array();
2092 $entities["hashtags"] = array();
2093 $entities["symbols"] = array();
2094 $entities["urls"] = array();
2095 $entities["user_mentions"] = array();
2097 $URLSearchString = "^\[\]";
2099 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2101 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2102 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2103 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2105 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2106 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2107 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2109 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2110 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2111 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2113 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2115 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2116 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2118 $ordered_urls = array();
2119 foreach ($urls[1] AS $id=>$url) {
2120 //$start = strpos($text, $url, $offset);
2121 $start = iconv_strpos($text, $url, 0, "UTF-8");
2122 if (!($start === false))
2123 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2126 ksort($ordered_urls);
2129 //foreach ($urls[1] AS $id=>$url) {
2130 foreach ($ordered_urls AS $url) {
2131 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2132 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2133 $display_url = $url["title"];
2135 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2136 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2138 if (strlen($display_url) > 26)
2139 $display_url = substr($display_url, 0, 25)."…";
2142 //$start = strpos($text, $url, $offset);
2143 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2144 if (!($start === false)) {
2145 $entities["urls"][] = array("url" => $url["url"],
2146 "expanded_url" => $url["url"],
2147 "display_url" => $display_url,
2148 "indices" => array($start, $start+strlen($url["url"])));
2149 $offset = $start + 1;
2153 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2154 $ordered_images = array();
2155 foreach ($images[1] AS $image) {
2156 //$start = strpos($text, $url, $offset);
2157 $start = iconv_strpos($text, $image, 0, "UTF-8");
2158 if (!($start === false))
2159 $ordered_images[$start] = $image;
2161 //$entities["media"] = array();
2164 foreach ($ordered_images AS $url) {
2165 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2166 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2168 if (strlen($display_url) > 26)
2169 $display_url = substr($display_url, 0, 25)."…";
2171 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2172 if (!($start === false)) {
2173 $image = get_photo_info($url);
2175 // If image cache is activated, then use the following sizes:
2176 // thumb (150), small (340), medium (600) and large (1024)
2177 if (!get_config("system", "proxy_disabled")) {
2178 $media_url = proxy_url($url);
2181 $scale = scale_image($image[0], $image[1], 150);
2182 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2184 if (($image[0] > 150) OR ($image[1] > 150)) {
2185 $scale = scale_image($image[0], $image[1], 340);
2186 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2189 $scale = scale_image($image[0], $image[1], 600);
2190 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2192 if (($image[0] > 600) OR ($image[1] > 600)) {
2193 $scale = scale_image($image[0], $image[1], 1024);
2194 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2198 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2201 $entities["media"][] = array(
2203 "id_str" => (string)$start+1,
2204 "indices" => array($start, $start+strlen($url)),
2205 "media_url" => normalise_link($media_url),
2206 "media_url_https" => $media_url,
2208 "display_url" => $display_url,
2209 "expanded_url" => $url,
2213 $offset = $start + 1;
2219 function api_format_items_embeded_images(&$item, $text){
2221 $text = preg_replace_callback(
2222 "|data:image/([^;]+)[^=]+=*|m",
2223 function($match) use ($a, $item) {
2224 return $a->get_baseurl()."/display/".$item['guid'];
2231 * @brief return likes, dislikes and attend status for item
2233 * @param array $item
2235 * likes => int count
2236 * dislikes => int count
2238 function api_format_items_likes(&$item) {
2239 $activities = array(
2241 'dislike' => array(),
2242 'attendyes' => array(),
2243 'attendno' => array(),
2244 'attendmaybe' => array()
2246 $items = q('SELECT * FROM item
2247 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2248 intval($item['uid']),
2249 dbesc($item['uri']));
2250 foreach ($items as $i){
2251 builtin_activity_puller($i, $activities);
2255 $uri = $item['uri'];
2256 foreach($activities as $k => $v) {
2257 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2264 * @brief format items to be returned by api
2266 * @param array $r array of items
2267 * @param array $user_info
2268 * @param bool $filter_user filter items by $user_info
2270 function api_format_items($r,$user_info, $filter_user = false) {
2275 foreach($r as $item) {
2276 api_share_as_retweet($item);
2278 localize_item($item);
2279 $status_user = api_item_get_user($a,$item);
2281 // Look if the posts are matching if they should be filtered by user id
2282 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2285 if ($item['thr-parent'] != $item['uri']) {
2286 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2288 dbesc($item['thr-parent']));
2290 $in_reply_to_status_id = intval($r[0]['id']);
2292 $in_reply_to_status_id = intval($item['parent']);
2294 $in_reply_to_status_id_str = (string) intval($item['parent']);
2296 $in_reply_to_screen_name = NULL;
2297 $in_reply_to_user_id = NULL;
2298 $in_reply_to_user_id_str = NULL;
2300 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2302 intval($in_reply_to_status_id));
2304 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2307 if ($r[0]['nick'] == "")
2308 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2310 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2311 $in_reply_to_user_id = intval($r[0]['id']);
2312 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2316 $in_reply_to_screen_name = NULL;
2317 $in_reply_to_user_id = NULL;
2318 $in_reply_to_status_id = NULL;
2319 $in_reply_to_user_id_str = NULL;
2320 $in_reply_to_status_id_str = NULL;
2323 $converted = api_convert_item($item);
2326 'text' => $converted["text"],
2327 'truncated' => False,
2328 'created_at'=> api_date($item['created']),
2329 'in_reply_to_status_id' => $in_reply_to_status_id,
2330 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2331 'source' => (($item['app']) ? $item['app'] : 'web'),
2332 'id' => intval($item['id']),
2333 'id_str' => (string) intval($item['id']),
2334 'in_reply_to_user_id' => $in_reply_to_user_id,
2335 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2336 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2338 'favorited' => $item['starred'] ? true : false,
2339 'user' => $status_user ,
2340 //'entities' => NULL,
2341 'statusnet_html' => $converted["html"],
2342 'statusnet_conversation_id' => $item['parent'],
2343 'friendica_activities' => api_format_items_likes($item),
2346 if (count($converted["attachments"]) > 0)
2347 $status["attachments"] = $converted["attachments"];
2349 if (count($converted["entities"]) > 0)
2350 $status["entities"] = $converted["entities"];
2352 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2353 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2354 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2355 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2358 // Retweets are only valid for top postings
2359 // It doesn't work reliable with the link if its a feed
2360 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2362 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2364 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2365 $retweeted_status = $status;
2366 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2368 $status["retweeted_status"] = $retweeted_status;
2371 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2372 unset($status["user"]["uid"]);
2373 unset($status["user"]["self"]);
2375 if ($item["coord"] != "") {
2376 $coords = explode(' ',$item["coord"]);
2377 if (count($coords) == 2) {
2378 $status["geo"] = array('type' => 'Point',
2379 'coordinates' => array((float) $coords[0],
2380 (float) $coords[1]));
2390 function api_account_rate_limit_status(&$a,$type) {
2392 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2393 'remaining_hits' => (string) 150,
2394 'hourly_limit' => (string) 150,
2395 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2398 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2400 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2402 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2404 function api_help_test(&$a,$type) {
2410 return api_apply_template('test', $type, array("$ok" => $ok));
2412 api_register_func('api/help/test','api_help_test',false);
2414 function api_lists(&$a,$type) {
2418 api_register_func('api/lists','api_lists',true);
2420 function api_lists_list(&$a,$type) {
2424 api_register_func('api/lists/list','api_lists_list',true);
2427 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2428 * This function is deprecated by Twitter
2429 * returns: json, xml
2431 function api_statuses_f(&$a, $type, $qtype) {
2432 if (api_user()===false) throw new ForbiddenException();
2433 $user_info = api_get_user($a);
2435 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2436 /* this is to stop Hotot to load friends multiple times
2437 * I'm not sure if I'm missing return something or
2438 * is a bug in hotot. Workaround, meantime
2442 return array('$users' => $ret);*/
2446 if($qtype == 'friends')
2447 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2448 if($qtype == 'followers')
2449 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2451 // friends and followers only for self
2452 if ($user_info['self'] == 0)
2453 $sql_extra = " AND false ";
2455 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2460 foreach($r as $cid){
2461 $user = api_get_user($a, $cid['nurl']);
2462 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2463 unset($user["uid"]);
2464 unset($user["self"]);
2470 return array('$users' => $ret);
2473 function api_statuses_friends(&$a, $type){
2474 $data = api_statuses_f($a,$type,"friends");
2475 if ($data===false) return false;
2476 return api_apply_template("friends", $type, $data);
2478 function api_statuses_followers(&$a, $type){
2479 $data = api_statuses_f($a,$type,"followers");
2480 if ($data===false) return false;
2481 return api_apply_template("friends", $type, $data);
2483 api_register_func('api/statuses/friends','api_statuses_friends',true);
2484 api_register_func('api/statuses/followers','api_statuses_followers',true);
2491 function api_statusnet_config(&$a,$type) {
2492 $name = $a->config['sitename'];
2493 $server = $a->get_hostname();
2494 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2495 $email = $a->config['admin_email'];
2496 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2497 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2498 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2499 if($a->config['api_import_size'])
2500 $texlimit = string($a->config['api_import_size']);
2501 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2502 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2505 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2506 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2507 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2508 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2509 'shorturllength' => '30',
2510 'friendica' => array(
2511 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2512 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2513 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2514 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2519 return api_apply_template('config', $type, array('$config' => $config));
2522 api_register_func('api/statusnet/config','api_statusnet_config',false);
2524 function api_statusnet_version(&$a,$type) {
2526 $fake_statusnet_version = "0.9.7";
2528 if($type === 'xml') {
2529 header("Content-type: application/xml");
2530 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2533 elseif($type === 'json') {
2534 header("Content-type: application/json");
2535 echo '"'.$fake_statusnet_version.'"';
2539 api_register_func('api/statusnet/version','api_statusnet_version',false);
2542 * @todo use api_apply_template() to return data
2544 function api_ff_ids(&$a,$type,$qtype) {
2545 if(! api_user()) throw new ForbiddenException();
2547 $user_info = api_get_user($a);
2549 if($qtype == 'friends')
2550 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2551 if($qtype == 'followers')
2552 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2554 if (!$user_info["self"])
2555 $sql_extra = " AND false ";
2557 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2559 $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",
2565 if($type === 'xml') {
2566 header("Content-type: application/xml");
2567 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2569 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2570 echo '</ids>' . "\r\n";
2573 elseif($type === 'json') {
2575 header("Content-type: application/json");
2580 $ret[] = intval($rr['id']);
2582 echo json_encode($ret);
2588 function api_friends_ids(&$a,$type) {
2589 api_ff_ids($a,$type,'friends');
2591 function api_followers_ids(&$a,$type) {
2592 api_ff_ids($a,$type,'followers');
2594 api_register_func('api/friends/ids','api_friends_ids',true);
2595 api_register_func('api/followers/ids','api_followers_ids',true);
2598 function api_direct_messages_new(&$a, $type) {
2599 if (api_user()===false) throw new ForbiddenException();
2601 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2603 $sender = api_get_user($a);
2605 if ($_POST['screen_name']) {
2606 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2608 dbesc($_POST['screen_name']));
2610 // Selecting the id by priority, friendica first
2611 api_best_nickname($r);
2613 $recipient = api_get_user($a, $r[0]['nurl']);
2615 $recipient = api_get_user($a, $_POST['user_id']);
2619 if (x($_REQUEST,'replyto')) {
2620 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2622 intval($_REQUEST['replyto']));
2623 $replyto = $r[0]['parent-uri'];
2624 $sub = $r[0]['title'];
2627 if (x($_REQUEST,'title')) {
2628 $sub = $_REQUEST['title'];
2631 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2635 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2638 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2639 $ret = api_format_messages($r[0], $recipient, $sender);
2642 $ret = array("error"=>$id);
2645 $data = Array('$messages'=>$ret);
2650 $data = api_rss_extra($a, $data, $user_info);
2653 return api_apply_template("direct_messages", $type, $data);
2656 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2658 function api_direct_messages_box(&$a, $type, $box) {
2659 if (api_user()===false) throw new ForbiddenException();
2662 $count = (x($_GET,'count')?$_GET['count']:20);
2663 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2664 if ($page<0) $page=0;
2666 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2667 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2669 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2670 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2673 unset($_REQUEST["user_id"]);
2674 unset($_GET["user_id"]);
2676 unset($_REQUEST["screen_name"]);
2677 unset($_GET["screen_name"]);
2679 $user_info = api_get_user($a);
2680 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2681 $profile_url = $user_info["url"];
2685 $start = $page*$count;
2688 if ($box=="sentbox") {
2689 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2691 elseif ($box=="conversation") {
2692 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2694 elseif ($box=="all") {
2695 $sql_extra = "true";
2697 elseif ($box=="inbox") {
2698 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2702 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2704 if ($user_id !="") {
2705 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2707 elseif($screen_name !=""){
2708 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2711 $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",
2714 intval($start), intval($count)
2719 foreach($r as $item) {
2720 if ($box == "inbox" || $item['from-url'] != $profile_url){
2721 $recipient = $user_info;
2722 $sender = api_get_user($a,normalise_link($item['contact-url']));
2724 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2725 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2726 $sender = $user_info;
2729 $ret[]=api_format_messages($item, $recipient, $sender);
2733 $data = array('$messages' => $ret);
2737 $data = api_rss_extra($a, $data, $user_info);
2740 return api_apply_template("direct_messages", $type, $data);
2744 function api_direct_messages_sentbox(&$a, $type){
2745 return api_direct_messages_box($a, $type, "sentbox");
2747 function api_direct_messages_inbox(&$a, $type){
2748 return api_direct_messages_box($a, $type, "inbox");
2750 function api_direct_messages_all(&$a, $type){
2751 return api_direct_messages_box($a, $type, "all");
2753 function api_direct_messages_conversation(&$a, $type){
2754 return api_direct_messages_box($a, $type, "conversation");
2756 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2757 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2758 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2759 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2763 function api_oauth_request_token(&$a, $type){
2765 $oauth = new FKOAuth1();
2766 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2767 }catch(Exception $e){
2768 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2773 function api_oauth_access_token(&$a, $type){
2775 $oauth = new FKOAuth1();
2776 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2777 }catch(Exception $e){
2778 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2784 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2785 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2788 function api_fr_photos_list(&$a,$type) {
2789 if (api_user()===false) throw new ForbiddenException();
2790 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2791 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2792 intval(local_user())
2795 'image/jpeg' => 'jpg',
2796 'image/png' => 'png',
2797 'image/gif' => 'gif'
2799 $data = array('photos'=>array());
2801 foreach($r as $rr) {
2803 $photo['id'] = $rr['resource-id'];
2804 $photo['album'] = $rr['album'];
2805 $photo['filename'] = $rr['filename'];
2806 $photo['type'] = $rr['type'];
2807 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2808 $data['photos'][] = $photo;
2811 return api_apply_template("photos_list", $type, $data);
2814 function api_fr_photo_detail(&$a,$type) {
2815 if (api_user()===false) throw new ForbiddenException();
2816 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2818 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2819 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2820 $data_sql = ($scale === false ? "" : "data, ");
2822 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2823 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2824 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2826 intval(local_user()),
2827 dbesc($_REQUEST['photo_id']),
2832 'image/jpeg' => 'jpg',
2833 'image/png' => 'png',
2834 'image/gif' => 'gif'
2838 $data = array('photo' => $r[0]);
2839 if ($scale !== false) {
2840 $data['photo']['data'] = base64_encode($data['photo']['data']);
2842 unset($data['photo']['datasize']); //needed only with scale param
2844 $data['photo']['link'] = array();
2845 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2846 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2848 $data['photo']['id'] = $data['photo']['resource-id'];
2849 unset($data['photo']['resource-id']);
2850 unset($data['photo']['minscale']);
2851 unset($data['photo']['maxscale']);
2854 throw new NotFoundException();
2857 return api_apply_template("photo_detail", $type, $data);
2860 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2861 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2866 * similar as /mod/redir.php
2867 * redirect to 'url' after dfrn auth
2869 * why this when there is mod/redir.php already?
2870 * This use api_user() and api_login()
2873 * c_url: url of remote contact to auth to
2874 * url: string, url to redirect after auth
2876 function api_friendica_remoteauth(&$a) {
2877 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2878 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2880 if ($url === '' || $c_url === '')
2881 throw new BadRequestException("Wrong parameters.");
2883 $c_url = normalise_link($c_url);
2887 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2892 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2893 throw new BadRequestException("Unknown contact");
2897 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2899 if($r[0]['duplex'] && $r[0]['issued-id']) {
2900 $orig_id = $r[0]['issued-id'];
2901 $dfrn_id = '1:' . $orig_id;
2903 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2904 $orig_id = $r[0]['dfrn-id'];
2905 $dfrn_id = '0:' . $orig_id;
2908 $sec = random_string();
2910 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2911 VALUES( %d, %s, '%s', '%s', %d )",
2919 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2920 $dest = (($url) ? '&destination_url=' . $url : '');
2921 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2922 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2923 . '&type=profile&sec=' . $sec . $dest . $quiet );
2925 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2928 function api_share_as_retweet(&$item) {
2929 $body = trim($item["body"]);
2931 // Skip if it isn't a pure repeated messages
2932 // Does it start with a share?
2933 if (strpos($body, "[share") > 0)
2936 // Does it end with a share?
2937 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2940 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2941 // Skip if there is no shared message in there
2942 if ($body == $attributes)
2946 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2947 if ($matches[1] != "")
2948 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2950 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2951 if ($matches[1] != "")
2952 $author = $matches[1];
2955 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2956 if ($matches[1] != "")
2957 $profile = $matches[1];
2959 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2960 if ($matches[1] != "")
2961 $profile = $matches[1];
2964 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2965 if ($matches[1] != "")
2966 $avatar = $matches[1];
2968 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2969 if ($matches[1] != "")
2970 $avatar = $matches[1];
2973 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2974 if ($matches[1] != "")
2975 $link = $matches[1];
2977 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2978 if ($matches[1] != "")
2979 $link = $matches[1];
2981 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2983 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2986 $item["body"] = $shared_body;
2987 $item["author-name"] = $author;
2988 $item["author-link"] = $profile;
2989 $item["author-avatar"] = $avatar;
2990 $item["plink"] = $link;
2996 function api_get_nick($profile) {
2998 - remove trailing junk from profile url
2999 - pump.io check has to check the website
3004 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3005 dbesc(normalise_link($profile)));
3007 $nick = $r[0]["nick"];
3010 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3011 dbesc(normalise_link($profile)));
3013 $nick = $r[0]["nick"];
3017 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3018 if ($friendica != $profile)
3023 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3024 if ($diaspora != $profile)
3029 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3030 if ($twitter != $profile)
3036 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3037 if ($StatusnetHost != $profile) {
3038 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3039 if ($StatusnetUser != $profile) {
3040 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3041 $user = json_decode($UserData);
3043 $nick = $user->screen_name;
3048 // To-Do: look at the page if its really a pumpio site
3049 //if (!$nick == "") {
3050 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3051 // if ($pumpio != $profile)
3053 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3063 function api_clean_plain_items($Text) {
3064 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3066 $Text = bb_CleanPictureLinks($Text);
3068 $URLSearchString = "^\[\]";
3070 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3072 if ($include_entities == "true") {
3073 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3076 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
3080 function api_cleanup_share($shared) {
3081 if ($shared[2] != "type-link")
3084 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
3090 if (isset($bookmark[2][0]))
3091 $title = $bookmark[2][0];
3093 if (isset($bookmark[1][0]))
3094 $link = $bookmark[1][0];
3096 if (strpos($shared[1],$title) !== false)
3099 if (strpos($shared[1],$link) !== false)
3102 $text = trim($shared[1]);
3104 //if (strlen($text) < strlen($title))
3105 if (($text == "") AND ($title != ""))
3106 $text .= "\n\n".trim($title);
3109 $text .= "\n".trim($link);
3111 return(trim($text));
3114 function api_best_nickname(&$contacts) {
3115 $best_contact = array();
3117 if (count($contact) == 0)
3120 foreach ($contacts AS $contact)
3121 if ($contact["network"] == "") {
3122 $contact["network"] = "dfrn";
3123 $best_contact = array($contact);
3126 if (sizeof($best_contact) == 0)
3127 foreach ($contacts AS $contact)
3128 if ($contact["network"] == "dfrn")
3129 $best_contact = array($contact);
3131 if (sizeof($best_contact) == 0)
3132 foreach ($contacts AS $contact)
3133 if ($contact["network"] == "dspr")
3134 $best_contact = array($contact);
3136 if (sizeof($best_contact) == 0)
3137 foreach ($contacts AS $contact)
3138 if ($contact["network"] == "stat")
3139 $best_contact = array($contact);
3141 if (sizeof($best_contact) == 0)
3142 foreach ($contacts AS $contact)
3143 if ($contact["network"] == "pump")
3144 $best_contact = array($contact);
3146 if (sizeof($best_contact) == 0)
3147 foreach ($contacts AS $contact)
3148 if ($contact["network"] == "twit")
3149 $best_contact = array($contact);
3151 if (sizeof($best_contact) == 1)
3152 $contacts = $best_contact;
3154 $contacts = array($contacts[0]);
3157 // return all or a specified group of the user with the containing contacts
3158 function api_friendica_group_show(&$a, $type) {
3159 if (api_user()===false) throw new ForbiddenException();
3162 $user_info = api_get_user($a);
3163 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3164 $uid = $user_info['uid'];
3166 // get data of the specified group id or all groups if not specified
3168 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3171 // error message if specified gid is not in database
3173 throw new BadRequestException("gid not available");
3176 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3179 // loop through all groups and retrieve all members for adding data in the user array
3180 foreach ($r as $rr) {
3181 $members = group_get_members($rr['id']);
3183 foreach ($members as $member) {
3184 $user = api_get_user($a, $member['nurl']);
3187 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3189 return api_apply_template("group_show", $type, array('$groups' => $grps));
3191 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3194 // delete the specified group of the user
3195 function api_friendica_group_delete(&$a, $type) {
3196 if (api_user()===false) throw new ForbiddenException();
3199 $user_info = api_get_user($a);
3200 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3201 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3202 $uid = $user_info['uid'];
3204 // error if no gid specified
3205 if ($gid == 0 || $name == "")
3206 throw new BadRequestException('gid or name not specified');
3208 // get data of the specified group id
3209 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3212 // error message if specified gid is not in database
3214 throw new BadRequestException('gid not available');
3216 // get data of the specified group id and group name
3217 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3221 // error message if specified gid is not in database
3222 if (count($rname) == 0)
3223 throw new BadRequestException('wrong group name');
3226 $ret = group_rmv($uid, $name);
3229 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3230 return api_apply_template("group_delete", $type, array('$result' => $success));
3233 throw new BadRequestException('other API error');
3235 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3238 // create the specified group with the posted array of contacts
3239 function api_friendica_group_create(&$a, $type) {
3240 if (api_user()===false) throw new ForbiddenException();
3243 $user_info = api_get_user($a);
3244 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3245 $uid = $user_info['uid'];
3246 $json = json_decode($_POST['json'], true);
3247 $users = $json['user'];
3249 // error if no name specified
3251 throw new BadRequestException('group name not specified');
3253 // get data of the specified group name
3254 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3257 // error message if specified group name already exists
3258 if (count($rname) != 0)
3259 throw new BadRequestException('group name already exists');
3261 // check if specified group name is a deleted group
3262 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3265 // error message if specified group name already exists
3266 if (count($rname) != 0)
3267 $reactivate_group = true;
3270 $ret = group_add($uid, $name);
3272 $gid = group_byname($uid, $name);
3274 throw new BadRequestException('other API error');
3277 $erroraddinguser = false;
3278 $errorusers = array();
3279 foreach ($users as $user) {
3280 $cid = $user['cid'];
3281 // check if user really exists as contact
3282 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3285 if (count($contact))
3286 $result = group_add_member($uid, $name, $cid, $gid);
3288 $erroraddinguser = true;
3289 $errorusers[] = $cid;
3293 // return success message incl. missing users in array
3294 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3295 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3296 return api_apply_template("group_create", $type, array('result' => $success));
3298 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3301 // update the specified group with the posted array of contacts
3302 function api_friendica_group_update(&$a, $type) {
3303 if (api_user()===false) throw new ForbiddenException();
3306 $user_info = api_get_user($a);
3307 $uid = $user_info['uid'];
3308 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3309 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3310 $json = json_decode($_POST['json'], true);
3311 $users = $json['user'];
3313 // error if no name specified
3315 throw new BadRequestException('group name not specified');
3317 // error if no gid specified
3319 throw new BadRequestException('gid not specified');
3322 $members = group_get_members($gid);
3323 foreach ($members as $member) {
3324 $cid = $member['id'];
3325 foreach ($users as $user) {
3326 $found = ($user['cid'] == $cid ? true : false);
3329 $ret = group_rmv_member($uid, $name, $cid);
3334 $erroraddinguser = false;
3335 $errorusers = array();
3336 foreach ($users as $user) {
3337 $cid = $user['cid'];
3338 // check if user really exists as contact
3339 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3342 if (count($contact))
3343 $result = group_add_member($uid, $name, $cid, $gid);
3345 $erroraddinguser = true;
3346 $errorusers[] = $cid;
3350 // return success message incl. missing users in array
3351 $status = ($erroraddinguser ? "missing user" : "ok");
3352 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3353 return api_apply_template("group_update", $type, array('result' => $success));
3355 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3358 function api_friendica_activity(&$a, $type) {
3359 if (api_user()===false) throw new ForbiddenException();
3360 $verb = strtolower($a->argv[3]);
3361 $verb = preg_replace("|\..*$|", "", $verb);
3363 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3365 $res = do_like($id, $verb);
3372 return api_apply_template('test', $type, array('ok' => $ok));
3374 throw new BadRequestException('Error adding activity');
3378 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3379 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3380 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3381 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3382 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3383 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3384 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3385 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3386 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3387 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3391 [pagename] => api/1.1/statuses/lookup.json
3392 [id] => 605138389168451584
3393 [include_cards] => true
3394 [cards_platform] => Android-12
3395 [include_entities] => true
3396 [include_my_retweet] => 1
3398 [include_reply_count] => true
3399 [include_descendent_reply_count] => true
3403 Not implemented by now:
3404 statuses/retweets_of_me
3409 account/update_location
3410 account/update_profile_background_image
3411 account/update_profile_image
3415 Not implemented in status.net:
3416 statuses/retweeted_to_me
3417 statuses/retweeted_by_me
3418 direct_messages/destroy
3420 account/update_delivery_device
3421 notifications/follow