3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
8 require_once('include/HTTPExceptions.php');
10 require_once('include/bbcode.php');
11 require_once('include/datetime.php');
12 require_once('include/conversation.php');
13 require_once('include/oauth.php');
14 require_once('include/html2plain.php');
15 require_once('mod/share.php');
16 require_once('include/Photo.php');
17 require_once('mod/item.php');
18 require_once('include/security.php');
19 require_once('include/contact_selectors.php');
20 require_once('include/html2bbcode.php');
21 require_once('mod/wall_upload.php');
22 require_once('mod/proxy.php');
23 require_once('include/message.php');
24 require_once('include/group.php');
25 require_once('include/like.php');
26 require_once('include/NotificationsManager.php');
27 require_once('include/plaintext.php');
30 define('API_METHOD_ANY','*');
31 define('API_METHOD_GET','GET');
32 define('API_METHOD_POST','POST,PUT');
33 define('API_METHOD_DELETE','POST,DELETE');
41 * @brief Auth API user
43 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
44 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
45 * into a page, and visitors will post something without noticing it).
48 if ($_SESSION['allow_api'])
55 * @brief Get source name from API client
57 * Clients can send 'source' parameter to be show in post metadata
58 * as "sent via <source>".
59 * Some clients doesn't send a source param, we support ones we know
63 * Client source name, default to "api" if unset/unknown
65 function api_source() {
66 if (requestdata('source'))
67 return (requestdata('source'));
69 // Support for known clients that doesn't send a source name
70 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
73 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
79 * @brief Format date for API
81 * @param string $str Source date, as UTC
82 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
84 function api_date($str){
85 //Wed May 23 06:01:13 +0000 2007
86 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
90 * @brief Register API endpoint
92 * Register a function to be the endpont for defined API path.
94 * @param string $path API URL path, relative to $a->get_baseurl()
95 * @param string $func Function name to call on path request
96 * @param bool $auth API need logged user
97 * @param string $method
98 * HTTP method reqiured to call this endpoint.
99 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
100 * Default to API_METHOD_ANY
102 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
110 // Workaround for hotot
111 $path = str_replace("api/", "api/1.1/", $path);
120 * @brief Login API user
122 * Log in user via OAuth1 or Simple HTTP Auth.
123 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
126 * @hook 'authenticate'
128 * 'username' => username from login form
129 * 'password' => password from login form
130 * 'authenticated' => return status,
131 * 'user_record' => return authenticated user record
133 * array $user logged user record
135 function api_login(&$a){
138 $oauth = new FKOAuth1();
139 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
140 if (!is_null($token)){
141 $oauth->loginUser($token->uid);
142 call_hooks('logged_in', $a->user);
145 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
146 }catch(Exception $e){
152 // workaround for HTTP-auth in CGI mode
153 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
154 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
155 if(strlen($userpass)) {
156 list($name, $password) = explode(':', $userpass);
157 $_SERVER['PHP_AUTH_USER'] = $name;
158 $_SERVER['PHP_AUTH_PW'] = $password;
162 if (!isset($_SERVER['PHP_AUTH_USER'])) {
163 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
164 header('WWW-Authenticate: Basic realm="Friendica"');
165 throw new UnauthorizedException("This API requires login");
168 $user = $_SERVER['PHP_AUTH_USER'];
169 $password = $_SERVER['PHP_AUTH_PW'];
170 $encrypted = hash('whirlpool',trim($password));
172 // allow "user@server" login (but ignore 'server' part)
173 $at=strstr($user, "@", true);
174 if ( $at ) $user=$at;
177 * next code from mod/auth.php. needs better solution
182 'username' => trim($user),
183 'password' => trim($password),
184 'authenticated' => 0,
185 'user_record' => null
190 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
191 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
192 * and later plugins should not interfere with an earlier one that succeeded.
196 call_hooks('authenticate', $addon_auth);
198 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
199 $record = $addon_auth['user_record'];
202 // process normal login request
204 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
205 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
214 if((! $record) || (! count($record))) {
215 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
216 header('WWW-Authenticate: Basic realm="Friendica"');
217 #header('HTTP/1.0 401 Unauthorized');
218 #die('This api requires login');
219 throw new UnauthorizedException("This API requires login");
222 authenticate_success($record); $_SESSION["allow_api"] = true;
224 call_hooks('logged_in', $a->user);
229 * @brief Check HTTP method of called API
231 * API endpoints can define which HTTP method to accept when called.
232 * This function check the current HTTP method agains endpoint
235 * @param string $method Required methods, uppercase, separated by comma
238 function api_check_method($method) {
239 if ($method=="*") return True;
240 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
244 * @brief Main API entry point
246 * Authenticate user, call registered API function, set HTTP headers
249 * @return string API call result
251 function api_call(&$a){
252 GLOBAL $API, $called_api;
255 if (strpos($a->query_string, ".xml")>0) $type="xml";
256 if (strpos($a->query_string, ".json")>0) $type="json";
257 if (strpos($a->query_string, ".rss")>0) $type="rss";
258 if (strpos($a->query_string, ".atom")>0) $type="atom";
259 if (strpos($a->query_string, ".as")>0) $type="as";
261 foreach ($API as $p=>$info){
262 if (strpos($a->query_string, $p)===0){
263 if (!api_check_method($info['method'])){
264 throw new MethodNotAllowedException();
267 $called_api= explode("/",$p);
268 //unset($_SERVER['PHP_AUTH_USER']);
269 if ($info['auth']===true && api_user()===false) {
273 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
274 logger('API parameters: ' . print_r($_REQUEST,true));
276 $stamp = microtime(true);
277 $r = call_user_func($info['func'], $a, $type);
278 $duration = (float)(microtime(true)-$stamp);
279 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
282 // api function returned false withour throw an
283 // exception. This should not happend, throw a 500
284 throw new InternalServerErrorException();
289 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
290 header ("Content-Type: text/xml");
291 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
294 header ("Content-Type: application/json");
296 $json = json_encode($rr);
297 if ($_GET['callback'])
298 $json = $_GET['callback']."(".$json.")";
302 header ("Content-Type: application/rss+xml");
303 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
306 header ("Content-Type: application/atom+xml");
307 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
310 //header ("Content-Type: application/json");
312 // return json_encode($rr);
313 return json_encode($r);
319 throw new NotImplementedException();
320 } catch (HTTPException $e) {
321 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
322 return api_error($a, $type, $e);
327 * @brief Format API error string
330 * @param string $type Return type (xml, json, rss, as)
331 * @param HTTPException $error Error object
332 * @return strin error message formatted as $type
334 function api_error(&$a, $type, $e) {
335 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
336 # TODO: https://dev.twitter.com/overview/api/response-codes
337 $xmlstr = "<status><error>{$error}</error><code>{$e->httpcode} {$e->httpdesc}</code><request>{$a->query_string}</request></status>";
340 header ("Content-Type: text/xml");
341 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
344 header ("Content-Type: application/json");
345 return json_encode(array(
347 'request' => $a->query_string,
348 'code' => $e->httpcode." ".$e->httpdesc
352 header ("Content-Type: application/rss+xml");
353 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
356 header ("Content-Type: application/atom+xml");
357 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$xmlstr;
363 * @brief Set values for RSS template
366 * @param array $arr Array to be passed to template
367 * @param array $user_info
370 function api_rss_extra(&$a, $arr, $user_info){
371 if (is_null($user_info)) $user_info = api_get_user($a);
372 $arr['$user'] = $user_info;
373 $arr['$rss'] = array(
374 'alternate' => $user_info['url'],
375 'self' => $a->get_baseurl(). "/". $a->query_string,
376 'base' => $a->get_baseurl(),
377 'updated' => api_date(null),
378 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
379 'language' => $user_info['language'],
380 'logo' => $a->get_baseurl()."/images/friendica-32.png",
388 * @brief Unique contact to contact url.
390 * @param int $id Contact id
391 * @return bool|string
392 * Contact url or False if contact id is unknown
394 function api_unique_id_to_url($id){
395 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
398 return ($r[0]["url"]);
404 * @brief Get user info array.
407 * @param int|string $contact_id Contact ID or URL
408 * @param string $type Return type (for errors)
410 function api_get_user(&$a, $contact_id = Null, $type = "json"){
417 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
419 // Searching for contact URL
420 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
421 $user = dbesc(normalise_link($contact_id));
423 $extra_query = "AND `contact`.`nurl` = '%s' ";
424 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
427 // Searching for unique contact id
428 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
429 $user = dbesc(api_unique_id_to_url($contact_id));
432 throw new BadRequestException("User not found.");
435 $extra_query = "AND `contact`.`nurl` = '%s' ";
436 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
439 if(is_null($user) && x($_GET, 'user_id')) {
440 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
443 throw new BadRequestException("User not found.");
446 $extra_query = "AND `contact`.`nurl` = '%s' ";
447 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
449 if(is_null($user) && x($_GET, 'screen_name')) {
450 $user = dbesc($_GET['screen_name']);
452 $extra_query = "AND `contact`.`nick` = '%s' ";
453 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
456 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
457 $argid = count($called_api);
458 list($user, $null) = explode(".",$a->argv[$argid]);
459 if(is_numeric($user)){
460 $user = dbesc(api_unique_id_to_url($user));
466 $extra_query = "AND `contact`.`nurl` = '%s' ";
467 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
469 $user = dbesc($user);
471 $extra_query = "AND `contact`.`nick` = '%s' ";
472 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
476 logger("api_get_user: user ".$user, LOGGER_DEBUG);
479 if (api_user()===false) {
483 $user = $_SESSION['uid'];
484 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
489 logger('api_user: ' . $extra_query . ', user: ' . $user);
491 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
497 // Selecting the id by priority, friendica first
498 api_best_nickname($uinfo);
500 // if the contact wasn't found, fetch it from the unique contacts
501 if (count($uinfo)==0) {
505 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
508 // If no nick where given, extract it from the address
509 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
510 $r[0]['nick'] = api_get_nick($r[0]["url"]);
514 'id_str' => (string) $r[0]["id"],
515 'name' => $r[0]["name"],
516 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
517 'location' => $r[0]["location"],
518 'description' => $r[0]["about"],
519 'url' => $r[0]["url"],
520 'protected' => false,
521 'followers_count' => 0,
522 'friends_count' => 0,
524 'created_at' => api_date($r[0]["created"]),
525 'favourites_count' => 0,
527 'time_zone' => 'UTC',
528 'geo_enabled' => false,
530 'statuses_count' => 0,
532 'contributors_enabled' => false,
533 'is_translator' => false,
534 'is_translation_enabled' => false,
535 'profile_image_url' => $r[0]["photo"],
536 'profile_image_url_https' => $r[0]["photo"],
537 'following' => false,
538 'follow_request_sent' => false,
539 'notifications' => false,
540 'statusnet_blocking' => false,
541 'notifications' => false,
542 'statusnet_profile_url' => $r[0]["url"],
546 'network' => $r[0]["network"],
551 throw new BadRequestException("User not found.");
555 if($uinfo[0]['self']) {
556 $usr = q("select * from user where uid = %d limit 1",
559 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
563 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
564 // count public wall messages
565 $r = q("SELECT count(*) as `count` FROM `item`
568 intval($uinfo[0]['uid'])
570 $countitms = $r[0]['count'];
573 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
574 $r = q("SELECT count(*) as `count` FROM `item`
575 WHERE `contact-id` = %d",
576 intval($uinfo[0]['id'])
578 $countitms = $r[0]['count'];
582 $r = q("SELECT count(*) as `count` FROM `contact`
583 WHERE `uid` = %d AND `rel` IN ( %d, %d )
584 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
585 intval($uinfo[0]['uid']),
586 intval(CONTACT_IS_SHARING),
587 intval(CONTACT_IS_FRIEND)
589 $countfriends = $r[0]['count'];
591 $r = q("SELECT count(*) as `count` FROM `contact`
592 WHERE `uid` = %d AND `rel` IN ( %d, %d )
593 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
594 intval($uinfo[0]['uid']),
595 intval(CONTACT_IS_FOLLOWER),
596 intval(CONTACT_IS_FRIEND)
598 $countfollowers = $r[0]['count'];
600 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
601 intval($uinfo[0]['uid'])
603 $starred = $r[0]['count'];
606 if(! $uinfo[0]['self']) {
612 // Add a nick if it isn't present there
613 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
614 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
617 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
619 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
620 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
623 'id' => intval($gcontact_id),
624 'id_str' => (string) intval($gcontact_id),
625 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
626 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
627 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
628 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
629 'profile_image_url' => $uinfo[0]['micro'],
630 'profile_image_url_https' => $uinfo[0]['micro'],
631 'url' => $uinfo[0]['url'],
632 'protected' => false,
633 'followers_count' => intval($countfollowers),
634 'friends_count' => intval($countfriends),
635 'created_at' => api_date($uinfo[0]['created']),
636 'favourites_count' => intval($starred),
638 'time_zone' => 'UTC',
639 'statuses_count' => intval($countitms),
640 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
642 'statusnet_blocking' => false,
643 'notifications' => false,
644 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
645 'statusnet_profile_url' => $uinfo[0]['url'],
646 'uid' => intval($uinfo[0]['uid']),
647 'cid' => intval($uinfo[0]['cid']),
648 'self' => $uinfo[0]['self'],
649 'network' => $uinfo[0]['network'],
657 * @brief return api-formatted array for item's author and owner
660 * @param array $item : item from db
661 * @return array(array:author, array:owner)
663 function api_item_get_user(&$a, $item) {
665 // Make sure that there is an entry in the global contacts for author and owner
666 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
667 "photo" => $item['author-avatar'], "name" => $item['author-name']));
669 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
670 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
672 $status_user = api_get_user($a,$item["author-link"]);
673 $status_user["protected"] = (($item["allow_cid"] != "") OR
674 ($item["allow_gid"] != "") OR
675 ($item["deny_cid"] != "") OR
676 ($item["deny_gid"] != "") OR
679 $owner_user = api_get_user($a,$item["owner-link"]);
681 return (array($status_user, $owner_user));
686 * @brief transform $data array in xml without a template
689 * @return string xml string
691 function api_array_to_xml($data, $ename="") {
694 if (count($data)==1 && !is_array($data[array_keys($data)[0]])) {
695 $ename = array_keys($data)[0];
696 $ename = trim($ename,'$');
698 return "<$ename>$v</$ename>";
700 foreach($data as $k=>$v) {
703 $attrs .= sprintf('%s="%s" ', $k, $v);
705 if (is_numeric($k)) $k=trim($ename,'s');
706 $childs.=api_array_to_xml($v, $k);
710 if ($ename!="") $res = "<$ename $attrs>$res</$ename>";
715 * load api $templatename for $type and replace $data array
717 function api_apply_template($templatename, $type, $data){
725 $data = array_xmlify($data);
726 if ($templatename==="<auto>") {
727 $ret = api_array_to_xml($data);
729 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
731 header ("Content-Type: text/xml");
732 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
735 $ret = replace_macros($tpl, $data);
751 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
752 * returns a 401 status code and an error message if not.
753 * http://developer.twitter.com/doc/get/account/verify_credentials
755 function api_account_verify_credentials(&$a, $type){
756 if (api_user()===false) throw new ForbiddenException();
758 unset($_REQUEST["user_id"]);
759 unset($_GET["user_id"]);
761 unset($_REQUEST["screen_name"]);
762 unset($_GET["screen_name"]);
764 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
766 $user_info = api_get_user($a);
768 // "verified" isn't used here in the standard
769 unset($user_info["verified"]);
771 // - Adding last status
773 $user_info["status"] = api_status_show($a,"raw");
774 if (!count($user_info["status"]))
775 unset($user_info["status"]);
777 unset($user_info["status"]["user"]);
780 // "uid" and "self" are only needed for some internal stuff, so remove it from here
781 unset($user_info["uid"]);
782 unset($user_info["self"]);
784 return api_apply_template("user", $type, array('$user' => $user_info));
787 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
791 * get data from $_POST or $_GET
793 function requestdata($k){
794 if (isset($_POST[$k])){
797 if (isset($_GET[$k])){
803 /*Waitman Gobble Mod*/
804 function api_statuses_mediap(&$a, $type) {
805 if (api_user()===false) {
806 logger('api_statuses_update: no user');
807 throw new ForbiddenException();
809 $user_info = api_get_user($a);
811 $_REQUEST['type'] = 'wall';
812 $_REQUEST['profile_uid'] = api_user();
813 $_REQUEST['api_source'] = true;
814 $txt = requestdata('status');
815 //$txt = urldecode(requestdata('status'));
817 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
819 $txt = html2bb_video($txt);
820 $config = HTMLPurifier_Config::createDefault();
821 $config->set('Cache.DefinitionImpl', null);
822 $purifier = new HTMLPurifier($config);
823 $txt = $purifier->purify($txt);
825 $txt = html2bbcode($txt);
827 $a->argv[1]=$user_info['screen_name']; //should be set to username?
829 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
830 $bebop = wall_upload_post($a);
832 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
833 $_REQUEST['body']=$txt."\n\n".$bebop;
836 // this should output the last post (the one we just posted).
837 return api_status_show($a,$type);
839 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
840 /*Waitman Gobble Mod*/
843 function api_statuses_update(&$a, $type) {
844 if (api_user()===false) {
845 logger('api_statuses_update: no user');
846 throw new ForbiddenException();
849 $user_info = api_get_user($a);
851 // convert $_POST array items to the form we use for web posts.
853 // logger('api_post: ' . print_r($_POST,true));
855 if(requestdata('htmlstatus')) {
856 $txt = requestdata('htmlstatus');
857 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
858 $txt = html2bb_video($txt);
860 $config = HTMLPurifier_Config::createDefault();
861 $config->set('Cache.DefinitionImpl', null);
863 $purifier = new HTMLPurifier($config);
864 $txt = $purifier->purify($txt);
866 $_REQUEST['body'] = html2bbcode($txt);
870 $_REQUEST['body'] = requestdata('status');
872 $_REQUEST['title'] = requestdata('title');
874 $parent = requestdata('in_reply_to_status_id');
876 // Twidere sends "-1" if it is no reply ...
880 if(ctype_digit($parent))
881 $_REQUEST['parent'] = $parent;
883 $_REQUEST['parent_uri'] = $parent;
885 if(requestdata('lat') && requestdata('long'))
886 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
887 $_REQUEST['profile_uid'] = api_user();
890 $_REQUEST['type'] = 'net-comment';
892 // Check for throttling (maximum posts per day, week and month)
893 $throttle_day = get_config('system','throttle_limit_day');
894 if ($throttle_day > 0) {
895 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
897 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
898 AND `created` > '%s' AND `id` = `parent`",
899 intval(api_user()), dbesc($datefrom));
902 $posts_day = $r[0]["posts_day"];
906 if ($posts_day > $throttle_day) {
907 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
908 #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
909 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
913 $throttle_week = get_config('system','throttle_limit_week');
914 if ($throttle_week > 0) {
915 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
917 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
918 AND `created` > '%s' AND `id` = `parent`",
919 intval(api_user()), dbesc($datefrom));
922 $posts_week = $r[0]["posts_week"];
926 if ($posts_week > $throttle_week) {
927 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
928 #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
929 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
934 $throttle_month = get_config('system','throttle_limit_month');
935 if ($throttle_month > 0) {
936 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
938 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
939 AND `created` > '%s' AND `id` = `parent`",
940 intval(api_user()), dbesc($datefrom));
943 $posts_month = $r[0]["posts_month"];
947 if ($posts_month > $throttle_month) {
948 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
949 #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
950 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
954 $_REQUEST['type'] = 'wall';
957 if(x($_FILES,'media')) {
958 // upload the image if we have one
959 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
960 $media = wall_upload_post($a);
962 $_REQUEST['body'] .= "\n\n".$media;
965 // To-Do: Multiple IDs
966 if (requestdata('media_ids')) {
967 $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",
968 intval(requestdata('media_ids')), api_user());
970 $phototypes = Photo::supportedTypes();
971 $ext = $phototypes[$r[0]['type']];
972 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
973 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
977 // set this so that the item_post() function is quiet and doesn't redirect or emit json
979 $_REQUEST['api_source'] = true;
981 if (!x($_REQUEST, "source"))
982 $_REQUEST["source"] = api_source();
984 // call out normal post function
988 // this should output the last post (the one we just posted).
989 return api_status_show($a,$type);
991 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
992 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
995 function api_media_upload(&$a, $type) {
996 if (api_user()===false) {
998 throw new ForbiddenException();
1001 $user_info = api_get_user($a);
1003 if(!x($_FILES,'media')) {
1005 throw new BadRequestException("No media.");
1008 $media = wall_upload_post($a, false);
1011 throw new InternalServerErrorException();
1014 $returndata = array();
1015 $returndata["media_id"] = $media["id"];
1016 $returndata["media_id_string"] = (string)$media["id"];
1017 $returndata["size"] = $media["size"];
1018 $returndata["image"] = array("w" => $media["width"],
1019 "h" => $media["height"],
1020 "image_type" => $media["type"]);
1022 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1024 return array("media" => $returndata);
1026 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1028 function api_status_show(&$a, $type){
1029 $user_info = api_get_user($a);
1031 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1034 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1038 // get last public wall message
1039 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1040 FROM `item`, `item` as `i`
1041 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1042 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1043 AND `i`.`id` = `item`.`parent`
1044 AND `item`.`type`!='activity' $privacy_sql
1045 ORDER BY `item`.`created` DESC
1047 intval($user_info['cid']),
1049 dbesc($user_info['url']),
1050 dbesc(normalise_link($user_info['url'])),
1051 dbesc($user_info['url']),
1052 dbesc(normalise_link($user_info['url']))
1055 if (count($lastwall)>0){
1056 $lastwall = $lastwall[0];
1058 $in_reply_to_status_id = NULL;
1059 $in_reply_to_user_id = NULL;
1060 $in_reply_to_status_id_str = NULL;
1061 $in_reply_to_user_id_str = NULL;
1062 $in_reply_to_screen_name = NULL;
1063 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1064 $in_reply_to_status_id= intval($lastwall['parent']);
1065 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1067 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1069 if ($r[0]['nick'] == "")
1070 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1072 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1073 $in_reply_to_user_id = intval($r[0]['id']);
1074 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1078 // There seems to be situation, where both fields are identical:
1079 // https://github.com/friendica/friendica/issues/1010
1080 // This is a bugfix for that.
1081 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1082 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1083 $in_reply_to_status_id = NULL;
1084 $in_reply_to_user_id = NULL;
1085 $in_reply_to_status_id_str = NULL;
1086 $in_reply_to_user_id_str = NULL;
1087 $in_reply_to_screen_name = NULL;
1090 $converted = api_convert_item($lastwall);
1092 $status_info = array(
1093 'created_at' => api_date($lastwall['created']),
1094 'id' => intval($lastwall['id']),
1095 'id_str' => (string) $lastwall['id'],
1096 'text' => $converted["text"],
1097 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1098 'truncated' => false,
1099 'in_reply_to_status_id' => $in_reply_to_status_id,
1100 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1101 'in_reply_to_user_id' => $in_reply_to_user_id,
1102 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1103 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1104 'user' => $user_info,
1106 'coordinates' => "",
1108 'contributors' => "",
1109 'is_quote_status' => false,
1110 'retweet_count' => 0,
1111 'favorite_count' => 0,
1112 'favorited' => $lastwall['starred'] ? true : false,
1113 'retweeted' => false,
1114 'possibly_sensitive' => false,
1116 'statusnet_html' => $converted["html"],
1117 'statusnet_conversation_id' => $lastwall['parent'],
1120 if (count($converted["attachments"]) > 0)
1121 $status_info["attachments"] = $converted["attachments"];
1123 if (count($converted["entities"]) > 0)
1124 $status_info["entities"] = $converted["entities"];
1126 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1127 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1128 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1129 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1131 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1132 unset($status_info["user"]["uid"]);
1133 unset($status_info["user"]["self"]);
1136 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1139 return($status_info);
1141 return api_apply_template("status", $type, array('$status' => $status_info));
1150 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1151 * The author's most recent status will be returned inline.
1152 * http://developer.twitter.com/doc/get/users/show
1154 function api_users_show(&$a, $type){
1155 $user_info = api_get_user($a);
1157 $lastwall = q("SELECT `item`.*
1158 FROM `item`, `contact`
1159 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1160 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1161 AND `contact`.`id`=`item`.`contact-id`
1162 AND `type`!='activity'
1163 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1164 ORDER BY `created` DESC
1167 dbesc(ACTIVITY_POST),
1168 intval($user_info['cid']),
1169 dbesc($user_info['url']),
1170 dbesc(normalise_link($user_info['url'])),
1171 dbesc($user_info['url']),
1172 dbesc(normalise_link($user_info['url']))
1174 if (count($lastwall)>0){
1175 $lastwall = $lastwall[0];
1177 $in_reply_to_status_id = NULL;
1178 $in_reply_to_user_id = NULL;
1179 $in_reply_to_status_id_str = NULL;
1180 $in_reply_to_user_id_str = NULL;
1181 $in_reply_to_screen_name = NULL;
1182 if ($lastwall['parent']!=$lastwall['id']) {
1183 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1184 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1185 if (count($reply)>0) {
1186 $in_reply_to_status_id = intval($lastwall['parent']);
1187 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1189 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1191 if ($r[0]['nick'] == "")
1192 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1194 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1195 $in_reply_to_user_id = intval($r[0]['id']);
1196 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1201 $converted = api_convert_item($lastwall);
1203 $user_info['status'] = array(
1204 'text' => $converted["text"],
1205 'truncated' => false,
1206 'created_at' => api_date($lastwall['created']),
1207 'in_reply_to_status_id' => $in_reply_to_status_id,
1208 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1209 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1210 'id' => intval($lastwall['contact-id']),
1211 'id_str' => (string) $lastwall['contact-id'],
1212 'in_reply_to_user_id' => $in_reply_to_user_id,
1213 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1214 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1216 'favorited' => $lastwall['starred'] ? true : false,
1217 'statusnet_html' => $converted["html"],
1218 'statusnet_conversation_id' => $lastwall['parent'],
1221 if (count($converted["attachments"]) > 0)
1222 $user_info["status"]["attachments"] = $converted["attachments"];
1224 if (count($converted["entities"]) > 0)
1225 $user_info["status"]["entities"] = $converted["entities"];
1227 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1228 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1229 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1230 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1234 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1235 unset($user_info["uid"]);
1236 unset($user_info["self"]);
1238 return api_apply_template("user", $type, array('$user' => $user_info));
1241 api_register_func('api/users/show','api_users_show');
1244 function api_users_search(&$a, $type) {
1245 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1247 $userlist = array();
1249 if (isset($_GET["q"])) {
1250 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1252 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1255 foreach ($r AS $user) {
1256 $user_info = api_get_user($a, $user["id"]);
1257 //echo print_r($user_info, true)."\n";
1258 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1259 $userlist[] = $userdata["user"];
1261 $userlist = array("users" => $userlist);
1263 throw new BadRequestException("User not found.");
1266 throw new BadRequestException("User not found.");
1271 api_register_func('api/users/search','api_users_search');
1275 * http://developer.twitter.com/doc/get/statuses/home_timeline
1277 * TODO: Optional parameters
1278 * TODO: Add reply info
1280 function api_statuses_home_timeline(&$a, $type){
1281 if (api_user()===false) throw new ForbiddenException();
1283 unset($_REQUEST["user_id"]);
1284 unset($_GET["user_id"]);
1286 unset($_REQUEST["screen_name"]);
1287 unset($_GET["screen_name"]);
1289 $user_info = api_get_user($a);
1290 // get last newtork messages
1294 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1295 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1296 if ($page<0) $page=0;
1297 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1298 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1299 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1300 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1301 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1303 $start = $page*$count;
1307 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1308 if ($exclude_replies > 0)
1309 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1310 if ($conversation_id > 0)
1311 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1313 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1314 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1315 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1316 `contact`.`id` AS `cid`
1317 FROM `item`, `contact`
1318 WHERE `item`.`uid` = %d AND `verb` = '%s'
1319 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1320 AND `contact`.`id` = `item`.`contact-id`
1321 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1324 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1326 dbesc(ACTIVITY_POST),
1328 intval($start), intval($count)
1331 $ret = api_format_items($r,$user_info);
1333 // Set all posts from the query above to seen
1335 foreach ($r AS $item)
1336 $idarray[] = intval($item["id"]);
1338 $idlist = implode(",", $idarray);
1340 if ($idlist != "") {
1341 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1344 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1347 $data = array('$statuses' => $ret);
1351 $data = api_rss_extra($a, $data, $user_info);
1354 $as = api_format_as($a, $ret, $user_info);
1355 $as['title'] = $a->config['sitename']." Home Timeline";
1356 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1361 return api_apply_template("timeline", $type, $data);
1363 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1364 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1366 function api_statuses_public_timeline(&$a, $type){
1367 if (api_user()===false) throw new ForbiddenException();
1369 $user_info = api_get_user($a);
1370 // get last newtork messages
1374 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1375 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1376 if ($page<0) $page=0;
1377 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1378 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1379 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1380 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1381 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1383 $start = $page*$count;
1386 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1387 if ($exclude_replies > 0)
1388 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1389 if ($conversation_id > 0)
1390 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1392 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1393 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1394 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1395 `contact`.`id` AS `cid`,
1396 `user`.`nickname`, `user`.`hidewall`
1397 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1398 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1399 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1400 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1401 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1402 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1403 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1406 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1407 dbesc(ACTIVITY_POST),
1412 $ret = api_format_items($r,$user_info);
1415 $data = array('$statuses' => $ret);
1419 $data = api_rss_extra($a, $data, $user_info);
1422 $as = api_format_as($a, $ret, $user_info);
1423 $as['title'] = $a->config['sitename']." Public Timeline";
1424 $as['link']['url'] = $a->get_baseurl()."/";
1429 return api_apply_template("timeline", $type, $data);
1431 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1436 function api_statuses_show(&$a, $type){
1437 if (api_user()===false) throw new ForbiddenException();
1439 $user_info = api_get_user($a);
1442 $id = intval($a->argv[3]);
1445 $id = intval($_REQUEST["id"]);
1449 $id = intval($a->argv[4]);
1451 logger('API: api_statuses_show: '.$id);
1453 $conversation = (x($_REQUEST,'conversation')?1:0);
1457 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1459 $sql_extra .= " AND `item`.`id` = %d";
1461 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1462 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1463 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1464 `contact`.`id` AS `cid`
1465 FROM `item`, `contact`
1466 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1467 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1468 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1471 dbesc(ACTIVITY_POST),
1476 throw new BadRequestException("There is no status with this id.");
1479 $ret = api_format_items($r,$user_info);
1481 if ($conversation) {
1482 $data = array('$statuses' => $ret);
1483 return api_apply_template("timeline", $type, $data);
1485 $data = array('$status' => $ret[0]);
1489 $data = api_rss_extra($a, $data, $user_info);
1491 return api_apply_template("status", $type, $data);
1494 api_register_func('api/statuses/show','api_statuses_show', true);
1500 function api_conversation_show(&$a, $type){
1501 if (api_user()===false) throw new ForbiddenException();
1503 $user_info = api_get_user($a);
1506 $id = intval($a->argv[3]);
1507 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1508 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1509 if ($page<0) $page=0;
1510 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1511 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1513 $start = $page*$count;
1516 $id = intval($_REQUEST["id"]);
1520 $id = intval($a->argv[4]);
1522 logger('API: api_conversation_show: '.$id);
1524 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1526 $id = $r[0]["parent"];
1531 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1533 // Not sure why this query was so complicated. We should keep it here for a while,
1534 // just to make sure that we really don't need it.
1535 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1536 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1538 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1539 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1540 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1541 `contact`.`id` AS `cid`
1543 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1544 WHERE `item`.`parent` = %d AND `item`.`visible`
1545 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1546 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1547 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1548 AND `item`.`id`>%d $sql_extra
1549 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1550 intval($id), intval(api_user()),
1551 dbesc(ACTIVITY_POST),
1553 intval($start), intval($count)
1557 throw new BadRequestException("There is no conversation with this id.");
1559 $ret = api_format_items($r,$user_info);
1561 $data = array('$statuses' => $ret);
1562 return api_apply_template("timeline", $type, $data);
1564 api_register_func('api/conversation/show','api_conversation_show', true);
1565 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1571 function api_statuses_repeat(&$a, $type){
1574 if (api_user()===false) throw new ForbiddenException();
1576 $user_info = api_get_user($a);
1579 $id = intval($a->argv[3]);
1582 $id = intval($_REQUEST["id"]);
1586 $id = intval($a->argv[4]);
1588 logger('API: api_statuses_repeat: '.$id);
1590 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1591 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1592 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1593 `contact`.`id` AS `cid`
1594 FROM `item`, `contact`
1595 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1596 AND `contact`.`id` = `item`.`contact-id`
1597 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1598 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1599 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1601 AND `item`.`id`=%d",
1605 if ($r[0]['body'] != "") {
1606 if (!intval(get_config('system','old_share'))) {
1607 if (strpos($r[0]['body'], "[/share]") !== false) {
1608 $pos = strpos($r[0]['body'], "[share");
1609 $post = substr($r[0]['body'], $pos);
1611 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1613 $post .= $r[0]['body'];
1614 $post .= "[/share]";
1616 $_REQUEST['body'] = $post;
1618 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1620 $_REQUEST['profile_uid'] = api_user();
1621 $_REQUEST['type'] = 'wall';
1622 $_REQUEST['api_source'] = true;
1624 if (!x($_REQUEST, "source"))
1625 $_REQUEST["source"] = api_source();
1629 throw new ForbiddenException();
1631 // this should output the last post (the one we just posted).
1633 return(api_status_show($a,$type));
1635 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1640 function api_statuses_destroy(&$a, $type){
1641 if (api_user()===false) throw new ForbiddenException();
1643 $user_info = api_get_user($a);
1646 $id = intval($a->argv[3]);
1649 $id = intval($_REQUEST["id"]);
1653 $id = intval($a->argv[4]);
1655 logger('API: api_statuses_destroy: '.$id);
1657 $ret = api_statuses_show($a, $type);
1659 drop_item($id, false);
1663 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1667 * http://developer.twitter.com/doc/get/statuses/mentions
1670 function api_statuses_mentions(&$a, $type){
1671 if (api_user()===false) throw new ForbiddenException();
1673 unset($_REQUEST["user_id"]);
1674 unset($_GET["user_id"]);
1676 unset($_REQUEST["screen_name"]);
1677 unset($_GET["screen_name"]);
1679 $user_info = api_get_user($a);
1680 // get last newtork messages
1684 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1685 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1686 if ($page<0) $page=0;
1687 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1688 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1689 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1691 $start = $page*$count;
1693 // Ugly code - should be changed
1694 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1695 $myurl = substr($myurl,strpos($myurl,'://')+3);
1696 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1697 $myurl = str_replace('www.','',$myurl);
1698 $diasp_url = str_replace('/profile/','/u/',$myurl);
1701 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1703 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1704 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1705 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1706 `contact`.`id` AS `cid`
1707 FROM `item` FORCE INDEX (`uid_id`), `contact`
1708 WHERE `item`.`uid` = %d AND `verb` = '%s'
1709 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1710 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1711 AND `contact`.`id` = `item`.`contact-id`
1712 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1713 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1716 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1718 dbesc(ACTIVITY_POST),
1719 dbesc(protect_sprintf($myurl)),
1720 dbesc(protect_sprintf($myurl)),
1723 intval($start), intval($count)
1726 $ret = api_format_items($r,$user_info);
1729 $data = array('$statuses' => $ret);
1733 $data = api_rss_extra($a, $data, $user_info);
1736 $as = api_format_as($a, $ret, $user_info);
1737 $as["title"] = $a->config['sitename']." Mentions";
1738 $as['link']['url'] = $a->get_baseurl()."/";
1743 return api_apply_template("timeline", $type, $data);
1745 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1746 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1749 function api_statuses_user_timeline(&$a, $type){
1750 if (api_user()===false) throw new ForbiddenException();
1752 $user_info = api_get_user($a);
1753 // get last network messages
1755 logger("api_statuses_user_timeline: api_user: ". api_user() .
1756 "\nuser_info: ".print_r($user_info, true) .
1757 "\n_REQUEST: ".print_r($_REQUEST, true),
1761 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1762 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1763 if ($page<0) $page=0;
1764 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1765 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1766 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1767 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1769 $start = $page*$count;
1772 if ($user_info['self']==1)
1773 $sql_extra .= " AND `item`.`wall` = 1 ";
1775 if ($exclude_replies > 0)
1776 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1777 if ($conversation_id > 0)
1778 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1780 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1781 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1782 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1783 `contact`.`id` AS `cid`
1784 FROM `item`, `contact`
1785 WHERE `item`.`uid` = %d AND `verb` = '%s'
1786 AND `item`.`contact-id` = %d
1787 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1788 AND `contact`.`id` = `item`.`contact-id`
1789 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1792 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1794 dbesc(ACTIVITY_POST),
1795 intval($user_info['cid']),
1797 intval($start), intval($count)
1800 $ret = api_format_items($r,$user_info, true);
1802 $data = array('$statuses' => $ret);
1806 $data = api_rss_extra($a, $data, $user_info);
1809 return api_apply_template("timeline", $type, $data);
1811 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1815 * Star/unstar an item
1816 * param: id : id of the item
1818 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1820 function api_favorites_create_destroy(&$a, $type){
1821 if (api_user()===false) throw new ForbiddenException();
1823 // for versioned api.
1824 /// @TODO We need a better global soluton
1826 if ($a->argv[1]=="1.1") $action_argv_id=3;
1828 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1829 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1830 if ($a->argc==$action_argv_id+2) {
1831 $itemid = intval($a->argv[$action_argv_id+1]);
1833 $itemid = intval($_REQUEST['id']);
1836 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1837 $itemid, api_user());
1839 if ($item===false || count($item)==0)
1840 throw new BadRequestException("Invalid item.");
1844 $item[0]['starred']=1;
1847 $item[0]['starred']=0;
1850 throw new BadRequestException("Invalid action ".$action);
1852 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1853 $item[0]['starred'], $itemid, api_user());
1855 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1856 $item[0]['starred'], $itemid, api_user());
1859 throw InternalServerErrorException("DB error");
1862 $user_info = api_get_user($a);
1863 $rets = api_format_items($item,$user_info);
1866 $data = array('$status' => $ret);
1870 $data = api_rss_extra($a, $data, $user_info);
1873 return api_apply_template("status", $type, $data);
1875 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1876 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1878 function api_favorites(&$a, $type){
1881 if (api_user()===false) throw new ForbiddenException();
1883 $called_api= array();
1885 $user_info = api_get_user($a);
1887 // in friendica starred item are private
1888 // return favorites only for self
1889 logger('api_favorites: self:' . $user_info['self']);
1891 if ($user_info['self']==0) {
1897 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1898 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1899 $count = (x($_GET,'count')?$_GET['count']:20);
1900 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1901 if ($page<0) $page=0;
1903 $start = $page*$count;
1906 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1908 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1909 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1910 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1911 `contact`.`id` AS `cid`
1912 FROM `item`, `contact`
1913 WHERE `item`.`uid` = %d
1914 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1915 AND `item`.`starred` = 1
1916 AND `contact`.`id` = `item`.`contact-id`
1917 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1920 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1923 intval($start), intval($count)
1926 $ret = api_format_items($r,$user_info);
1930 $data = array('$statuses' => $ret);
1934 $data = api_rss_extra($a, $data, $user_info);
1937 return api_apply_template("timeline", $type, $data);
1939 api_register_func('api/favorites','api_favorites', true);
1944 function api_format_as($a, $ret, $user_info) {
1946 $as['title'] = $a->config['sitename']." Public Timeline";
1948 foreach ($ret as $item) {
1949 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1950 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1951 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1952 $avatar[0]["rel"] = "avatar";
1953 $avatar[0]["type"] = "";
1954 $avatar[0]["width"] = 96;
1955 $avatar[0]["height"] = 96;
1956 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1957 $avatar[1]["rel"] = "avatar";
1958 $avatar[1]["type"] = "";
1959 $avatar[1]["width"] = 48;
1960 $avatar[1]["height"] = 48;
1961 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1962 $avatar[2]["rel"] = "avatar";
1963 $avatar[2]["type"] = "";
1964 $avatar[2]["width"] = 24;
1965 $avatar[2]["height"] = 24;
1966 $singleitem["actor"]["avatarLinks"] = $avatar;
1968 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1969 $singleitem["actor"]["image"]["rel"] = "avatar";
1970 $singleitem["actor"]["image"]["type"] = "";
1971 $singleitem["actor"]["image"]["width"] = 96;
1972 $singleitem["actor"]["image"]["height"] = 96;
1973 $singleitem["actor"]["type"] = "person";
1974 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1975 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1976 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1977 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1978 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1979 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1980 $singleitem["actor"]["contact"]["addresses"] = "";
1982 $singleitem["body"] = $item["text"];
1983 $singleitem["object"]["displayName"] = $item["text"];
1984 $singleitem["object"]["id"] = $item["url"];
1985 $singleitem["object"]["type"] = "note";
1986 $singleitem["object"]["url"] = $item["url"];
1987 //$singleitem["context"] =;
1988 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1989 $singleitem["provider"]["objectType"] = "service";
1990 $singleitem["provider"]["displayName"] = "Test";
1991 $singleitem["provider"]["url"] = "http://test.tld";
1992 $singleitem["title"] = $item["text"];
1993 $singleitem["verb"] = "post";
1994 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1995 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1996 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1997 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1998 //$singleitem["original"] = $item;
1999 $items[] = $singleitem;
2001 $as['items'] = $items;
2002 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
2003 $as['link']['rel'] = "alternate";
2004 $as['link']['type'] = "text/html";
2008 function api_format_messages($item, $recipient, $sender) {
2009 // standard meta information
2011 'id' => $item['id'],
2012 'sender_id' => $sender['id'] ,
2014 'recipient_id' => $recipient['id'],
2015 'created_at' => api_date($item['created']),
2016 'sender_screen_name' => $sender['screen_name'],
2017 'recipient_screen_name' => $recipient['screen_name'],
2018 'sender' => $sender,
2019 'recipient' => $recipient,
2022 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2023 unset($ret["sender"]["uid"]);
2024 unset($ret["sender"]["self"]);
2025 unset($ret["recipient"]["uid"]);
2026 unset($ret["recipient"]["self"]);
2028 //don't send title to regular StatusNET requests to avoid confusing these apps
2029 if (x($_GET, 'getText')) {
2030 $ret['title'] = $item['title'] ;
2031 if ($_GET["getText"] == "html") {
2032 $ret['text'] = bbcode($item['body'], false, false);
2034 elseif ($_GET["getText"] == "plain") {
2035 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2036 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2040 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2042 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2043 unset($ret['sender']);
2044 unset($ret['recipient']);
2050 function api_convert_item($item) {
2051 $body = $item['body'];
2052 $attachments = api_get_attachments($body);
2054 // Workaround for ostatus messages where the title is identically to the body
2055 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2056 $statusbody = trim(html2plain($html, 0));
2058 // handle data: images
2059 $statusbody = api_format_items_embeded_images($item,$statusbody);
2061 $statustitle = trim($item['title']);
2063 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2064 $statustext = trim($statusbody);
2066 $statustext = trim($statustitle."\n\n".$statusbody);
2068 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2069 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2071 $statushtml = trim(bbcode($body, false, false));
2073 $search = array("<br>", "<blockquote>", "</blockquote>",
2074 "<h1>", "</h1>", "<h2>", "</h2>",
2075 "<h3>", "</h3>", "<h4>", "</h4>",
2076 "<h5>", "</h5>", "<h6>", "</h6>");
2077 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2078 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2079 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2080 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2081 $statushtml = str_replace($search, $replace, $statushtml);
2083 if ($item['title'] != "")
2084 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2086 $entities = api_get_entitities($statustext, $body);
2089 "text" => $statustext,
2090 "html" => $statushtml,
2091 "attachments" => $attachments,
2092 "entities" => $entities
2096 function api_get_attachments(&$body) {
2099 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2101 $URLSearchString = "^\[\]";
2102 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2107 $attachments = array();
2109 foreach ($images[1] AS $image) {
2110 $imagedata = get_photo_info($image);
2113 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2116 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2117 foreach ($images[0] AS $orig)
2118 $body = str_replace($orig, "", $body);
2120 return $attachments;
2123 function api_get_entitities(&$text, $bbcode) {
2126 * Links at the first character of the post
2131 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2133 if ($include_entities != "true") {
2135 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2137 foreach ($images[1] AS $image) {
2138 $replace = proxy_url($image);
2139 $text = str_replace($image, $replace, $text);
2144 $bbcode = bb_CleanPictureLinks($bbcode);
2146 // Change pure links in text to bbcode uris
2147 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2149 $entities = array();
2150 $entities["hashtags"] = array();
2151 $entities["symbols"] = array();
2152 $entities["urls"] = array();
2153 $entities["user_mentions"] = array();
2155 $URLSearchString = "^\[\]";
2157 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2159 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2160 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2161 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2163 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2164 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2165 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2167 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2168 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2169 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2171 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2173 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2174 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2176 $ordered_urls = array();
2177 foreach ($urls[1] AS $id=>$url) {
2178 //$start = strpos($text, $url, $offset);
2179 $start = iconv_strpos($text, $url, 0, "UTF-8");
2180 if (!($start === false))
2181 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2184 ksort($ordered_urls);
2187 //foreach ($urls[1] AS $id=>$url) {
2188 foreach ($ordered_urls AS $url) {
2189 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2190 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2191 $display_url = $url["title"];
2193 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["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)."…";
2200 //$start = strpos($text, $url, $offset);
2201 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2202 if (!($start === false)) {
2203 $entities["urls"][] = array("url" => $url["url"],
2204 "expanded_url" => $url["url"],
2205 "display_url" => $display_url,
2206 "indices" => array($start, $start+strlen($url["url"])));
2207 $offset = $start + 1;
2211 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2212 $ordered_images = array();
2213 foreach ($images[1] AS $image) {
2214 //$start = strpos($text, $url, $offset);
2215 $start = iconv_strpos($text, $image, 0, "UTF-8");
2216 if (!($start === false))
2217 $ordered_images[$start] = $image;
2219 //$entities["media"] = array();
2222 foreach ($ordered_images AS $url) {
2223 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2224 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2226 if (strlen($display_url) > 26)
2227 $display_url = substr($display_url, 0, 25)."…";
2229 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2230 if (!($start === false)) {
2231 $image = get_photo_info($url);
2233 // If image cache is activated, then use the following sizes:
2234 // thumb (150), small (340), medium (600) and large (1024)
2235 if (!get_config("system", "proxy_disabled")) {
2236 $media_url = proxy_url($url);
2239 $scale = scale_image($image[0], $image[1], 150);
2240 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2242 if (($image[0] > 150) OR ($image[1] > 150)) {
2243 $scale = scale_image($image[0], $image[1], 340);
2244 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2247 $scale = scale_image($image[0], $image[1], 600);
2248 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2250 if (($image[0] > 600) OR ($image[1] > 600)) {
2251 $scale = scale_image($image[0], $image[1], 1024);
2252 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2256 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2259 $entities["media"][] = array(
2261 "id_str" => (string)$start+1,
2262 "indices" => array($start, $start+strlen($url)),
2263 "media_url" => normalise_link($media_url),
2264 "media_url_https" => $media_url,
2266 "display_url" => $display_url,
2267 "expanded_url" => $url,
2271 $offset = $start + 1;
2277 function api_format_items_embeded_images(&$item, $text){
2279 $text = preg_replace_callback(
2280 "|data:image/([^;]+)[^=]+=*|m",
2281 function($match) use ($a, $item) {
2282 return $a->get_baseurl()."/display/".$item['guid'];
2290 * @brief return <a href='url'>name</a> as array
2292 * @param string $txt
2297 function api_contactlink_to_array($txt) {
2299 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2300 if ($r && count($match)==3) {
2302 'name' => $match[2],
2316 * @brief return likes, dislikes and attend status for item
2318 * @param array $item
2320 * likes => int count
2321 * dislikes => int count
2323 function api_format_items_activities(&$item) {
2324 $activities = array(
2326 'dislike' => array(),
2327 'attendyes' => array(),
2328 'attendno' => array(),
2329 'attendmaybe' => array()
2331 $items = q('SELECT * FROM item
2332 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2333 intval($item['uid']),
2334 dbesc($item['uri']));
2335 foreach ($items as $i){
2336 builtin_activity_puller($i, $activities);
2340 $uri = $item['uri']."-l";
2341 foreach($activities as $k => $v) {
2342 $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2349 * @brief format items to be returned by api
2351 * @param array $r array of items
2352 * @param array $user_info
2353 * @param bool $filter_user filter items by $user_info
2355 function api_format_items($r,$user_info, $filter_user = false) {
2360 foreach($r as $item) {
2362 localize_item($item);
2363 list($status_user, $owner_user) = api_item_get_user($a,$item);
2365 // Look if the posts are matching if they should be filtered by user id
2366 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2369 if ($item['thr-parent'] != $item['uri']) {
2370 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2372 dbesc($item['thr-parent']));
2374 $in_reply_to_status_id = intval($r[0]['id']);
2376 $in_reply_to_status_id = intval($item['parent']);
2378 $in_reply_to_status_id_str = (string) intval($item['parent']);
2380 $in_reply_to_screen_name = NULL;
2381 $in_reply_to_user_id = NULL;
2382 $in_reply_to_user_id_str = NULL;
2384 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2386 intval($in_reply_to_status_id));
2388 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2391 if ($r[0]['nick'] == "")
2392 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2394 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2395 $in_reply_to_user_id = intval($r[0]['id']);
2396 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2400 $in_reply_to_screen_name = NULL;
2401 $in_reply_to_user_id = NULL;
2402 $in_reply_to_status_id = NULL;
2403 $in_reply_to_user_id_str = NULL;
2404 $in_reply_to_status_id_str = NULL;
2407 $converted = api_convert_item($item);
2410 'text' => $converted["text"],
2411 'truncated' => False,
2412 'created_at'=> api_date($item['created']),
2413 'in_reply_to_status_id' => $in_reply_to_status_id,
2414 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2415 'source' => (($item['app']) ? $item['app'] : 'web'),
2416 'id' => intval($item['id']),
2417 'id_str' => (string) intval($item['id']),
2418 'in_reply_to_user_id' => $in_reply_to_user_id,
2419 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2420 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2422 'favorited' => $item['starred'] ? true : false,
2423 'user' => $status_user ,
2424 'friendica_owner' => $owner_user,
2425 //'entities' => NULL,
2426 'statusnet_html' => $converted["html"],
2427 'statusnet_conversation_id' => $item['parent'],
2428 'friendica_activities' => api_format_items_activities($item),
2431 if (count($converted["attachments"]) > 0)
2432 $status["attachments"] = $converted["attachments"];
2434 if (count($converted["entities"]) > 0)
2435 $status["entities"] = $converted["entities"];
2437 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2438 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2439 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2440 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2443 // Retweets are only valid for top postings
2444 // It doesn't work reliable with the link if its a feed
2445 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2447 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2450 if ($item["id"] == $item["parent"]) {
2451 $retweeted_item = api_share_as_retweet($item);
2452 if ($retweeted_item !== false) {
2453 $retweeted_status = $status;
2455 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2456 } catch( BadRequestException $e ) {
2457 // user not found. should be found?
2458 /// @todo check if the user should be always found
2459 $retweeted_status["user"] = array();
2462 $rt_converted = api_convert_item($retweeted_item);
2464 $retweeted_status['text'] = $rt_converted["text"];
2465 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2466 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item);
2467 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2468 $status['retweeted_status'] = $retweeted_status;
2472 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2473 unset($status["user"]["uid"]);
2474 unset($status["user"]["self"]);
2476 if ($item["coord"] != "") {
2477 $coords = explode(' ',$item["coord"]);
2478 if (count($coords) == 2) {
2479 $status["geo"] = array('type' => 'Point',
2480 'coordinates' => array((float) $coords[0],
2481 (float) $coords[1]));
2491 function api_account_rate_limit_status(&$a,$type) {
2493 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2494 'remaining_hits' => (string) 150,
2495 'hourly_limit' => (string) 150,
2496 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2499 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2501 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2503 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2505 function api_help_test(&$a,$type) {
2511 return api_apply_template('test', $type, array("$ok" => $ok));
2513 api_register_func('api/help/test','api_help_test',false);
2515 function api_lists(&$a,$type) {
2519 api_register_func('api/lists','api_lists',true);
2521 function api_lists_list(&$a,$type) {
2525 api_register_func('api/lists/list','api_lists_list',true);
2528 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2529 * This function is deprecated by Twitter
2530 * returns: json, xml
2532 function api_statuses_f(&$a, $type, $qtype) {
2533 if (api_user()===false) throw new ForbiddenException();
2534 $user_info = api_get_user($a);
2536 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2537 /* this is to stop Hotot to load friends multiple times
2538 * I'm not sure if I'm missing return something or
2539 * is a bug in hotot. Workaround, meantime
2543 return array('$users' => $ret);*/
2547 if($qtype == 'friends')
2548 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2549 if($qtype == 'followers')
2550 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2552 // friends and followers only for self
2553 if ($user_info['self'] == 0)
2554 $sql_extra = " AND false ";
2556 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2561 foreach($r as $cid){
2562 $user = api_get_user($a, $cid['nurl']);
2563 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2564 unset($user["uid"]);
2565 unset($user["self"]);
2571 return array('$users' => $ret);
2574 function api_statuses_friends(&$a, $type){
2575 $data = api_statuses_f($a,$type,"friends");
2576 if ($data===false) return false;
2577 return api_apply_template("friends", $type, $data);
2579 function api_statuses_followers(&$a, $type){
2580 $data = api_statuses_f($a,$type,"followers");
2581 if ($data===false) return false;
2582 return api_apply_template("friends", $type, $data);
2584 api_register_func('api/statuses/friends','api_statuses_friends',true);
2585 api_register_func('api/statuses/followers','api_statuses_followers',true);
2592 function api_statusnet_config(&$a,$type) {
2593 $name = $a->config['sitename'];
2594 $server = $a->get_hostname();
2595 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2596 $email = $a->config['admin_email'];
2597 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2598 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2599 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2600 if($a->config['api_import_size'])
2601 $texlimit = string($a->config['api_import_size']);
2602 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2603 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2606 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2607 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2608 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2609 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2610 'shorturllength' => '30',
2611 'friendica' => array(
2612 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2613 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2614 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2615 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2620 return api_apply_template('config', $type, array('$config' => $config));
2623 api_register_func('api/statusnet/config','api_statusnet_config',false);
2625 function api_statusnet_version(&$a,$type) {
2627 $fake_statusnet_version = "0.9.7";
2629 if($type === 'xml') {
2630 header("Content-type: application/xml");
2631 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>'.$fake_statusnet_version.'</version>' . "\r\n";
2634 elseif($type === 'json') {
2635 header("Content-type: application/json");
2636 echo '"'.$fake_statusnet_version.'"';
2640 api_register_func('api/statusnet/version','api_statusnet_version',false);
2643 * @todo use api_apply_template() to return data
2645 function api_ff_ids(&$a,$type,$qtype) {
2646 if(! api_user()) throw new ForbiddenException();
2648 $user_info = api_get_user($a);
2650 if($qtype == 'friends')
2651 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2652 if($qtype == 'followers')
2653 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2655 if (!$user_info["self"])
2656 $sql_extra = " AND false ";
2658 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2660 $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",
2666 if($type === 'xml') {
2667 header("Content-type: application/xml");
2668 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2670 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2671 echo '</ids>' . "\r\n";
2674 elseif($type === 'json') {
2676 header("Content-type: application/json");
2681 $ret[] = intval($rr['id']);
2683 echo json_encode($ret);
2689 function api_friends_ids(&$a,$type) {
2690 api_ff_ids($a,$type,'friends');
2692 function api_followers_ids(&$a,$type) {
2693 api_ff_ids($a,$type,'followers');
2695 api_register_func('api/friends/ids','api_friends_ids',true);
2696 api_register_func('api/followers/ids','api_followers_ids',true);
2699 function api_direct_messages_new(&$a, $type) {
2700 if (api_user()===false) throw new ForbiddenException();
2702 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2704 $sender = api_get_user($a);
2706 if ($_POST['screen_name']) {
2707 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2709 dbesc($_POST['screen_name']));
2711 // Selecting the id by priority, friendica first
2712 api_best_nickname($r);
2714 $recipient = api_get_user($a, $r[0]['nurl']);
2716 $recipient = api_get_user($a, $_POST['user_id']);
2720 if (x($_REQUEST,'replyto')) {
2721 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2723 intval($_REQUEST['replyto']));
2724 $replyto = $r[0]['parent-uri'];
2725 $sub = $r[0]['title'];
2728 if (x($_REQUEST,'title')) {
2729 $sub = $_REQUEST['title'];
2732 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2736 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2739 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2740 $ret = api_format_messages($r[0], $recipient, $sender);
2743 $ret = array("error"=>$id);
2746 $data = Array('$messages'=>$ret);
2751 $data = api_rss_extra($a, $data, $user_info);
2754 return api_apply_template("direct_messages", $type, $data);
2757 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2759 function api_direct_messages_box(&$a, $type, $box) {
2760 if (api_user()===false) throw new ForbiddenException();
2763 $count = (x($_GET,'count')?$_GET['count']:20);
2764 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2765 if ($page<0) $page=0;
2767 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2768 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2770 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2771 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2774 unset($_REQUEST["user_id"]);
2775 unset($_GET["user_id"]);
2777 unset($_REQUEST["screen_name"]);
2778 unset($_GET["screen_name"]);
2780 $user_info = api_get_user($a);
2781 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2782 $profile_url = $user_info["url"];
2786 $start = $page*$count;
2789 if ($box=="sentbox") {
2790 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2792 elseif ($box=="conversation") {
2793 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2795 elseif ($box=="all") {
2796 $sql_extra = "true";
2798 elseif ($box=="inbox") {
2799 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2803 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2805 if ($user_id !="") {
2806 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2808 elseif($screen_name !=""){
2809 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2812 $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",
2815 intval($start), intval($count)
2820 foreach($r as $item) {
2821 if ($box == "inbox" || $item['from-url'] != $profile_url){
2822 $recipient = $user_info;
2823 $sender = api_get_user($a,normalise_link($item['contact-url']));
2825 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2826 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2827 $sender = $user_info;
2830 $ret[]=api_format_messages($item, $recipient, $sender);
2834 $data = array('$messages' => $ret);
2838 $data = api_rss_extra($a, $data, $user_info);
2841 return api_apply_template("direct_messages", $type, $data);
2845 function api_direct_messages_sentbox(&$a, $type){
2846 return api_direct_messages_box($a, $type, "sentbox");
2848 function api_direct_messages_inbox(&$a, $type){
2849 return api_direct_messages_box($a, $type, "inbox");
2851 function api_direct_messages_all(&$a, $type){
2852 return api_direct_messages_box($a, $type, "all");
2854 function api_direct_messages_conversation(&$a, $type){
2855 return api_direct_messages_box($a, $type, "conversation");
2857 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2858 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2859 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2860 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2864 function api_oauth_request_token(&$a, $type){
2866 $oauth = new FKOAuth1();
2867 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2868 }catch(Exception $e){
2869 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2874 function api_oauth_access_token(&$a, $type){
2876 $oauth = new FKOAuth1();
2877 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2878 }catch(Exception $e){
2879 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2885 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2886 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2889 function api_fr_photos_list(&$a,$type) {
2890 if (api_user()===false) throw new ForbiddenException();
2891 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2892 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2893 intval(local_user())
2896 'image/jpeg' => 'jpg',
2897 'image/png' => 'png',
2898 'image/gif' => 'gif'
2900 $data = array('photos'=>array());
2902 foreach($r as $rr) {
2904 $photo['id'] = $rr['resource-id'];
2905 $photo['album'] = $rr['album'];
2906 $photo['filename'] = $rr['filename'];
2907 $photo['type'] = $rr['type'];
2908 $photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2909 $data['photos'][] = $photo;
2912 return api_apply_template("photos_list", $type, $data);
2915 function api_fr_photo_detail(&$a,$type) {
2916 if (api_user()===false) throw new ForbiddenException();
2917 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2919 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2920 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2921 $data_sql = ($scale === false ? "" : "data, ");
2923 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2924 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2925 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2927 intval(local_user()),
2928 dbesc($_REQUEST['photo_id']),
2933 'image/jpeg' => 'jpg',
2934 'image/png' => 'png',
2935 'image/gif' => 'gif'
2939 $data = array('photo' => $r[0]);
2940 if ($scale !== false) {
2941 $data['photo']['data'] = base64_encode($data['photo']['data']);
2943 unset($data['photo']['datasize']); //needed only with scale param
2945 $data['photo']['link'] = array();
2946 for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2947 $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2949 $data['photo']['id'] = $data['photo']['resource-id'];
2950 unset($data['photo']['resource-id']);
2951 unset($data['photo']['minscale']);
2952 unset($data['photo']['maxscale']);
2955 throw new NotFoundException();
2958 return api_apply_template("photo_detail", $type, $data);
2961 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2962 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2967 * similar as /mod/redir.php
2968 * redirect to 'url' after dfrn auth
2970 * why this when there is mod/redir.php already?
2971 * This use api_user() and api_login()
2974 * c_url: url of remote contact to auth to
2975 * url: string, url to redirect after auth
2977 function api_friendica_remoteauth(&$a) {
2978 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2979 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2981 if ($url === '' || $c_url === '')
2982 throw new BadRequestException("Wrong parameters.");
2984 $c_url = normalise_link($c_url);
2988 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2993 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2994 throw new BadRequestException("Unknown contact");
2998 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3000 if($r[0]['duplex'] && $r[0]['issued-id']) {
3001 $orig_id = $r[0]['issued-id'];
3002 $dfrn_id = '1:' . $orig_id;
3004 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3005 $orig_id = $r[0]['dfrn-id'];
3006 $dfrn_id = '0:' . $orig_id;
3009 $sec = random_string();
3011 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3012 VALUES( %d, %s, '%s', '%s', %d )",
3020 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3021 $dest = (($url) ? '&destination_url=' . $url : '');
3022 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3023 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3024 . '&type=profile&sec=' . $sec . $dest . $quiet );
3026 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3029 * @brief Return the item shared, if the item contains only the [share] tag
3031 * @param array $item Sharer item
3032 * @return array Shared item or false if not a reshare
3034 function api_share_as_retweet(&$item) {
3035 $body = trim($item["body"]);
3037 if (diaspora::is_reshare($body, false)===false) {
3041 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3042 // Skip if there is no shared message in there
3043 // we already checked this in diaspora::is_reshare()
3044 // but better one more than one less...
3045 if ($body == $attributes)
3049 // build the fake reshared item
3050 $reshared_item = $item;
3053 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3054 if ($matches[1] != "")
3055 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3057 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3058 if ($matches[1] != "")
3059 $author = $matches[1];
3062 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3063 if ($matches[1] != "")
3064 $profile = $matches[1];
3066 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3067 if ($matches[1] != "")
3068 $profile = $matches[1];
3071 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3072 if ($matches[1] != "")
3073 $avatar = $matches[1];
3075 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3076 if ($matches[1] != "")
3077 $avatar = $matches[1];
3080 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3081 if ($matches[1] != "")
3082 $link = $matches[1];
3084 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3085 if ($matches[1] != "")
3086 $link = $matches[1];
3089 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3090 if ($matches[1] != "")
3091 $posted= $matches[1];
3093 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3094 if ($matches[1] != "")
3095 $posted = $matches[1];
3097 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3099 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3104 $reshared_item["body"] = $shared_body;
3105 $reshared_item["author-name"] = $author;
3106 $reshared_item["author-link"] = $profile;
3107 $reshared_item["author-avatar"] = $avatar;
3108 $reshared_item["plink"] = $link;
3109 $reshared_item["created"] = $posted;
3110 $reshared_item["edited"] = $posted;
3112 return $reshared_item;
3116 function api_get_nick($profile) {
3118 - remove trailing junk from profile url
3119 - pump.io check has to check the website
3124 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3125 dbesc(normalise_link($profile)));
3127 $nick = $r[0]["nick"];
3130 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3131 dbesc(normalise_link($profile)));
3133 $nick = $r[0]["nick"];
3137 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3138 if ($friendica != $profile)
3143 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3144 if ($diaspora != $profile)
3149 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3150 if ($twitter != $profile)
3156 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3157 if ($StatusnetHost != $profile) {
3158 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3159 if ($StatusnetUser != $profile) {
3160 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3161 $user = json_decode($UserData);
3163 $nick = $user->screen_name;
3168 // To-Do: look at the page if its really a pumpio site
3169 //if (!$nick == "") {
3170 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3171 // if ($pumpio != $profile)
3173 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3183 function api_clean_plain_items($Text) {
3184 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3186 $Text = bb_CleanPictureLinks($Text);
3188 $URLSearchString = "^\[\]";
3190 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3192 if ($include_entities == "true") {
3193 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3196 // Simplify "attachment" element
3197 $Text = api_clean_attachments($Text);
3203 * @brief Removes most sharing information for API text export
3205 * @param string $body The original body
3207 * @return string Cleaned body
3209 function api_clean_attachments($body) {
3210 $data = get_attachment_data($body);
3217 if (isset($data["text"]))
3218 $body = $data["text"];
3220 if (($body == "") AND (isset($data["title"])))
3221 $body = $data["title"];
3223 if (isset($data["url"]))
3224 $body .= "\n".$data["url"];
3229 function api_best_nickname(&$contacts) {
3230 $best_contact = array();
3232 if (count($contact) == 0)
3235 foreach ($contacts AS $contact)
3236 if ($contact["network"] == "") {
3237 $contact["network"] = "dfrn";
3238 $best_contact = array($contact);
3241 if (sizeof($best_contact) == 0)
3242 foreach ($contacts AS $contact)
3243 if ($contact["network"] == "dfrn")
3244 $best_contact = array($contact);
3246 if (sizeof($best_contact) == 0)
3247 foreach ($contacts AS $contact)
3248 if ($contact["network"] == "dspr")
3249 $best_contact = array($contact);
3251 if (sizeof($best_contact) == 0)
3252 foreach ($contacts AS $contact)
3253 if ($contact["network"] == "stat")
3254 $best_contact = array($contact);
3256 if (sizeof($best_contact) == 0)
3257 foreach ($contacts AS $contact)
3258 if ($contact["network"] == "pump")
3259 $best_contact = array($contact);
3261 if (sizeof($best_contact) == 0)
3262 foreach ($contacts AS $contact)
3263 if ($contact["network"] == "twit")
3264 $best_contact = array($contact);
3266 if (sizeof($best_contact) == 1)
3267 $contacts = $best_contact;
3269 $contacts = array($contacts[0]);
3272 // return all or a specified group of the user with the containing contacts
3273 function api_friendica_group_show(&$a, $type) {
3274 if (api_user()===false) throw new ForbiddenException();
3277 $user_info = api_get_user($a);
3278 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3279 $uid = $user_info['uid'];
3281 // get data of the specified group id or all groups if not specified
3283 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3286 // error message if specified gid is not in database
3288 throw new BadRequestException("gid not available");
3291 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3294 // loop through all groups and retrieve all members for adding data in the user array
3295 foreach ($r as $rr) {
3296 $members = group_get_members($rr['id']);
3298 foreach ($members as $member) {
3299 $user = api_get_user($a, $member['nurl']);
3302 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
3304 return api_apply_template("group_show", $type, array('$groups' => $grps));
3306 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3309 // delete the specified group of the user
3310 function api_friendica_group_delete(&$a, $type) {
3311 if (api_user()===false) throw new ForbiddenException();
3314 $user_info = api_get_user($a);
3315 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3316 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3317 $uid = $user_info['uid'];
3319 // error if no gid specified
3320 if ($gid == 0 || $name == "")
3321 throw new BadRequestException('gid or name not specified');
3323 // get data of the specified group id
3324 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3327 // error message if specified gid is not in database
3329 throw new BadRequestException('gid not available');
3331 // get data of the specified group id and group name
3332 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3336 // error message if specified gid is not in database
3337 if (count($rname) == 0)
3338 throw new BadRequestException('wrong group name');
3341 $ret = group_rmv($uid, $name);
3344 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3345 return api_apply_template("group_delete", $type, array('$result' => $success));
3348 throw new BadRequestException('other API error');
3350 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3353 // create the specified group with the posted array of contacts
3354 function api_friendica_group_create(&$a, $type) {
3355 if (api_user()===false) throw new ForbiddenException();
3358 $user_info = api_get_user($a);
3359 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3360 $uid = $user_info['uid'];
3361 $json = json_decode($_POST['json'], true);
3362 $users = $json['user'];
3364 // error if no name specified
3366 throw new BadRequestException('group name not specified');
3368 // get data of the specified group name
3369 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3372 // error message if specified group name already exists
3373 if (count($rname) != 0)
3374 throw new BadRequestException('group name already exists');
3376 // check if specified group name is a deleted group
3377 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3380 // error message if specified group name already exists
3381 if (count($rname) != 0)
3382 $reactivate_group = true;
3385 $ret = group_add($uid, $name);
3387 $gid = group_byname($uid, $name);
3389 throw new BadRequestException('other API error');
3392 $erroraddinguser = false;
3393 $errorusers = array();
3394 foreach ($users as $user) {
3395 $cid = $user['cid'];
3396 // check if user really exists as contact
3397 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3400 if (count($contact))
3401 $result = group_add_member($uid, $name, $cid, $gid);
3403 $erroraddinguser = true;
3404 $errorusers[] = $cid;
3408 // return success message incl. missing users in array
3409 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3410 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3411 return api_apply_template("group_create", $type, array('result' => $success));
3413 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3416 // update the specified group with the posted array of contacts
3417 function api_friendica_group_update(&$a, $type) {
3418 if (api_user()===false) throw new ForbiddenException();
3421 $user_info = api_get_user($a);
3422 $uid = $user_info['uid'];
3423 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3424 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3425 $json = json_decode($_POST['json'], true);
3426 $users = $json['user'];
3428 // error if no name specified
3430 throw new BadRequestException('group name not specified');
3432 // error if no gid specified
3434 throw new BadRequestException('gid not specified');
3437 $members = group_get_members($gid);
3438 foreach ($members as $member) {
3439 $cid = $member['id'];
3440 foreach ($users as $user) {
3441 $found = ($user['cid'] == $cid ? true : false);
3444 $ret = group_rmv_member($uid, $name, $cid);
3449 $erroraddinguser = false;
3450 $errorusers = array();
3451 foreach ($users as $user) {
3452 $cid = $user['cid'];
3453 // check if user really exists as contact
3454 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3457 if (count($contact))
3458 $result = group_add_member($uid, $name, $cid, $gid);
3460 $erroraddinguser = true;
3461 $errorusers[] = $cid;
3465 // return success message incl. missing users in array
3466 $status = ($erroraddinguser ? "missing user" : "ok");
3467 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3468 return api_apply_template("group_update", $type, array('result' => $success));
3470 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3473 function api_friendica_activity(&$a, $type) {
3474 if (api_user()===false) throw new ForbiddenException();
3475 $verb = strtolower($a->argv[3]);
3476 $verb = preg_replace("|\..*$|", "", $verb);
3478 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3480 $res = do_like($id, $verb);
3487 return api_apply_template('test', $type, array('ok' => $ok));
3489 throw new BadRequestException('Error adding activity');
3493 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3494 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3495 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3496 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3497 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3498 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3499 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3500 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3501 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3502 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3505 * @brief Returns notifications
3508 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3511 function api_friendica_notification(&$a, $type) {
3512 if (api_user()===false) throw new ForbiddenException();
3513 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3514 $nm = new NotificationsManager();
3516 $notes = $nm->getAll(array(), "+seen -date", 50);
3517 return api_apply_template("<auto>", $type, array('$notes' => $notes));
3521 * @brief Set notification as seen and returns associated item (if possible)
3523 * POST request with 'id' param as notification id
3526 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3529 function api_friendica_notification_seen(&$a, $type){
3530 if (api_user()===false) throw new ForbiddenException();
3531 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3533 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3535 $nm = new NotificationsManager();
3536 $note = $nm->getByID($id);
3537 if (is_null($note)) throw new BadRequestException("Invalid argument");
3539 $nm->setSeen($note);
3540 if ($note['otype']=='item') {
3541 // would be really better with an ItemsManager and $im->getByID() :-P
3542 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3543 intval($note['iid']),
3544 intval(local_user())
3547 // we found the item, return it to the user
3548 $user_info = api_get_user($a);
3549 $ret = api_format_items($r,$user_info);
3550 $data = array('$statuses' => $ret);
3551 return api_apply_template("timeline", $type, $data);
3553 // the item can't be found, but we set the note as seen, so we count this as a success
3555 return api_apply_template('<auto>', $type, array('status' => "success"));
3558 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3559 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3564 [pagename] => api/1.1/statuses/lookup.json
3565 [id] => 605138389168451584
3566 [include_cards] => true
3567 [cards_platform] => Android-12
3568 [include_entities] => true
3569 [include_my_retweet] => 1
3571 [include_reply_count] => true
3572 [include_descendent_reply_count] => true
3576 Not implemented by now:
3577 statuses/retweets_of_me
3582 account/update_location
3583 account/update_profile_background_image
3584 account/update_profile_image
3588 Not implemented in status.net:
3589 statuses/retweeted_to_me
3590 statuses/retweeted_by_me
3591 direct_messages/destroy
3593 account/update_delivery_device
3594 notifications/follow