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
1555 AND `item`.`id`=%d",
1559 if ($r[0]['body'] != "") {
1560 if (!intval(get_config('system','old_share'))) {
1561 if (strpos($r[0]['body'], "[/share]") !== false) {
1562 $pos = strpos($r[0]['body'], "[share");
1563 $post = substr($r[0]['body'], $pos);
1565 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1567 $post .= $r[0]['body'];
1568 $post .= "[/share]";
1570 $_REQUEST['body'] = $post;
1572 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1574 $_REQUEST['profile_uid'] = api_user();
1575 $_REQUEST['type'] = 'wall';
1576 $_REQUEST['api_source'] = true;
1578 if (!x($_REQUEST, "source"))
1579 $_REQUEST["source"] = api_source();
1584 // this should output the last post (the one we just posted).
1586 return(api_status_show($a,$type));
1588 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1593 function api_statuses_destroy(&$a, $type){
1594 if (api_user()===false) throw new ForbiddenException();
1596 $user_info = api_get_user($a);
1599 $id = intval($a->argv[3]);
1602 $id = intval($_REQUEST["id"]);
1606 $id = intval($a->argv[4]);
1608 logger('API: api_statuses_destroy: '.$id);
1610 $ret = api_statuses_show($a, $type);
1612 drop_item($id, false);
1616 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1620 * http://developer.twitter.com/doc/get/statuses/mentions
1623 function api_statuses_mentions(&$a, $type){
1624 if (api_user()===false) throw new ForbiddenException();
1626 unset($_REQUEST["user_id"]);
1627 unset($_GET["user_id"]);
1629 unset($_REQUEST["screen_name"]);
1630 unset($_GET["screen_name"]);
1632 $user_info = api_get_user($a);
1633 // get last newtork messages
1637 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1638 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1639 if ($page<0) $page=0;
1640 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1641 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1642 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1644 $start = $page*$count;
1646 // Ugly code - should be changed
1647 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1648 $myurl = substr($myurl,strpos($myurl,'://')+3);
1649 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1650 $myurl = str_replace('www.','',$myurl);
1651 $diasp_url = str_replace('/profile/','/u/',$myurl);
1654 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1656 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1657 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1658 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1659 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1660 FROM `item`, `contact`
1661 WHERE `item`.`uid` = %d AND `verb` = '%s'
1662 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1663 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1664 AND `contact`.`id` = `item`.`contact-id`
1665 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1666 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1669 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1671 dbesc(ACTIVITY_POST),
1672 dbesc(protect_sprintf($myurl)),
1673 dbesc(protect_sprintf($myurl)),
1676 intval($start), intval($count)
1679 $ret = api_format_items($r,$user_info);
1682 $data = array('$statuses' => $ret);
1686 $data = api_rss_extra($a, $data, $user_info);
1689 $as = api_format_as($a, $ret, $user_info);
1690 $as["title"] = $a->config['sitename']." Mentions";
1691 $as['link']['url'] = $a->get_baseurl()."/";
1696 return api_apply_template("timeline", $type, $data);
1698 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1699 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1702 function api_statuses_user_timeline(&$a, $type){
1703 if (api_user()===false) throw new ForbiddenException();
1705 $user_info = api_get_user($a);
1706 // get last network messages
1708 logger("api_statuses_user_timeline: api_user: ". api_user() .
1709 "\nuser_info: ".print_r($user_info, true) .
1710 "\n_REQUEST: ".print_r($_REQUEST, true),
1714 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1715 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1716 if ($page<0) $page=0;
1717 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1718 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1719 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1720 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1722 $start = $page*$count;
1725 if ($user_info['self']==1)
1726 $sql_extra .= " AND `item`.`wall` = 1 ";
1728 if ($exclude_replies > 0)
1729 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1730 if ($conversation_id > 0)
1731 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1733 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1734 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1735 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1736 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1737 FROM `item`, `contact`
1738 WHERE `item`.`uid` = %d AND `verb` = '%s'
1739 AND `item`.`contact-id` = %d
1740 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1741 AND `contact`.`id` = `item`.`contact-id`
1742 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1745 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1747 dbesc(ACTIVITY_POST),
1748 intval($user_info['cid']),
1750 intval($start), intval($count)
1753 $ret = api_format_items($r,$user_info, true);
1755 $data = array('$statuses' => $ret);
1759 $data = api_rss_extra($a, $data, $user_info);
1762 return api_apply_template("timeline", $type, $data);
1764 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1768 * Star/unstar an item
1769 * param: id : id of the item
1771 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1773 function api_favorites_create_destroy(&$a, $type){
1774 if (api_user()===false) throw new ForbiddenException();
1776 // for versioned api.
1777 /// @TODO We need a better global soluton
1779 if ($a->argv[1]=="1.1") $action_argv_id=3;
1781 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1782 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1783 if ($a->argc==$action_argv_id+2) {
1784 $itemid = intval($a->argv[$action_argv_id+1]);
1786 $itemid = intval($_REQUEST['id']);
1789 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1790 $itemid, api_user());
1792 if ($item===false || count($item)==0)
1793 throw new BadRequestException("Invalid item.");
1797 $item[0]['starred']=1;
1800 $item[0]['starred']=0;
1803 throw new BadRequestException("Invalid action ".$action);
1805 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1806 $item[0]['starred'], $itemid, api_user());
1808 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1809 $item[0]['starred'], $itemid, api_user());
1812 throw InternalServerErrorException("DB error");
1815 $user_info = api_get_user($a);
1816 $rets = api_format_items($item,$user_info);
1819 $data = array('$status' => $ret);
1823 $data = api_rss_extra($a, $data, $user_info);
1826 return api_apply_template("status", $type, $data);
1828 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1829 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1831 function api_favorites(&$a, $type){
1834 if (api_user()===false) throw new ForbiddenException();
1836 $called_api= array();
1838 $user_info = api_get_user($a);
1840 // in friendica starred item are private
1841 // return favorites only for self
1842 logger('api_favorites: self:' . $user_info['self']);
1844 if ($user_info['self']==0) {
1850 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1851 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1852 $count = (x($_GET,'count')?$_GET['count']:20);
1853 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1854 if ($page<0) $page=0;
1856 $start = $page*$count;
1859 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1861 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1862 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1863 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1864 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1865 FROM `item`, `contact`
1866 WHERE `item`.`uid` = %d
1867 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1868 AND `item`.`starred` = 1
1869 AND `contact`.`id` = `item`.`contact-id`
1870 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1873 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1876 intval($start), intval($count)
1879 $ret = api_format_items($r,$user_info);
1883 $data = array('$statuses' => $ret);
1887 $data = api_rss_extra($a, $data, $user_info);
1890 return api_apply_template("timeline", $type, $data);
1892 api_register_func('api/favorites','api_favorites', true);
1897 function api_format_as($a, $ret, $user_info) {
1899 $as['title'] = $a->config['sitename']." Public Timeline";
1901 foreach ($ret as $item) {
1902 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1903 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1904 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1905 $avatar[0]["rel"] = "avatar";
1906 $avatar[0]["type"] = "";
1907 $avatar[0]["width"] = 96;
1908 $avatar[0]["height"] = 96;
1909 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1910 $avatar[1]["rel"] = "avatar";
1911 $avatar[1]["type"] = "";
1912 $avatar[1]["width"] = 48;
1913 $avatar[1]["height"] = 48;
1914 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1915 $avatar[2]["rel"] = "avatar";
1916 $avatar[2]["type"] = "";
1917 $avatar[2]["width"] = 24;
1918 $avatar[2]["height"] = 24;
1919 $singleitem["actor"]["avatarLinks"] = $avatar;
1921 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1922 $singleitem["actor"]["image"]["rel"] = "avatar";
1923 $singleitem["actor"]["image"]["type"] = "";
1924 $singleitem["actor"]["image"]["width"] = 96;
1925 $singleitem["actor"]["image"]["height"] = 96;
1926 $singleitem["actor"]["type"] = "person";
1927 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1928 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1929 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1930 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1931 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1932 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1933 $singleitem["actor"]["contact"]["addresses"] = "";
1935 $singleitem["body"] = $item["text"];
1936 $singleitem["object"]["displayName"] = $item["text"];
1937 $singleitem["object"]["id"] = $item["url"];
1938 $singleitem["object"]["type"] = "note";
1939 $singleitem["object"]["url"] = $item["url"];
1940 //$singleitem["context"] =;
1941 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1942 $singleitem["provider"]["objectType"] = "service";
1943 $singleitem["provider"]["displayName"] = "Test";
1944 $singleitem["provider"]["url"] = "http://test.tld";
1945 $singleitem["title"] = $item["text"];
1946 $singleitem["verb"] = "post";
1947 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1948 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1949 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1950 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1951 //$singleitem["original"] = $item;
1952 $items[] = $singleitem;
1954 $as['items'] = $items;
1955 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1956 $as['link']['rel'] = "alternate";
1957 $as['link']['type'] = "text/html";
1961 function api_format_messages($item, $recipient, $sender) {
1962 // standard meta information
1964 'id' => $item['id'],
1965 'sender_id' => $sender['id'] ,
1967 'recipient_id' => $recipient['id'],
1968 'created_at' => api_date($item['created']),
1969 'sender_screen_name' => $sender['screen_name'],
1970 'recipient_screen_name' => $recipient['screen_name'],
1971 'sender' => $sender,
1972 'recipient' => $recipient,
1975 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1976 unset($ret["sender"]["uid"]);
1977 unset($ret["sender"]["self"]);
1978 unset($ret["recipient"]["uid"]);
1979 unset($ret["recipient"]["self"]);
1981 //don't send title to regular StatusNET requests to avoid confusing these apps
1982 if (x($_GET, 'getText')) {
1983 $ret['title'] = $item['title'] ;
1984 if ($_GET["getText"] == "html") {
1985 $ret['text'] = bbcode($item['body'], false, false);
1987 elseif ($_GET["getText"] == "plain") {
1988 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1989 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1993 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1995 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1996 unset($ret['sender']);
1997 unset($ret['recipient']);
2003 function api_convert_item($item) {
2005 $body = $item['body'];
2006 $attachments = api_get_attachments($body);
2008 // Workaround for ostatus messages where the title is identically to the body
2009 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2010 $statusbody = trim(html2plain($html, 0));
2012 // handle data: images
2013 $statusbody = api_format_items_embeded_images($item,$statusbody);
2015 $statustitle = trim($item['title']);
2017 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2018 $statustext = trim($statusbody);
2020 $statustext = trim($statustitle."\n\n".$statusbody);
2022 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2023 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2025 $statushtml = trim(bbcode($body, false, false));
2027 if ($item['title'] != "")
2028 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2030 $entities = api_get_entitities($statustext, $body);
2032 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2035 function api_get_attachments(&$body) {
2038 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2040 $URLSearchString = "^\[\]";
2041 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2046 $attachments = array();
2048 foreach ($images[1] AS $image) {
2049 $imagedata = get_photo_info($image);
2052 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2055 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2056 foreach ($images[0] AS $orig)
2057 $body = str_replace($orig, "", $body);
2059 return $attachments;
2062 function api_get_entitities(&$text, $bbcode) {
2065 * Links at the first character of the post
2070 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2072 if ($include_entities != "true") {
2074 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2076 foreach ($images[1] AS $image) {
2077 $replace = proxy_url($image);
2078 $text = str_replace($image, $replace, $text);
2083 $bbcode = bb_CleanPictureLinks($bbcode);
2085 // Change pure links in text to bbcode uris
2086 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2088 $entities = array();
2089 $entities["hashtags"] = array();
2090 $entities["symbols"] = array();
2091 $entities["urls"] = array();
2092 $entities["user_mentions"] = array();
2094 $URLSearchString = "^\[\]";
2096 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2098 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2099 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2100 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2102 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2103 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2104 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2106 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2107 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2108 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2110 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2112 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2113 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2115 $ordered_urls = array();
2116 foreach ($urls[1] AS $id=>$url) {
2117 //$start = strpos($text, $url, $offset);
2118 $start = iconv_strpos($text, $url, 0, "UTF-8");
2119 if (!($start === false))
2120 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2123 ksort($ordered_urls);
2126 //foreach ($urls[1] AS $id=>$url) {
2127 foreach ($ordered_urls AS $url) {
2128 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2129 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2130 $display_url = $url["title"];
2132 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2133 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2135 if (strlen($display_url) > 26)
2136 $display_url = substr($display_url, 0, 25)."…";
2139 //$start = strpos($text, $url, $offset);
2140 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2141 if (!($start === false)) {
2142 $entities["urls"][] = array("url" => $url["url"],
2143 "expanded_url" => $url["url"],
2144 "display_url" => $display_url,
2145 "indices" => array($start, $start+strlen($url["url"])));
2146 $offset = $start + 1;
2150 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2151 $ordered_images = array();
2152 foreach ($images[1] AS $image) {
2153 //$start = strpos($text, $url, $offset);
2154 $start = iconv_strpos($text, $image, 0, "UTF-8");
2155 if (!($start === false))
2156 $ordered_images[$start] = $image;
2158 //$entities["media"] = array();
2161 foreach ($ordered_images AS $url) {
2162 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2163 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2165 if (strlen($display_url) > 26)
2166 $display_url = substr($display_url, 0, 25)."…";
2168 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2169 if (!($start === false)) {
2170 $image = get_photo_info($url);
2172 // If image cache is activated, then use the following sizes:
2173 // thumb (150), small (340), medium (600) and large (1024)
2174 if (!get_config("system", "proxy_disabled")) {
2175 $media_url = proxy_url($url);
2178 $scale = scale_image($image[0], $image[1], 150);
2179 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2181 if (($image[0] > 150) OR ($image[1] > 150)) {
2182 $scale = scale_image($image[0], $image[1], 340);
2183 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2186 $scale = scale_image($image[0], $image[1], 600);
2187 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2189 if (($image[0] > 600) OR ($image[1] > 600)) {
2190 $scale = scale_image($image[0], $image[1], 1024);
2191 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2195 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2198 $entities["media"][] = array(
2200 "id_str" => (string)$start+1,
2201 "indices" => array($start, $start+strlen($url)),
2202 "media_url" => normalise_link($media_url),
2203 "media_url_https" => $media_url,
2205 "display_url" => $display_url,
2206 "expanded_url" => $url,
2210 $offset = $start + 1;
2216 function api_format_items_embeded_images(&$item, $text){
2218 $text = preg_replace_callback(
2219 "|data:image/([^;]+)[^=]+=*|m",
2220 function($match) use ($a, $item) {
2221 return $a->get_baseurl()."/display/".$item['guid'];
2228 * @brief return likes, dislikes and attend status for item
2230 * @param array $item
2232 * likes => int count
2233 * dislikes => int count
2235 function api_format_items_likes(&$item) {
2236 $activities = array(
2238 'dislike' => array(),
2239 'attendyes' => array(),
2240 'attendno' => array(),
2241 'attendmaybe' => array()
2243 $items = q('SELECT * FROM item
2244 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2245 intval($item['uid']),
2246 dbesc($item['uri']));
2247 foreach ($items as $i){
2248 builtin_activity_puller($i, $activities);
2252 $uri = $item['uri'];
2253 foreach($activities as $k => $v) {
2254 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2261 * @brief format items to be returned by api
2263 * @param array $r array of items
2264 * @param array $user_info
2265 * @param bool $filter_user filter items by $user_info
2267 function api_format_items($r,$user_info, $filter_user = false) {
2272 foreach($r as $item) {
2273 api_share_as_retweet($item);
2275 localize_item($item);
2276 $status_user = api_item_get_user($a,$item);
2278 // Look if the posts are matching if they should be filtered by user id
2279 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2282 if ($item['thr-parent'] != $item['uri']) {
2283 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2285 dbesc($item['thr-parent']));
2287 $in_reply_to_status_id = intval($r[0]['id']);
2289 $in_reply_to_status_id = intval($item['parent']);
2291 $in_reply_to_status_id_str = (string) intval($item['parent']);
2293 $in_reply_to_screen_name = NULL;
2294 $in_reply_to_user_id = NULL;
2295 $in_reply_to_user_id_str = NULL;
2297 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2299 intval($in_reply_to_status_id));
2301 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2304 if ($r[0]['nick'] == "")
2305 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2307 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2308 $in_reply_to_user_id = intval($r[0]['id']);
2309 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2313 $in_reply_to_screen_name = NULL;
2314 $in_reply_to_user_id = NULL;
2315 $in_reply_to_status_id = NULL;
2316 $in_reply_to_user_id_str = NULL;
2317 $in_reply_to_status_id_str = NULL;
2320 $converted = api_convert_item($item);
2323 'text' => $converted["text"],
2324 'truncated' => False,
2325 'created_at'=> api_date($item['created']),
2326 'in_reply_to_status_id' => $in_reply_to_status_id,
2327 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2328 'source' => (($item['app']) ? $item['app'] : 'web'),
2329 'id' => intval($item['id']),
2330 'id_str' => (string) intval($item['id']),
2331 'in_reply_to_user_id' => $in_reply_to_user_id,
2332 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2333 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2335 'favorited' => $item['starred'] ? true : false,
2336 'user' => $status_user ,
2337 //'entities' => NULL,
2338 'statusnet_html' => $converted["html"],
2339 'statusnet_conversation_id' => $item['parent'],
2340 'friendica_activities' => api_format_items_likes($item),
2343 if (count($converted["attachments"]) > 0)
2344 $status["attachments"] = $converted["attachments"];
2346 if (count($converted["entities"]) > 0)
2347 $status["entities"] = $converted["entities"];
2349 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2350 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2351 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2352 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2355 // Retweets are only valid for top postings
2356 // It doesn't work reliable with the link if its a feed
2357 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2359 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2361 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2362 $retweeted_status = $status;
2363 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2365 $status["retweeted_status"] = $retweeted_status;
2368 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2369 unset($status["user"]["uid"]);
2370 unset($status["user"]["self"]);
2372 if ($item["coord"] != "") {
2373 $coords = explode(' ',$item["coord"]);
2374 if (count($coords) == 2) {
2375 $status["geo"] = array('type' => 'Point',
2376 'coordinates' => array((float) $coords[0],
2377 (float) $coords[1]));
2387 function api_account_rate_limit_status(&$a,$type) {
2389 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2390 'remaining_hits' => (string) 150,
2391 'hourly_limit' => (string) 150,
2392 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2395 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2397 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2399 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2401 function api_help_test(&$a,$type) {
2407 return api_apply_template('test', $type, array("$ok" => $ok));
2409 api_register_func('api/help/test','api_help_test',false);
2411 function api_lists(&$a,$type) {
2415 api_register_func('api/lists','api_lists',true);
2417 function api_lists_list(&$a,$type) {
2421 api_register_func('api/lists/list','api_lists_list',true);
2424 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2425 * This function is deprecated by Twitter
2426 * returns: json, xml
2428 function api_statuses_f(&$a, $type, $qtype) {
2429 if (api_user()===false) throw new ForbiddenException();
2430 $user_info = api_get_user($a);
2432 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2433 /* this is to stop Hotot to load friends multiple times
2434 * I'm not sure if I'm missing return something or
2435 * is a bug in hotot. Workaround, meantime
2439 return array('$users' => $ret);*/
2443 if($qtype == 'friends')
2444 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2445 if($qtype == 'followers')
2446 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2448 // friends and followers only for self
2449 if ($user_info['self'] == 0)
2450 $sql_extra = " AND false ";
2452 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2457 foreach($r as $cid){
2458 $user = api_get_user($a, $cid['nurl']);
2459 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2460 unset($user["uid"]);
2461 unset($user["self"]);
2467 return array('$users' => $ret);
2470 function api_statuses_friends(&$a, $type){
2471 $data = api_statuses_f($a,$type,"friends");
2472 if ($data===false) return false;
2473 return api_apply_template("friends", $type, $data);
2475 function api_statuses_followers(&$a, $type){
2476 $data = api_statuses_f($a,$type,"followers");
2477 if ($data===false) return false;
2478 return api_apply_template("friends", $type, $data);
2480 api_register_func('api/statuses/friends','api_statuses_friends',true);
2481 api_register_func('api/statuses/followers','api_statuses_followers',true);
2488 function api_statusnet_config(&$a,$type) {
2489 $name = $a->config['sitename'];
2490 $server = $a->get_hostname();
2491 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2492 $email = $a->config['admin_email'];
2493 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2494 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2495 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2496 if($a->config['api_import_size'])
2497 $texlimit = string($a->config['api_import_size']);
2498 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2499 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2502 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2503 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2504 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2505 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2506 'shorturllength' => '30',
2507 'friendica' => array(
2508 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2509 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2510 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2511 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2516 return api_apply_template('config', $type, array('$config' => $config));
2519 api_register_func('api/statusnet/config','api_statusnet_config',false);
2521 function api_statusnet_version(&$a,$type) {
2523 $fake_statusnet_version = "0.9.7";
2525 if($type === 'xml') {
2526 header("Content-type: application/xml");
2527 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2530 elseif($type === 'json') {
2531 header("Content-type: application/json");
2532 echo '"'.$fake_statusnet_version.'"';
2536 api_register_func('api/statusnet/version','api_statusnet_version',false);
2539 * @todo use api_apply_template() to return data
2541 function api_ff_ids(&$a,$type,$qtype) {
2542 if(! api_user()) throw new ForbiddenException();
2544 $user_info = api_get_user($a);
2546 if($qtype == 'friends')
2547 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2548 if($qtype == 'followers')
2549 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2551 if (!$user_info["self"])
2552 $sql_extra = " AND false ";
2554 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2556 $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",
2562 if($type === 'xml') {
2563 header("Content-type: application/xml");
2564 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2566 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2567 echo '</ids>' . "\r\n";
2570 elseif($type === 'json') {
2572 header("Content-type: application/json");
2577 $ret[] = intval($rr['id']);
2579 echo json_encode($ret);
2585 function api_friends_ids(&$a,$type) {
2586 api_ff_ids($a,$type,'friends');
2588 function api_followers_ids(&$a,$type) {
2589 api_ff_ids($a,$type,'followers');
2591 api_register_func('api/friends/ids','api_friends_ids',true);
2592 api_register_func('api/followers/ids','api_followers_ids',true);
2595 function api_direct_messages_new(&$a, $type) {
2596 if (api_user()===false) throw new ForbiddenException();
2598 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2600 $sender = api_get_user($a);
2602 if ($_POST['screen_name']) {
2603 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2605 dbesc($_POST['screen_name']));
2607 // Selecting the id by priority, friendica first
2608 api_best_nickname($r);
2610 $recipient = api_get_user($a, $r[0]['nurl']);
2612 $recipient = api_get_user($a, $_POST['user_id']);
2616 if (x($_REQUEST,'replyto')) {
2617 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2619 intval($_REQUEST['replyto']));
2620 $replyto = $r[0]['parent-uri'];
2621 $sub = $r[0]['title'];
2624 if (x($_REQUEST,'title')) {
2625 $sub = $_REQUEST['title'];
2628 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2632 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2635 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2636 $ret = api_format_messages($r[0], $recipient, $sender);
2639 $ret = array("error"=>$id);
2642 $data = Array('$messages'=>$ret);
2647 $data = api_rss_extra($a, $data, $user_info);
2650 return api_apply_template("direct_messages", $type, $data);
2653 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2655 function api_direct_messages_box(&$a, $type, $box) {
2656 if (api_user()===false) throw new ForbiddenException();
2659 $count = (x($_GET,'count')?$_GET['count']:20);
2660 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2661 if ($page<0) $page=0;
2663 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2664 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2666 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2667 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2670 unset($_REQUEST["user_id"]);
2671 unset($_GET["user_id"]);
2673 unset($_REQUEST["screen_name"]);
2674 unset($_GET["screen_name"]);
2676 $user_info = api_get_user($a);
2677 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2678 $profile_url = $user_info["url"];
2682 $start = $page*$count;
2685 if ($box=="sentbox") {
2686 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2688 elseif ($box=="conversation") {
2689 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2691 elseif ($box=="all") {
2692 $sql_extra = "true";
2694 elseif ($box=="inbox") {
2695 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2699 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2701 if ($user_id !="") {
2702 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2704 elseif($screen_name !=""){
2705 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2708 $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",
2711 intval($start), intval($count)
2716 foreach($r as $item) {
2717 if ($box == "inbox" || $item['from-url'] != $profile_url){
2718 $recipient = $user_info;
2719 $sender = api_get_user($a,normalise_link($item['contact-url']));
2721 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2722 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2723 $sender = $user_info;
2726 $ret[]=api_format_messages($item, $recipient, $sender);
2730 $data = array('$messages' => $ret);
2734 $data = api_rss_extra($a, $data, $user_info);
2737 return api_apply_template("direct_messages", $type, $data);
2741 function api_direct_messages_sentbox(&$a, $type){
2742 return api_direct_messages_box($a, $type, "sentbox");
2744 function api_direct_messages_inbox(&$a, $type){
2745 return api_direct_messages_box($a, $type, "inbox");
2747 function api_direct_messages_all(&$a, $type){
2748 return api_direct_messages_box($a, $type, "all");
2750 function api_direct_messages_conversation(&$a, $type){
2751 return api_direct_messages_box($a, $type, "conversation");
2753 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2754 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2755 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2756 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2760 function api_oauth_request_token(&$a, $type){
2762 $oauth = new FKOAuth1();
2763 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2764 }catch(Exception $e){
2765 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2770 function api_oauth_access_token(&$a, $type){
2772 $oauth = new FKOAuth1();
2773 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2774 }catch(Exception $e){
2775 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2781 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2782 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2785 function api_fr_photos_list(&$a,$type) {
2786 if (api_user()===false) throw new ForbiddenException();
2787 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2788 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2789 intval(local_user())
2792 'image/jpeg' => 'jpg',
2793 'image/png' => 'png',
2794 'image/gif' => 'gif'
2796 $data = array('photos'=>array());
2798 foreach($r as $rr) {
2800 $photo['id'] = $rr['resource-id'];
2801 $photo['album'] = $rr['album'];
2802 $photo['filename'] = $rr['filename'];
2803 $photo['type'] = $rr['type'];
2804 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2805 $data['photos'][] = $photo;
2808 return api_apply_template("photos_list", $type, $data);
2811 function api_fr_photo_detail(&$a,$type) {
2812 if (api_user()===false) throw new ForbiddenException();
2813 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2815 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2816 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2817 $data_sql = ($scale === false ? "" : "data, ");
2819 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2820 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2821 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2823 intval(local_user()),
2824 dbesc($_REQUEST['photo_id']),
2829 'image/jpeg' => 'jpg',
2830 'image/png' => 'png',
2831 'image/gif' => 'gif'
2835 $data = array('photo' => $r[0]);
2836 if ($scale !== false) {
2837 $data['photo']['data'] = base64_encode($data['photo']['data']);
2839 unset($data['photo']['datasize']); //needed only with scale param
2841 $data['photo']['link'] = array();
2842 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2843 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2845 $data['photo']['id'] = $data['photo']['resource-id'];
2846 unset($data['photo']['resource-id']);
2847 unset($data['photo']['minscale']);
2848 unset($data['photo']['maxscale']);
2851 throw new NotFoundException();
2854 return api_apply_template("photo_detail", $type, $data);
2857 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2858 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2863 * similar as /mod/redir.php
2864 * redirect to 'url' after dfrn auth
2866 * why this when there is mod/redir.php already?
2867 * This use api_user() and api_login()
2870 * c_url: url of remote contact to auth to
2871 * url: string, url to redirect after auth
2873 function api_friendica_remoteauth(&$a) {
2874 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2875 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2877 if ($url === '' || $c_url === '')
2878 throw new BadRequestException("Wrong parameters.");
2880 $c_url = normalise_link($c_url);
2884 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2889 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2890 throw new BadRequestException("Unknown contact");
2894 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2896 if($r[0]['duplex'] && $r[0]['issued-id']) {
2897 $orig_id = $r[0]['issued-id'];
2898 $dfrn_id = '1:' . $orig_id;
2900 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2901 $orig_id = $r[0]['dfrn-id'];
2902 $dfrn_id = '0:' . $orig_id;
2905 $sec = random_string();
2907 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2908 VALUES( %d, %s, '%s', '%s', %d )",
2916 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2917 $dest = (($url) ? '&destination_url=' . $url : '');
2918 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2919 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2920 . '&type=profile&sec=' . $sec . $dest . $quiet );
2922 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2925 function api_share_as_retweet(&$item) {
2926 $body = trim($item["body"]);
2928 // Skip if it isn't a pure repeated messages
2929 // Does it start with a share?
2930 if (strpos($body, "[share") > 0)
2933 // Does it end with a share?
2934 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2937 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2938 // Skip if there is no shared message in there
2939 if ($body == $attributes)
2943 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2944 if ($matches[1] != "")
2945 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2947 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2948 if ($matches[1] != "")
2949 $author = $matches[1];
2952 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2953 if ($matches[1] != "")
2954 $profile = $matches[1];
2956 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2957 if ($matches[1] != "")
2958 $profile = $matches[1];
2961 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2962 if ($matches[1] != "")
2963 $avatar = $matches[1];
2965 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2966 if ($matches[1] != "")
2967 $avatar = $matches[1];
2970 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2971 if ($matches[1] != "")
2972 $link = $matches[1];
2974 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2975 if ($matches[1] != "")
2976 $link = $matches[1];
2978 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2980 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2983 $item["body"] = $shared_body;
2984 $item["author-name"] = $author;
2985 $item["author-link"] = $profile;
2986 $item["author-avatar"] = $avatar;
2987 $item["plink"] = $link;
2993 function api_get_nick($profile) {
2995 - remove trailing junk from profile url
2996 - pump.io check has to check the website
3001 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3002 dbesc(normalise_link($profile)));
3004 $nick = $r[0]["nick"];
3007 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3008 dbesc(normalise_link($profile)));
3010 $nick = $r[0]["nick"];
3014 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3015 if ($friendica != $profile)
3020 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3021 if ($diaspora != $profile)
3026 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3027 if ($twitter != $profile)
3033 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3034 if ($StatusnetHost != $profile) {
3035 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3036 if ($StatusnetUser != $profile) {
3037 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3038 $user = json_decode($UserData);
3040 $nick = $user->screen_name;
3045 // To-Do: look at the page if its really a pumpio site
3046 //if (!$nick == "") {
3047 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3048 // if ($pumpio != $profile)
3050 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3060 function api_clean_plain_items($Text) {
3061 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3063 $Text = bb_CleanPictureLinks($Text);
3065 $URLSearchString = "^\[\]";
3067 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3069 if ($include_entities == "true") {
3070 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3073 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
3077 function api_cleanup_share($shared) {
3078 if ($shared[2] != "type-link")
3081 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
3087 if (isset($bookmark[2][0]))
3088 $title = $bookmark[2][0];
3090 if (isset($bookmark[1][0]))
3091 $link = $bookmark[1][0];
3093 if (strpos($shared[1],$title) !== false)
3096 if (strpos($shared[1],$link) !== false)
3099 $text = trim($shared[1]);
3101 //if (strlen($text) < strlen($title))
3102 if (($text == "") AND ($title != ""))
3103 $text .= "\n\n".trim($title);
3106 $text .= "\n".trim($link);
3108 return(trim($text));
3111 function api_best_nickname(&$contacts) {
3112 $best_contact = array();
3114 if (count($contact) == 0)
3117 foreach ($contacts AS $contact)
3118 if ($contact["network"] == "") {
3119 $contact["network"] = "dfrn";
3120 $best_contact = array($contact);
3123 if (sizeof($best_contact) == 0)
3124 foreach ($contacts AS $contact)
3125 if ($contact["network"] == "dfrn")
3126 $best_contact = array($contact);
3128 if (sizeof($best_contact) == 0)
3129 foreach ($contacts AS $contact)
3130 if ($contact["network"] == "dspr")
3131 $best_contact = array($contact);
3133 if (sizeof($best_contact) == 0)
3134 foreach ($contacts AS $contact)
3135 if ($contact["network"] == "stat")
3136 $best_contact = array($contact);
3138 if (sizeof($best_contact) == 0)
3139 foreach ($contacts AS $contact)
3140 if ($contact["network"] == "pump")
3141 $best_contact = array($contact);
3143 if (sizeof($best_contact) == 0)
3144 foreach ($contacts AS $contact)
3145 if ($contact["network"] == "twit")
3146 $best_contact = array($contact);
3148 if (sizeof($best_contact) == 1)
3149 $contacts = $best_contact;
3151 $contacts = array($contacts[0]);
3154 // return all or a specified group of the user with the containing contacts
3155 function api_friendica_group_show(&$a, $type) {
3156 if (api_user()===false) throw new ForbiddenException();
3159 $user_info = api_get_user($a);
3160 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3161 $uid = $user_info['uid'];
3163 // get data of the specified group id or all groups if not specified
3165 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3168 // error message if specified gid is not in database
3170 throw new BadRequestException("gid not available");
3173 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3176 // loop through all groups and retrieve all members for adding data in the user array
3177 foreach ($r as $rr) {
3178 $members = group_get_members($rr['id']);
3180 foreach ($members as $member) {
3181 $user = api_get_user($a, $member['nurl']);
3184 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3186 return api_apply_template("group_show", $type, array('$groups' => $grps));
3188 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3191 // delete the specified group of the user
3192 function api_friendica_group_delete(&$a, $type) {
3193 if (api_user()===false) throw new ForbiddenException();
3196 $user_info = api_get_user($a);
3197 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3198 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3199 $uid = $user_info['uid'];
3201 // error if no gid specified
3202 if ($gid == 0 || $name == "")
3203 throw new BadRequestException('gid or name not specified');
3205 // get data of the specified group id
3206 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3209 // error message if specified gid is not in database
3211 throw new BadRequestException('gid not available');
3213 // get data of the specified group id and group name
3214 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3218 // error message if specified gid is not in database
3219 if (count($rname) == 0)
3220 throw new BadRequestException('wrong group name');
3223 $ret = group_rmv($uid, $name);
3226 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3227 return api_apply_template("group_delete", $type, array('$result' => $success));
3230 throw new BadRequestException('other API error');
3232 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3235 // create the specified group with the posted array of contacts
3236 function api_friendica_group_create(&$a, $type) {
3237 if (api_user()===false) throw new ForbiddenException();
3240 $user_info = api_get_user($a);
3241 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3242 $uid = $user_info['uid'];
3243 $json = json_decode($_POST['json'], true);
3244 $users = $json['user'];
3246 // error if no name specified
3248 throw new BadRequestException('group name not specified');
3250 // get data of the specified group name
3251 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3254 // error message if specified group name already exists
3255 if (count($rname) != 0)
3256 throw new BadRequestException('group name already exists');
3258 // check if specified group name is a deleted group
3259 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3262 // error message if specified group name already exists
3263 if (count($rname) != 0)
3264 $reactivate_group = true;
3267 $ret = group_add($uid, $name);
3269 $gid = group_byname($uid, $name);
3271 throw new BadRequestException('other API error');
3274 $erroraddinguser = false;
3275 $errorusers = array();
3276 foreach ($users as $user) {
3277 $cid = $user['cid'];
3278 // check if user really exists as contact
3279 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3282 if (count($contact))
3283 $result = group_add_member($uid, $name, $cid, $gid);
3285 $erroraddinguser = true;
3286 $errorusers[] = $cid;
3290 // return success message incl. missing users in array
3291 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3292 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3293 return api_apply_template("group_create", $type, array('result' => $success));
3295 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3298 // update the specified group with the posted array of contacts
3299 function api_friendica_group_update(&$a, $type) {
3300 if (api_user()===false) throw new ForbiddenException();
3303 $user_info = api_get_user($a);
3304 $uid = $user_info['uid'];
3305 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3306 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3307 $json = json_decode($_POST['json'], true);
3308 $users = $json['user'];
3310 // error if no name specified
3312 throw new BadRequestException('group name not specified');
3314 // error if no gid specified
3316 throw new BadRequestException('gid not specified');
3319 $members = group_get_members($gid);
3320 foreach ($members as $member) {
3321 $cid = $member['id'];
3322 foreach ($users as $user) {
3323 $found = ($user['cid'] == $cid ? true : false);
3326 $ret = group_rmv_member($uid, $name, $cid);
3331 $erroraddinguser = false;
3332 $errorusers = array();
3333 foreach ($users as $user) {
3334 $cid = $user['cid'];
3335 // check if user really exists as contact
3336 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3339 if (count($contact))
3340 $result = group_add_member($uid, $name, $cid, $gid);
3342 $erroraddinguser = true;
3343 $errorusers[] = $cid;
3347 // return success message incl. missing users in array
3348 $status = ($erroraddinguser ? "missing user" : "ok");
3349 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3350 return api_apply_template("group_update", $type, array('result' => $success));
3352 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3355 function api_friendica_activity(&$a, $type) {
3356 if (api_user()===false) throw new ForbiddenException();
3357 $verb = strtolower($a->argv[3]);
3358 $verb = preg_replace("|\..*$|", "", $verb);
3360 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3362 $res = do_like($id, $verb);
3369 return api_apply_template('test', $type, array('ok' => $ok));
3371 throw new BadRequestException('Error adding activity');
3375 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3376 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3377 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3378 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3379 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3380 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3381 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3382 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3383 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3384 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3388 [pagename] => api/1.1/statuses/lookup.json
3389 [id] => 605138389168451584
3390 [include_cards] => true
3391 [cards_platform] => Android-12
3392 [include_entities] => true
3393 [include_my_retweet] => 1
3395 [include_reply_count] => true
3396 [include_descendent_reply_count] => true
3400 Not implemented by now:
3401 statuses/retweets_of_me
3406 account/update_location
3407 account/update_profile_background_image
3408 account/update_profile_image
3412 Not implemented in status.net:
3413 statuses/retweeted_to_me
3414 statuses/retweeted_by_me
3415 direct_messages/destroy
3417 account/update_delivery_device
3418 notifications/follow