3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
29 define('API_METHOD_ANY','*');
30 define('API_METHOD_GET','GET');
31 define('API_METHOD_POST','POST,PUT');
32 define('API_METHOD_DELETE','POST,DELETE');
40 * @brief Auth API user
42 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
43 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
44 * into a page, and visitors will post something without noticing it).
47 if ($_SESSION['allow_api'])
54 * @brief Get source name from API client
56 * Clients can send 'source' parameter to be show in post metadata
57 * as "sent via <source>".
58 * Some clients doesn't send a source param, we support ones we know
62 * Client source name, default to "api" if unset/unknown
64 function api_source() {
65 if (requestdata('source'))
66 return (requestdata('source'));
68 // Support for known clients that doesn't send a source name
69 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
72 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
78 * @brief Format date for API
80 * @param string $str Source date, as UTC
81 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
83 function api_date($str){
84 //Wed May 23 06:01:13 +0000 2007
85 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
89 * @brief Register API endpoint
91 * Register a function to be the endpont for defined API path.
93 * @param string $path API URL path, relative to $a->get_baseurl()
94 * @param string $func Function name to call on path request
95 * @param bool $auth API need logged user
96 * @param string $method
97 * HTTP method reqiured to call this endpoint.
98 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
99 * Default to API_METHOD_ANY
101 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
109 // Workaround for hotot
110 $path = str_replace("api/", "api/1.1/", $path);
119 * @brief Login API user
121 * Log in user via OAuth1 or Simple HTTP Auth.
122 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
125 * @hook 'authenticate'
127 * 'username' => username from login form
128 * 'password' => password from login form
129 * 'authenticated' => return status,
130 * 'user_record' => return authenticated user record
132 * array $user logged user record
134 function api_login(&$a){
137 $oauth = new FKOAuth1();
138 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
139 if (!is_null($token)){
140 $oauth->loginUser($token->uid);
141 call_hooks('logged_in', $a->user);
144 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
145 }catch(Exception $e){
151 // workaround for HTTP-auth in CGI mode
152 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
153 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
154 if(strlen($userpass)) {
155 list($name, $password) = explode(':', $userpass);
156 $_SERVER['PHP_AUTH_USER'] = $name;
157 $_SERVER['PHP_AUTH_PW'] = $password;
161 if (!isset($_SERVER['PHP_AUTH_USER'])) {
162 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
163 header('WWW-Authenticate: Basic realm="Friendica"');
164 header('HTTP/1.0 401 Unauthorized');
165 die((api_error($a, 'json', "This api requires login")));
167 //die('This api requires login');
170 $user = $_SERVER['PHP_AUTH_USER'];
171 $password = $_SERVER['PHP_AUTH_PW'];
172 $encrypted = hash('whirlpool',trim($password));
174 // allow "user@server" login (but ignore 'server' part)
175 $at=strstr($user, "@", true);
176 if ( $at ) $user=$at;
179 * next code from mod/auth.php. needs better solution
184 'username' => trim($user),
185 'password' => trim($password),
186 'authenticated' => 0,
187 'user_record' => null
192 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
193 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
194 * and later plugins should not interfere with an earlier one that succeeded.
198 call_hooks('authenticate', $addon_auth);
200 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
201 $record = $addon_auth['user_record'];
204 // process normal login request
206 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
207 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
216 if((! $record) || (! count($record))) {
217 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
218 header('WWW-Authenticate: Basic realm="Friendica"');
219 header('HTTP/1.0 401 Unauthorized');
220 die('This api requires login');
223 authenticate_success($record); $_SESSION["allow_api"] = true;
225 call_hooks('logged_in', $a->user);
230 * @brief Check HTTP method of called API
232 * API endpoints can define which HTTP method to accept when called.
233 * This function check the current HTTP method agains endpoint
236 * @param string $method Required methods, uppercase, separated by comma
239 function api_check_method($method) {
240 if ($method=="*") return True;
241 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
245 * @brief Main API entry point
247 * Authenticate user, call registered API function, set HTTP headers
250 * @return string API call result
252 function api_call(&$a){
253 GLOBAL $API, $called_api;
256 if (strpos($a->query_string, ".xml")>0) $type="xml";
257 if (strpos($a->query_string, ".json")>0) $type="json";
258 if (strpos($a->query_string, ".rss")>0) $type="rss";
259 if (strpos($a->query_string, ".atom")>0) $type="atom";
260 if (strpos($a->query_string, ".as")>0) $type="as";
262 foreach ($API as $p=>$info){
263 if (strpos($a->query_string, $p)===0){
264 if (!api_check_method($info['method'])){
265 throw new MethodNotAllowedException();
268 $called_api= explode("/",$p);
269 //unset($_SERVER['PHP_AUTH_USER']);
270 if ($info['auth']===true && api_user()===false) {
274 load_contact_links(api_user());
276 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
277 logger('API parameters: ' . print_r($_REQUEST,true));
279 $stamp = microtime(true);
280 $r = call_user_func($info['func'], $a, $type);
281 $duration = (float)(microtime(true)-$stamp);
282 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
285 // api function returned false withour throw an
286 // exception. This should not happend, throw a 500
287 throw new InternalServerErrorException();
292 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
293 header ("Content-Type: text/xml");
294 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
297 header ("Content-Type: application/json");
299 $json = json_encode($rr);
300 if ($_GET['callback'])
301 $json = $_GET['callback']."(".$json.")";
305 header ("Content-Type: application/rss+xml");
306 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
309 header ("Content-Type: application/atom+xml");
310 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
313 //header ("Content-Type: application/json");
315 // return json_encode($rr);
316 return json_encode($r);
322 throw new NotImplementedException();
323 } catch (HTTPException $e) {
324 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
325 return api_error($a, $type, $e);
330 * @brief Format API error string
333 * @param string $type Return type (xml, json, rss, as)
334 * @param string $error Error message
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 foreach($data as $k=>$v) {
696 $attrs .= sprintf('%s="%s" ', $k, $v);
698 if (is_numeric($k)) $k=trim($ename,'s');
699 $childs.=api_array_to_xml($v, $k);
703 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
708 * load api $templatename for $type and replace $data array
710 function api_apply_template($templatename, $type, $data){
718 $data = array_xmlify($data);
719 if ($templatename==="<auto>") {
720 $ret = api_array_to_xml($data);
722 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
724 header ("Content-Type: text/xml");
725 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
728 $ret = replace_macros($tpl, $data);
744 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
745 * returns a 401 status code and an error message if not.
746 * http://developer.twitter.com/doc/get/account/verify_credentials
748 function api_account_verify_credentials(&$a, $type){
749 if (api_user()===false) throw new ForbiddenException();
751 unset($_REQUEST["user_id"]);
752 unset($_GET["user_id"]);
754 unset($_REQUEST["screen_name"]);
755 unset($_GET["screen_name"]);
757 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
759 $user_info = api_get_user($a);
761 // "verified" isn't used here in the standard
762 unset($user_info["verified"]);
764 // - Adding last status
766 $user_info["status"] = api_status_show($a,"raw");
767 if (!count($user_info["status"]))
768 unset($user_info["status"]);
770 unset($user_info["status"]["user"]);
773 // "uid" and "self" are only needed for some internal stuff, so remove it from here
774 unset($user_info["uid"]);
775 unset($user_info["self"]);
777 return api_apply_template("user", $type, array('$user' => $user_info));
780 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
784 * get data from $_POST or $_GET
786 function requestdata($k){
787 if (isset($_POST[$k])){
790 if (isset($_GET[$k])){
796 /*Waitman Gobble Mod*/
797 function api_statuses_mediap(&$a, $type) {
798 if (api_user()===false) {
799 logger('api_statuses_update: no user');
800 throw new ForbiddenException();
802 $user_info = api_get_user($a);
804 $_REQUEST['type'] = 'wall';
805 $_REQUEST['profile_uid'] = api_user();
806 $_REQUEST['api_source'] = true;
807 $txt = requestdata('status');
808 //$txt = urldecode(requestdata('status'));
810 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
812 require_once('library/HTMLPurifier.auto.php');
814 $txt = html2bb_video($txt);
815 $config = HTMLPurifier_Config::createDefault();
816 $config->set('Cache.DefinitionImpl', null);
817 $purifier = new HTMLPurifier($config);
818 $txt = $purifier->purify($txt);
820 $txt = html2bbcode($txt);
822 $a->argv[1]=$user_info['screen_name']; //should be set to username?
824 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
825 $bebop = wall_upload_post($a);
827 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
828 $_REQUEST['body']=$txt."\n\n".$bebop;
831 // this should output the last post (the one we just posted).
832 return api_status_show($a,$type);
834 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
835 /*Waitman Gobble Mod*/
838 function api_statuses_update(&$a, $type) {
839 if (api_user()===false) {
840 logger('api_statuses_update: no user');
841 throw new ForbiddenException();
844 $user_info = api_get_user($a);
846 // convert $_POST array items to the form we use for web posts.
848 // logger('api_post: ' . print_r($_POST,true));
850 if(requestdata('htmlstatus')) {
851 $txt = requestdata('htmlstatus');
852 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
854 require_once('library/HTMLPurifier.auto.php');
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)));
910 $throttle_week = get_config('system','throttle_limit_week');
911 if ($throttle_week > 0) {
912 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
914 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
915 AND `created` > '%s' AND `id` = `parent`",
916 intval(api_user()), dbesc($datefrom));
919 $posts_week = $r[0]["posts_week"];
923 if ($posts_week > $throttle_week) {
924 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
925 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
929 $throttle_month = get_config('system','throttle_limit_month');
930 if ($throttle_month > 0) {
931 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
933 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
934 AND `created` > '%s' AND `id` = `parent`",
935 intval(api_user()), dbesc($datefrom));
938 $posts_month = $r[0]["posts_month"];
942 if ($posts_month > $throttle_month) {
943 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
944 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
948 $_REQUEST['type'] = 'wall';
951 if(x($_FILES,'media')) {
952 // upload the image if we have one
953 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
954 $media = wall_upload_post($a);
956 $_REQUEST['body'] .= "\n\n".$media;
959 // To-Do: Multiple IDs
960 if (requestdata('media_ids')) {
961 $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",
962 intval(requestdata('media_ids')), api_user());
964 $phototypes = Photo::supportedTypes();
965 $ext = $phototypes[$r[0]['type']];
966 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
967 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
971 // set this so that the item_post() function is quiet and doesn't redirect or emit json
973 $_REQUEST['api_source'] = true;
975 if (!x($_REQUEST, "source"))
976 $_REQUEST["source"] = api_source();
978 // call out normal post function
982 // this should output the last post (the one we just posted).
983 return api_status_show($a,$type);
985 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
986 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
989 function api_media_upload(&$a, $type) {
990 if (api_user()===false) {
992 throw new ForbiddenException();
995 $user_info = api_get_user($a);
997 if(!x($_FILES,'media')) {
999 throw new BadRequestException("No media.");
1002 $media = wall_upload_post($a, false);
1005 throw new InternalServerErrorException();
1008 $returndata = array();
1009 $returndata["media_id"] = $media["id"];
1010 $returndata["media_id_string"] = (string)$media["id"];
1011 $returndata["size"] = $media["size"];
1012 $returndata["image"] = array("w" => $media["width"],
1013 "h" => $media["height"],
1014 "image_type" => $media["type"]);
1016 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1018 return array("media" => $returndata);
1020 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1022 function api_status_show(&$a, $type){
1023 $user_info = api_get_user($a);
1025 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1028 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1032 // get last public wall message
1033 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1034 FROM `item`, `item` as `i`
1035 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1036 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1037 AND `i`.`id` = `item`.`parent`
1038 AND `item`.`type`!='activity' $privacy_sql
1039 ORDER BY `item`.`created` DESC
1041 intval($user_info['cid']),
1043 dbesc($user_info['url']),
1044 dbesc(normalise_link($user_info['url'])),
1045 dbesc($user_info['url']),
1046 dbesc(normalise_link($user_info['url']))
1049 if (count($lastwall)>0){
1050 $lastwall = $lastwall[0];
1052 $in_reply_to_status_id = NULL;
1053 $in_reply_to_user_id = NULL;
1054 $in_reply_to_status_id_str = NULL;
1055 $in_reply_to_user_id_str = NULL;
1056 $in_reply_to_screen_name = NULL;
1057 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1058 $in_reply_to_status_id= intval($lastwall['parent']);
1059 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1061 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1063 if ($r[0]['nick'] == "")
1064 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1066 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1067 $in_reply_to_user_id = intval($r[0]['id']);
1068 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1072 // There seems to be situation, where both fields are identical:
1073 // https://github.com/friendica/friendica/issues/1010
1074 // This is a bugfix for that.
1075 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1076 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1077 $in_reply_to_status_id = NULL;
1078 $in_reply_to_user_id = NULL;
1079 $in_reply_to_status_id_str = NULL;
1080 $in_reply_to_user_id_str = NULL;
1081 $in_reply_to_screen_name = NULL;
1084 $converted = api_convert_item($lastwall);
1086 $status_info = array(
1087 'created_at' => api_date($lastwall['created']),
1088 'id' => intval($lastwall['id']),
1089 'id_str' => (string) $lastwall['id'],
1090 'text' => $converted["text"],
1091 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1092 'truncated' => false,
1093 'in_reply_to_status_id' => $in_reply_to_status_id,
1094 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1095 'in_reply_to_user_id' => $in_reply_to_user_id,
1096 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1097 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1098 'user' => $user_info,
1100 'coordinates' => "",
1102 'contributors' => "",
1103 'is_quote_status' => false,
1104 'retweet_count' => 0,
1105 'favorite_count' => 0,
1106 'favorited' => $lastwall['starred'] ? true : false,
1107 'retweeted' => false,
1108 'possibly_sensitive' => false,
1110 'statusnet_html' => $converted["html"],
1111 'statusnet_conversation_id' => $lastwall['parent'],
1114 if (count($converted["attachments"]) > 0)
1115 $status_info["attachments"] = $converted["attachments"];
1117 if (count($converted["entities"]) > 0)
1118 $status_info["entities"] = $converted["entities"];
1120 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1121 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1122 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1123 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1125 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1126 unset($status_info["user"]["uid"]);
1127 unset($status_info["user"]["self"]);
1130 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1133 return($status_info);
1135 return api_apply_template("status", $type, array('$status' => $status_info));
1144 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1145 * The author's most recent status will be returned inline.
1146 * http://developer.twitter.com/doc/get/users/show
1148 function api_users_show(&$a, $type){
1149 $user_info = api_get_user($a);
1151 $lastwall = q("SELECT `item`.*
1152 FROM `item`, `contact`
1153 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1154 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1155 AND `contact`.`id`=`item`.`contact-id`
1156 AND `type`!='activity'
1157 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1158 ORDER BY `created` DESC
1161 dbesc(ACTIVITY_POST),
1162 intval($user_info['cid']),
1163 dbesc($user_info['url']),
1164 dbesc(normalise_link($user_info['url'])),
1165 dbesc($user_info['url']),
1166 dbesc(normalise_link($user_info['url']))
1168 if (count($lastwall)>0){
1169 $lastwall = $lastwall[0];
1171 $in_reply_to_status_id = NULL;
1172 $in_reply_to_user_id = NULL;
1173 $in_reply_to_status_id_str = NULL;
1174 $in_reply_to_user_id_str = NULL;
1175 $in_reply_to_screen_name = NULL;
1176 if ($lastwall['parent']!=$lastwall['id']) {
1177 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1178 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1179 if (count($reply)>0) {
1180 $in_reply_to_status_id = intval($lastwall['parent']);
1181 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1183 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1185 if ($r[0]['nick'] == "")
1186 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1188 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1189 $in_reply_to_user_id = intval($r[0]['id']);
1190 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1195 $converted = api_convert_item($lastwall);
1197 $user_info['status'] = array(
1198 'text' => $converted["text"],
1199 'truncated' => false,
1200 'created_at' => api_date($lastwall['created']),
1201 'in_reply_to_status_id' => $in_reply_to_status_id,
1202 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1203 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1204 'id' => intval($lastwall['contact-id']),
1205 'id_str' => (string) $lastwall['contact-id'],
1206 'in_reply_to_user_id' => $in_reply_to_user_id,
1207 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1208 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1210 'favorited' => $lastwall['starred'] ? true : false,
1211 'statusnet_html' => $converted["html"],
1212 'statusnet_conversation_id' => $lastwall['parent'],
1215 if (count($converted["attachments"]) > 0)
1216 $user_info["status"]["attachments"] = $converted["attachments"];
1218 if (count($converted["entities"]) > 0)
1219 $user_info["status"]["entities"] = $converted["entities"];
1221 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1222 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1223 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1224 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1228 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1229 unset($user_info["uid"]);
1230 unset($user_info["self"]);
1232 return api_apply_template("user", $type, array('$user' => $user_info));
1235 api_register_func('api/users/show','api_users_show');
1238 function api_users_search(&$a, $type) {
1239 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1241 $userlist = array();
1243 if (isset($_GET["q"])) {
1244 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1246 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1249 foreach ($r AS $user) {
1250 $user_info = api_get_user($a, $user["id"]);
1251 //echo print_r($user_info, true)."\n";
1252 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1253 $userlist[] = $userdata["user"];
1255 $userlist = array("users" => $userlist);
1257 throw new BadRequestException("User not found.");
1260 throw new BadRequestException("User not found.");
1265 api_register_func('api/users/search','api_users_search');
1269 * http://developer.twitter.com/doc/get/statuses/home_timeline
1271 * TODO: Optional parameters
1272 * TODO: Add reply info
1274 function api_statuses_home_timeline(&$a, $type){
1275 if (api_user()===false) throw new ForbiddenException();
1277 unset($_REQUEST["user_id"]);
1278 unset($_GET["user_id"]);
1280 unset($_REQUEST["screen_name"]);
1281 unset($_GET["screen_name"]);
1283 $user_info = api_get_user($a);
1284 // get last newtork messages
1288 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1289 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1290 if ($page<0) $page=0;
1291 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1292 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1293 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1294 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1295 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1297 $start = $page*$count;
1301 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1302 if ($exclude_replies > 0)
1303 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1304 if ($conversation_id > 0)
1305 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1307 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1308 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1309 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1310 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1311 FROM `item`, `contact`
1312 WHERE `item`.`uid` = %d AND `verb` = '%s'
1313 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1314 AND `contact`.`id` = `item`.`contact-id`
1315 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1318 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1320 dbesc(ACTIVITY_POST),
1322 intval($start), intval($count)
1325 $ret = api_format_items($r,$user_info);
1327 // Set all posts from the query above to seen
1329 foreach ($r AS $item)
1330 $idarray[] = intval($item["id"]);
1332 $idlist = implode(",", $idarray);
1335 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1338 $data = array('$statuses' => $ret);
1342 $data = api_rss_extra($a, $data, $user_info);
1345 $as = api_format_as($a, $ret, $user_info);
1346 $as['title'] = $a->config['sitename']." Home Timeline";
1347 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1352 return api_apply_template("timeline", $type, $data);
1354 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1355 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1357 function api_statuses_public_timeline(&$a, $type){
1358 if (api_user()===false) throw new ForbiddenException();
1360 $user_info = api_get_user($a);
1361 // get last newtork messages
1365 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1366 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1367 if ($page<0) $page=0;
1368 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1369 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1370 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1371 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1372 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1374 $start = $page*$count;
1377 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1378 if ($exclude_replies > 0)
1379 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1380 if ($conversation_id > 0)
1381 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1383 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1384 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1385 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1386 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1387 `user`.`nickname`, `user`.`hidewall`
1388 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1389 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1390 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1391 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1392 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1393 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1394 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1397 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1398 dbesc(ACTIVITY_POST),
1403 $ret = api_format_items($r,$user_info);
1406 $data = array('$statuses' => $ret);
1410 $data = api_rss_extra($a, $data, $user_info);
1413 $as = api_format_as($a, $ret, $user_info);
1414 $as['title'] = $a->config['sitename']." Public Timeline";
1415 $as['link']['url'] = $a->get_baseurl()."/";
1420 return api_apply_template("timeline", $type, $data);
1422 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1427 function api_statuses_show(&$a, $type){
1428 if (api_user()===false) throw new ForbiddenException();
1430 $user_info = api_get_user($a);
1433 $id = intval($a->argv[3]);
1436 $id = intval($_REQUEST["id"]);
1440 $id = intval($a->argv[4]);
1442 logger('API: api_statuses_show: '.$id);
1444 $conversation = (x($_REQUEST,'conversation')?1:0);
1448 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1450 $sql_extra .= " AND `item`.`id` = %d";
1452 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1453 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1454 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1455 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1456 FROM `item`, `contact`
1457 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1458 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1459 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1462 dbesc(ACTIVITY_POST),
1467 throw new BadRequestException("There is no status with this id.");
1470 $ret = api_format_items($r,$user_info);
1472 if ($conversation) {
1473 $data = array('$statuses' => $ret);
1474 return api_apply_template("timeline", $type, $data);
1476 $data = array('$status' => $ret[0]);
1480 $data = api_rss_extra($a, $data, $user_info);
1482 return api_apply_template("status", $type, $data);
1485 api_register_func('api/statuses/show','api_statuses_show', true);
1491 function api_conversation_show(&$a, $type){
1492 if (api_user()===false) throw new ForbiddenException();
1494 $user_info = api_get_user($a);
1497 $id = intval($a->argv[3]);
1498 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1499 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1500 if ($page<0) $page=0;
1501 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1502 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1504 $start = $page*$count;
1507 $id = intval($_REQUEST["id"]);
1511 $id = intval($a->argv[4]);
1513 logger('API: api_conversation_show: '.$id);
1515 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1517 $id = $r[0]["parent"];
1522 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1524 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1525 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1526 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1527 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1528 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1529 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1530 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1531 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1532 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1533 AND `item`.`id`>%d $sql_extra
1534 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1535 intval($id), intval(api_user()),
1536 dbesc(ACTIVITY_POST),
1538 intval($start), intval($count)
1542 throw new BadRequestException("There is no conversation with this id.");
1544 $ret = api_format_items($r,$user_info);
1546 $data = array('$statuses' => $ret);
1547 return api_apply_template("timeline", $type, $data);
1549 api_register_func('api/conversation/show','api_conversation_show', true);
1555 function api_statuses_repeat(&$a, $type){
1558 if (api_user()===false) throw new ForbiddenException();
1560 $user_info = api_get_user($a);
1563 $id = intval($a->argv[3]);
1566 $id = intval($_REQUEST["id"]);
1570 $id = intval($a->argv[4]);
1572 logger('API: api_statuses_repeat: '.$id);
1574 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1575 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1576 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1577 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1578 FROM `item`, `contact`
1579 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1580 AND `contact`.`id` = `item`.`contact-id`
1581 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1582 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1583 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1585 AND `item`.`id`=%d",
1589 if ($r[0]['body'] != "") {
1590 if (!intval(get_config('system','old_share'))) {
1591 if (strpos($r[0]['body'], "[/share]") !== false) {
1592 $pos = strpos($r[0]['body'], "[share");
1593 $post = substr($r[0]['body'], $pos);
1595 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1597 $post .= $r[0]['body'];
1598 $post .= "[/share]";
1600 $_REQUEST['body'] = $post;
1602 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1604 $_REQUEST['profile_uid'] = api_user();
1605 $_REQUEST['type'] = 'wall';
1606 $_REQUEST['api_source'] = true;
1608 if (!x($_REQUEST, "source"))
1609 $_REQUEST["source"] = api_source();
1613 throw new ForbiddenException();
1615 // this should output the last post (the one we just posted).
1617 return(api_status_show($a,$type));
1619 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1624 function api_statuses_destroy(&$a, $type){
1625 if (api_user()===false) throw new ForbiddenException();
1627 $user_info = api_get_user($a);
1630 $id = intval($a->argv[3]);
1633 $id = intval($_REQUEST["id"]);
1637 $id = intval($a->argv[4]);
1639 logger('API: api_statuses_destroy: '.$id);
1641 $ret = api_statuses_show($a, $type);
1643 drop_item($id, false);
1647 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1651 * http://developer.twitter.com/doc/get/statuses/mentions
1654 function api_statuses_mentions(&$a, $type){
1655 if (api_user()===false) throw new ForbiddenException();
1657 unset($_REQUEST["user_id"]);
1658 unset($_GET["user_id"]);
1660 unset($_REQUEST["screen_name"]);
1661 unset($_GET["screen_name"]);
1663 $user_info = api_get_user($a);
1664 // get last newtork messages
1668 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1669 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1670 if ($page<0) $page=0;
1671 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1672 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1673 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1675 $start = $page*$count;
1677 // Ugly code - should be changed
1678 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1679 $myurl = substr($myurl,strpos($myurl,'://')+3);
1680 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1681 $myurl = str_replace('www.','',$myurl);
1682 $diasp_url = str_replace('/profile/','/u/',$myurl);
1685 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1687 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1688 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1689 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1690 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1691 FROM `item`, `contact`
1692 WHERE `item`.`uid` = %d AND `verb` = '%s'
1693 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1694 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1695 AND `contact`.`id` = `item`.`contact-id`
1696 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1697 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1700 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1702 dbesc(ACTIVITY_POST),
1703 dbesc(protect_sprintf($myurl)),
1704 dbesc(protect_sprintf($myurl)),
1707 intval($start), intval($count)
1710 $ret = api_format_items($r,$user_info);
1713 $data = array('$statuses' => $ret);
1717 $data = api_rss_extra($a, $data, $user_info);
1720 $as = api_format_as($a, $ret, $user_info);
1721 $as["title"] = $a->config['sitename']." Mentions";
1722 $as['link']['url'] = $a->get_baseurl()."/";
1727 return api_apply_template("timeline", $type, $data);
1729 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1730 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1733 function api_statuses_user_timeline(&$a, $type){
1734 if (api_user()===false) throw new ForbiddenException();
1736 $user_info = api_get_user($a);
1737 // get last network messages
1739 logger("api_statuses_user_timeline: api_user: ". api_user() .
1740 "\nuser_info: ".print_r($user_info, true) .
1741 "\n_REQUEST: ".print_r($_REQUEST, true),
1745 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1746 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1747 if ($page<0) $page=0;
1748 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1749 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1750 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1751 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1753 $start = $page*$count;
1756 if ($user_info['self']==1)
1757 $sql_extra .= " AND `item`.`wall` = 1 ";
1759 if ($exclude_replies > 0)
1760 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1761 if ($conversation_id > 0)
1762 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1764 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1765 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1766 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1767 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1768 FROM `item`, `contact`
1769 WHERE `item`.`uid` = %d AND `verb` = '%s'
1770 AND `item`.`contact-id` = %d
1771 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1772 AND `contact`.`id` = `item`.`contact-id`
1773 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1776 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1778 dbesc(ACTIVITY_POST),
1779 intval($user_info['cid']),
1781 intval($start), intval($count)
1784 $ret = api_format_items($r,$user_info, true);
1786 $data = array('$statuses' => $ret);
1790 $data = api_rss_extra($a, $data, $user_info);
1793 return api_apply_template("timeline", $type, $data);
1795 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1799 * Star/unstar an item
1800 * param: id : id of the item
1802 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1804 function api_favorites_create_destroy(&$a, $type){
1805 if (api_user()===false) throw new ForbiddenException();
1807 // for versioned api.
1808 /// @TODO We need a better global soluton
1810 if ($a->argv[1]=="1.1") $action_argv_id=3;
1812 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1813 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1814 if ($a->argc==$action_argv_id+2) {
1815 $itemid = intval($a->argv[$action_argv_id+1]);
1817 $itemid = intval($_REQUEST['id']);
1820 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1821 $itemid, api_user());
1823 if ($item===false || count($item)==0)
1824 throw new BadRequestException("Invalid item.");
1828 $item[0]['starred']=1;
1831 $item[0]['starred']=0;
1834 throw new BadRequestException("Invalid action ".$action);
1836 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1837 $item[0]['starred'], $itemid, api_user());
1839 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1840 $item[0]['starred'], $itemid, api_user());
1843 throw InternalServerErrorException("DB error");
1846 $user_info = api_get_user($a);
1847 $rets = api_format_items($item,$user_info);
1850 $data = array('$status' => $ret);
1854 $data = api_rss_extra($a, $data, $user_info);
1857 return api_apply_template("status", $type, $data);
1859 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1860 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1862 function api_favorites(&$a, $type){
1865 if (api_user()===false) throw new ForbiddenException();
1867 $called_api= array();
1869 $user_info = api_get_user($a);
1871 // in friendica starred item are private
1872 // return favorites only for self
1873 logger('api_favorites: self:' . $user_info['self']);
1875 if ($user_info['self']==0) {
1881 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1882 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1883 $count = (x($_GET,'count')?$_GET['count']:20);
1884 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1885 if ($page<0) $page=0;
1887 $start = $page*$count;
1890 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1892 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1893 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1894 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1895 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1896 FROM `item`, `contact`
1897 WHERE `item`.`uid` = %d
1898 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1899 AND `item`.`starred` = 1
1900 AND `contact`.`id` = `item`.`contact-id`
1901 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1904 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1907 intval($start), intval($count)
1910 $ret = api_format_items($r,$user_info);
1914 $data = array('$statuses' => $ret);
1918 $data = api_rss_extra($a, $data, $user_info);
1921 return api_apply_template("timeline", $type, $data);
1923 api_register_func('api/favorites','api_favorites', true);
1928 function api_format_as($a, $ret, $user_info) {
1930 $as['title'] = $a->config['sitename']." Public Timeline";
1932 foreach ($ret as $item) {
1933 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1934 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1935 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1936 $avatar[0]["rel"] = "avatar";
1937 $avatar[0]["type"] = "";
1938 $avatar[0]["width"] = 96;
1939 $avatar[0]["height"] = 96;
1940 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1941 $avatar[1]["rel"] = "avatar";
1942 $avatar[1]["type"] = "";
1943 $avatar[1]["width"] = 48;
1944 $avatar[1]["height"] = 48;
1945 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1946 $avatar[2]["rel"] = "avatar";
1947 $avatar[2]["type"] = "";
1948 $avatar[2]["width"] = 24;
1949 $avatar[2]["height"] = 24;
1950 $singleitem["actor"]["avatarLinks"] = $avatar;
1952 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1953 $singleitem["actor"]["image"]["rel"] = "avatar";
1954 $singleitem["actor"]["image"]["type"] = "";
1955 $singleitem["actor"]["image"]["width"] = 96;
1956 $singleitem["actor"]["image"]["height"] = 96;
1957 $singleitem["actor"]["type"] = "person";
1958 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1959 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1960 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1961 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1962 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1963 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1964 $singleitem["actor"]["contact"]["addresses"] = "";
1966 $singleitem["body"] = $item["text"];
1967 $singleitem["object"]["displayName"] = $item["text"];
1968 $singleitem["object"]["id"] = $item["url"];
1969 $singleitem["object"]["type"] = "note";
1970 $singleitem["object"]["url"] = $item["url"];
1971 //$singleitem["context"] =;
1972 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1973 $singleitem["provider"]["objectType"] = "service";
1974 $singleitem["provider"]["displayName"] = "Test";
1975 $singleitem["provider"]["url"] = "http://test.tld";
1976 $singleitem["title"] = $item["text"];
1977 $singleitem["verb"] = "post";
1978 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1979 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1980 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1981 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1982 //$singleitem["original"] = $item;
1983 $items[] = $singleitem;
1985 $as['items'] = $items;
1986 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1987 $as['link']['rel'] = "alternate";
1988 $as['link']['type'] = "text/html";
1992 function api_format_messages($item, $recipient, $sender) {
1993 // standard meta information
1995 'id' => $item['id'],
1996 'sender_id' => $sender['id'] ,
1998 'recipient_id' => $recipient['id'],
1999 'created_at' => api_date($item['created']),
2000 'sender_screen_name' => $sender['screen_name'],
2001 'recipient_screen_name' => $recipient['screen_name'],
2002 'sender' => $sender,
2003 'recipient' => $recipient,
2006 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2007 unset($ret["sender"]["uid"]);
2008 unset($ret["sender"]["self"]);
2009 unset($ret["recipient"]["uid"]);
2010 unset($ret["recipient"]["self"]);
2012 //don't send title to regular StatusNET requests to avoid confusing these apps
2013 if (x($_GET, 'getText')) {
2014 $ret['title'] = $item['title'] ;
2015 if ($_GET["getText"] == "html") {
2016 $ret['text'] = bbcode($item['body'], false, false);
2018 elseif ($_GET["getText"] == "plain") {
2019 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2020 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2024 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2026 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2027 unset($ret['sender']);
2028 unset($ret['recipient']);
2034 function api_convert_item($item) {
2036 $body = $item['body'];
2037 $attachments = api_get_attachments($body);
2039 // Workaround for ostatus messages where the title is identically to the body
2040 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2041 $statusbody = trim(html2plain($html, 0));
2043 // handle data: images
2044 $statusbody = api_format_items_embeded_images($item,$statusbody);
2046 $statustitle = trim($item['title']);
2048 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2049 $statustext = trim($statusbody);
2051 $statustext = trim($statustitle."\n\n".$statusbody);
2053 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2054 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2056 $statushtml = trim(bbcode($body, false, false));
2058 if ($item['title'] != "")
2059 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2061 $entities = api_get_entitities($statustext, $body);
2063 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
2066 function api_get_attachments(&$body) {
2069 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2071 $URLSearchString = "^\[\]";
2072 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2077 $attachments = array();
2079 foreach ($images[1] AS $image) {
2080 $imagedata = get_photo_info($image);
2083 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2086 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2087 foreach ($images[0] AS $orig)
2088 $body = str_replace($orig, "", $body);
2090 return $attachments;
2093 function api_get_entitities(&$text, $bbcode) {
2096 * Links at the first character of the post
2101 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2103 if ($include_entities != "true") {
2105 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2107 foreach ($images[1] AS $image) {
2108 $replace = proxy_url($image);
2109 $text = str_replace($image, $replace, $text);
2114 $bbcode = bb_CleanPictureLinks($bbcode);
2116 // Change pure links in text to bbcode uris
2117 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2119 $entities = array();
2120 $entities["hashtags"] = array();
2121 $entities["symbols"] = array();
2122 $entities["urls"] = array();
2123 $entities["user_mentions"] = array();
2125 $URLSearchString = "^\[\]";
2127 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2129 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2130 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2131 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2133 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2134 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2135 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2137 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2138 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2139 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2141 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2143 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2144 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2146 $ordered_urls = array();
2147 foreach ($urls[1] AS $id=>$url) {
2148 //$start = strpos($text, $url, $offset);
2149 $start = iconv_strpos($text, $url, 0, "UTF-8");
2150 if (!($start === false))
2151 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2154 ksort($ordered_urls);
2157 //foreach ($urls[1] AS $id=>$url) {
2158 foreach ($ordered_urls AS $url) {
2159 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2160 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2161 $display_url = $url["title"];
2163 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2164 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2166 if (strlen($display_url) > 26)
2167 $display_url = substr($display_url, 0, 25)."…";
2170 //$start = strpos($text, $url, $offset);
2171 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2172 if (!($start === false)) {
2173 $entities["urls"][] = array("url" => $url["url"],
2174 "expanded_url" => $url["url"],
2175 "display_url" => $display_url,
2176 "indices" => array($start, $start+strlen($url["url"])));
2177 $offset = $start + 1;
2181 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2182 $ordered_images = array();
2183 foreach ($images[1] AS $image) {
2184 //$start = strpos($text, $url, $offset);
2185 $start = iconv_strpos($text, $image, 0, "UTF-8");
2186 if (!($start === false))
2187 $ordered_images[$start] = $image;
2189 //$entities["media"] = array();
2192 foreach ($ordered_images AS $url) {
2193 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2194 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2196 if (strlen($display_url) > 26)
2197 $display_url = substr($display_url, 0, 25)."…";
2199 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2200 if (!($start === false)) {
2201 $image = get_photo_info($url);
2203 // If image cache is activated, then use the following sizes:
2204 // thumb (150), small (340), medium (600) and large (1024)
2205 if (!get_config("system", "proxy_disabled")) {
2206 $media_url = proxy_url($url);
2209 $scale = scale_image($image[0], $image[1], 150);
2210 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2212 if (($image[0] > 150) OR ($image[1] > 150)) {
2213 $scale = scale_image($image[0], $image[1], 340);
2214 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2217 $scale = scale_image($image[0], $image[1], 600);
2218 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2220 if (($image[0] > 600) OR ($image[1] > 600)) {
2221 $scale = scale_image($image[0], $image[1], 1024);
2222 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2226 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2229 $entities["media"][] = array(
2231 "id_str" => (string)$start+1,
2232 "indices" => array($start, $start+strlen($url)),
2233 "media_url" => normalise_link($media_url),
2234 "media_url_https" => $media_url,
2236 "display_url" => $display_url,
2237 "expanded_url" => $url,
2241 $offset = $start + 1;
2247 function api_format_items_embeded_images(&$item, $text){
2249 $text = preg_replace_callback(
2250 "|data:image/([^;]+)[^=]+=*|m",
2251 function($match) use ($a, $item) {
2252 return $a->get_baseurl()."/display/".$item['guid'];
2259 * @brief return likes, dislikes and attend status for item
2261 * @param array $item
2263 * likes => int count
2264 * dislikes => int count
2266 function api_format_items_likes(&$item) {
2267 $activities = array(
2269 'dislike' => array(),
2270 'attendyes' => array(),
2271 'attendno' => array(),
2272 'attendmaybe' => array()
2274 $items = q('SELECT * FROM item
2275 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2276 intval($item['uid']),
2277 dbesc($item['uri']));
2278 foreach ($items as $i){
2279 builtin_activity_puller($i, $activities);
2283 $uri = $item['uri'];
2284 foreach($activities as $k => $v) {
2285 $res[$k] = (x($v,$uri)?$v[$uri]:0);
2292 * @brief format items to be returned by api
2294 * @param array $r array of items
2295 * @param array $user_info
2296 * @param bool $filter_user filter items by $user_info
2298 function api_format_items($r,$user_info, $filter_user = false) {
2303 foreach($r as $item) {
2304 api_share_as_retweet($item);
2306 localize_item($item);
2307 $status_user = api_item_get_user($a,$item);
2309 // Look if the posts are matching if they should be filtered by user id
2310 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2313 if ($item['thr-parent'] != $item['uri']) {
2314 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2316 dbesc($item['thr-parent']));
2318 $in_reply_to_status_id = intval($r[0]['id']);
2320 $in_reply_to_status_id = intval($item['parent']);
2322 $in_reply_to_status_id_str = (string) intval($item['parent']);
2324 $in_reply_to_screen_name = NULL;
2325 $in_reply_to_user_id = NULL;
2326 $in_reply_to_user_id_str = NULL;
2328 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2330 intval($in_reply_to_status_id));
2332 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2335 if ($r[0]['nick'] == "")
2336 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2338 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2339 $in_reply_to_user_id = intval($r[0]['id']);
2340 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2344 $in_reply_to_screen_name = NULL;
2345 $in_reply_to_user_id = NULL;
2346 $in_reply_to_status_id = NULL;
2347 $in_reply_to_user_id_str = NULL;
2348 $in_reply_to_status_id_str = NULL;
2351 $converted = api_convert_item($item);
2354 'text' => $converted["text"],
2355 'truncated' => False,
2356 'created_at'=> api_date($item['created']),
2357 'in_reply_to_status_id' => $in_reply_to_status_id,
2358 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2359 'source' => (($item['app']) ? $item['app'] : 'web'),
2360 'id' => intval($item['id']),
2361 'id_str' => (string) intval($item['id']),
2362 'in_reply_to_user_id' => $in_reply_to_user_id,
2363 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2364 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2366 'favorited' => $item['starred'] ? true : false,
2367 'user' => $status_user ,
2368 //'entities' => NULL,
2369 'statusnet_html' => $converted["html"],
2370 'statusnet_conversation_id' => $item['parent'],
2371 'friendica_activities' => api_format_items_likes($item),
2374 if (count($converted["attachments"]) > 0)
2375 $status["attachments"] = $converted["attachments"];
2377 if (count($converted["entities"]) > 0)
2378 $status["entities"] = $converted["entities"];
2380 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2381 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2382 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2383 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2386 // Retweets are only valid for top postings
2387 // It doesn't work reliable with the link if its a feed
2388 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2390 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2392 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2393 $retweeted_status = $status;
2394 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2396 $status["retweeted_status"] = $retweeted_status;
2399 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2400 unset($status["user"]["uid"]);
2401 unset($status["user"]["self"]);
2403 if ($item["coord"] != "") {
2404 $coords = explode(' ',$item["coord"]);
2405 if (count($coords) == 2) {
2406 $status["geo"] = array('type' => 'Point',
2407 'coordinates' => array((float) $coords[0],
2408 (float) $coords[1]));
2418 function api_account_rate_limit_status(&$a,$type) {
2420 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2421 'remaining_hits' => (string) 150,
2422 'hourly_limit' => (string) 150,
2423 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2426 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2428 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2430 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2432 function api_help_test(&$a,$type) {
2438 return api_apply_template('test', $type, array("$ok" => $ok));
2440 api_register_func('api/help/test','api_help_test',false);
2442 function api_lists(&$a,$type) {
2446 api_register_func('api/lists','api_lists',true);
2448 function api_lists_list(&$a,$type) {
2452 api_register_func('api/lists/list','api_lists_list',true);
2455 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2456 * This function is deprecated by Twitter
2457 * returns: json, xml
2459 function api_statuses_f(&$a, $type, $qtype) {
2460 if (api_user()===false) throw new ForbiddenException();
2461 $user_info = api_get_user($a);
2463 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2464 /* this is to stop Hotot to load friends multiple times
2465 * I'm not sure if I'm missing return something or
2466 * is a bug in hotot. Workaround, meantime
2470 return array('$users' => $ret);*/
2474 if($qtype == 'friends')
2475 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2476 if($qtype == 'followers')
2477 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2479 // friends and followers only for self
2480 if ($user_info['self'] == 0)
2481 $sql_extra = " AND false ";
2483 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2488 foreach($r as $cid){
2489 $user = api_get_user($a, $cid['nurl']);
2490 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2491 unset($user["uid"]);
2492 unset($user["self"]);
2498 return array('$users' => $ret);
2501 function api_statuses_friends(&$a, $type){
2502 $data = api_statuses_f($a,$type,"friends");
2503 if ($data===false) return false;
2504 return api_apply_template("friends", $type, $data);
2506 function api_statuses_followers(&$a, $type){
2507 $data = api_statuses_f($a,$type,"followers");
2508 if ($data===false) return false;
2509 return api_apply_template("friends", $type, $data);
2511 api_register_func('api/statuses/friends','api_statuses_friends',true);
2512 api_register_func('api/statuses/followers','api_statuses_followers',true);
2519 function api_statusnet_config(&$a,$type) {
2520 $name = $a->config['sitename'];
2521 $server = $a->get_hostname();
2522 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2523 $email = $a->config['admin_email'];
2524 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2525 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2526 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2527 if($a->config['api_import_size'])
2528 $texlimit = string($a->config['api_import_size']);
2529 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2530 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2533 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2534 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2535 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2536 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2537 'shorturllength' => '30',
2538 'friendica' => array(
2539 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2540 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2541 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2542 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2547 return api_apply_template('config', $type, array('$config' => $config));
2550 api_register_func('api/statusnet/config','api_statusnet_config',false);
2552 function api_statusnet_version(&$a,$type) {
2554 $fake_statusnet_version = "0.9.7";
2556 if($type === 'xml') {
2557 header("Content-type: application/xml");
2558 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2561 elseif($type === 'json') {
2562 header("Content-type: application/json");
2563 echo '"'.$fake_statusnet_version.'"';
2567 api_register_func('api/statusnet/version','api_statusnet_version',false);
2570 * @todo use api_apply_template() to return data
2572 function api_ff_ids(&$a,$type,$qtype) {
2573 if(! api_user()) throw new ForbiddenException();
2575 $user_info = api_get_user($a);
2577 if($qtype == 'friends')
2578 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2579 if($qtype == 'followers')
2580 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2582 if (!$user_info["self"])
2583 $sql_extra = " AND false ";
2585 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2587 $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",
2593 if($type === 'xml') {
2594 header("Content-type: application/xml");
2595 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2597 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2598 echo '</ids>' . "\r\n";
2601 elseif($type === 'json') {
2603 header("Content-type: application/json");
2608 $ret[] = intval($rr['id']);
2610 echo json_encode($ret);
2616 function api_friends_ids(&$a,$type) {
2617 api_ff_ids($a,$type,'friends');
2619 function api_followers_ids(&$a,$type) {
2620 api_ff_ids($a,$type,'followers');
2622 api_register_func('api/friends/ids','api_friends_ids',true);
2623 api_register_func('api/followers/ids','api_followers_ids',true);
2626 function api_direct_messages_new(&$a, $type) {
2627 if (api_user()===false) throw new ForbiddenException();
2629 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2631 $sender = api_get_user($a);
2633 if ($_POST['screen_name']) {
2634 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2636 dbesc($_POST['screen_name']));
2638 // Selecting the id by priority, friendica first
2639 api_best_nickname($r);
2641 $recipient = api_get_user($a, $r[0]['nurl']);
2643 $recipient = api_get_user($a, $_POST['user_id']);
2647 if (x($_REQUEST,'replyto')) {
2648 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2650 intval($_REQUEST['replyto']));
2651 $replyto = $r[0]['parent-uri'];
2652 $sub = $r[0]['title'];
2655 if (x($_REQUEST,'title')) {
2656 $sub = $_REQUEST['title'];
2659 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2663 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2666 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2667 $ret = api_format_messages($r[0], $recipient, $sender);
2670 $ret = array("error"=>$id);
2673 $data = Array('$messages'=>$ret);
2678 $data = api_rss_extra($a, $data, $user_info);
2681 return api_apply_template("direct_messages", $type, $data);
2684 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2686 function api_direct_messages_box(&$a, $type, $box) {
2687 if (api_user()===false) throw new ForbiddenException();
2690 $count = (x($_GET,'count')?$_GET['count']:20);
2691 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2692 if ($page<0) $page=0;
2694 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2695 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2697 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2698 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2701 unset($_REQUEST["user_id"]);
2702 unset($_GET["user_id"]);
2704 unset($_REQUEST["screen_name"]);
2705 unset($_GET["screen_name"]);
2707 $user_info = api_get_user($a);
2708 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2709 $profile_url = $user_info["url"];
2713 $start = $page*$count;
2716 if ($box=="sentbox") {
2717 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2719 elseif ($box=="conversation") {
2720 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2722 elseif ($box=="all") {
2723 $sql_extra = "true";
2725 elseif ($box=="inbox") {
2726 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2730 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2732 if ($user_id !="") {
2733 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2735 elseif($screen_name !=""){
2736 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2739 $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",
2742 intval($start), intval($count)
2747 foreach($r as $item) {
2748 if ($box == "inbox" || $item['from-url'] != $profile_url){
2749 $recipient = $user_info;
2750 $sender = api_get_user($a,normalise_link($item['contact-url']));
2752 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2753 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2754 $sender = $user_info;
2757 $ret[]=api_format_messages($item, $recipient, $sender);
2761 $data = array('$messages' => $ret);
2765 $data = api_rss_extra($a, $data, $user_info);
2768 return api_apply_template("direct_messages", $type, $data);
2772 function api_direct_messages_sentbox(&$a, $type){
2773 return api_direct_messages_box($a, $type, "sentbox");
2775 function api_direct_messages_inbox(&$a, $type){
2776 return api_direct_messages_box($a, $type, "inbox");
2778 function api_direct_messages_all(&$a, $type){
2779 return api_direct_messages_box($a, $type, "all");
2781 function api_direct_messages_conversation(&$a, $type){
2782 return api_direct_messages_box($a, $type, "conversation");
2784 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2785 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2786 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2787 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2791 function api_oauth_request_token(&$a, $type){
2793 $oauth = new FKOAuth1();
2794 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2795 }catch(Exception $e){
2796 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2801 function api_oauth_access_token(&$a, $type){
2803 $oauth = new FKOAuth1();
2804 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2805 }catch(Exception $e){
2806 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2812 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2813 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2816 function api_fr_photos_list(&$a,$type) {
2817 if (api_user()===false) throw new ForbiddenException();
2818 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2819 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2820 intval(local_user())
2823 'image/jpeg' => 'jpg',
2824 'image/png' => 'png',
2825 'image/gif' => 'gif'
2827 $data = array('photos'=>array());
2829 foreach($r as $rr) {
2831 $photo['id'] = $rr['resource-id'];
2832 $photo['album'] = $rr['album'];
2833 $photo['filename'] = $rr['filename'];
2834 $photo['type'] = $rr['type'];
2835 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2836 $data['photos'][] = $photo;
2839 return api_apply_template("photos_list", $type, $data);
2842 function api_fr_photo_detail(&$a,$type) {
2843 if (api_user()===false) throw new ForbiddenException();
2844 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2846 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2847 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2848 $data_sql = ($scale === false ? "" : "data, ");
2850 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2851 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2852 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2854 intval(local_user()),
2855 dbesc($_REQUEST['photo_id']),
2860 'image/jpeg' => 'jpg',
2861 'image/png' => 'png',
2862 'image/gif' => 'gif'
2866 $data = array('photo' => $r[0]);
2867 if ($scale !== false) {
2868 $data['photo']['data'] = base64_encode($data['photo']['data']);
2870 unset($data['photo']['datasize']); //needed only with scale param
2872 $data['photo']['link'] = array();
2873 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2874 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2876 $data['photo']['id'] = $data['photo']['resource-id'];
2877 unset($data['photo']['resource-id']);
2878 unset($data['photo']['minscale']);
2879 unset($data['photo']['maxscale']);
2882 throw new NotFoundException();
2885 return api_apply_template("photo_detail", $type, $data);
2888 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2889 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2894 * similar as /mod/redir.php
2895 * redirect to 'url' after dfrn auth
2897 * why this when there is mod/redir.php already?
2898 * This use api_user() and api_login()
2901 * c_url: url of remote contact to auth to
2902 * url: string, url to redirect after auth
2904 function api_friendica_remoteauth(&$a) {
2905 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2906 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2908 if ($url === '' || $c_url === '')
2909 throw new BadRequestException("Wrong parameters.");
2911 $c_url = normalise_link($c_url);
2915 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2920 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2921 throw new BadRequestException("Unknown contact");
2925 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2927 if($r[0]['duplex'] && $r[0]['issued-id']) {
2928 $orig_id = $r[0]['issued-id'];
2929 $dfrn_id = '1:' . $orig_id;
2931 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2932 $orig_id = $r[0]['dfrn-id'];
2933 $dfrn_id = '0:' . $orig_id;
2936 $sec = random_string();
2938 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2939 VALUES( %d, %s, '%s', '%s', %d )",
2947 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2948 $dest = (($url) ? '&destination_url=' . $url : '');
2949 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2950 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2951 . '&type=profile&sec=' . $sec . $dest . $quiet );
2953 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2956 function api_share_as_retweet(&$item) {
2957 $body = trim($item["body"]);
2959 // Skip if it isn't a pure repeated messages
2960 // Does it start with a share?
2961 if (strpos($body, "[share") > 0)
2964 // Does it end with a share?
2965 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2968 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2969 // Skip if there is no shared message in there
2970 if ($body == $attributes)
2974 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2975 if ($matches[1] != "")
2976 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2978 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2979 if ($matches[1] != "")
2980 $author = $matches[1];
2983 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2984 if ($matches[1] != "")
2985 $profile = $matches[1];
2987 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2988 if ($matches[1] != "")
2989 $profile = $matches[1];
2992 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2993 if ($matches[1] != "")
2994 $avatar = $matches[1];
2996 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2997 if ($matches[1] != "")
2998 $avatar = $matches[1];
3001 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3002 if ($matches[1] != "")
3003 $link = $matches[1];
3005 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3006 if ($matches[1] != "")
3007 $link = $matches[1];
3009 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3011 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
3014 $item["body"] = $shared_body;
3015 $item["author-name"] = $author;
3016 $item["author-link"] = $profile;
3017 $item["author-avatar"] = $avatar;
3018 $item["plink"] = $link;
3024 function api_get_nick($profile) {
3026 - remove trailing junk from profile url
3027 - pump.io check has to check the website
3032 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3033 dbesc(normalise_link($profile)));
3035 $nick = $r[0]["nick"];
3038 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3039 dbesc(normalise_link($profile)));
3041 $nick = $r[0]["nick"];
3045 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3046 if ($friendica != $profile)
3051 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3052 if ($diaspora != $profile)
3057 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3058 if ($twitter != $profile)
3064 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3065 if ($StatusnetHost != $profile) {
3066 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3067 if ($StatusnetUser != $profile) {
3068 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3069 $user = json_decode($UserData);
3071 $nick = $user->screen_name;
3076 // To-Do: look at the page if its really a pumpio site
3077 //if (!$nick == "") {
3078 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3079 // if ($pumpio != $profile)
3081 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3091 function api_clean_plain_items($Text) {
3092 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3094 $Text = bb_CleanPictureLinks($Text);
3096 $URLSearchString = "^\[\]";
3098 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3100 if ($include_entities == "true") {
3101 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3104 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
3108 function api_cleanup_share($shared) {
3109 if ($shared[2] != "type-link")
3112 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
3118 if (isset($bookmark[2][0]))
3119 $title = $bookmark[2][0];
3121 if (isset($bookmark[1][0]))
3122 $link = $bookmark[1][0];
3124 if (strpos($shared[1],$title) !== false)
3127 if (strpos($shared[1],$link) !== false)
3130 $text = trim($shared[1]);
3132 //if (strlen($text) < strlen($title))
3133 if (($text == "") AND ($title != ""))
3134 $text .= "\n\n".trim($title);
3137 $text .= "\n".trim($link);
3139 return(trim($text));
3142 function api_best_nickname(&$contacts) {
3143 $best_contact = array();
3145 if (count($contact) == 0)
3148 foreach ($contacts AS $contact)
3149 if ($contact["network"] == "") {
3150 $contact["network"] = "dfrn";
3151 $best_contact = array($contact);
3154 if (sizeof($best_contact) == 0)
3155 foreach ($contacts AS $contact)
3156 if ($contact["network"] == "dfrn")
3157 $best_contact = array($contact);
3159 if (sizeof($best_contact) == 0)
3160 foreach ($contacts AS $contact)
3161 if ($contact["network"] == "dspr")
3162 $best_contact = array($contact);
3164 if (sizeof($best_contact) == 0)
3165 foreach ($contacts AS $contact)
3166 if ($contact["network"] == "stat")
3167 $best_contact = array($contact);
3169 if (sizeof($best_contact) == 0)
3170 foreach ($contacts AS $contact)
3171 if ($contact["network"] == "pump")
3172 $best_contact = array($contact);
3174 if (sizeof($best_contact) == 0)
3175 foreach ($contacts AS $contact)
3176 if ($contact["network"] == "twit")
3177 $best_contact = array($contact);
3179 if (sizeof($best_contact) == 1)
3180 $contacts = $best_contact;
3182 $contacts = array($contacts[0]);
3185 // return all or a specified group of the user with the containing contacts
3186 function api_friendica_group_show(&$a, $type) {
3187 if (api_user()===false) throw new ForbiddenException();
3190 $user_info = api_get_user($a);
3191 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3192 $uid = $user_info['uid'];
3194 // get data of the specified group id or all groups if not specified
3196 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3199 // error message if specified gid is not in database
3201 throw new BadRequestException("gid not available");
3204 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3207 // loop through all groups and retrieve all members for adding data in the user array
3208 foreach ($r as $rr) {
3209 $members = group_get_members($rr['id']);
3211 foreach ($members as $member) {
3212 $user = api_get_user($a, $member['nurl']);
3215 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3217 return api_apply_template("group_show", $type, array('$groups' => $grps));
3219 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3222 // delete the specified group of the user
3223 function api_friendica_group_delete(&$a, $type) {
3224 if (api_user()===false) throw new ForbiddenException();
3227 $user_info = api_get_user($a);
3228 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3229 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3230 $uid = $user_info['uid'];
3232 // error if no gid specified
3233 if ($gid == 0 || $name == "")
3234 throw new BadRequestException('gid or name not specified');
3236 // get data of the specified group id
3237 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3240 // error message if specified gid is not in database
3242 throw new BadRequestException('gid not available');
3244 // get data of the specified group id and group name
3245 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3249 // error message if specified gid is not in database
3250 if (count($rname) == 0)
3251 throw new BadRequestException('wrong group name');
3254 $ret = group_rmv($uid, $name);
3257 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3258 return api_apply_template("group_delete", $type, array('$result' => $success));
3261 throw new BadRequestException('other API error');
3263 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3266 // create the specified group with the posted array of contacts
3267 function api_friendica_group_create(&$a, $type) {
3268 if (api_user()===false) throw new ForbiddenException();
3271 $user_info = api_get_user($a);
3272 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3273 $uid = $user_info['uid'];
3274 $json = json_decode($_POST['json'], true);
3275 $users = $json['user'];
3277 // error if no name specified
3279 throw new BadRequestException('group name not specified');
3281 // get data of the specified group name
3282 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3285 // error message if specified group name already exists
3286 if (count($rname) != 0)
3287 throw new BadRequestException('group name already exists');
3289 // check if specified group name is a deleted group
3290 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3293 // error message if specified group name already exists
3294 if (count($rname) != 0)
3295 $reactivate_group = true;
3298 $ret = group_add($uid, $name);
3300 $gid = group_byname($uid, $name);
3302 throw new BadRequestException('other API error');
3305 $erroraddinguser = false;
3306 $errorusers = array();
3307 foreach ($users as $user) {
3308 $cid = $user['cid'];
3309 // check if user really exists as contact
3310 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3313 if (count($contact))
3314 $result = group_add_member($uid, $name, $cid, $gid);
3316 $erroraddinguser = true;
3317 $errorusers[] = $cid;
3321 // return success message incl. missing users in array
3322 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3323 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3324 return api_apply_template("group_create", $type, array('result' => $success));
3326 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3329 // update the specified group with the posted array of contacts
3330 function api_friendica_group_update(&$a, $type) {
3331 if (api_user()===false) throw new ForbiddenException();
3334 $user_info = api_get_user($a);
3335 $uid = $user_info['uid'];
3336 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3337 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3338 $json = json_decode($_POST['json'], true);
3339 $users = $json['user'];
3341 // error if no name specified
3343 throw new BadRequestException('group name not specified');
3345 // error if no gid specified
3347 throw new BadRequestException('gid not specified');
3350 $members = group_get_members($gid);
3351 foreach ($members as $member) {
3352 $cid = $member['id'];
3353 foreach ($users as $user) {
3354 $found = ($user['cid'] == $cid ? true : false);
3357 $ret = group_rmv_member($uid, $name, $cid);
3362 $erroraddinguser = false;
3363 $errorusers = array();
3364 foreach ($users as $user) {
3365 $cid = $user['cid'];
3366 // check if user really exists as contact
3367 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3370 if (count($contact))
3371 $result = group_add_member($uid, $name, $cid, $gid);
3373 $erroraddinguser = true;
3374 $errorusers[] = $cid;
3378 // return success message incl. missing users in array
3379 $status = ($erroraddinguser ? "missing user" : "ok");
3380 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3381 return api_apply_template("group_update", $type, array('result' => $success));
3383 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3386 function api_friendica_activity(&$a, $type) {
3387 if (api_user()===false) throw new ForbiddenException();
3388 $verb = strtolower($a->argv[3]);
3389 $verb = preg_replace("|\..*$|", "", $verb);
3391 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3393 $res = do_like($id, $verb);
3400 return api_apply_template('test', $type, array('ok' => $ok));
3402 throw new BadRequestException('Error adding activity');
3406 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3407 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3408 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3409 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3410 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3411 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3412 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3413 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3414 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3415 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3418 * returns notifications
3419 * if called with note id set note seen and returns associated item (if possible)
3421 function api_friendica_notification(&$a, $type) {
3422 if (api_user()===false) throw new ForbiddenException();
3424 $nm = new NotificationsManager();
3427 $notes = $nm->getAll(array(), "+seen -date", 50);
3428 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3431 $note = $nm->getByID(intval($a->argv[3]));
3432 if (is_null($note)) throw new BadRequestException("Invalid argument");
3433 $nm->setSeen($note);
3434 if ($note['otype']=='item') {
3435 // would be really better with a ItemsManager and $im->getByID() :-P
3436 $r = q("SELECT * FROM item WHERE id=%d AND uid=%d",
3437 intval($note['iid']),
3438 intval(local_user())
3440 if ($r===false) throw new NotFoundException();
3441 $user_info = api_get_user($a);
3442 $ret = api_format_items($r,$user_info);
3443 $data = array('$statuses' => $ret);
3444 return api_apply_template("timeline", $type, $data);
3446 return api_apply_template('test', $type, array('ok' => $ok));
3450 throw new BadRequestException("Invalid argument count");
3452 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3456 [pagename] => api/1.1/statuses/lookup.json
3457 [id] => 605138389168451584
3458 [include_cards] => true
3459 [cards_platform] => Android-12
3460 [include_entities] => true
3461 [include_my_retweet] => 1
3463 [include_reply_count] => true
3464 [include_descendent_reply_count] => true
3468 Not implemented by now:
3469 statuses/retweets_of_me
3474 account/update_location
3475 account/update_profile_background_image
3476 account/update_profile_image
3480 Not implemented in status.net:
3481 statuses/retweeted_to_me
3482 statuses/retweeted_by_me
3483 direct_messages/destroy
3485 account/update_delivery_device
3486 notifications/follow