3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
27 require_once('include/plaintext.php');
30 define('API_METHOD_ANY','*');
31 define('API_METHOD_GET','GET');
32 define('API_METHOD_POST','POST,PUT');
33 define('API_METHOD_DELETE','POST,DELETE');
41 * @brief Auth API user
43 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
44 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
45 * into a page, and visitors will post something without noticing it).
48 if ($_SESSION['allow_api'])
55 * @brief Get source name from API client
57 * Clients can send 'source' parameter to be show in post metadata
58 * as "sent via <source>".
59 * Some clients doesn't send a source param, we support ones we know
63 * Client source name, default to "api" if unset/unknown
65 function api_source() {
66 if (requestdata('source'))
67 return (requestdata('source'));
69 // Support for known clients that doesn't send a source name
70 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
73 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
79 * @brief Format date for API
81 * @param string $str Source date, as UTC
82 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
84 function api_date($str){
85 //Wed May 23 06:01:13 +0000 2007
86 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
90 * @brief Register API endpoint
92 * Register a function to be the endpont for defined API path.
94 * @param string $path API URL path, relative to $a->get_baseurl()
95 * @param string $func Function name to call on path request
96 * @param bool $auth API need logged user
97 * @param string $method
98 * HTTP method reqiured to call this endpoint.
99 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
100 * Default to API_METHOD_ANY
102 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
110 // Workaround for hotot
111 $path = str_replace("api/", "api/1.1/", $path);
120 * @brief Login API user
122 * Log in user via OAuth1 or Simple HTTP Auth.
123 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
126 * @hook 'authenticate'
128 * 'username' => username from login form
129 * 'password' => password from login form
130 * 'authenticated' => return status,
131 * 'user_record' => return authenticated user record
133 * array $user logged user record
135 function api_login(&$a){
138 $oauth = new FKOAuth1();
139 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
140 if (!is_null($token)){
141 $oauth->loginUser($token->uid);
142 call_hooks('logged_in', $a->user);
145 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
146 }catch(Exception $e){
152 // workaround for HTTP-auth in CGI mode
153 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
154 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
155 if(strlen($userpass)) {
156 list($name, $password) = explode(':', $userpass);
157 $_SERVER['PHP_AUTH_USER'] = $name;
158 $_SERVER['PHP_AUTH_PW'] = $password;
162 if (!isset($_SERVER['PHP_AUTH_USER'])) {
163 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
164 header('WWW-Authenticate: Basic realm="Friendica"');
165 throw new UnauthorizedException("This API requires login");
168 $user = $_SERVER['PHP_AUTH_USER'];
169 $password = $_SERVER['PHP_AUTH_PW'];
170 $encrypted = hash('whirlpool',trim($password));
172 // allow "user@server" login (but ignore 'server' part)
173 $at=strstr($user, "@", true);
174 if ( $at ) $user=$at;
177 * next code from mod/auth.php. needs better solution
182 'username' => trim($user),
183 'password' => trim($password),
184 'authenticated' => 0,
185 'user_record' => null
190 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
191 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
192 * and later plugins should not interfere with an earlier one that succeeded.
196 call_hooks('authenticate', $addon_auth);
198 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
199 $record = $addon_auth['user_record'];
202 // process normal login request
204 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
205 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
214 if((! $record) || (! count($record))) {
215 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
216 header('WWW-Authenticate: Basic realm="Friendica"');
217 #header('HTTP/1.0 401 Unauthorized');
218 #die('This api requires login');
219 throw new UnauthorizedException("This API requires login");
222 authenticate_success($record); $_SESSION["allow_api"] = true;
224 call_hooks('logged_in', $a->user);
229 * @brief Check HTTP method of called API
231 * API endpoints can define which HTTP method to accept when called.
232 * This function check the current HTTP method agains endpoint
235 * @param string $method Required methods, uppercase, separated by comma
238 function api_check_method($method) {
239 if ($method=="*") return True;
240 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
244 * @brief Main API entry point
246 * Authenticate user, call registered API function, set HTTP headers
249 * @return string API call result
251 function api_call(&$a){
252 GLOBAL $API, $called_api;
255 if (strpos($a->query_string, ".xml")>0) $type="xml";
256 if (strpos($a->query_string, ".json")>0) $type="json";
257 if (strpos($a->query_string, ".rss")>0) $type="rss";
258 if (strpos($a->query_string, ".atom")>0) $type="atom";
259 if (strpos($a->query_string, ".as")>0) $type="as";
261 foreach ($API as $p=>$info){
262 if (strpos($a->query_string, $p)===0){
263 if (!api_check_method($info['method'])){
264 throw new MethodNotAllowedException();
267 $called_api= explode("/",$p);
268 //unset($_SERVER['PHP_AUTH_USER']);
269 if ($info['auth']===true && api_user()===false) {
273 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 HTTPException $error Error object
334 * @return strin error message formatted as $type
336 function api_error(&$a, $type, $e) {
337 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
338 # TODO: https://dev.twitter.com/overview/api/response-codes
339 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
342 header ("Content-Type: text/xml");
343 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
346 header ("Content-Type: application/json");
347 return json_encode(array(
349 'request' => $a->query_string,
350 'code' => $e->httpcode." ".$e->httpdesc
354 header ("Content-Type: application/rss+xml");
355 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
358 header ("Content-Type: application/atom+xml");
359 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
365 * @brief Set values for RSS template
368 * @param array $arr Array to be passed to template
369 * @param array $user_info
372 function api_rss_extra(&$a, $arr, $user_info){
373 if (is_null($user_info)) $user_info = api_get_user($a);
374 $arr['$user'] = $user_info;
375 $arr['$rss'] = array(
376 'alternate' => $user_info['url'],
377 'self' => $a->get_baseurl(). "/". $a->query_string,
378 'base' => $a->get_baseurl(),
379 'updated' => api_date(null),
380 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
381 'language' => $user_info['language'],
382 'logo' => $a->get_baseurl()."/images/friendica-32.png",
390 * @brief Unique contact to contact url.
392 * @param int $id Contact id
393 * @return bool|string
394 * Contact url or False if contact id is unknown
396 function api_unique_id_to_url($id){
397 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
400 return ($r[0]["url"]);
406 * @brief Get user info array.
409 * @param int|string $contact_id Contact ID or URL
410 * @param string $type Return type (for errors)
412 function api_get_user(&$a, $contact_id = Null, $type = "json"){
419 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
421 // Searching for contact URL
422 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
423 $user = dbesc(normalise_link($contact_id));
425 $extra_query = "AND `contact`.`nurl` = '%s' ";
426 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
429 // Searching for unique contact id
430 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
431 $user = dbesc(api_unique_id_to_url($contact_id));
434 throw new BadRequestException("User not found.");
437 $extra_query = "AND `contact`.`nurl` = '%s' ";
438 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
441 if(is_null($user) && x($_GET, 'user_id')) {
442 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
445 throw new BadRequestException("User not found.");
448 $extra_query = "AND `contact`.`nurl` = '%s' ";
449 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
451 if(is_null($user) && x($_GET, 'screen_name')) {
452 $user = dbesc($_GET['screen_name']);
454 $extra_query = "AND `contact`.`nick` = '%s' ";
455 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
458 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
459 $argid = count($called_api);
460 list($user, $null) = explode(".",$a->argv[$argid]);
461 if(is_numeric($user)){
462 $user = dbesc(api_unique_id_to_url($user));
468 $extra_query = "AND `contact`.`nurl` = '%s' ";
469 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
471 $user = dbesc($user);
473 $extra_query = "AND `contact`.`nick` = '%s' ";
474 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
478 logger("api_get_user: user ".$user, LOGGER_DEBUG);
481 if (api_user()===false) {
485 $user = $_SESSION['uid'];
486 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
491 logger('api_user: ' . $extra_query . ', user: ' . $user);
493 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
499 // Selecting the id by priority, friendica first
500 api_best_nickname($uinfo);
502 // if the contact wasn't found, fetch it from the unique contacts
503 if (count($uinfo)==0) {
507 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
510 // If no nick where given, extract it from the address
511 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
512 $r[0]['nick'] = api_get_nick($r[0]["url"]);
516 'id_str' => (string) $r[0]["id"],
517 'name' => $r[0]["name"],
518 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
519 'location' => $r[0]["location"],
520 'description' => $r[0]["about"],
521 'url' => $r[0]["url"],
522 'protected' => false,
523 'followers_count' => 0,
524 'friends_count' => 0,
526 'created_at' => api_date($r[0]["created"]),
527 'favourites_count' => 0,
529 'time_zone' => 'UTC',
530 'geo_enabled' => false,
532 'statuses_count' => 0,
534 'contributors_enabled' => false,
535 'is_translator' => false,
536 'is_translation_enabled' => false,
537 'profile_image_url' => $r[0]["photo"],
538 'profile_image_url_https' => $r[0]["photo"],
539 'following' => false,
540 'follow_request_sent' => false,
541 'notifications' => false,
542 'statusnet_blocking' => false,
543 'notifications' => false,
544 'statusnet_profile_url' => $r[0]["url"],
548 'network' => $r[0]["network"],
553 throw new BadRequestException("User not found.");
557 if($uinfo[0]['self']) {
558 $usr = q("select * from user where uid = %d limit 1",
561 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
565 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
566 // count public wall messages
567 $r = q("SELECT count(*) as `count` FROM `item`
570 intval($uinfo[0]['uid'])
572 $countitms = $r[0]['count'];
575 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
576 $r = q("SELECT count(*) as `count` FROM `item`
577 WHERE `contact-id` = %d",
578 intval($uinfo[0]['id'])
580 $countitms = $r[0]['count'];
584 $r = q("SELECT count(*) as `count` FROM `contact`
585 WHERE `uid` = %d AND `rel` IN ( %d, %d )
586 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
587 intval($uinfo[0]['uid']),
588 intval(CONTACT_IS_SHARING),
589 intval(CONTACT_IS_FRIEND)
591 $countfriends = $r[0]['count'];
593 $r = q("SELECT count(*) as `count` FROM `contact`
594 WHERE `uid` = %d AND `rel` IN ( %d, %d )
595 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
596 intval($uinfo[0]['uid']),
597 intval(CONTACT_IS_FOLLOWER),
598 intval(CONTACT_IS_FRIEND)
600 $countfollowers = $r[0]['count'];
602 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
603 intval($uinfo[0]['uid'])
605 $starred = $r[0]['count'];
608 if(! $uinfo[0]['self']) {
614 // Add a nick if it isn't present there
615 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
616 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
619 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
621 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
622 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
625 'id' => intval($gcontact_id),
626 'id_str' => (string) intval($gcontact_id),
627 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
628 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
629 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
630 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
631 'profile_image_url' => $uinfo[0]['micro'],
632 'profile_image_url_https' => $uinfo[0]['micro'],
633 'url' => $uinfo[0]['url'],
634 'protected' => false,
635 'followers_count' => intval($countfollowers),
636 'friends_count' => intval($countfriends),
637 'created_at' => api_date($uinfo[0]['created']),
638 'favourites_count' => intval($starred),
640 'time_zone' => 'UTC',
641 'statuses_count' => intval($countitms),
642 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
644 'statusnet_blocking' => false,
645 'notifications' => false,
646 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
647 'statusnet_profile_url' => $uinfo[0]['url'],
648 'uid' => intval($uinfo[0]['uid']),
649 'cid' => intval($uinfo[0]['cid']),
650 'self' => $uinfo[0]['self'],
651 'network' => $uinfo[0]['network'],
658 function api_item_get_user(&$a, $item) {
660 // Make sure that there is an entry in the global contacts for author and owner
661 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
662 "photo" => $item['author-avatar'], "name" => $item['author-name']));
664 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
665 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
667 // Comments in threads may appear as wall-to-wall postings.
668 // So only take the owner at the top posting.
669 if ($item["id"] == $item["parent"])
670 $status_user = api_get_user($a,$item["owner-link"]);
672 $status_user = api_get_user($a,$item["author-link"]);
674 $status_user["protected"] = (($item["allow_cid"] != "") OR
675 ($item["allow_gid"] != "") OR
676 ($item["deny_cid"] != "") OR
677 ($item["deny_gid"] != "") OR
680 return ($status_user);
685 * @brief transform $data array in xml without a template
688 * @return string xml string
690 function api_array_to_xml($data, $ename="") {
693 if (count($data)==1 && !is_array($data[0])) {
694 $ename = array_keys($data)[0];
696 return "<$ename>$v</$ename>";
698 foreach($data as $k=>$v) {
701 $attrs .= sprintf('%s="%s" ', $k, $v);
703 if (is_numeric($k)) $k=trim($ename,'s');
704 $childs.=api_array_to_xml($v, $k);
708 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
713 * load api $templatename for $type and replace $data array
715 function api_apply_template($templatename, $type, $data){
723 $data = array_xmlify($data);
724 if ($templatename==="<auto>") {
725 $ret = api_array_to_xml($data);
727 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
729 header ("Content-Type: text/xml");
730 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
733 $ret = replace_macros($tpl, $data);
749 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
750 * returns a 401 status code and an error message if not.
751 * http://developer.twitter.com/doc/get/account/verify_credentials
753 function api_account_verify_credentials(&$a, $type){
754 if (api_user()===false) throw new ForbiddenException();
756 unset($_REQUEST["user_id"]);
757 unset($_GET["user_id"]);
759 unset($_REQUEST["screen_name"]);
760 unset($_GET["screen_name"]);
762 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
764 $user_info = api_get_user($a);
766 // "verified" isn't used here in the standard
767 unset($user_info["verified"]);
769 // - Adding last status
771 $user_info["status"] = api_status_show($a,"raw");
772 if (!count($user_info["status"]))
773 unset($user_info["status"]);
775 unset($user_info["status"]["user"]);
778 // "uid" and "self" are only needed for some internal stuff, so remove it from here
779 unset($user_info["uid"]);
780 unset($user_info["self"]);
782 return api_apply_template("user", $type, array('$user' => $user_info));
785 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
789 * get data from $_POST or $_GET
791 function requestdata($k){
792 if (isset($_POST[$k])){
795 if (isset($_GET[$k])){
801 /*Waitman Gobble Mod*/
802 function api_statuses_mediap(&$a, $type) {
803 if (api_user()===false) {
804 logger('api_statuses_update: no user');
805 throw new ForbiddenException();
807 $user_info = api_get_user($a);
809 $_REQUEST['type'] = 'wall';
810 $_REQUEST['profile_uid'] = api_user();
811 $_REQUEST['api_source'] = true;
812 $txt = requestdata('status');
813 //$txt = urldecode(requestdata('status'));
815 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
817 $txt = html2bb_video($txt);
818 $config = HTMLPurifier_Config::createDefault();
819 $config->set('Cache.DefinitionImpl', null);
820 $purifier = new HTMLPurifier($config);
821 $txt = $purifier->purify($txt);
823 $txt = html2bbcode($txt);
825 $a->argv[1]=$user_info['screen_name']; //should be set to username?
827 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
828 $bebop = wall_upload_post($a);
830 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
831 $_REQUEST['body']=$txt."\n\n".$bebop;
834 // this should output the last post (the one we just posted).
835 return api_status_show($a,$type);
837 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
838 /*Waitman Gobble Mod*/
841 function api_statuses_update(&$a, $type) {
842 if (api_user()===false) {
843 logger('api_statuses_update: no user');
844 throw new ForbiddenException();
847 $user_info = api_get_user($a);
849 // convert $_POST array items to the form we use for web posts.
851 // logger('api_post: ' . print_r($_POST,true));
853 if(requestdata('htmlstatus')) {
854 $txt = requestdata('htmlstatus');
855 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
856 $txt = html2bb_video($txt);
858 $config = HTMLPurifier_Config::createDefault();
859 $config->set('Cache.DefinitionImpl', null);
861 $purifier = new HTMLPurifier($config);
862 $txt = $purifier->purify($txt);
864 $_REQUEST['body'] = html2bbcode($txt);
868 $_REQUEST['body'] = requestdata('status');
870 $_REQUEST['title'] = requestdata('title');
872 $parent = requestdata('in_reply_to_status_id');
874 // Twidere sends "-1" if it is no reply ...
878 if(ctype_digit($parent))
879 $_REQUEST['parent'] = $parent;
881 $_REQUEST['parent_uri'] = $parent;
883 if(requestdata('lat') && requestdata('long'))
884 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
885 $_REQUEST['profile_uid'] = api_user();
888 $_REQUEST['type'] = 'net-comment';
890 // Check for throttling (maximum posts per day, week and month)
891 $throttle_day = get_config('system','throttle_limit_day');
892 if ($throttle_day > 0) {
893 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
895 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
896 AND `created` > '%s' AND `id` = `parent`",
897 intval(api_user()), dbesc($datefrom));
900 $posts_day = $r[0]["posts_day"];
904 if ($posts_day > $throttle_day) {
905 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
906 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
907 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
911 $throttle_week = get_config('system','throttle_limit_week');
912 if ($throttle_week > 0) {
913 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
915 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
916 AND `created` > '%s' AND `id` = `parent`",
917 intval(api_user()), dbesc($datefrom));
920 $posts_week = $r[0]["posts_week"];
924 if ($posts_week > $throttle_week) {
925 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
926 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
927 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
932 $throttle_month = get_config('system','throttle_limit_month');
933 if ($throttle_month > 0) {
934 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
936 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
937 AND `created` > '%s' AND `id` = `parent`",
938 intval(api_user()), dbesc($datefrom));
941 $posts_month = $r[0]["posts_month"];
945 if ($posts_month > $throttle_month) {
946 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
947 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
948 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
952 $_REQUEST['type'] = 'wall';
955 if(x($_FILES,'media')) {
956 // upload the image if we have one
957 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
958 $media = wall_upload_post($a);
960 $_REQUEST['body'] .= "\n\n".$media;
963 // To-Do: Multiple IDs
964 if (requestdata('media_ids')) {
965 $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",
966 intval(requestdata('media_ids')), api_user());
968 $phototypes = Photo::supportedTypes();
969 $ext = $phototypes[$r[0]['type']];
970 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
971 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
975 // set this so that the item_post() function is quiet and doesn't redirect or emit json
977 $_REQUEST['api_source'] = true;
979 if (!x($_REQUEST, "source"))
980 $_REQUEST["source"] = api_source();
982 // call out normal post function
986 // this should output the last post (the one we just posted).
987 return api_status_show($a,$type);
989 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
990 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
993 function api_media_upload(&$a, $type) {
994 if (api_user()===false) {
996 throw new ForbiddenException();
999 $user_info = api_get_user($a);
1001 if(!x($_FILES,'media')) {
1003 throw new BadRequestException("No media.");
1006 $media = wall_upload_post($a, false);
1009 throw new InternalServerErrorException();
1012 $returndata = array();
1013 $returndata["media_id"] = $media["id"];
1014 $returndata["media_id_string"] = (string)$media["id"];
1015 $returndata["size"] = $media["size"];
1016 $returndata["image"] = array("w" => $media["width"],
1017 "h" => $media["height"],
1018 "image_type" => $media["type"]);
1020 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1022 return array("media" => $returndata);
1024 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1026 function api_status_show(&$a, $type){
1027 $user_info = api_get_user($a);
1029 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1032 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1036 // get last public wall message
1037 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1038 FROM `item`, `item` as `i`
1039 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1040 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1041 AND `i`.`id` = `item`.`parent`
1042 AND `item`.`type`!='activity' $privacy_sql
1043 ORDER BY `item`.`created` DESC
1045 intval($user_info['cid']),
1047 dbesc($user_info['url']),
1048 dbesc(normalise_link($user_info['url'])),
1049 dbesc($user_info['url']),
1050 dbesc(normalise_link($user_info['url']))
1053 if (count($lastwall)>0){
1054 $lastwall = $lastwall[0];
1056 $in_reply_to_status_id = NULL;
1057 $in_reply_to_user_id = NULL;
1058 $in_reply_to_status_id_str = NULL;
1059 $in_reply_to_user_id_str = NULL;
1060 $in_reply_to_screen_name = NULL;
1061 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1062 $in_reply_to_status_id= intval($lastwall['parent']);
1063 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1065 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1067 if ($r[0]['nick'] == "")
1068 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1070 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1071 $in_reply_to_user_id = intval($r[0]['id']);
1072 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1076 // There seems to be situation, where both fields are identical:
1077 // https://github.com/friendica/friendica/issues/1010
1078 // This is a bugfix for that.
1079 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1080 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1081 $in_reply_to_status_id = NULL;
1082 $in_reply_to_user_id = NULL;
1083 $in_reply_to_status_id_str = NULL;
1084 $in_reply_to_user_id_str = NULL;
1085 $in_reply_to_screen_name = NULL;
1088 $converted = api_convert_item($lastwall);
1090 $status_info = array(
1091 'created_at' => api_date($lastwall['created']),
1092 'id' => intval($lastwall['id']),
1093 'id_str' => (string) $lastwall['id'],
1094 'text' => $converted["text"],
1095 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1096 'truncated' => false,
1097 'in_reply_to_status_id' => $in_reply_to_status_id,
1098 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1099 'in_reply_to_user_id' => $in_reply_to_user_id,
1100 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1101 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1102 'user' => $user_info,
1104 'coordinates' => "",
1106 'contributors' => "",
1107 'is_quote_status' => false,
1108 'retweet_count' => 0,
1109 'favorite_count' => 0,
1110 'favorited' => $lastwall['starred'] ? true : false,
1111 'retweeted' => false,
1112 'possibly_sensitive' => false,
1114 'statusnet_html' => $converted["html"],
1115 'statusnet_conversation_id' => $lastwall['parent'],
1118 if (count($converted["attachments"]) > 0)
1119 $status_info["attachments"] = $converted["attachments"];
1121 if (count($converted["entities"]) > 0)
1122 $status_info["entities"] = $converted["entities"];
1124 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1125 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1126 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1127 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1129 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1130 unset($status_info["user"]["uid"]);
1131 unset($status_info["user"]["self"]);
1134 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1137 return($status_info);
1139 return api_apply_template("status", $type, array('$status' => $status_info));
1148 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1149 * The author's most recent status will be returned inline.
1150 * http://developer.twitter.com/doc/get/users/show
1152 function api_users_show(&$a, $type){
1153 $user_info = api_get_user($a);
1155 $lastwall = q("SELECT `item`.*
1156 FROM `item`, `contact`
1157 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1158 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1159 AND `contact`.`id`=`item`.`contact-id`
1160 AND `type`!='activity'
1161 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1162 ORDER BY `created` DESC
1165 dbesc(ACTIVITY_POST),
1166 intval($user_info['cid']),
1167 dbesc($user_info['url']),
1168 dbesc(normalise_link($user_info['url'])),
1169 dbesc($user_info['url']),
1170 dbesc(normalise_link($user_info['url']))
1172 if (count($lastwall)>0){
1173 $lastwall = $lastwall[0];
1175 $in_reply_to_status_id = NULL;
1176 $in_reply_to_user_id = NULL;
1177 $in_reply_to_status_id_str = NULL;
1178 $in_reply_to_user_id_str = NULL;
1179 $in_reply_to_screen_name = NULL;
1180 if ($lastwall['parent']!=$lastwall['id']) {
1181 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1182 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1183 if (count($reply)>0) {
1184 $in_reply_to_status_id = intval($lastwall['parent']);
1185 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1187 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1189 if ($r[0]['nick'] == "")
1190 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1192 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1193 $in_reply_to_user_id = intval($r[0]['id']);
1194 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1199 $converted = api_convert_item($lastwall);
1201 $user_info['status'] = array(
1202 'text' => $converted["text"],
1203 'truncated' => false,
1204 'created_at' => api_date($lastwall['created']),
1205 'in_reply_to_status_id' => $in_reply_to_status_id,
1206 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1207 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1208 'id' => intval($lastwall['contact-id']),
1209 'id_str' => (string) $lastwall['contact-id'],
1210 'in_reply_to_user_id' => $in_reply_to_user_id,
1211 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1212 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1214 'favorited' => $lastwall['starred'] ? true : false,
1215 'statusnet_html' => $converted["html"],
1216 'statusnet_conversation_id' => $lastwall['parent'],
1219 if (count($converted["attachments"]) > 0)
1220 $user_info["status"]["attachments"] = $converted["attachments"];
1222 if (count($converted["entities"]) > 0)
1223 $user_info["status"]["entities"] = $converted["entities"];
1225 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1226 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1227 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1228 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1232 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1233 unset($user_info["uid"]);
1234 unset($user_info["self"]);
1236 return api_apply_template("user", $type, array('$user' => $user_info));
1239 api_register_func('api/users/show','api_users_show');
1242 function api_users_search(&$a, $type) {
1243 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1245 $userlist = array();
1247 if (isset($_GET["q"])) {
1248 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1250 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1253 foreach ($r AS $user) {
1254 $user_info = api_get_user($a, $user["id"]);
1255 //echo print_r($user_info, true)."\n";
1256 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1257 $userlist[] = $userdata["user"];
1259 $userlist = array("users" => $userlist);
1261 throw new BadRequestException("User not found.");
1264 throw new BadRequestException("User not found.");
1269 api_register_func('api/users/search','api_users_search');
1273 * http://developer.twitter.com/doc/get/statuses/home_timeline
1275 * TODO: Optional parameters
1276 * TODO: Add reply info
1278 function api_statuses_home_timeline(&$a, $type){
1279 if (api_user()===false) throw new ForbiddenException();
1281 unset($_REQUEST["user_id"]);
1282 unset($_GET["user_id"]);
1284 unset($_REQUEST["screen_name"]);
1285 unset($_GET["screen_name"]);
1287 $user_info = api_get_user($a);
1288 // get last newtork messages
1292 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1293 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1294 if ($page<0) $page=0;
1295 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1296 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1297 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1298 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1299 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1301 $start = $page*$count;
1305 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1306 if ($exclude_replies > 0)
1307 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1308 if ($conversation_id > 0)
1309 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1311 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1312 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1313 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1314 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1315 FROM `item`, `contact`
1316 WHERE `item`.`uid` = %d AND `verb` = '%s'
1317 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1318 AND `contact`.`id` = `item`.`contact-id`
1319 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1322 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1324 dbesc(ACTIVITY_POST),
1326 intval($start), intval($count)
1329 $ret = api_format_items($r,$user_info);
1331 // Set all posts from the query above to seen
1333 foreach ($r AS $item)
1334 $idarray[] = intval($item["id"]);
1336 $idlist = implode(",", $idarray);
1339 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1342 $data = array('$statuses' => $ret);
1346 $data = api_rss_extra($a, $data, $user_info);
1349 $as = api_format_as($a, $ret, $user_info);
1350 $as['title'] = $a->config['sitename']." Home Timeline";
1351 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1356 return api_apply_template("timeline", $type, $data);
1358 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1359 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1361 function api_statuses_public_timeline(&$a, $type){
1362 if (api_user()===false) throw new ForbiddenException();
1364 $user_info = api_get_user($a);
1365 // get last newtork messages
1369 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1370 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1371 if ($page<0) $page=0;
1372 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1373 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1374 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1375 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1376 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1378 $start = $page*$count;
1381 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1382 if ($exclude_replies > 0)
1383 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1384 if ($conversation_id > 0)
1385 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1387 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1388 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1389 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1390 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1391 `user`.`nickname`, `user`.`hidewall`
1392 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1393 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1394 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1395 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1396 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1397 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1398 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1401 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1402 dbesc(ACTIVITY_POST),
1407 $ret = api_format_items($r,$user_info);
1410 $data = array('$statuses' => $ret);
1414 $data = api_rss_extra($a, $data, $user_info);
1417 $as = api_format_as($a, $ret, $user_info);
1418 $as['title'] = $a->config['sitename']." Public Timeline";
1419 $as['link']['url'] = $a->get_baseurl()."/";
1424 return api_apply_template("timeline", $type, $data);
1426 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1431 function api_statuses_show(&$a, $type){
1432 if (api_user()===false) throw new ForbiddenException();
1434 $user_info = api_get_user($a);
1437 $id = intval($a->argv[3]);
1440 $id = intval($_REQUEST["id"]);
1444 $id = intval($a->argv[4]);
1446 logger('API: api_statuses_show: '.$id);
1448 $conversation = (x($_REQUEST,'conversation')?1:0);
1452 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1454 $sql_extra .= " AND `item`.`id` = %d";
1456 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1457 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1458 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1459 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1460 FROM `item`, `contact`
1461 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1462 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1463 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1466 dbesc(ACTIVITY_POST),
1471 throw new BadRequestException("There is no status with this id.");
1474 $ret = api_format_items($r,$user_info);
1476 if ($conversation) {
1477 $data = array('$statuses' => $ret);
1478 return api_apply_template("timeline", $type, $data);
1480 $data = array('$status' => $ret[0]);
1484 $data = api_rss_extra($a, $data, $user_info);
1486 return api_apply_template("status", $type, $data);
1489 api_register_func('api/statuses/show','api_statuses_show', true);
1495 function api_conversation_show(&$a, $type){
1496 if (api_user()===false) throw new ForbiddenException();
1498 $user_info = api_get_user($a);
1501 $id = intval($a->argv[3]);
1502 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1503 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1504 if ($page<0) $page=0;
1505 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1506 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1508 $start = $page*$count;
1511 $id = intval($_REQUEST["id"]);
1515 $id = intval($a->argv[4]);
1517 logger('API: api_conversation_show: '.$id);
1519 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1521 $id = $r[0]["parent"];
1526 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1528 // Not sure why this query was so complicated. We should keep it here for a while,
1529 // just to make sure that we really don't need it.
1530 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1531 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1533 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1534 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1535 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1536 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1538 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1539 WHERE `item`.`parent` = %d AND `item`.`visible`
1540 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1541 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1542 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1543 AND `item`.`id`>%d $sql_extra
1544 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1545 intval($id), intval(api_user()),
1546 dbesc(ACTIVITY_POST),
1548 intval($start), intval($count)
1552 throw new BadRequestException("There is no conversation with this id.");
1554 $ret = api_format_items($r,$user_info);
1556 $data = array('$statuses' => $ret);
1557 return api_apply_template("timeline", $type, $data);
1559 api_register_func('api/conversation/show','api_conversation_show', true);
1560 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1566 function api_statuses_repeat(&$a, $type){
1569 if (api_user()===false) throw new ForbiddenException();
1571 $user_info = api_get_user($a);
1574 $id = intval($a->argv[3]);
1577 $id = intval($_REQUEST["id"]);
1581 $id = intval($a->argv[4]);
1583 logger('API: api_statuses_repeat: '.$id);
1585 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1586 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1587 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1588 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1589 FROM `item`, `contact`
1590 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1591 AND `contact`.`id` = `item`.`contact-id`
1592 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1593 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1594 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1596 AND `item`.`id`=%d",
1600 if ($r[0]['body'] != "") {
1601 if (!intval(get_config('system','old_share'))) {
1602 if (strpos($r[0]['body'], "[/share]") !== false) {
1603 $pos = strpos($r[0]['body'], "[share");
1604 $post = substr($r[0]['body'], $pos);
1606 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1608 $post .= $r[0]['body'];
1609 $post .= "[/share]";
1611 $_REQUEST['body'] = $post;
1613 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1615 $_REQUEST['profile_uid'] = api_user();
1616 $_REQUEST['type'] = 'wall';
1617 $_REQUEST['api_source'] = true;
1619 if (!x($_REQUEST, "source"))
1620 $_REQUEST["source"] = api_source();
1624 throw new ForbiddenException();
1626 // this should output the last post (the one we just posted).
1628 return(api_status_show($a,$type));
1630 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1635 function api_statuses_destroy(&$a, $type){
1636 if (api_user()===false) throw new ForbiddenException();
1638 $user_info = api_get_user($a);
1641 $id = intval($a->argv[3]);
1644 $id = intval($_REQUEST["id"]);
1648 $id = intval($a->argv[4]);
1650 logger('API: api_statuses_destroy: '.$id);
1652 $ret = api_statuses_show($a, $type);
1654 drop_item($id, false);
1658 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1662 * http://developer.twitter.com/doc/get/statuses/mentions
1665 function api_statuses_mentions(&$a, $type){
1666 if (api_user()===false) throw new ForbiddenException();
1668 unset($_REQUEST["user_id"]);
1669 unset($_GET["user_id"]);
1671 unset($_REQUEST["screen_name"]);
1672 unset($_GET["screen_name"]);
1674 $user_info = api_get_user($a);
1675 // get last newtork messages
1679 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1680 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1681 if ($page<0) $page=0;
1682 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1683 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1684 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1686 $start = $page*$count;
1688 // Ugly code - should be changed
1689 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1690 $myurl = substr($myurl,strpos($myurl,'://')+3);
1691 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1692 $myurl = str_replace('www.','',$myurl);
1693 $diasp_url = str_replace('/profile/','/u/',$myurl);
1696 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1698 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1699 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1700 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1701 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1702 FROM `item` FORCE INDEX (`uid_id`), `contact`
1703 WHERE `item`.`uid` = %d AND `verb` = '%s'
1704 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1705 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1706 AND `contact`.`id` = `item`.`contact-id`
1707 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1708 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1711 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1713 dbesc(ACTIVITY_POST),
1714 dbesc(protect_sprintf($myurl)),
1715 dbesc(protect_sprintf($myurl)),
1718 intval($start), intval($count)
1721 $ret = api_format_items($r,$user_info);
1724 $data = array('$statuses' => $ret);
1728 $data = api_rss_extra($a, $data, $user_info);
1731 $as = api_format_as($a, $ret, $user_info);
1732 $as["title"] = $a->config['sitename']." Mentions";
1733 $as['link']['url'] = $a->get_baseurl()."/";
1738 return api_apply_template("timeline", $type, $data);
1740 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1741 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1744 function api_statuses_user_timeline(&$a, $type){
1745 if (api_user()===false) throw new ForbiddenException();
1747 $user_info = api_get_user($a);
1748 // get last network messages
1750 logger("api_statuses_user_timeline: api_user: ". api_user() .
1751 "\nuser_info: ".print_r($user_info, true) .
1752 "\n_REQUEST: ".print_r($_REQUEST, true),
1756 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1757 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1758 if ($page<0) $page=0;
1759 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1760 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1761 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1762 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1764 $start = $page*$count;
1767 if ($user_info['self']==1)
1768 $sql_extra .= " AND `item`.`wall` = 1 ";
1770 if ($exclude_replies > 0)
1771 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1772 if ($conversation_id > 0)
1773 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1775 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1776 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1777 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1778 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1779 FROM `item`, `contact`
1780 WHERE `item`.`uid` = %d AND `verb` = '%s'
1781 AND `item`.`contact-id` = %d
1782 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1783 AND `contact`.`id` = `item`.`contact-id`
1784 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1787 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1789 dbesc(ACTIVITY_POST),
1790 intval($user_info['cid']),
1792 intval($start), intval($count)
1795 $ret = api_format_items($r,$user_info, true);
1797 $data = array('$statuses' => $ret);
1801 $data = api_rss_extra($a, $data, $user_info);
1804 return api_apply_template("timeline", $type, $data);
1806 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1810 * Star/unstar an item
1811 * param: id : id of the item
1813 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1815 function api_favorites_create_destroy(&$a, $type){
1816 if (api_user()===false) throw new ForbiddenException();
1818 // for versioned api.
1819 /// @TODO We need a better global soluton
1821 if ($a->argv[1]=="1.1") $action_argv_id=3;
1823 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1824 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1825 if ($a->argc==$action_argv_id+2) {
1826 $itemid = intval($a->argv[$action_argv_id+1]);
1828 $itemid = intval($_REQUEST['id']);
1831 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1832 $itemid, api_user());
1834 if ($item===false || count($item)==0)
1835 throw new BadRequestException("Invalid item.");
1839 $item[0]['starred']=1;
1842 $item[0]['starred']=0;
1845 throw new BadRequestException("Invalid action ".$action);
1847 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1848 $item[0]['starred'], $itemid, api_user());
1850 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1851 $item[0]['starred'], $itemid, api_user());
1854 throw InternalServerErrorException("DB error");
1857 $user_info = api_get_user($a);
1858 $rets = api_format_items($item,$user_info);
1861 $data = array('$status' => $ret);
1865 $data = api_rss_extra($a, $data, $user_info);
1868 return api_apply_template("status", $type, $data);
1870 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1871 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1873 function api_favorites(&$a, $type){
1876 if (api_user()===false) throw new ForbiddenException();
1878 $called_api= array();
1880 $user_info = api_get_user($a);
1882 // in friendica starred item are private
1883 // return favorites only for self
1884 logger('api_favorites: self:' . $user_info['self']);
1886 if ($user_info['self']==0) {
1892 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1893 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1894 $count = (x($_GET,'count')?$_GET['count']:20);
1895 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1896 if ($page<0) $page=0;
1898 $start = $page*$count;
1901 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1903 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1904 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1905 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1906 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1907 FROM `item`, `contact`
1908 WHERE `item`.`uid` = %d
1909 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1910 AND `item`.`starred` = 1
1911 AND `contact`.`id` = `item`.`contact-id`
1912 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1915 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1918 intval($start), intval($count)
1921 $ret = api_format_items($r,$user_info);
1925 $data = array('$statuses' => $ret);
1929 $data = api_rss_extra($a, $data, $user_info);
1932 return api_apply_template("timeline", $type, $data);
1934 api_register_func('api/favorites','api_favorites', true);
1939 function api_format_as($a, $ret, $user_info) {
1941 $as['title'] = $a->config['sitename']." Public Timeline";
1943 foreach ($ret as $item) {
1944 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1945 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1946 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1947 $avatar[0]["rel"] = "avatar";
1948 $avatar[0]["type"] = "";
1949 $avatar[0]["width"] = 96;
1950 $avatar[0]["height"] = 96;
1951 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1952 $avatar[1]["rel"] = "avatar";
1953 $avatar[1]["type"] = "";
1954 $avatar[1]["width"] = 48;
1955 $avatar[1]["height"] = 48;
1956 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1957 $avatar[2]["rel"] = "avatar";
1958 $avatar[2]["type"] = "";
1959 $avatar[2]["width"] = 24;
1960 $avatar[2]["height"] = 24;
1961 $singleitem["actor"]["avatarLinks"] = $avatar;
1963 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1964 $singleitem["actor"]["image"]["rel"] = "avatar";
1965 $singleitem["actor"]["image"]["type"] = "";
1966 $singleitem["actor"]["image"]["width"] = 96;
1967 $singleitem["actor"]["image"]["height"] = 96;
1968 $singleitem["actor"]["type"] = "person";
1969 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1970 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1971 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1972 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1973 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1974 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1975 $singleitem["actor"]["contact"]["addresses"] = "";
1977 $singleitem["body"] = $item["text"];
1978 $singleitem["object"]["displayName"] = $item["text"];
1979 $singleitem["object"]["id"] = $item["url"];
1980 $singleitem["object"]["type"] = "note";
1981 $singleitem["object"]["url"] = $item["url"];
1982 //$singleitem["context"] =;
1983 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1984 $singleitem["provider"]["objectType"] = "service";
1985 $singleitem["provider"]["displayName"] = "Test";
1986 $singleitem["provider"]["url"] = "http://test.tld";
1987 $singleitem["title"] = $item["text"];
1988 $singleitem["verb"] = "post";
1989 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1990 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1991 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1992 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1993 //$singleitem["original"] = $item;
1994 $items[] = $singleitem;
1996 $as['items'] = $items;
1997 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1998 $as['link']['rel'] = "alternate";
1999 $as['link']['type'] = "text/html";
2003 function api_format_messages($item, $recipient, $sender) {
2004 // standard meta information
2006 'id' => $item['id'],
2007 'sender_id' => $sender['id'] ,
2009 'recipient_id' => $recipient['id'],
2010 'created_at' => api_date($item['created']),
2011 'sender_screen_name' => $sender['screen_name'],
2012 'recipient_screen_name' => $recipient['screen_name'],
2013 'sender' => $sender,
2014 'recipient' => $recipient,
2017 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2018 unset($ret["sender"]["uid"]);
2019 unset($ret["sender"]["self"]);
2020 unset($ret["recipient"]["uid"]);
2021 unset($ret["recipient"]["self"]);
2023 //don't send title to regular StatusNET requests to avoid confusing these apps
2024 if (x($_GET, 'getText')) {
2025 $ret['title'] = $item['title'] ;
2026 if ($_GET["getText"] == "html") {
2027 $ret['text'] = bbcode($item['body'], false, false);
2029 elseif ($_GET["getText"] == "plain") {
2030 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2031 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2035 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2037 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2038 unset($ret['sender']);
2039 unset($ret['recipient']);
2045 function api_convert_item($item) {
2047 $body = $item['body'];
2048 $attachments = api_get_attachments($body);
2050 // Workaround for ostatus messages where the title is identically to the body
2051 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2052 $statusbody = trim(html2plain($html, 0));
2054 // handle data: images
2055 $statusbody = api_format_items_embeded_images($item,$statusbody);
2057 $statustitle = trim($item['title']);
2059 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2060 $statustext = trim($statusbody);
2062 $statustext = trim($statustitle."\n\n".$statusbody);
2064 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2065 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2067 $statushtml = trim(bbcode($body, false, false));
2069 $search = array("<br>", "<blockquote>", "</blockquote>",
2070 "<h1>", "</h1>", "<h2>", "</h2>",
2071 "<h3>", "</h3>", "<h4>", "</h4>",
2072 "<h5>", "</h5>", "<h6>", "</h6>");
2073 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2074 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2075 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2076 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2077 $statushtml = str_replace($search, $replace, $statushtml);
2079 if ($item['title'] != "")
2080 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2082 $entities = api_get_entitities($statustext, $body);
2084 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2087 function api_get_attachments(&$body) {
2090 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2092 $URLSearchString = "^\[\]";
2093 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2098 $attachments = array();
2100 foreach ($images[1] AS $image) {
2101 $imagedata = get_photo_info($image);
2104 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2107 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2108 foreach ($images[0] AS $orig)
2109 $body = str_replace($orig, "", $body);
2111 return $attachments;
2114 function api_get_entitities(&$text, $bbcode) {
2117 * Links at the first character of the post
2122 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2124 if ($include_entities != "true") {
2126 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2128 foreach ($images[1] AS $image) {
2129 $replace = proxy_url($image);
2130 $text = str_replace($image, $replace, $text);
2135 $bbcode = bb_CleanPictureLinks($bbcode);
2137 // Change pure links in text to bbcode uris
2138 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2140 $entities = array();
2141 $entities["hashtags"] = array();
2142 $entities["symbols"] = array();
2143 $entities["urls"] = array();
2144 $entities["user_mentions"] = array();
2146 $URLSearchString = "^\[\]";
2148 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2150 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2151 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2152 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2154 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2155 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2156 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2158 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2159 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2160 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2162 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2164 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2165 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2167 $ordered_urls = array();
2168 foreach ($urls[1] AS $id=>$url) {
2169 //$start = strpos($text, $url, $offset);
2170 $start = iconv_strpos($text, $url, 0, "UTF-8");
2171 if (!($start === false))
2172 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2175 ksort($ordered_urls);
2178 //foreach ($urls[1] AS $id=>$url) {
2179 foreach ($ordered_urls AS $url) {
2180 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2181 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2182 $display_url = $url["title"];
2184 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2185 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2187 if (strlen($display_url) > 26)
2188 $display_url = substr($display_url, 0, 25)."…";
2191 //$start = strpos($text, $url, $offset);
2192 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2193 if (!($start === false)) {
2194 $entities["urls"][] = array("url" => $url["url"],
2195 "expanded_url" => $url["url"],
2196 "display_url" => $display_url,
2197 "indices" => array($start, $start+strlen($url["url"])));
2198 $offset = $start + 1;
2202 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2203 $ordered_images = array();
2204 foreach ($images[1] AS $image) {
2205 //$start = strpos($text, $url, $offset);
2206 $start = iconv_strpos($text, $image, 0, "UTF-8");
2207 if (!($start === false))
2208 $ordered_images[$start] = $image;
2210 //$entities["media"] = array();
2213 foreach ($ordered_images AS $url) {
2214 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2215 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2217 if (strlen($display_url) > 26)
2218 $display_url = substr($display_url, 0, 25)."…";
2220 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2221 if (!($start === false)) {
2222 $image = get_photo_info($url);
2224 // If image cache is activated, then use the following sizes:
2225 // thumb (150), small (340), medium (600) and large (1024)
2226 if (!get_config("system", "proxy_disabled")) {
2227 $media_url = proxy_url($url);
2230 $scale = scale_image($image[0], $image[1], 150);
2231 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2233 if (($image[0] > 150) OR ($image[1] > 150)) {
2234 $scale = scale_image($image[0], $image[1], 340);
2235 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2238 $scale = scale_image($image[0], $image[1], 600);
2239 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2241 if (($image[0] > 600) OR ($image[1] > 600)) {
2242 $scale = scale_image($image[0], $image[1], 1024);
2243 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2247 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2250 $entities["media"][] = array(
2252 "id_str" => (string)$start+1,
2253 "indices" => array($start, $start+strlen($url)),
2254 "media_url" => normalise_link($media_url),
2255 "media_url_https" => $media_url,
2257 "display_url" => $display_url,
2258 "expanded_url" => $url,
2262 $offset = $start + 1;
2268 function api_format_items_embeded_images(&$item, $text){
2270 $text = preg_replace_callback(
2271 "|data:image/([^;]+)[^=]+=*|m",
2272 function($match) use ($a, $item) {
2273 return $a->get_baseurl()."/display/".$item['guid'];
2280 * @brief return likes, dislikes and attend status for item
2282 * @param array $item
2284 * likes => int count
2285 * dislikes => int count
2287 function api_format_items_likes(&$item) {
2288 $activities = array(
2290 'dislike' => array(),
2291 'attendyes' => array(),
2292 'attendno' => array(),
2293 'attendmaybe' => array()
2295 $items = q('SELECT * FROM item
2296 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2297 intval($item['uid']),
2298 dbesc($item['uri']));
2299 foreach ($items as $i){
2300 builtin_activity_puller($i, $activities);
2304 $uri = $item['uri'];
2305 foreach($activities as $k => $v) {
2306 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2313 * @brief format items to be returned by api
2315 * @param array $r array of items
2316 * @param array $user_info
2317 * @param bool $filter_user filter items by $user_info
2319 function api_format_items($r,$user_info, $filter_user = false) {
2324 foreach($r as $item) {
2325 api_share_as_retweet($item);
2327 localize_item($item);
2328 $status_user = api_item_get_user($a,$item);
2330 // Look if the posts are matching if they should be filtered by user id
2331 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2334 if ($item['thr-parent'] != $item['uri']) {
2335 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2337 dbesc($item['thr-parent']));
2339 $in_reply_to_status_id = intval($r[0]['id']);
2341 $in_reply_to_status_id = intval($item['parent']);
2343 $in_reply_to_status_id_str = (string) intval($item['parent']);
2345 $in_reply_to_screen_name = NULL;
2346 $in_reply_to_user_id = NULL;
2347 $in_reply_to_user_id_str = NULL;
2349 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2351 intval($in_reply_to_status_id));
2353 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2356 if ($r[0]['nick'] == "")
2357 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2359 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2360 $in_reply_to_user_id = intval($r[0]['id']);
2361 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2365 $in_reply_to_screen_name = NULL;
2366 $in_reply_to_user_id = NULL;
2367 $in_reply_to_status_id = NULL;
2368 $in_reply_to_user_id_str = NULL;
2369 $in_reply_to_status_id_str = NULL;
2372 $converted = api_convert_item($item);
2375 'text' => $converted["text"],
2376 'truncated' => False,
2377 'created_at'=> api_date($item['created']),
2378 'in_reply_to_status_id' => $in_reply_to_status_id,
2379 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2380 'source' => (($item['app']) ? $item['app'] : 'web'),
2381 'id' => intval($item['id']),
2382 'id_str' => (string) intval($item['id']),
2383 'in_reply_to_user_id' => $in_reply_to_user_id,
2384 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2385 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2387 'favorited' => $item['starred'] ? true : false,
2388 'user' => $status_user ,
2389 //'entities' => NULL,
2390 'statusnet_html' => $converted["html"],
2391 'statusnet_conversation_id' => $item['parent'],
2392 'friendica_activities' => api_format_items_likes($item),
2395 if (count($converted["attachments"]) > 0)
2396 $status["attachments"] = $converted["attachments"];
2398 if (count($converted["entities"]) > 0)
2399 $status["entities"] = $converted["entities"];
2401 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2402 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2403 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2404 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2407 // Retweets are only valid for top postings
2408 // It doesn't work reliable with the link if its a feed
2409 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2411 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2413 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2414 $retweeted_status = $status;
2415 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2417 $status["retweeted_status"] = $retweeted_status;
2420 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2421 unset($status["user"]["uid"]);
2422 unset($status["user"]["self"]);
2424 if ($item["coord"] != "") {
2425 $coords = explode(' ',$item["coord"]);
2426 if (count($coords) == 2) {
2427 $status["geo"] = array('type' => 'Point',
2428 'coordinates' => array((float) $coords[0],
2429 (float) $coords[1]));
2439 function api_account_rate_limit_status(&$a,$type) {
2441 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2442 'remaining_hits' => (string) 150,
2443 'hourly_limit' => (string) 150,
2444 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2447 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2449 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2451 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2453 function api_help_test(&$a,$type) {
2459 return api_apply_template('test', $type, array("$ok" => $ok));
2461 api_register_func('api/help/test','api_help_test',false);
2463 function api_lists(&$a,$type) {
2467 api_register_func('api/lists','api_lists',true);
2469 function api_lists_list(&$a,$type) {
2473 api_register_func('api/lists/list','api_lists_list',true);
2476 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2477 * This function is deprecated by Twitter
2478 * returns: json, xml
2480 function api_statuses_f(&$a, $type, $qtype) {
2481 if (api_user()===false) throw new ForbiddenException();
2482 $user_info = api_get_user($a);
2484 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2485 /* this is to stop Hotot to load friends multiple times
2486 * I'm not sure if I'm missing return something or
2487 * is a bug in hotot. Workaround, meantime
2491 return array('$users' => $ret);*/
2495 if($qtype == 'friends')
2496 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2497 if($qtype == 'followers')
2498 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2500 // friends and followers only for self
2501 if ($user_info['self'] == 0)
2502 $sql_extra = " AND false ";
2504 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2509 foreach($r as $cid){
2510 $user = api_get_user($a, $cid['nurl']);
2511 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2512 unset($user["uid"]);
2513 unset($user["self"]);
2519 return array('$users' => $ret);
2522 function api_statuses_friends(&$a, $type){
2523 $data = api_statuses_f($a,$type,"friends");
2524 if ($data===false) return false;
2525 return api_apply_template("friends", $type, $data);
2527 function api_statuses_followers(&$a, $type){
2528 $data = api_statuses_f($a,$type,"followers");
2529 if ($data===false) return false;
2530 return api_apply_template("friends", $type, $data);
2532 api_register_func('api/statuses/friends','api_statuses_friends',true);
2533 api_register_func('api/statuses/followers','api_statuses_followers',true);
2540 function api_statusnet_config(&$a,$type) {
2541 $name = $a->config['sitename'];
2542 $server = $a->get_hostname();
2543 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2544 $email = $a->config['admin_email'];
2545 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2546 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2547 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2548 if($a->config['api_import_size'])
2549 $texlimit = string($a->config['api_import_size']);
2550 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2551 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2554 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2555 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2556 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2557 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2558 'shorturllength' => '30',
2559 'friendica' => array(
2560 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2561 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2562 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2563 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2568 return api_apply_template('config', $type, array('$config' => $config));
2571 api_register_func('api/statusnet/config','api_statusnet_config',false);
2573 function api_statusnet_version(&$a,$type) {
2575 $fake_statusnet_version = "0.9.7";
2577 if($type === 'xml') {
2578 header("Content-type: application/xml");
2579 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2582 elseif($type === 'json') {
2583 header("Content-type: application/json");
2584 echo '"'.$fake_statusnet_version.'"';
2588 api_register_func('api/statusnet/version','api_statusnet_version',false);
2591 * @todo use api_apply_template() to return data
2593 function api_ff_ids(&$a,$type,$qtype) {
2594 if(! api_user()) throw new ForbiddenException();
2596 $user_info = api_get_user($a);
2598 if($qtype == 'friends')
2599 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2600 if($qtype == 'followers')
2601 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2603 if (!$user_info["self"])
2604 $sql_extra = " AND false ";
2606 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2608 $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",
2614 if($type === 'xml') {
2615 header("Content-type: application/xml");
2616 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2618 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2619 echo '</ids>' . "\r\n";
2622 elseif($type === 'json') {
2624 header("Content-type: application/json");
2629 $ret[] = intval($rr['id']);
2631 echo json_encode($ret);
2637 function api_friends_ids(&$a,$type) {
2638 api_ff_ids($a,$type,'friends');
2640 function api_followers_ids(&$a,$type) {
2641 api_ff_ids($a,$type,'followers');
2643 api_register_func('api/friends/ids','api_friends_ids',true);
2644 api_register_func('api/followers/ids','api_followers_ids',true);
2647 function api_direct_messages_new(&$a, $type) {
2648 if (api_user()===false) throw new ForbiddenException();
2650 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2652 $sender = api_get_user($a);
2654 if ($_POST['screen_name']) {
2655 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2657 dbesc($_POST['screen_name']));
2659 // Selecting the id by priority, friendica first
2660 api_best_nickname($r);
2662 $recipient = api_get_user($a, $r[0]['nurl']);
2664 $recipient = api_get_user($a, $_POST['user_id']);
2668 if (x($_REQUEST,'replyto')) {
2669 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2671 intval($_REQUEST['replyto']));
2672 $replyto = $r[0]['parent-uri'];
2673 $sub = $r[0]['title'];
2676 if (x($_REQUEST,'title')) {
2677 $sub = $_REQUEST['title'];
2680 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2684 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2687 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2688 $ret = api_format_messages($r[0], $recipient, $sender);
2691 $ret = array("error"=>$id);
2694 $data = Array('$messages'=>$ret);
2699 $data = api_rss_extra($a, $data, $user_info);
2702 return api_apply_template("direct_messages", $type, $data);
2705 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2707 function api_direct_messages_box(&$a, $type, $box) {
2708 if (api_user()===false) throw new ForbiddenException();
2711 $count = (x($_GET,'count')?$_GET['count']:20);
2712 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2713 if ($page<0) $page=0;
2715 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2716 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2718 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2719 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2722 unset($_REQUEST["user_id"]);
2723 unset($_GET["user_id"]);
2725 unset($_REQUEST["screen_name"]);
2726 unset($_GET["screen_name"]);
2728 $user_info = api_get_user($a);
2729 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2730 $profile_url = $user_info["url"];
2734 $start = $page*$count;
2737 if ($box=="sentbox") {
2738 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2740 elseif ($box=="conversation") {
2741 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2743 elseif ($box=="all") {
2744 $sql_extra = "true";
2746 elseif ($box=="inbox") {
2747 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2751 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2753 if ($user_id !="") {
2754 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2756 elseif($screen_name !=""){
2757 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2760 $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",
2763 intval($start), intval($count)
2768 foreach($r as $item) {
2769 if ($box == "inbox" || $item['from-url'] != $profile_url){
2770 $recipient = $user_info;
2771 $sender = api_get_user($a,normalise_link($item['contact-url']));
2773 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2774 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2775 $sender = $user_info;
2778 $ret[]=api_format_messages($item, $recipient, $sender);
2782 $data = array('$messages' => $ret);
2786 $data = api_rss_extra($a, $data, $user_info);
2789 return api_apply_template("direct_messages", $type, $data);
2793 function api_direct_messages_sentbox(&$a, $type){
2794 return api_direct_messages_box($a, $type, "sentbox");
2796 function api_direct_messages_inbox(&$a, $type){
2797 return api_direct_messages_box($a, $type, "inbox");
2799 function api_direct_messages_all(&$a, $type){
2800 return api_direct_messages_box($a, $type, "all");
2802 function api_direct_messages_conversation(&$a, $type){
2803 return api_direct_messages_box($a, $type, "conversation");
2805 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2806 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2807 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2808 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2812 function api_oauth_request_token(&$a, $type){
2814 $oauth = new FKOAuth1();
2815 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2816 }catch(Exception $e){
2817 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2822 function api_oauth_access_token(&$a, $type){
2824 $oauth = new FKOAuth1();
2825 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2826 }catch(Exception $e){
2827 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2833 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2834 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2837 function api_fr_photos_list(&$a,$type) {
2838 if (api_user()===false) throw new ForbiddenException();
2839 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2840 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2841 intval(local_user())
2844 'image/jpeg' => 'jpg',
2845 'image/png' => 'png',
2846 'image/gif' => 'gif'
2848 $data = array('photos'=>array());
2850 foreach($r as $rr) {
2852 $photo['id'] = $rr['resource-id'];
2853 $photo['album'] = $rr['album'];
2854 $photo['filename'] = $rr['filename'];
2855 $photo['type'] = $rr['type'];
2856 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2857 $data['photos'][] = $photo;
2860 return api_apply_template("photos_list", $type, $data);
2863 function api_fr_photo_detail(&$a,$type) {
2864 if (api_user()===false) throw new ForbiddenException();
2865 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2867 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2868 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2869 $data_sql = ($scale === false ? "" : "data, ");
2871 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2872 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2873 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2875 intval(local_user()),
2876 dbesc($_REQUEST['photo_id']),
2881 'image/jpeg' => 'jpg',
2882 'image/png' => 'png',
2883 'image/gif' => 'gif'
2887 $data = array('photo' => $r[0]);
2888 if ($scale !== false) {
2889 $data['photo']['data'] = base64_encode($data['photo']['data']);
2891 unset($data['photo']['datasize']); //needed only with scale param
2893 $data['photo']['link'] = array();
2894 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2895 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2897 $data['photo']['id'] = $data['photo']['resource-id'];
2898 unset($data['photo']['resource-id']);
2899 unset($data['photo']['minscale']);
2900 unset($data['photo']['maxscale']);
2903 throw new NotFoundException();
2906 return api_apply_template("photo_detail", $type, $data);
2909 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2910 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2915 * similar as /mod/redir.php
2916 * redirect to 'url' after dfrn auth
2918 * why this when there is mod/redir.php already?
2919 * This use api_user() and api_login()
2922 * c_url: url of remote contact to auth to
2923 * url: string, url to redirect after auth
2925 function api_friendica_remoteauth(&$a) {
2926 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2927 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2929 if ($url === '' || $c_url === '')
2930 throw new BadRequestException("Wrong parameters.");
2932 $c_url = normalise_link($c_url);
2936 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2941 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2942 throw new BadRequestException("Unknown contact");
2946 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2948 if($r[0]['duplex'] && $r[0]['issued-id']) {
2949 $orig_id = $r[0]['issued-id'];
2950 $dfrn_id = '1:' . $orig_id;
2952 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2953 $orig_id = $r[0]['dfrn-id'];
2954 $dfrn_id = '0:' . $orig_id;
2957 $sec = random_string();
2959 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2960 VALUES( %d, %s, '%s', '%s', %d )",
2968 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2969 $dest = (($url) ? '&destination_url=' . $url : '');
2970 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2971 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2972 . '&type=profile&sec=' . $sec . $dest . $quiet );
2974 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2977 function api_share_as_retweet(&$item) {
2978 $body = trim($item["body"]);
2980 // Skip if it isn't a pure repeated messages
2981 // Does it start with a share?
2982 if (strpos($body, "[share") > 0)
2985 // Does it end with a share?
2986 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2989 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2990 // Skip if there is no shared message in there
2991 if ($body == $attributes)
2995 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2996 if ($matches[1] != "")
2997 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2999 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3000 if ($matches[1] != "")
3001 $author = $matches[1];
3004 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3005 if ($matches[1] != "")
3006 $profile = $matches[1];
3008 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3009 if ($matches[1] != "")
3010 $profile = $matches[1];
3013 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3014 if ($matches[1] != "")
3015 $avatar = $matches[1];
3017 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3018 if ($matches[1] != "")
3019 $avatar = $matches[1];
3022 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3023 if ($matches[1] != "")
3024 $link = $matches[1];
3026 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3027 if ($matches[1] != "")
3028 $link = $matches[1];
3030 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3032 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
3035 $item["body"] = $shared_body;
3036 $item["author-name"] = $author;
3037 $item["author-link"] = $profile;
3038 $item["author-avatar"] = $avatar;
3039 $item["plink"] = $link;
3045 function api_get_nick($profile) {
3047 - remove trailing junk from profile url
3048 - pump.io check has to check the website
3053 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3054 dbesc(normalise_link($profile)));
3056 $nick = $r[0]["nick"];
3059 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3060 dbesc(normalise_link($profile)));
3062 $nick = $r[0]["nick"];
3066 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3067 if ($friendica != $profile)
3072 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3073 if ($diaspora != $profile)
3078 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3079 if ($twitter != $profile)
3085 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3086 if ($StatusnetHost != $profile) {
3087 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3088 if ($StatusnetUser != $profile) {
3089 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3090 $user = json_decode($UserData);
3092 $nick = $user->screen_name;
3097 // To-Do: look at the page if its really a pumpio site
3098 //if (!$nick == "") {
3099 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3100 // if ($pumpio != $profile)
3102 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3112 function api_clean_plain_items($Text) {
3113 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3115 $Text = bb_CleanPictureLinks($Text);
3117 $URLSearchString = "^\[\]";
3119 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3121 if ($include_entities == "true") {
3122 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3125 // Simplify "attachment" element
3126 $Text = api_clean_attachments($Text);
3132 * @brief Removes most sharing information for API text export
3134 * @param string $body The original body
3136 * @return string Cleaned body
3138 function api_clean_attachments($body) {
3139 $data = get_attachment_data($body);
3146 if (isset($data["text"]))
3147 $body = $data["text"];
3149 if (($body == "") AND (isset($data["title"])))
3150 $body = $data["title"];
3152 if (isset($data["url"]))
3153 $body .= "\n".$data["url"];
3158 function api_best_nickname(&$contacts) {
3159 $best_contact = array();
3161 if (count($contact) == 0)
3164 foreach ($contacts AS $contact)
3165 if ($contact["network"] == "") {
3166 $contact["network"] = "dfrn";
3167 $best_contact = array($contact);
3170 if (sizeof($best_contact) == 0)
3171 foreach ($contacts AS $contact)
3172 if ($contact["network"] == "dfrn")
3173 $best_contact = array($contact);
3175 if (sizeof($best_contact) == 0)
3176 foreach ($contacts AS $contact)
3177 if ($contact["network"] == "dspr")
3178 $best_contact = array($contact);
3180 if (sizeof($best_contact) == 0)
3181 foreach ($contacts AS $contact)
3182 if ($contact["network"] == "stat")
3183 $best_contact = array($contact);
3185 if (sizeof($best_contact) == 0)
3186 foreach ($contacts AS $contact)
3187 if ($contact["network"] == "pump")
3188 $best_contact = array($contact);
3190 if (sizeof($best_contact) == 0)
3191 foreach ($contacts AS $contact)
3192 if ($contact["network"] == "twit")
3193 $best_contact = array($contact);
3195 if (sizeof($best_contact) == 1)
3196 $contacts = $best_contact;
3198 $contacts = array($contacts[0]);
3201 // return all or a specified group of the user with the containing contacts
3202 function api_friendica_group_show(&$a, $type) {
3203 if (api_user()===false) throw new ForbiddenException();
3206 $user_info = api_get_user($a);
3207 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3208 $uid = $user_info['uid'];
3210 // get data of the specified group id or all groups if not specified
3212 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3215 // error message if specified gid is not in database
3217 throw new BadRequestException("gid not available");
3220 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3223 // loop through all groups and retrieve all members for adding data in the user array
3224 foreach ($r as $rr) {
3225 $members = group_get_members($rr['id']);
3227 foreach ($members as $member) {
3228 $user = api_get_user($a, $member['nurl']);
3231 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3233 return api_apply_template("group_show", $type, array('$groups' => $grps));
3235 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3238 // delete the specified group of the user
3239 function api_friendica_group_delete(&$a, $type) {
3240 if (api_user()===false) throw new ForbiddenException();
3243 $user_info = api_get_user($a);
3244 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3245 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3246 $uid = $user_info['uid'];
3248 // error if no gid specified
3249 if ($gid == 0 || $name == "")
3250 throw new BadRequestException('gid or name not specified');
3252 // get data of the specified group id
3253 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3256 // error message if specified gid is not in database
3258 throw new BadRequestException('gid not available');
3260 // get data of the specified group id and group name
3261 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3265 // error message if specified gid is not in database
3266 if (count($rname) == 0)
3267 throw new BadRequestException('wrong group name');
3270 $ret = group_rmv($uid, $name);
3273 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3274 return api_apply_template("group_delete", $type, array('$result' => $success));
3277 throw new BadRequestException('other API error');
3279 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3282 // create the specified group with the posted array of contacts
3283 function api_friendica_group_create(&$a, $type) {
3284 if (api_user()===false) throw new ForbiddenException();
3287 $user_info = api_get_user($a);
3288 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3289 $uid = $user_info['uid'];
3290 $json = json_decode($_POST['json'], true);
3291 $users = $json['user'];
3293 // error if no name specified
3295 throw new BadRequestException('group name not specified');
3297 // get data of the specified group name
3298 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3301 // error message if specified group name already exists
3302 if (count($rname) != 0)
3303 throw new BadRequestException('group name already exists');
3305 // check if specified group name is a deleted group
3306 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3309 // error message if specified group name already exists
3310 if (count($rname) != 0)
3311 $reactivate_group = true;
3314 $ret = group_add($uid, $name);
3316 $gid = group_byname($uid, $name);
3318 throw new BadRequestException('other API error');
3321 $erroraddinguser = false;
3322 $errorusers = array();
3323 foreach ($users as $user) {
3324 $cid = $user['cid'];
3325 // check if user really exists as contact
3326 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3329 if (count($contact))
3330 $result = group_add_member($uid, $name, $cid, $gid);
3332 $erroraddinguser = true;
3333 $errorusers[] = $cid;
3337 // return success message incl. missing users in array
3338 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3339 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3340 return api_apply_template("group_create", $type, array('result' => $success));
3342 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3345 // update the specified group with the posted array of contacts
3346 function api_friendica_group_update(&$a, $type) {
3347 if (api_user()===false) throw new ForbiddenException();
3350 $user_info = api_get_user($a);
3351 $uid = $user_info['uid'];
3352 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3353 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3354 $json = json_decode($_POST['json'], true);
3355 $users = $json['user'];
3357 // error if no name specified
3359 throw new BadRequestException('group name not specified');
3361 // error if no gid specified
3363 throw new BadRequestException('gid not specified');
3366 $members = group_get_members($gid);
3367 foreach ($members as $member) {
3368 $cid = $member['id'];
3369 foreach ($users as $user) {
3370 $found = ($user['cid'] == $cid ? true : false);
3373 $ret = group_rmv_member($uid, $name, $cid);
3378 $erroraddinguser = false;
3379 $errorusers = array();
3380 foreach ($users as $user) {
3381 $cid = $user['cid'];
3382 // check if user really exists as contact
3383 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3386 if (count($contact))
3387 $result = group_add_member($uid, $name, $cid, $gid);
3389 $erroraddinguser = true;
3390 $errorusers[] = $cid;
3394 // return success message incl. missing users in array
3395 $status = ($erroraddinguser ? "missing user" : "ok");
3396 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3397 return api_apply_template("group_update", $type, array('result' => $success));
3399 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3402 function api_friendica_activity(&$a, $type) {
3403 if (api_user()===false) throw new ForbiddenException();
3404 $verb = strtolower($a->argv[3]);
3405 $verb = preg_replace("|\..*$|", "", $verb);
3407 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3409 $res = do_like($id, $verb);
3416 return api_apply_template('test', $type, array('ok' => $ok));
3418 throw new BadRequestException('Error adding activity');
3422 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3423 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3424 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3425 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3426 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3427 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3428 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3429 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3430 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3431 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3434 * @brief Returns notifications
3437 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3440 function api_friendica_notification(&$a, $type) {
3441 if (api_user()===false) throw new ForbiddenException();
3442 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3443 $nm = new NotificationsManager();
3445 $notes = $nm->getAll(array(), "+seen -date", 50);
3446 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3450 * @brief Set notification as seen and returns associated item (if possible)
3452 * POST request with 'id' param as notification id
3455 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3458 function api_friendica_notification_seen(&$a, $type){
3459 if (api_user()===false) throw new ForbiddenException();
3460 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3462 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3464 $nm = new NotificationsManager();
3465 $note = $nm->getByID($id);
3466 if (is_null($note)) throw new BadRequestException("Invalid argument");
3468 $nm->setSeen($note);
3469 if ($note['otype']=='item') {
3470 // would be really better with an ItemsManager and $im->getByID() :-P
3471 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3472 intval($note['iid']),
3473 intval(local_user())
3476 // we found the item, return it to the user
3477 $user_info = api_get_user($a);
3478 $ret = api_format_items($r,$user_info);
3479 $data = array('$statuses' => $ret);
3480 return api_apply_template("timeline", $type, $data);
3482 // the item can't be found, but we set the note as seen, so we count this as a success
3484 return api_apply_template('<auto>', $type, array('status' => "success"));
3487 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3488 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3493 [pagename] => api/1.1/statuses/lookup.json
3494 [id] => 605138389168451584
3495 [include_cards] => true
3496 [cards_platform] => Android-12
3497 [include_entities] => true
3498 [include_my_retweet] => 1
3500 [include_reply_count] => true
3501 [include_descendent_reply_count] => true
3505 Not implemented by now:
3506 statuses/retweets_of_me
3511 account/update_location
3512 account/update_profile_background_image
3513 account/update_profile_image
3517 Not implemented in status.net:
3518 statuses/retweeted_to_me
3519 statuses/retweeted_by_me
3520 direct_messages/destroy
3522 account/update_delivery_device
3523 notifications/follow