3 * @file include/api.php
\r
4 * Friendica implementation of statusnet/twitter API
\r
6 * @todo Automatically detect if incoming data is HTML or BBCode
\r
8 require_once('include/HTTPExceptions.php');
\r
10 require_once('include/bbcode.php');
\r
11 require_once('include/datetime.php');
\r
12 require_once('include/conversation.php');
\r
13 require_once('include/oauth.php');
\r
14 require_once('include/html2plain.php');
\r
15 require_once('mod/share.php');
\r
16 require_once('include/Photo.php');
\r
17 require_once('mod/item.php');
\r
18 require_once('include/security.php');
\r
19 require_once('include/contact_selectors.php');
\r
20 require_once('include/html2bbcode.php');
\r
21 require_once('mod/wall_upload.php');
\r
22 require_once('mod/proxy.php');
\r
23 require_once('include/message.php');
\r
24 require_once('include/group.php');
\r
25 require_once('include/like.php');
\r
26 require_once('include/NotificationsManager.php');
\r
27 require_once('include/plaintext.php');
\r
28 require_once('include/xml.php');
\r
31 define('API_METHOD_ANY','*');
\r
32 define('API_METHOD_GET','GET');
\r
33 define('API_METHOD_POST','POST,PUT');
\r
34 define('API_METHOD_DELETE','POST,DELETE');
\r
42 * @brief Auth API user
\r
44 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
\r
45 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
\r
46 * into a page, and visitors will post something without noticing it).
\r
48 function api_user() {
\r
49 if ($_SESSION['allow_api'])
\r
50 return local_user();
\r
56 * @brief Get source name from API client
\r
58 * Clients can send 'source' parameter to be show in post metadata
\r
59 * as "sent via <source>".
\r
60 * Some clients doesn't send a source param, we support ones we know
\r
61 * (only Twidere, atm)
\r
64 * Client source name, default to "api" if unset/unknown
\r
66 function api_source() {
\r
67 if (requestdata('source'))
\r
68 return (requestdata('source'));
\r
70 // Support for known clients that doesn't send a source name
\r
71 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
\r
74 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
\r
80 * @brief Format date for API
\r
82 * @param string $str Source date, as UTC
\r
83 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
\r
85 function api_date($str){
\r
86 //Wed May 23 06:01:13 +0000 2007
\r
87 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
\r
91 * @brief Register API endpoint
\r
93 * Register a function to be the endpont for defined API path.
\r
95 * @param string $path API URL path, relative to App::get_baseurl()
\r
96 * @param string $func Function name to call on path request
\r
97 * @param bool $auth API need logged user
\r
98 * @param string $method
\r
99 * HTTP method reqiured to call this endpoint.
\r
100 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
\r
101 * Default to API_METHOD_ANY
\r
103 function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
\r
105 $API[$path] = array(
\r
111 // Workaround for hotot
\r
112 $path = str_replace("api/", "api/1.1/", $path);
\r
113 $API[$path] = array(
\r
121 * @brief Login API user
\r
123 * Log in user via OAuth1 or Simple HTTP Auth.
\r
124 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
\r
127 * @hook 'authenticate'
\r
128 * array $addon_auth
\r
129 * 'username' => username from login form
\r
130 * 'password' => password from login form
\r
131 * 'authenticated' => return status,
\r
132 * 'user_record' => return authenticated user record
\r
133 * @hook 'logged_in'
\r
134 * array $user logged user record
\r
136 function api_login(&$a){
\r
137 // login with oauth
\r
139 $oauth = new FKOAuth1();
\r
140 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
\r
141 if (!is_null($token)){
\r
142 $oauth->loginUser($token->uid);
\r
143 call_hooks('logged_in', $a->user);
\r
146 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
\r
147 }catch(Exception $e){
\r
153 // workaround for HTTP-auth in CGI mode
\r
154 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
\r
155 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
\r
156 if(strlen($userpass)) {
\r
157 list($name, $password) = explode(':', $userpass);
\r
158 $_SERVER['PHP_AUTH_USER'] = $name;
\r
159 $_SERVER['PHP_AUTH_PW'] = $password;
\r
163 if (!isset($_SERVER['PHP_AUTH_USER'])) {
\r
164 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
\r
165 header('WWW-Authenticate: Basic realm="Friendica"');
\r
166 throw new UnauthorizedException("This API requires login");
\r
169 $user = $_SERVER['PHP_AUTH_USER'];
\r
170 $password = $_SERVER['PHP_AUTH_PW'];
\r
171 $encrypted = hash('whirlpool',trim($password));
\r
173 // allow "user@server" login (but ignore 'server' part)
\r
174 $at=strstr($user, "@", true);
\r
175 if ( $at ) $user=$at;
\r
178 * next code from mod/auth.php. needs better solution
\r
182 $addon_auth = array(
\r
183 'username' => trim($user),
\r
184 'password' => trim($password),
\r
185 'authenticated' => 0,
\r
186 'user_record' => null
\r
191 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
\r
192 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
\r
193 * and later plugins should not interfere with an earlier one that succeeded.
\r
197 call_hooks('authenticate', $addon_auth);
\r
199 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
\r
200 $record = $addon_auth['user_record'];
\r
203 // process normal login request
\r
205 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
\r
206 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
\r
207 dbesc(trim($user)),
\r
208 dbesc(trim($user)),
\r
215 if((! $record) || (! count($record))) {
\r
216 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
\r
217 header('WWW-Authenticate: Basic realm="Friendica"');
\r
218 #header('HTTP/1.0 401 Unauthorized');
\r
219 #die('This api requires login');
\r
220 throw new UnauthorizedException("This API requires login");
\r
223 authenticate_success($record);
\r
225 $_SESSION["allow_api"] = true;
\r
227 call_hooks('logged_in', $a->user);
\r
232 * @brief Check HTTP method of called API
\r
234 * API endpoints can define which HTTP method to accept when called.
\r
235 * This function check the current HTTP method agains endpoint
\r
236 * registered method.
\r
238 * @param string $method Required methods, uppercase, separated by comma
\r
241 function api_check_method($method) {
\r
242 if ($method=="*") return True;
\r
243 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
\r
247 * @brief Main API entry point
\r
249 * Authenticate user, call registered API function, set HTTP headers
\r
252 * @return string API call result
\r
254 function api_call(&$a){
\r
255 GLOBAL $API, $called_api;
\r
258 if (strpos($a->query_string, ".xml")>0) $type="xml";
\r
259 if (strpos($a->query_string, ".json")>0) $type="json";
\r
260 if (strpos($a->query_string, ".rss")>0) $type="rss";
\r
261 if (strpos($a->query_string, ".atom")>0) $type="atom";
\r
263 foreach ($API as $p=>$info){
\r
264 if (strpos($a->query_string, $p)===0){
\r
265 if (!api_check_method($info['method'])){
\r
266 throw new MethodNotAllowedException();
\r
269 $called_api= explode("/",$p);
\r
270 //unset($_SERVER['PHP_AUTH_USER']);
\r
271 if ($info['auth']===true && api_user()===false) {
\r
275 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
\r
276 logger('API parameters: ' . print_r($_REQUEST,true));
\r
278 $stamp = microtime(true);
\r
279 $r = call_user_func($info['func'], $type);
\r
280 $duration = (float)(microtime(true)-$stamp);
\r
281 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
\r
284 // api function returned false withour throw an
\r
285 // exception. This should not happend, throw a 500
\r
286 throw new InternalServerErrorException();
\r
291 header ("Content-Type: text/xml");
\r
295 header ("Content-Type: application/json");
\r
297 $json = json_encode($rr);
\r
298 if ($_GET['callback'])
\r
299 $json = $_GET['callback']."(".$json.")";
\r
303 header ("Content-Type: application/rss+xml");
\r
304 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
\r
307 header ("Content-Type: application/atom+xml");
\r
308 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
\r
314 throw new NotImplementedException();
\r
315 } catch (HTTPException $e) {
\r
316 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
\r
317 return api_error($type, $e);
\r
322 * @brief Format API error string
\r
324 * @param string $type Return type (xml, json, rss, as)
\r
325 * @param HTTPException $error Error object
\r
326 * @return strin error message formatted as $type
\r
328 function api_error($type, $e) {
\r
332 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
\r
333 # TODO: https://dev.twitter.com/overview/api/response-codes
\r
335 $error = array("error" => $error,
\r
336 "code" => $e->httpcode." ".$e->httpdesc,
\r
337 "request" => $a->query_string);
\r
339 $ret = api_format_data('status', $type, array('status' => $error));
\r
343 header ("Content-Type: text/xml");
\r
347 header ("Content-Type: application/json");
\r
348 return json_encode($ret);
\r
351 header ("Content-Type: application/rss+xml");
\r
355 header ("Content-Type: application/atom+xml");
\r
362 * @brief Set values for RSS template
\r
365 * @param array $arr Array to be passed to template
\r
366 * @param array $user_info
\r
369 function api_rss_extra(&$a, $arr, $user_info){
\r
370 if (is_null($user_info)) $user_info = api_get_user($a);
\r
371 $arr['$user'] = $user_info;
\r
372 $arr['$rss'] = array(
\r
373 'alternate' => $user_info['url'],
\r
374 'self' => App::get_baseurl(). "/". $a->query_string,
\r
375 'base' => App::get_baseurl(),
\r
376 'updated' => api_date(null),
\r
377 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
\r
378 'language' => $user_info['language'],
\r
379 'logo' => App::get_baseurl()."/images/friendica-32.png",
\r
387 * @brief Unique contact to contact url.
\r
389 * @param int $id Contact id
\r
390 * @return bool|string
\r
391 * Contact url or False if contact id is unknown
\r
393 function api_unique_id_to_url($id){
\r
394 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
\r
397 return ($r[0]["url"]);
\r
403 * @brief Get user info array.
\r
406 * @param int|string $contact_id Contact ID or URL
\r
407 * @param string $type Return type (for errors)
\r
409 function api_get_user(&$a, $contact_id = Null, $type = "json"){
\r
410 global $called_api;
\r
416 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
\r
418 // Searching for contact URL
\r
419 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
\r
420 $user = dbesc(normalise_link($contact_id));
\r
422 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
423 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
426 // Searching for unique contact id
\r
427 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
\r
428 $user = dbesc(api_unique_id_to_url($contact_id));
\r
431 throw new BadRequestException("User not found.");
\r
434 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
435 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
438 if(is_null($user) && x($_GET, 'user_id')) {
\r
439 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
\r
442 throw new BadRequestException("User not found.");
\r
445 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
446 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
448 if(is_null($user) && x($_GET, 'screen_name')) {
\r
449 $user = dbesc($_GET['screen_name']);
\r
451 $extra_query = "AND `contact`.`nick` = '%s' ";
\r
452 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
455 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
\r
456 $argid = count($called_api);
\r
457 list($user, $null) = explode(".",$a->argv[$argid]);
\r
458 if(is_numeric($user)){
\r
459 $user = dbesc(api_unique_id_to_url($user));
\r
465 $extra_query = "AND `contact`.`nurl` = '%s' ";
\r
466 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
468 $user = dbesc($user);
\r
470 $extra_query = "AND `contact`.`nick` = '%s' ";
\r
471 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
\r
475 logger("api_get_user: user ".$user, LOGGER_DEBUG);
\r
478 if (api_user()===false) {
\r
482 $user = $_SESSION['uid'];
\r
483 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
\r
488 logger('api_user: ' . $extra_query . ', user: ' . $user);
\r
490 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
\r
496 // Selecting the id by priority, friendica first
\r
497 api_best_nickname($uinfo);
\r
499 // if the contact wasn't found, fetch it from the unique contacts
\r
500 if (count($uinfo)==0) {
\r
504 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
\r
507 // If no nick where given, extract it from the address
\r
508 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
\r
509 $r[0]['nick'] = api_get_nick($r[0]["url"]);
\r
512 'id' => $r[0]["id"],
\r
513 'id_str' => (string) $r[0]["id"],
\r
514 'name' => $r[0]["name"],
\r
515 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
\r
516 'location' => $r[0]["location"],
\r
517 'description' => $r[0]["about"],
\r
518 'url' => $r[0]["url"],
\r
519 'protected' => false,
\r
520 'followers_count' => 0,
\r
521 'friends_count' => 0,
\r
522 'listed_count' => 0,
\r
523 'created_at' => api_date($r[0]["created"]),
\r
524 'favourites_count' => 0,
\r
526 'time_zone' => 'UTC',
\r
527 'geo_enabled' => false,
\r
528 'verified' => false,
\r
529 'statuses_count' => 0,
\r
531 'contributors_enabled' => false,
\r
532 'is_translator' => false,
\r
533 'is_translation_enabled' => false,
\r
534 'profile_image_url' => $r[0]["photo"],
\r
535 'profile_image_url_https' => $r[0]["photo"],
\r
536 'following' => false,
\r
537 'follow_request_sent' => false,
\r
538 'notifications' => false,
\r
539 'statusnet_blocking' => false,
\r
540 'notifications' => false,
\r
541 'statusnet_profile_url' => $r[0]["url"],
\r
543 'cid' => get_contact($r[0]["url"], api_user()),
\r
545 'network' => $r[0]["network"],
\r
550 throw new BadRequestException("User not found.");
\r
554 if($uinfo[0]['self']) {
\r
556 if ($uinfo[0]['network'] == "")
\r
557 $uinfo[0]['network'] = NETWORK_DFRN;
\r
559 $usr = q("select * from user where uid = %d limit 1",
\r
562 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
\r
566 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
\r
567 // count public wall messages
\r
568 $r = q("SELECT count(*) as `count` FROM `item`
\r
570 AND `type`='wall'",
\r
571 intval($uinfo[0]['uid'])
\r
573 $countitms = $r[0]['count'];
\r
576 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
\r
577 $r = q("SELECT count(*) as `count` FROM `item`
\r
578 WHERE `contact-id` = %d",
\r
579 intval($uinfo[0]['id'])
\r
581 $countitms = $r[0]['count'];
\r
585 $r = q("SELECT count(*) as `count` FROM `contact`
\r
586 WHERE `uid` = %d AND `rel` IN ( %d, %d )
\r
587 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
\r
588 intval($uinfo[0]['uid']),
\r
589 intval(CONTACT_IS_SHARING),
\r
590 intval(CONTACT_IS_FRIEND)
\r
592 $countfriends = $r[0]['count'];
\r
594 $r = q("SELECT count(*) as `count` FROM `contact`
\r
595 WHERE `uid` = %d AND `rel` IN ( %d, %d )
\r
596 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
\r
597 intval($uinfo[0]['uid']),
\r
598 intval(CONTACT_IS_FOLLOWER),
\r
599 intval(CONTACT_IS_FRIEND)
\r
601 $countfollowers = $r[0]['count'];
\r
603 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
\r
604 intval($uinfo[0]['uid'])
\r
606 $starred = $r[0]['count'];
\r
609 if(! $uinfo[0]['self']) {
\r
611 $countfollowers = 0;
\r
615 // Add a nick if it isn't present there
\r
616 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
\r
617 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
\r
620 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
\r
622 $gcontact_id = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
\r
623 "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
\r
626 'id' => intval($gcontact_id),
\r
627 'id_str' => (string) intval($gcontact_id),
\r
628 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
\r
629 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
\r
630 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
\r
631 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
\r
632 'profile_image_url' => $uinfo[0]['micro'],
\r
633 'profile_image_url_https' => $uinfo[0]['micro'],
\r
634 'url' => $uinfo[0]['url'],
\r
635 'protected' => false,
\r
636 'followers_count' => intval($countfollowers),
\r
637 'friends_count' => intval($countfriends),
\r
638 'created_at' => api_date($uinfo[0]['created']),
\r
639 'favourites_count' => intval($starred),
\r
640 'utc_offset' => "0",
\r
641 'time_zone' => 'UTC',
\r
642 'statuses_count' => intval($countitms),
\r
643 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
\r
644 'verified' => true,
\r
645 'statusnet_blocking' => false,
\r
646 'notifications' => false,
\r
647 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
\r
648 'statusnet_profile_url' => $uinfo[0]['url'],
\r
649 'uid' => intval($uinfo[0]['uid']),
\r
650 'cid' => intval($uinfo[0]['cid']),
\r
651 'self' => $uinfo[0]['self'],
\r
652 'network' => $uinfo[0]['network'],
\r
660 * @brief return api-formatted array for item's author and owner
\r
663 * @param array $item : item from db
\r
664 * @return array(array:author, array:owner)
\r
666 function api_item_get_user(&$a, $item) {
\r
668 // Make sure that there is an entry in the global contacts for author and owner
\r
669 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
\r
670 "photo" => $item['author-avatar'], "name" => $item['author-name']));
\r
672 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
\r
673 "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
\r
675 $status_user = api_get_user($a,$item["author-link"]);
\r
676 $status_user["protected"] = (($item["allow_cid"] != "") OR
\r
677 ($item["allow_gid"] != "") OR
\r
678 ($item["deny_cid"] != "") OR
\r
679 ($item["deny_gid"] != "") OR
\r
682 $owner_user = api_get_user($a,$item["owner-link"]);
\r
684 return (array($status_user, $owner_user));
\r
688 * @brief walks recursively through an array with the possibility to change value and key
\r
690 * @param array $array The array to walk through
\r
691 * @param string $callback The callback function
\r
693 * @return array the transformed array
\r
695 function api_walk_recursive(array &$array, callable $callback) {
\r
697 $new_array = array();
\r
699 foreach ($array as $k => $v) {
\r
700 if (is_array($v)) {
\r
701 if ($callback($v, $k))
\r
702 $new_array[$k] = api_walk_recursive($v, $callback);
\r
704 if ($callback($v, $k))
\r
705 $new_array[$k] = $v;
\r
708 $array = $new_array;
\r
714 * @brief Callback function to transform the array in an array that can be transformed in a XML file
\r
716 * @param variant $item Array item value
\r
717 * @param string $key Array key
\r
719 * @return boolean Should the array item be deleted?
\r
721 function api_reformat_xml(&$item, &$key) {
\r
722 if (is_bool($item))
\r
723 $item = ($item ? "true" : "false");
\r
725 if (substr($key, 0, 10) == "statusnet_")
\r
726 $key = "statusnet:".substr($key, 10);
\r
727 elseif (substr($key, 0, 10) == "friendica_")
\r
728 $key = "friendica:".substr($key, 10);
\r
730 // $key = "default:".$key;
\r
736 * @brief Creates the XML from a JSON style array
\r
738 * @param array $data JSON style array
\r
739 * @param string $root_element Name of the root element
\r
741 * @return string The XML data
\r
743 function api_create_xml($data, $root_element) {
\r
744 $childname = key($data);
\r
745 $data2 = array_pop($data);
\r
746 $key = key($data2);
\r
748 $namespaces = array("" => "http://api.twitter.com",
\r
749 "statusnet" => "http://status.net/schema/api/1/",
\r
750 "friendica" => "http://friendi.ca/schema/api/1/",
\r
751 "georss" => "http://www.georss.org/georss");
\r
753 /// @todo Auto detection of needed namespaces
\r
754 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
\r
755 $namespaces = array();
\r
757 if (is_array($data2))
\r
758 api_walk_recursive($data2, "api_reformat_xml");
\r
764 foreach ($data2 AS $item)
\r
765 $data4[$i++.":".$childname] = $item;
\r
770 $data3 = array($root_element => $data2);
\r
772 $ret = xml::from_array($data3, $xml, false, $namespaces);
\r
777 * @brief Formats the data according to the data type
\r
779 * @param string $root_element Name of the root element
\r
780 * @param string $type Return type (atom, rss, xml, json)
\r
781 * @param array $data JSON style array
\r
783 * @return (string|object) XML data or JSON data
\r
785 function api_format_data($root_element, $type, $data){
\r
793 $ret = api_create_xml($data, $root_element);
\r
808 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
\r
809 * returns a 401 status code and an error message if not.
\r
810 * http://developer.twitter.com/doc/get/account/verify_credentials
\r
812 function api_account_verify_credentials($type){
\r
816 if (api_user()===false) throw new ForbiddenException();
\r
818 unset($_REQUEST["user_id"]);
\r
819 unset($_GET["user_id"]);
\r
821 unset($_REQUEST["screen_name"]);
\r
822 unset($_GET["screen_name"]);
\r
824 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
\r
826 $user_info = api_get_user($a);
\r
828 // "verified" isn't used here in the standard
\r
829 unset($user_info["verified"]);
\r
831 // - Adding last status
\r
832 if (!$skip_status) {
\r
833 $user_info["status"] = api_status_show("raw");
\r
834 if (!count($user_info["status"]))
\r
835 unset($user_info["status"]);
\r
837 unset($user_info["status"]["user"]);
\r
840 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
841 unset($user_info["uid"]);
\r
842 unset($user_info["self"]);
\r
844 return api_format_data("user", $type, array('user' => $user_info));
\r
847 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
\r
851 * get data from $_POST or $_GET
\r
853 function requestdata($k){
\r
854 if (isset($_POST[$k])){
\r
857 if (isset($_GET[$k])){
\r
863 /*Waitman Gobble Mod*/
\r
864 function api_statuses_mediap($type) {
\r
868 if (api_user()===false) {
\r
869 logger('api_statuses_update: no user');
\r
870 throw new ForbiddenException();
\r
872 $user_info = api_get_user($a);
\r
874 $_REQUEST['type'] = 'wall';
\r
875 $_REQUEST['profile_uid'] = api_user();
\r
876 $_REQUEST['api_source'] = true;
\r
877 $txt = requestdata('status');
\r
878 //$txt = urldecode(requestdata('status'));
\r
880 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
\r
882 $txt = html2bb_video($txt);
\r
883 $config = HTMLPurifier_Config::createDefault();
\r
884 $config->set('Cache.DefinitionImpl', null);
\r
885 $purifier = new HTMLPurifier($config);
\r
886 $txt = $purifier->purify($txt);
\r
888 $txt = html2bbcode($txt);
\r
890 $a->argv[1]=$user_info['screen_name']; //should be set to username?
\r
892 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
\r
893 $bebop = wall_upload_post($a);
\r
895 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
\r
896 $_REQUEST['body']=$txt."\n\n".$bebop;
\r
899 // this should output the last post (the one we just posted).
\r
900 return api_status_show($type);
\r
902 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
\r
903 /*Waitman Gobble Mod*/
\r
906 function api_statuses_update($type) {
\r
910 if (api_user()===false) {
\r
911 logger('api_statuses_update: no user');
\r
912 throw new ForbiddenException();
\r
915 $user_info = api_get_user($a);
\r
917 // convert $_POST array items to the form we use for web posts.
\r
919 // logger('api_post: ' . print_r($_POST,true));
\r
921 if(requestdata('htmlstatus')) {
\r
922 $txt = requestdata('htmlstatus');
\r
923 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
\r
924 $txt = html2bb_video($txt);
\r
926 $config = HTMLPurifier_Config::createDefault();
\r
927 $config->set('Cache.DefinitionImpl', null);
\r
929 $purifier = new HTMLPurifier($config);
\r
930 $txt = $purifier->purify($txt);
\r
932 $_REQUEST['body'] = html2bbcode($txt);
\r
936 $_REQUEST['body'] = requestdata('status');
\r
938 $_REQUEST['title'] = requestdata('title');
\r
940 $parent = requestdata('in_reply_to_status_id');
\r
942 // Twidere sends "-1" if it is no reply ...
\r
946 if(ctype_digit($parent))
\r
947 $_REQUEST['parent'] = $parent;
\r
949 $_REQUEST['parent_uri'] = $parent;
\r
951 if(requestdata('lat') && requestdata('long'))
\r
952 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
\r
953 $_REQUEST['profile_uid'] = api_user();
\r
956 $_REQUEST['type'] = 'net-comment';
\r
958 // Check for throttling (maximum posts per day, week and month)
\r
959 $throttle_day = get_config('system','throttle_limit_day');
\r
960 if ($throttle_day > 0) {
\r
961 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
\r
963 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
\r
964 AND `created` > '%s' AND `id` = `parent`",
\r
965 intval(api_user()), dbesc($datefrom));
\r
968 $posts_day = $r[0]["posts_day"];
\r
972 if ($posts_day > $throttle_day) {
\r
973 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
\r
974 #die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
\r
975 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
\r
979 $throttle_week = get_config('system','throttle_limit_week');
\r
980 if ($throttle_week > 0) {
\r
981 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
\r
983 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
\r
984 AND `created` > '%s' AND `id` = `parent`",
\r
985 intval(api_user()), dbesc($datefrom));
\r
988 $posts_week = $r[0]["posts_week"];
\r
992 if ($posts_week > $throttle_week) {
\r
993 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
\r
994 #die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
\r
995 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
\r
1000 $throttle_month = get_config('system','throttle_limit_month');
\r
1001 if ($throttle_month > 0) {
\r
1002 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
\r
1004 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
\r
1005 AND `created` > '%s' AND `id` = `parent`",
\r
1006 intval(api_user()), dbesc($datefrom));
\r
1009 $posts_month = $r[0]["posts_month"];
\r
1013 if ($posts_month > $throttle_month) {
\r
1014 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
\r
1015 #die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
\r
1016 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
\r
1020 $_REQUEST['type'] = 'wall';
\r
1023 if(x($_FILES,'media')) {
\r
1024 // upload the image if we have one
\r
1025 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
\r
1026 $media = wall_upload_post($a);
\r
1027 if(strlen($media)>0)
\r
1028 $_REQUEST['body'] .= "\n\n".$media;
\r
1031 // To-Do: Multiple IDs
\r
1032 if (requestdata('media_ids')) {
\r
1033 $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",
\r
1034 intval(requestdata('media_ids')), api_user());
\r
1036 $phototypes = Photo::supportedTypes();
\r
1037 $ext = $phototypes[$r[0]['type']];
\r
1038 $_REQUEST['body'] .= "\n\n".'[url='.App::get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
\r
1039 $_REQUEST['body'] .= '[img]'.App::get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
\r
1043 // set this so that the item_post() function is quiet and doesn't redirect or emit json
\r
1045 $_REQUEST['api_source'] = true;
\r
1047 if (!x($_REQUEST, "source"))
\r
1048 $_REQUEST["source"] = api_source();
\r
1050 // call out normal post function
\r
1054 // this should output the last post (the one we just posted).
\r
1055 return api_status_show($type);
\r
1057 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
\r
1058 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
\r
1061 function api_media_upload($type) {
\r
1065 if (api_user()===false) {
\r
1066 logger('no user');
\r
1067 throw new ForbiddenException();
\r
1070 $user_info = api_get_user($a);
\r
1072 if(!x($_FILES,'media')) {
\r
1074 throw new BadRequestException("No media.");
\r
1077 $media = wall_upload_post($a, false);
\r
1080 throw new InternalServerErrorException();
\r
1083 $returndata = array();
\r
1084 $returndata["media_id"] = $media["id"];
\r
1085 $returndata["media_id_string"] = (string)$media["id"];
\r
1086 $returndata["size"] = $media["size"];
\r
1087 $returndata["image"] = array("w" => $media["width"],
\r
1088 "h" => $media["height"],
\r
1089 "image_type" => $media["type"]);
\r
1091 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
\r
1093 return array("media" => $returndata);
\r
1095 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
\r
1097 function api_status_show($type){
\r
1101 $user_info = api_get_user($a);
\r
1103 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
\r
1105 if ($type == "raw")
\r
1106 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
\r
1108 $privacy_sql = "";
\r
1110 // get last public wall message
\r
1111 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
\r
1112 FROM `item`, `item` as `i`
\r
1113 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
\r
1114 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
\r
1115 AND `i`.`id` = `item`.`parent`
\r
1116 AND `item`.`type`!='activity' $privacy_sql
\r
1117 ORDER BY `item`.`id` DESC
\r
1119 intval($user_info['cid']),
\r
1120 intval(api_user()),
\r
1121 dbesc($user_info['url']),
\r
1122 dbesc(normalise_link($user_info['url'])),
\r
1123 dbesc($user_info['url']),
\r
1124 dbesc(normalise_link($user_info['url']))
\r
1127 if (count($lastwall)>0){
\r
1128 $lastwall = $lastwall[0];
\r
1130 $in_reply_to_status_id = NULL;
\r
1131 $in_reply_to_user_id = NULL;
\r
1132 $in_reply_to_status_id_str = NULL;
\r
1133 $in_reply_to_user_id_str = NULL;
\r
1134 $in_reply_to_screen_name = NULL;
\r
1135 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
\r
1136 $in_reply_to_status_id= intval($lastwall['parent']);
\r
1137 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
\r
1139 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
\r
1141 if ($r[0]['nick'] == "")
\r
1142 $r[0]['nick'] = api_get_nick($r[0]["url"]);
\r
1144 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
\r
1145 $in_reply_to_user_id = intval($r[0]['id']);
\r
1146 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
\r
1150 // There seems to be situation, where both fields are identical:
\r
1151 // https://github.com/friendica/friendica/issues/1010
\r
1152 // This is a bugfix for that.
\r
1153 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
\r
1154 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
\r
1155 $in_reply_to_status_id = NULL;
\r
1156 $in_reply_to_user_id = NULL;
\r
1157 $in_reply_to_status_id_str = NULL;
\r
1158 $in_reply_to_user_id_str = NULL;
\r
1159 $in_reply_to_screen_name = NULL;
\r
1162 $converted = api_convert_item($lastwall);
\r
1164 if ($type == "xml")
\r
1165 $geo = "georss:point";
\r
1169 $status_info = array(
\r
1170 'created_at' => api_date($lastwall['created']),
\r
1171 'id' => intval($lastwall['id']),
\r
1172 'id_str' => (string) $lastwall['id'],
\r
1173 'text' => $converted["text"],
\r
1174 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
\r
1175 'truncated' => false,
\r
1176 'in_reply_to_status_id' => $in_reply_to_status_id,
\r
1177 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
\r
1178 'in_reply_to_user_id' => $in_reply_to_user_id,
\r
1179 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
\r
1180 'in_reply_to_screen_name' => $in_reply_to_screen_name,
\r
1181 'user' => $user_info,
\r
1183 'coordinates' => "",
\r
1185 'contributors' => "",
\r
1186 'is_quote_status' => false,
\r
1187 'retweet_count' => 0,
\r
1188 'favorite_count' => 0,
\r
1189 'favorited' => $lastwall['starred'] ? true : false,
\r
1190 'retweeted' => false,
\r
1191 'possibly_sensitive' => false,
\r
1193 'statusnet_html' => $converted["html"],
\r
1194 'statusnet_conversation_id' => $lastwall['parent'],
\r
1197 if (count($converted["attachments"]) > 0)
\r
1198 $status_info["attachments"] = $converted["attachments"];
\r
1200 if (count($converted["entities"]) > 0)
\r
1201 $status_info["entities"] = $converted["entities"];
\r
1203 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
\r
1204 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
\r
1205 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
\r
1206 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
\r
1208 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
1209 unset($status_info["user"]["uid"]);
\r
1210 unset($status_info["user"]["self"]);
\r
1213 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
\r
1215 if ($type == "raw")
\r
1216 return($status_info);
\r
1218 return api_format_data("statuses", $type, array('status' => $status_info));
\r
1227 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
\r
1228 * The author's most recent status will be returned inline.
\r
1229 * http://developer.twitter.com/doc/get/users/show
\r
1231 function api_users_show($type){
\r
1235 $user_info = api_get_user($a);
\r
1236 $lastwall = q("SELECT `item`.*
\r
1238 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1239 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
\r
1240 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
\r
1241 AND `type`!='activity'
\r
1242 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
\r
1243 ORDER BY `id` DESC
\r
1245 intval(api_user()),
\r
1246 dbesc(ACTIVITY_POST),
\r
1247 intval($user_info['cid']),
\r
1248 dbesc($user_info['url']),
\r
1249 dbesc(normalise_link($user_info['url'])),
\r
1250 dbesc($user_info['url']),
\r
1251 dbesc(normalise_link($user_info['url']))
\r
1254 if (count($lastwall)>0){
\r
1255 $lastwall = $lastwall[0];
\r
1257 $in_reply_to_status_id = NULL;
\r
1258 $in_reply_to_user_id = NULL;
\r
1259 $in_reply_to_status_id_str = NULL;
\r
1260 $in_reply_to_user_id_str = NULL;
\r
1261 $in_reply_to_screen_name = NULL;
\r
1262 if ($lastwall['parent']!=$lastwall['id']) {
\r
1263 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
\r
1264 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
\r
1265 if (count($reply)>0) {
\r
1266 $in_reply_to_status_id = intval($lastwall['parent']);
\r
1267 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
\r
1269 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
\r
1271 if ($r[0]['nick'] == "")
\r
1272 $r[0]['nick'] = api_get_nick($r[0]["url"]);
\r
1274 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
\r
1275 $in_reply_to_user_id = intval($r[0]['id']);
\r
1276 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
\r
1281 $converted = api_convert_item($lastwall);
\r
1283 if ($type == "xml")
\r
1284 $geo = "georss:point";
\r
1288 $user_info['status'] = array(
\r
1289 'text' => $converted["text"],
\r
1290 'truncated' => false,
\r
1291 'created_at' => api_date($lastwall['created']),
\r
1292 'in_reply_to_status_id' => $in_reply_to_status_id,
\r
1293 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
\r
1294 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
\r
1295 'id' => intval($lastwall['contact-id']),
\r
1296 'id_str' => (string) $lastwall['contact-id'],
\r
1297 'in_reply_to_user_id' => $in_reply_to_user_id,
\r
1298 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
\r
1299 'in_reply_to_screen_name' => $in_reply_to_screen_name,
\r
1301 'favorited' => $lastwall['starred'] ? true : false,
\r
1302 'statusnet_html' => $converted["html"],
\r
1303 'statusnet_conversation_id' => $lastwall['parent'],
\r
1306 if (count($converted["attachments"]) > 0)
\r
1307 $user_info["status"]["attachments"] = $converted["attachments"];
\r
1309 if (count($converted["entities"]) > 0)
\r
1310 $user_info["status"]["entities"] = $converted["entities"];
\r
1312 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
\r
1313 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
\r
1314 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
\r
1315 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
\r
1319 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
1320 unset($user_info["uid"]);
\r
1321 unset($user_info["self"]);
\r
1323 return api_format_data("user", $type, array('user' => $user_info));
\r
1326 api_register_func('api/users/show','api_users_show');
\r
1329 function api_users_search($type) {
\r
1333 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
1335 $userlist = array();
\r
1337 if (isset($_GET["q"])) {
\r
1338 $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
\r
1340 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
\r
1344 foreach ($r AS $user) {
\r
1345 $user_info = api_get_user($a, $user["id"], "json");
\r
1347 if ($type == "xml")
\r
1348 $userlist[$k++.":user"] = $user_info;
\r
1350 $userlist[] = $user_info;
\r
1352 $userlist = array("users" => $userlist);
\r
1354 throw new BadRequestException("User not found.");
\r
1357 throw new BadRequestException("User not found.");
\r
1359 return api_format_data("users", $type, $userlist);
\r
1362 api_register_func('api/users/search','api_users_search');
\r
1366 * http://developer.twitter.com/doc/get/statuses/home_timeline
\r
1368 * TODO: Optional parameters
\r
1369 * TODO: Add reply info
\r
1371 function api_statuses_home_timeline($type){
\r
1375 if (api_user()===false) throw new ForbiddenException();
\r
1377 unset($_REQUEST["user_id"]);
\r
1378 unset($_GET["user_id"]);
\r
1380 unset($_REQUEST["screen_name"]);
\r
1381 unset($_GET["screen_name"]);
\r
1383 $user_info = api_get_user($a);
\r
1384 // get last newtork messages
\r
1388 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
\r
1389 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
1390 if ($page<0) $page=0;
\r
1391 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1392 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
\r
1393 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1394 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
\r
1395 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
\r
1397 $start = $page*$count;
\r
1401 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
\r
1402 if ($exclude_replies > 0)
\r
1403 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
\r
1404 if ($conversation_id > 0)
\r
1405 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
\r
1407 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1408 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1409 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1410 `contact`.`id` AS `cid`
\r
1412 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1413 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1414 WHERE `item`.`uid` = %d AND `verb` = '%s'
\r
1415 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1417 AND `item`.`id`>%d
\r
1418 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
1419 intval(api_user()),
\r
1420 dbesc(ACTIVITY_POST),
\r
1421 intval($since_id),
\r
1422 intval($start), intval($count)
\r
1425 $ret = api_format_items($r,$user_info, false, $type);
\r
1427 // Set all posts from the query above to seen
\r
1428 $idarray = array();
\r
1429 foreach ($r AS $item)
\r
1430 $idarray[] = intval($item["id"]);
\r
1432 $idlist = implode(",", $idarray);
\r
1434 if ($idlist != "") {
\r
1435 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
\r
1438 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
\r
1441 $data = array('status' => $ret);
\r
1445 $data = api_rss_extra($a, $data, $user_info);
\r
1449 return api_format_data("statuses", $type, $data);
\r
1451 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
\r
1452 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
\r
1454 function api_statuses_public_timeline($type){
\r
1458 if (api_user()===false) throw new ForbiddenException();
\r
1460 $user_info = api_get_user($a);
\r
1461 // get last newtork messages
\r
1465 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
\r
1466 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
1467 if ($page<0) $page=0;
\r
1468 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1469 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
\r
1470 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1471 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
\r
1472 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
\r
1474 $start = $page*$count;
\r
1477 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
\r
1478 if ($exclude_replies > 0)
\r
1479 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
\r
1480 if ($conversation_id > 0)
\r
1481 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
\r
1483 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1484 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1485 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
\r
1486 `contact`.`id` AS `cid`,
\r
1487 `user`.`nickname`, `user`.`hidewall`
\r
1489 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1490 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1491 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
\r
1492 AND NOT `user`.`hidewall`
\r
1493 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
\r
1494 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
\r
1495 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
\r
1496 AND NOT `item`.`private` AND `item`.`wall`
\r
1498 AND `item`.`id`>%d
\r
1499 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
\r
1500 dbesc(ACTIVITY_POST),
\r
1501 intval($since_id),
\r
1505 $ret = api_format_items($r,$user_info, false, $type);
\r
1508 $data = array('status' => $ret);
\r
1512 $data = api_rss_extra($a, $data, $user_info);
\r
1516 return api_format_data("statuses", $type, $data);
\r
1518 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
\r
1523 function api_statuses_show($type){
\r
1527 if (api_user()===false) throw new ForbiddenException();
\r
1529 $user_info = api_get_user($a);
\r
1532 $id = intval($a->argv[3]);
\r
1535 $id = intval($_REQUEST["id"]);
\r
1537 // Hotot workaround
\r
1539 $id = intval($a->argv[4]);
\r
1541 logger('API: api_statuses_show: '.$id);
\r
1543 $conversation = (x($_REQUEST,'conversation')?1:0);
\r
1546 if ($conversation)
\r
1547 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
\r
1549 $sql_extra .= " AND `item`.`id` = %d";
\r
1551 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1552 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1553 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1554 `contact`.`id` AS `cid`
\r
1556 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1557 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1558 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1559 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
\r
1561 intval(api_user()),
\r
1562 dbesc(ACTIVITY_POST),
\r
1567 throw new BadRequestException("There is no status with this id.");
\r
1570 $ret = api_format_items($r,$user_info, false, $type);
\r
1572 if ($conversation) {
\r
1573 $data = array('status' => $ret);
\r
1574 return api_format_data("statuses", $type, $data);
\r
1576 $data = array('status' => $ret[0]);
\r
1577 return api_format_data("status", $type, $data);
\r
1580 api_register_func('api/statuses/show','api_statuses_show', true);
\r
1586 function api_conversation_show($type){
\r
1590 if (api_user()===false) throw new ForbiddenException();
\r
1592 $user_info = api_get_user($a);
\r
1595 $id = intval($a->argv[3]);
\r
1596 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
\r
1597 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
1598 if ($page<0) $page=0;
\r
1599 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1600 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
\r
1602 $start = $page*$count;
\r
1605 $id = intval($_REQUEST["id"]);
\r
1607 // Hotot workaround
\r
1609 $id = intval($a->argv[4]);
\r
1611 logger('API: api_conversation_show: '.$id);
\r
1613 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
\r
1615 $id = $r[0]["parent"];
\r
1620 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
\r
1622 // Not sure why this query was so complicated. We should keep it here for a while,
\r
1623 // just to make sure that we really don't need it.
\r
1624 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
\r
1625 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
\r
1627 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1628 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1629 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1630 `contact`.`id` AS `cid`
\r
1632 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1633 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1634 WHERE `item`.`parent` = %d AND `item`.`visible`
\r
1635 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1636 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
\r
1637 AND `item`.`id`>%d $sql_extra
\r
1638 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
\r
1639 intval($id), intval(api_user()),
\r
1640 dbesc(ACTIVITY_POST),
\r
1641 intval($since_id),
\r
1642 intval($start), intval($count)
\r
1646 throw new BadRequestException("There is no conversation with this id.");
\r
1648 $ret = api_format_items($r,$user_info, false, $type);
\r
1650 $data = array('status' => $ret);
\r
1651 return api_format_data("statuses", $type, $data);
\r
1653 api_register_func('api/conversation/show','api_conversation_show', true);
\r
1654 api_register_func('api/statusnet/conversation','api_conversation_show', true);
\r
1660 function api_statuses_repeat($type){
\r
1661 global $called_api;
\r
1665 if (api_user()===false) throw new ForbiddenException();
\r
1667 $user_info = api_get_user($a);
\r
1670 $id = intval($a->argv[3]);
\r
1673 $id = intval($_REQUEST["id"]);
\r
1675 // Hotot workaround
\r
1677 $id = intval($a->argv[4]);
\r
1679 logger('API: api_statuses_repeat: '.$id);
\r
1681 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
\r
1682 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
\r
1683 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1684 `contact`.`id` AS `cid`
\r
1686 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1687 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1688 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1689 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
\r
1690 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
\r
1692 AND `item`.`id`=%d",
\r
1696 if ($r[0]['body'] != "") {
\r
1697 if (!intval(get_config('system','old_share'))) {
\r
1698 if (strpos($r[0]['body'], "[/share]") !== false) {
\r
1699 $pos = strpos($r[0]['body'], "[share");
\r
1700 $post = substr($r[0]['body'], $pos);
\r
1702 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
\r
1704 $post .= $r[0]['body'];
\r
1705 $post .= "[/share]";
\r
1707 $_REQUEST['body'] = $post;
\r
1709 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
\r
1711 $_REQUEST['profile_uid'] = api_user();
\r
1712 $_REQUEST['type'] = 'wall';
\r
1713 $_REQUEST['api_source'] = true;
\r
1715 if (!x($_REQUEST, "source"))
\r
1716 $_REQUEST["source"] = api_source();
\r
1720 throw new ForbiddenException();
\r
1722 // this should output the last post (the one we just posted).
\r
1723 $called_api = null;
\r
1724 return(api_status_show($type));
\r
1726 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
\r
1731 function api_statuses_destroy($type){
\r
1735 if (api_user()===false) throw new ForbiddenException();
\r
1737 $user_info = api_get_user($a);
\r
1740 $id = intval($a->argv[3]);
\r
1743 $id = intval($_REQUEST["id"]);
\r
1745 // Hotot workaround
\r
1747 $id = intval($a->argv[4]);
\r
1749 logger('API: api_statuses_destroy: '.$id);
\r
1751 $ret = api_statuses_show($type);
\r
1753 drop_item($id, false);
\r
1757 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
\r
1761 * http://developer.twitter.com/doc/get/statuses/mentions
\r
1764 function api_statuses_mentions($type){
\r
1768 if (api_user()===false) throw new ForbiddenException();
\r
1770 unset($_REQUEST["user_id"]);
\r
1771 unset($_GET["user_id"]);
\r
1773 unset($_REQUEST["screen_name"]);
\r
1774 unset($_GET["screen_name"]);
\r
1776 $user_info = api_get_user($a);
\r
1777 // get last newtork messages
\r
1781 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
\r
1782 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
1783 if ($page<0) $page=0;
\r
1784 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1785 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
\r
1786 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1788 $start = $page*$count;
\r
1790 // Ugly code - should be changed
\r
1791 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
\r
1792 $myurl = substr($myurl,strpos($myurl,'://')+3);
\r
1793 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
\r
1794 $myurl = str_replace('www.','',$myurl);
\r
1795 $diasp_url = str_replace('/profile/','/u/',$myurl);
\r
1798 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
\r
1800 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1801 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1802 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1803 `contact`.`id` AS `cid`
\r
1804 FROM `item` FORCE INDEX (`uid_id`)
\r
1805 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1806 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1807 WHERE `item`.`uid` = %d AND `verb` = '%s'
\r
1808 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
\r
1809 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1810 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
\r
1812 AND `item`.`id`>%d
\r
1813 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
1814 intval(api_user()),
\r
1815 dbesc(ACTIVITY_POST),
\r
1816 dbesc(protect_sprintf($myurl)),
\r
1817 dbesc(protect_sprintf($myurl)),
\r
1818 intval(api_user()),
\r
1819 intval($since_id),
\r
1820 intval($start), intval($count)
\r
1823 $ret = api_format_items($r,$user_info, false, $type);
\r
1826 $data = array('status' => $ret);
\r
1830 $data = api_rss_extra($a, $data, $user_info);
\r
1834 return api_format_data("statuses", $type, $data);
\r
1836 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
\r
1837 api_register_func('api/statuses/replies','api_statuses_mentions', true);
\r
1840 function api_statuses_user_timeline($type){
\r
1844 if (api_user()===false) throw new ForbiddenException();
\r
1846 $user_info = api_get_user($a);
\r
1847 // get last network messages
\r
1849 logger("api_statuses_user_timeline: api_user: ". api_user() .
\r
1850 "\nuser_info: ".print_r($user_info, true) .
\r
1851 "\n_REQUEST: ".print_r($_REQUEST, true),
\r
1855 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
\r
1856 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
1857 if ($page<0) $page=0;
\r
1858 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1859 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1860 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
\r
1861 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
\r
1863 $start = $page*$count;
\r
1866 if ($user_info['self']==1)
\r
1867 $sql_extra .= " AND `item`.`wall` = 1 ";
\r
1869 if ($exclude_replies > 0)
\r
1870 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
\r
1871 if ($conversation_id > 0)
\r
1872 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
\r
1874 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
1875 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
1876 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
1877 `contact`.`id` AS `cid`
\r
1878 FROM `item` FORCE INDEX (`uid_contactid_id`)
\r
1879 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
\r
1880 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
\r
1881 WHERE `item`.`uid` = %d AND `verb` = '%s'
\r
1882 AND `item`.`contact-id` = %d
\r
1883 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
\r
1885 AND `item`.`id`>%d
\r
1886 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
1887 intval(api_user()),
\r
1888 dbesc(ACTIVITY_POST),
\r
1889 intval($user_info['cid']),
\r
1890 intval($since_id),
\r
1891 intval($start), intval($count)
\r
1894 $ret = api_format_items($r,$user_info, true, $type);
\r
1896 $data = array('status' => $ret);
\r
1900 $data = api_rss_extra($a, $data, $user_info);
\r
1903 return api_format_data("statuses", $type, $data);
\r
1905 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
\r
1909 * Star/unstar an item
\r
1910 * param: id : id of the item
\r
1912 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
\r
1914 function api_favorites_create_destroy($type){
\r
1918 if (api_user()===false) throw new ForbiddenException();
\r
1920 // for versioned api.
\r
1921 /// @TODO We need a better global soluton
\r
1922 $action_argv_id=2;
\r
1923 if ($a->argv[1]=="1.1") $action_argv_id=3;
\r
1925 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
\r
1926 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
\r
1927 if ($a->argc==$action_argv_id+2) {
\r
1928 $itemid = intval($a->argv[$action_argv_id+1]);
\r
1930 $itemid = intval($_REQUEST['id']);
\r
1933 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
\r
1934 $itemid, api_user());
\r
1936 if ($item===false || count($item)==0)
\r
1937 throw new BadRequestException("Invalid item.");
\r
1941 $item[0]['starred']=1;
\r
1944 $item[0]['starred']=0;
\r
1947 throw new BadRequestException("Invalid action ".$action);
\r
1949 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
\r
1950 $item[0]['starred'], $itemid, api_user());
\r
1952 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
\r
1953 $item[0]['starred'], $itemid, api_user());
\r
1956 throw InternalServerErrorException("DB error");
\r
1959 $user_info = api_get_user($a);
\r
1960 $rets = api_format_items($item, $user_info, false, $type);
\r
1963 $data = array('status' => $ret);
\r
1967 $data = api_rss_extra($a, $data, $user_info);
\r
1970 return api_format_data("status", $type, $data);
\r
1972 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
\r
1973 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
\r
1975 function api_favorites($type){
\r
1976 global $called_api;
\r
1980 if (api_user()===false) throw new ForbiddenException();
\r
1982 $called_api= array();
\r
1984 $user_info = api_get_user($a);
\r
1986 // in friendica starred item are private
\r
1987 // return favorites only for self
\r
1988 logger('api_favorites: self:' . $user_info['self']);
\r
1990 if ($user_info['self']==0) {
\r
1996 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
1997 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
\r
1998 $count = (x($_GET,'count')?$_GET['count']:20);
\r
1999 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
2000 if ($page<0) $page=0;
\r
2002 $start = $page*$count;
\r
2005 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
\r
2007 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
\r
2008 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
\r
2009 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
\r
2010 `contact`.`id` AS `cid`
\r
2011 FROM `item`, `contact`
\r
2012 WHERE `item`.`uid` = %d
\r
2013 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
\r
2014 AND `item`.`starred` = 1
\r
2015 AND `contact`.`id` = `item`.`contact-id`
\r
2016 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
\r
2018 AND `item`.`id`>%d
\r
2019 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
\r
2020 intval(api_user()),
\r
2021 intval($since_id),
\r
2022 intval($start), intval($count)
\r
2025 $ret = api_format_items($r,$user_info, false, $type);
\r
2029 $data = array('status' => $ret);
\r
2033 $data = api_rss_extra($a, $data, $user_info);
\r
2036 return api_format_data("statuses", $type, $data);
\r
2038 api_register_func('api/favorites','api_favorites', true);
\r
2040 function api_format_messages($item, $recipient, $sender) {
\r
2041 // standard meta information
\r
2043 'id' => $item['id'],
\r
2044 'sender_id' => $sender['id'] ,
\r
2046 'recipient_id' => $recipient['id'],
\r
2047 'created_at' => api_date($item['created']),
\r
2048 'sender_screen_name' => $sender['screen_name'],
\r
2049 'recipient_screen_name' => $recipient['screen_name'],
\r
2050 'sender' => $sender,
\r
2051 'recipient' => $recipient,
\r
2053 'friendica_seen' => $item['seen'],
\r
2054 'friendica_parent_uri' => $item['parent-uri'],
\r
2057 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
2058 unset($ret["sender"]["uid"]);
\r
2059 unset($ret["sender"]["self"]);
\r
2060 unset($ret["recipient"]["uid"]);
\r
2061 unset($ret["recipient"]["self"]);
\r
2063 //don't send title to regular StatusNET requests to avoid confusing these apps
\r
2064 if (x($_GET, 'getText')) {
\r
2065 $ret['title'] = $item['title'] ;
\r
2066 if ($_GET["getText"] == "html") {
\r
2067 $ret['text'] = bbcode($item['body'], false, false);
\r
2069 elseif ($_GET["getText"] == "plain") {
\r
2070 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
\r
2071 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
\r
2075 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
\r
2077 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
\r
2078 unset($ret['sender']);
\r
2079 unset($ret['recipient']);
\r
2085 function api_convert_item($item) {
\r
2086 $body = $item['body'];
\r
2087 $attachments = api_get_attachments($body);
\r
2089 // Workaround for ostatus messages where the title is identically to the body
\r
2090 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
\r
2091 $statusbody = trim(html2plain($html, 0));
\r
2093 // handle data: images
\r
2094 $statusbody = api_format_items_embeded_images($item,$statusbody);
\r
2096 $statustitle = trim($item['title']);
\r
2098 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
\r
2099 $statustext = trim($statusbody);
\r
2101 $statustext = trim($statustitle."\n\n".$statusbody);
\r
2103 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
\r
2104 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
\r
2106 $statushtml = trim(bbcode($body, false, false));
\r
2108 $search = array("<br>", "<blockquote>", "</blockquote>",
\r
2109 "<h1>", "</h1>", "<h2>", "</h2>",
\r
2110 "<h3>", "</h3>", "<h4>", "</h4>",
\r
2111 "<h5>", "</h5>", "<h6>", "</h6>");
\r
2112 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
\r
2113 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
\r
2114 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
\r
2115 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
\r
2116 $statushtml = str_replace($search, $replace, $statushtml);
\r
2118 if ($item['title'] != "")
\r
2119 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
\r
2121 $entities = api_get_entitities($statustext, $body);
\r
2124 "text" => $statustext,
\r
2125 "html" => $statushtml,
\r
2126 "attachments" => $attachments,
\r
2127 "entities" => $entities
\r
2131 function api_get_attachments(&$body) {
\r
2134 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
\r
2136 $URLSearchString = "^\[\]";
\r
2137 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
\r
2142 $attachments = array();
\r
2144 foreach ($images[1] AS $image) {
\r
2145 $imagedata = get_photo_info($image);
\r
2148 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
\r
2151 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
\r
2152 foreach ($images[0] AS $orig)
\r
2153 $body = str_replace($orig, "", $body);
\r
2155 return $attachments;
\r
2158 function api_get_entitities(&$text, $bbcode) {
\r
2161 * Links at the first character of the post
\r
2166 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
\r
2168 if ($include_entities != "true") {
\r
2170 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
\r
2172 foreach ($images[1] AS $image) {
\r
2173 $replace = proxy_url($image);
\r
2174 $text = str_replace($image, $replace, $text);
\r
2179 $bbcode = bb_CleanPictureLinks($bbcode);
\r
2181 // Change pure links in text to bbcode uris
\r
2182 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
\r
2184 $entities = array();
\r
2185 $entities["hashtags"] = array();
\r
2186 $entities["symbols"] = array();
\r
2187 $entities["urls"] = array();
\r
2188 $entities["user_mentions"] = array();
\r
2190 $URLSearchString = "^\[\]";
\r
2192 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
\r
2194 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
\r
2195 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2196 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2198 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
\r
2199 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
\r
2200 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2202 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
\r
2203 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
\r
2204 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
\r
2206 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
\r
2208 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
\r
2209 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
\r
2211 $ordered_urls = array();
\r
2212 foreach ($urls[1] AS $id=>$url) {
\r
2213 //$start = strpos($text, $url, $offset);
\r
2214 $start = iconv_strpos($text, $url, 0, "UTF-8");
\r
2215 if (!($start === false))
\r
2216 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
\r
2219 ksort($ordered_urls);
\r
2222 //foreach ($urls[1] AS $id=>$url) {
\r
2223 foreach ($ordered_urls AS $url) {
\r
2224 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
\r
2225 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
\r
2226 $display_url = $url["title"];
\r
2228 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
\r
2229 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
\r
2231 if (strlen($display_url) > 26)
\r
2232 $display_url = substr($display_url, 0, 25)."…";
\r
2235 //$start = strpos($text, $url, $offset);
\r
2236 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
\r
2237 if (!($start === false)) {
\r
2238 $entities["urls"][] = array("url" => $url["url"],
\r
2239 "expanded_url" => $url["url"],
\r
2240 "display_url" => $display_url,
\r
2241 "indices" => array($start, $start+strlen($url["url"])));
\r
2242 $offset = $start + 1;
\r
2246 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
\r
2247 $ordered_images = array();
\r
2248 foreach ($images[1] AS $image) {
\r
2249 //$start = strpos($text, $url, $offset);
\r
2250 $start = iconv_strpos($text, $image, 0, "UTF-8");
\r
2251 if (!($start === false))
\r
2252 $ordered_images[$start] = $image;
\r
2254 //$entities["media"] = array();
\r
2257 foreach ($ordered_images AS $url) {
\r
2258 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
\r
2259 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
\r
2261 if (strlen($display_url) > 26)
\r
2262 $display_url = substr($display_url, 0, 25)."…";
\r
2264 $start = iconv_strpos($text, $url, $offset, "UTF-8");
\r
2265 if (!($start === false)) {
\r
2266 $image = get_photo_info($url);
\r
2268 // If image cache is activated, then use the following sizes:
\r
2269 // thumb (150), small (340), medium (600) and large (1024)
\r
2270 if (!get_config("system", "proxy_disabled")) {
\r
2271 $media_url = proxy_url($url);
\r
2274 $scale = scale_image($image[0], $image[1], 150);
\r
2275 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2277 if (($image[0] > 150) OR ($image[1] > 150)) {
\r
2278 $scale = scale_image($image[0], $image[1], 340);
\r
2279 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2282 $scale = scale_image($image[0], $image[1], 600);
\r
2283 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2285 if (($image[0] > 600) OR ($image[1] > 600)) {
\r
2286 $scale = scale_image($image[0], $image[1], 1024);
\r
2287 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
\r
2290 $media_url = $url;
\r
2291 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
\r
2294 $entities["media"][] = array(
\r
2296 "id_str" => (string)$start+1,
\r
2297 "indices" => array($start, $start+strlen($url)),
\r
2298 "media_url" => normalise_link($media_url),
\r
2299 "media_url_https" => $media_url,
\r
2301 "display_url" => $display_url,
\r
2302 "expanded_url" => $url,
\r
2303 "type" => "photo",
\r
2304 "sizes" => $sizes);
\r
2306 $offset = $start + 1;
\r
2310 return($entities);
\r
2312 function api_format_items_embeded_images(&$item, $text){
\r
2313 $text = preg_replace_callback(
\r
2314 "|data:image/([^;]+)[^=]+=*|m",
\r
2315 function($match) use ($item) {
\r
2316 return App::get_baseurl()."/display/".$item['guid'];
\r
2324 * @brief return <a href='url'>name</a> as array
\r
2326 * @param string $txt
\r
2331 function api_contactlink_to_array($txt) {
\r
2333 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
\r
2334 if ($r && count($match)==3) {
\r
2336 'name' => $match[2],
\r
2337 'url' => $match[1]
\r
2350 * @brief return likes, dislikes and attend status for item
\r
2352 * @param array $item
\r
2354 * likes => int count
\r
2355 * dislikes => int count
\r
2357 function api_format_items_activities(&$item, $type = "json") {
\r
2358 $activities = array(
\r
2359 'like' => array(),
\r
2360 'dislike' => array(),
\r
2361 'attendyes' => array(),
\r
2362 'attendno' => array(),
\r
2363 'attendmaybe' => array()
\r
2366 $items = q('SELECT * FROM item
\r
2367 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
\r
2368 intval($item['uid']),
\r
2369 dbesc($item['uri']));
\r
2371 foreach ($items as $i){
\r
2372 // not used as result should be structured like other user data
\r
2373 //builtin_activity_puller($i, $activities);
\r
2375 // get user data and add it to the array of the activity
\r
2376 $user = api_get_user($a, $i['author-link']);
\r
2377 switch($i['verb']) {
\r
2378 case ACTIVITY_LIKE:
\r
2379 $activities['like'][] = $user;
\r
2381 case ACTIVITY_DISLIKE:
\r
2382 $activities['dislike'][] = $user;
\r
2384 case ACTIVITY_ATTEND:
\r
2385 $activities['attendyes'][] = $user;
\r
2387 case ACTIVITY_ATTENDNO:
\r
2388 $activities['attendno'][] = $user;
\r
2390 case ACTIVITY_ATTENDMAYBE:
\r
2391 $activities['attendmaybe'][] = $user;
\r
2398 if ($type == "xml") {
\r
2399 $xml_activities = array();
\r
2400 foreach ($activities as $k => $v) {
\r
2401 // change xml element from "like" to "friendica:like"
\r
2402 $xml_activities["friendica:".$k] = $v;
\r
2403 // add user data into xml output
\r
2405 foreach ($v as $user)
\r
2406 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
\r
2408 $activities = $xml_activities;
\r
2411 return $activities;
\r
2417 * @brief return data from profiles
\r
2419 * @param array $profile
\r
2422 function api_format_items_profiles(&$profile = null, $type = "json") {
\r
2423 if ($profile != null) {
\r
2424 $profile = array('profile_id' => $profile['id'],
\r
2425 'profile_name' => $profile['profile-name'],
\r
2426 'is_default' => $profile['is-default'] ? true : false,
\r
2427 'hide_friends'=> $profile['hide-friends'] ? true : false,
\r
2428 'profile_photo' => $profile['photo'],
\r
2429 'profile_thumb' => $profile['thumb'],
\r
2430 'publish' => $profile['publish'] ? true : false,
\r
2431 'net_publish' => $profile['net-publish'] ? true : false,
\r
2432 'description' => $profile['pdesc'],
\r
2433 'date_of_birth' => $profile['dob'],
\r
2434 'address' => $profile['address'],
\r
2435 'city' => $profile['locality'],
\r
2436 'region' => $profile['region'],
\r
2437 'postal_code' => $profile['postal-code'],
\r
2438 'country' => $profile['country-name'],
\r
2439 'hometown' => $profile['hometown'],
\r
2440 'gender' => $profile['gender'],
\r
2441 'marital' => $profile['marital'],
\r
2442 'marital_with' => $profile['with'],
\r
2443 'marital_since' => $profile['howlong'],
\r
2444 'sexual' => $profile['sexual'],
\r
2445 'politic' => $profile['politic'],
\r
2446 'religion' => $profile['religion'],
\r
2447 'public_keywords' => $profile['pub_keywords'],
\r
2448 'private_keywords' => $profile['prv_keywords'],
\r
2449 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, true),
\r
2450 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, true),
\r
2451 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, true),
\r
2452 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, true),
\r
2453 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, true),
\r
2454 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, true),
\r
2455 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, true),
\r
2456 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, true),
\r
2457 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, true),
\r
2458 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, true),
\r
2459 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, true),
\r
2460 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, true),
\r
2461 'homepage' => $profile['homepage'],
\r
2468 * @brief format items to be returned by api
\r
2470 * @param array $r array of items
\r
2471 * @param array $user_info
\r
2472 * @param bool $filter_user filter items by $user_info
\r
2474 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
\r
2480 foreach($r as $item) {
\r
2482 localize_item($item);
\r
2483 list($status_user, $owner_user) = api_item_get_user($a,$item);
\r
2485 // Look if the posts are matching if they should be filtered by user id
\r
2486 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
\r
2489 if ($item['thr-parent'] != $item['uri']) {
\r
2490 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
\r
2491 intval(api_user()),
\r
2492 dbesc($item['thr-parent']));
\r
2494 $in_reply_to_status_id = intval($r[0]['id']);
\r
2496 $in_reply_to_status_id = intval($item['parent']);
\r
2498 $in_reply_to_status_id_str = (string) intval($item['parent']);
\r
2500 $in_reply_to_screen_name = NULL;
\r
2501 $in_reply_to_user_id = NULL;
\r
2502 $in_reply_to_user_id_str = NULL;
\r
2504 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
\r
2505 intval(api_user()),
\r
2506 intval($in_reply_to_status_id));
\r
2508 $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
\r
2511 if ($r[0]['nick'] == "")
\r
2512 $r[0]['nick'] = api_get_nick($r[0]["url"]);
\r
2514 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
\r
2515 $in_reply_to_user_id = intval($r[0]['id']);
\r
2516 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
\r
2520 $in_reply_to_screen_name = NULL;
\r
2521 $in_reply_to_user_id = NULL;
\r
2522 $in_reply_to_status_id = NULL;
\r
2523 $in_reply_to_user_id_str = NULL;
\r
2524 $in_reply_to_status_id_str = NULL;
\r
2527 $converted = api_convert_item($item);
\r
2529 if ($type == "xml")
\r
2530 $geo = "georss:point";
\r
2535 'text' => $converted["text"],
\r
2536 'truncated' => False,
\r
2537 'created_at'=> api_date($item['created']),
\r
2538 'in_reply_to_status_id' => $in_reply_to_status_id,
\r
2539 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
\r
2540 'source' => (($item['app']) ? $item['app'] : 'web'),
\r
2541 'id' => intval($item['id']),
\r
2542 'id_str' => (string) intval($item['id']),
\r
2543 'in_reply_to_user_id' => $in_reply_to_user_id,
\r
2544 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
\r
2545 'in_reply_to_screen_name' => $in_reply_to_screen_name,
\r
2547 'favorited' => $item['starred'] ? true : false,
\r
2548 'user' => $status_user ,
\r
2549 'friendica_owner' => $owner_user,
\r
2550 //'entities' => NULL,
\r
2551 'statusnet_html' => $converted["html"],
\r
2552 'statusnet_conversation_id' => $item['parent'],
\r
2553 'friendica_activities' => api_format_items_activities($item, $type),
\r
2556 if (count($converted["attachments"]) > 0)
\r
2557 $status["attachments"] = $converted["attachments"];
\r
2559 if (count($converted["entities"]) > 0)
\r
2560 $status["entities"] = $converted["entities"];
\r
2562 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
\r
2563 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
\r
2564 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
\r
2565 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
\r
2568 // Retweets are only valid for top postings
\r
2569 // It doesn't work reliable with the link if its a feed
\r
2570 #$IsRetweet = ($item['owner-link'] != $item['author-link']);
\r
2572 # $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
\r
2575 if ($item["id"] == $item["parent"]) {
\r
2576 $retweeted_item = api_share_as_retweet($item);
\r
2577 if ($retweeted_item !== false) {
\r
2578 $retweeted_status = $status;
\r
2580 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
\r
2581 } catch( BadRequestException $e ) {
\r
2582 // user not found. should be found?
\r
2583 /// @todo check if the user should be always found
\r
2584 $retweeted_status["user"] = array();
\r
2587 $rt_converted = api_convert_item($retweeted_item);
\r
2589 $retweeted_status['text'] = $rt_converted["text"];
\r
2590 $retweeted_status['statusnet_html'] = $rt_converted["html"];
\r
2591 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
\r
2592 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
\r
2593 $status['retweeted_status'] = $retweeted_status;
\r
2597 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
2598 unset($status["user"]["uid"]);
\r
2599 unset($status["user"]["self"]);
\r
2601 if ($item["coord"] != "") {
\r
2602 $coords = explode(' ',$item["coord"]);
\r
2603 if (count($coords) == 2) {
\r
2604 if ($type == "json")
\r
2605 $status["geo"] = array('type' => 'Point',
\r
2606 'coordinates' => array((float) $coords[0],
\r
2607 (float) $coords[1]));
\r
2608 else // Not sure if this is the official format - if someone founds a documentation we can check
\r
2609 $status["georss:point"] = $item["coord"];
\r
2618 function api_account_rate_limit_status($type) {
\r
2620 if ($type == "xml")
\r
2622 'remaining-hits' => (string) 150,
\r
2623 '@attributes' => array("type" => "integer"),
\r
2624 'hourly-limit' => (string) 150,
\r
2625 '@attributes2' => array("type" => "integer"),
\r
2626 'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
\r
2627 '@attributes3' => array("type" => "datetime"),
\r
2628 'reset_time_in_seconds' => strtotime('now + 1 hour'),
\r
2629 '@attributes4' => array("type" => "integer"),
\r
2633 'reset_time_in_seconds' => strtotime('now + 1 hour'),
\r
2634 'remaining_hits' => (string) 150,
\r
2635 'hourly_limit' => (string) 150,
\r
2636 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
\r
2639 return api_format_data('hash', $type, array('hash' => $hash));
\r
2641 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
\r
2643 function api_help_test($type) {
\r
2644 if ($type == 'xml')
\r
2649 return api_format_data('ok', $type, array("ok" => $ok));
\r
2651 api_register_func('api/help/test','api_help_test',false);
\r
2653 function api_lists($type) {
\r
2655 return api_format_data('lists', $type, array("lists_list" => $ret));
\r
2657 api_register_func('api/lists','api_lists',true);
\r
2659 function api_lists_list($type) {
\r
2661 return api_format_data('lists', $type, array("lists_list" => $ret));
\r
2663 api_register_func('api/lists/list','api_lists_list',true);
\r
2666 * https://dev.twitter.com/docs/api/1/get/statuses/friends
\r
2667 * This function is deprecated by Twitter
\r
2668 * returns: json, xml
\r
2670 function api_statuses_f($type, $qtype) {
\r
2674 if (api_user()===false) throw new ForbiddenException();
\r
2675 $user_info = api_get_user($a);
\r
2677 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
\r
2678 /* this is to stop Hotot to load friends multiple times
\r
2679 * I'm not sure if I'm missing return something or
\r
2680 * is a bug in hotot. Workaround, meantime
\r
2684 return array('$users' => $ret);*/
\r
2688 if($qtype == 'friends')
\r
2689 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
\r
2690 if($qtype == 'followers')
\r
2691 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
\r
2693 // friends and followers only for self
\r
2694 if ($user_info['self'] == 0)
\r
2695 $sql_extra = " AND false ";
\r
2697 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
\r
2698 intval(api_user())
\r
2702 foreach($r as $cid){
\r
2703 $user = api_get_user($a, $cid['nurl']);
\r
2704 // "uid" and "self" are only needed for some internal stuff, so remove it from here
\r
2705 unset($user["uid"]);
\r
2706 unset($user["self"]);
\r
2712 return array('user' => $ret);
\r
2715 function api_statuses_friends($type){
\r
2716 $data = api_statuses_f($type, "friends");
\r
2717 if ($data===false) return false;
\r
2718 return api_format_data("users", $type, $data);
\r
2720 function api_statuses_followers($type){
\r
2721 $data = api_statuses_f($type, "followers");
\r
2722 if ($data===false) return false;
\r
2723 return api_format_data("users", $type, $data);
\r
2725 api_register_func('api/statuses/friends','api_statuses_friends',true);
\r
2726 api_register_func('api/statuses/followers','api_statuses_followers',true);
\r
2733 function api_statusnet_config($type) {
\r
2737 $name = $a->config['sitename'];
\r
2738 $server = $a->get_hostname();
\r
2739 $logo = App::get_baseurl() . '/images/friendica-64.png';
\r
2740 $email = $a->config['admin_email'];
\r
2741 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
\r
2742 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
\r
2743 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
\r
2744 if($a->config['api_import_size'])
\r
2745 $texlimit = string($a->config['api_import_size']);
\r
2746 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
\r
2747 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
\r
2750 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
\r
2751 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
\r
2752 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
\r
2753 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
\r
2754 'shorturllength' => '30',
\r
2755 'friendica' => array(
\r
2756 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
\r
2757 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
\r
2758 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
\r
2759 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
\r
2764 return api_format_data('config', $type, array('config' => $config));
\r
2767 api_register_func('api/statusnet/config','api_statusnet_config',false);
\r
2769 function api_statusnet_version($type) {
\r
2771 $fake_statusnet_version = "0.9.7";
\r
2773 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
\r
2775 api_register_func('api/statusnet/version','api_statusnet_version',false);
\r
2778 * @todo use api_format_data() to return data
\r
2780 function api_ff_ids($type,$qtype) {
\r
2784 if(! api_user()) throw new ForbiddenException();
\r
2786 $user_info = api_get_user($a);
\r
2788 if($qtype == 'friends')
\r
2789 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
\r
2790 if($qtype == 'followers')
\r
2791 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
\r
2793 if (!$user_info["self"])
\r
2794 $sql_extra = " AND false ";
\r
2796 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
\r
2798 $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",
\r
2799 intval(api_user())
\r
2802 if(!dbm::is_result($r))
\r
2806 foreach($r as $rr)
\r
2807 if ($stringify_ids)
\r
2808 $ids[] = $rr['id'];
\r
2810 $ids[] = intval($rr['id']);
\r
2812 return api_format_data("ids", $type, array('id' => $ids));
\r
2815 function api_friends_ids($type) {
\r
2816 return api_ff_ids($type,'friends');
\r
2818 function api_followers_ids($type) {
\r
2819 return api_ff_ids($type,'followers');
\r
2821 api_register_func('api/friends/ids','api_friends_ids',true);
\r
2822 api_register_func('api/followers/ids','api_followers_ids',true);
\r
2825 function api_direct_messages_new($type) {
\r
2829 if (api_user()===false) throw new ForbiddenException();
\r
2831 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
\r
2833 $sender = api_get_user($a);
\r
2835 if ($_POST['screen_name']) {
\r
2836 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
\r
2837 intval(api_user()),
\r
2838 dbesc($_POST['screen_name']));
\r
2840 // Selecting the id by priority, friendica first
\r
2841 api_best_nickname($r);
\r
2843 $recipient = api_get_user($a, $r[0]['nurl']);
\r
2845 $recipient = api_get_user($a, $_POST['user_id']);
\r
2849 if (x($_REQUEST,'replyto')) {
\r
2850 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
\r
2851 intval(api_user()),
\r
2852 intval($_REQUEST['replyto']));
\r
2853 $replyto = $r[0]['parent-uri'];
\r
2854 $sub = $r[0]['title'];
\r
2857 if (x($_REQUEST,'title')) {
\r
2858 $sub = $_REQUEST['title'];
\r
2861 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
\r
2865 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
\r
2868 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
\r
2869 $ret = api_format_messages($r[0], $recipient, $sender);
\r
2872 $ret = array("error"=>$id);
\r
2875 $data = Array('direct_message'=>$ret);
\r
2880 $data = api_rss_extra($a, $data, $user_info);
\r
2883 return api_format_data("direct-messages", $type, $data);
\r
2886 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
\r
2890 * @brief delete a direct_message from mail table through api
\r
2892 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
2895 function api_direct_messages_destroy($type){
\r
2898 if (api_user()===false) throw new ForbiddenException();
\r
2901 $user_info = api_get_user($a);
\r
2903 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);
\r
2905 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
\r
2906 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
\r
2907 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
\r
2909 $uid = $user_info['uid'];
\r
2910 // error if no id or parenturi specified (for clients posting parent-uri as well)
\r
2911 if ($verbose == "true") {
\r
2912 if ($id == 0 || $parenturi == "") {
\r
2913 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
\r
2914 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
\r
2918 // BadRequestException if no id specified (for clients using Twitter API)
\r
2919 if ($id == 0) throw new BadRequestException('Message id not specified');
\r
2921 // add parent-uri to sql command if specified by calling app
\r
2922 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
\r
2924 // get data of the specified message id
\r
2925 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
\r
2929 // error message if specified id is not in database
\r
2930 if (!dbm::is_result($r)) {
\r
2931 if ($verbose == "true") {
\r
2932 $answer = array('result' => 'error', 'message' => 'message id not in database');
\r
2933 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
\r
2935 /// @todo BadRequestException ok for Twitter API clients?
\r
2936 throw new BadRequestException('message id not in database');
\r
2940 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
\r
2944 if ($verbose == "true") {
\r
2947 $answer = array('result' => 'ok', 'message' => 'message deleted');
\r
2948 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
\r
2951 $answer = array('result' => 'error', 'message' => 'unknown error');
\r
2952 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
\r
2955 /// @todo return JSON data like Twitter API not yet implemented
\r
2958 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
\r
2961 function api_direct_messages_box($type, $box, $verbose) {
\r
2965 if (api_user()===false) throw new ForbiddenException();
\r
2968 $count = (x($_GET,'count')?$_GET['count']:20);
\r
2969 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
\r
2970 if ($page<0) $page=0;
\r
2972 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
\r
2973 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
\r
2975 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
\r
2976 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
\r
2978 // caller user info
\r
2979 unset($_REQUEST["user_id"]);
\r
2980 unset($_GET["user_id"]);
\r
2982 unset($_REQUEST["screen_name"]);
\r
2983 unset($_GET["screen_name"]);
\r
2985 $user_info = api_get_user($a);
\r
2986 $profile_url = $user_info["url"];
\r
2990 $start = $page*$count;
\r
2993 if ($box=="sentbox") {
\r
2994 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
\r
2996 elseif ($box=="conversation") {
\r
2997 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
\r
2999 elseif ($box=="all") {
\r
3000 $sql_extra = "true";
\r
3002 elseif ($box=="inbox") {
\r
3003 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
\r
3007 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
\r
3009 if ($user_id !="") {
\r
3010 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
\r
3012 elseif($screen_name !=""){
\r
3013 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
\r
3016 $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",
\r
3017 intval(api_user()),
\r
3018 intval($since_id),
\r
3019 intval($start), intval($count)
\r
3021 if ($verbose == "true") {
\r
3022 // stop execution and return error message if no mails available
\r
3024 $answer = array('result' => 'error', 'message' => 'no mails available');
\r
3025 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
\r
3030 foreach($r as $item) {
\r
3031 if ($box == "inbox" || $item['from-url'] != $profile_url){
\r
3032 $recipient = $user_info;
\r
3033 $sender = api_get_user($a,normalise_link($item['contact-url']));
\r
3035 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
\r
3036 $recipient = api_get_user($a,normalise_link($item['contact-url']));
\r
3037 $sender = $user_info;
\r
3040 $ret[]=api_format_messages($item, $recipient, $sender);
\r
3044 $data = array('direct_message' => $ret);
\r
3048 $data = api_rss_extra($a, $data, $user_info);
\r
3051 return api_format_data("direct-messages", $type, $data);
\r
3055 function api_direct_messages_sentbox($type){
\r
3056 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
\r
3057 return api_direct_messages_box($type, "sentbox", $verbose);
\r
3059 function api_direct_messages_inbox($type){
\r
3060 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
\r
3061 return api_direct_messages_box($type, "inbox", $verbose);
\r
3063 function api_direct_messages_all($type){
\r
3064 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
\r
3065 return api_direct_messages_box($type, "all", $verbose);
\r
3067 function api_direct_messages_conversation($type){
\r
3068 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
\r
3069 return api_direct_messages_box($type, "conversation", $verbose);
\r
3071 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
\r
3072 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
\r
3073 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
\r
3074 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
\r
3078 function api_oauth_request_token($type){
\r
3080 $oauth = new FKOAuth1();
\r
3081 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
\r
3082 }catch(Exception $e){
\r
3083 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
\r
3088 function api_oauth_access_token($type){
\r
3090 $oauth = new FKOAuth1();
\r
3091 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
\r
3092 }catch(Exception $e){
\r
3093 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
\r
3099 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
\r
3100 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
\r
3103 function api_fr_photos_list($type) {
\r
3104 if (api_user()===false) throw new ForbiddenException();
\r
3105 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
\r
3106 where uid = %d and album != 'Contact Photos' group by `resource-id`",
\r
3107 intval(local_user())
\r
3109 $typetoext = array(
\r
3110 'image/jpeg' => 'jpg',
\r
3111 'image/png' => 'png',
\r
3112 'image/gif' => 'gif'
\r
3114 $data = array('photo'=>array());
\r
3116 foreach($r as $rr) {
\r
3118 $photo['id'] = $rr['resource-id'];
\r
3119 $photo['album'] = $rr['album'];
\r
3120 $photo['filename'] = $rr['filename'];
\r
3121 $photo['type'] = $rr['type'];
\r
3122 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
\r
3124 if ($type == "xml")
\r
3125 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
\r
3127 $photo['thumb'] = $thumb;
\r
3128 $data['photo'][] = $photo;
\r
3132 return api_format_data("photos", $type, $data);
\r
3135 function api_fr_photo_detail($type) {
\r
3136 if (api_user()===false) throw new ForbiddenException();
\r
3137 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
\r
3139 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
\r
3140 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
\r
3141 $data_sql = ($scale === false ? "" : "data, ");
\r
3143 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
\r
3144 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
\r
3145 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
\r
3147 intval(local_user()),
\r
3148 dbesc($_REQUEST['photo_id']),
\r
3152 $typetoext = array(
\r
3153 'image/jpeg' => 'jpg',
\r
3154 'image/png' => 'png',
\r
3155 'image/gif' => 'gif'
\r
3159 $data = array('photo' => $r[0]);
\r
3160 $data['photo']['id'] = $data['photo']['resource-id'];
\r
3161 if ($scale !== false) {
\r
3162 $data['photo']['data'] = base64_encode($data['photo']['data']);
\r
3164 unset($data['photo']['datasize']); //needed only with scale param
\r
3166 if ($type == "xml") {
\r
3167 $data['photo']['links'] = array();
\r
3168 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
\r
3169 $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
\r
3171 "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
\r
3173 $data['photo']['link'] = array();
\r
3174 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
\r
3175 $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
\r
3178 unset($data['photo']['resource-id']);
\r
3179 unset($data['photo']['minscale']);
\r
3180 unset($data['photo']['maxscale']);
\r
3183 throw new NotFoundException();
\r
3186 return api_format_data("photo_detail", $type, $data);
\r
3189 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
\r
3190 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
\r
3195 * similar as /mod/redir.php
\r
3196 * redirect to 'url' after dfrn auth
\r
3198 * why this when there is mod/redir.php already?
\r
3199 * This use api_user() and api_login()
\r
3202 * c_url: url of remote contact to auth to
\r
3203 * url: string, url to redirect after auth
\r
3205 function api_friendica_remoteauth() {
\r
3206 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
\r
3207 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
\r
3209 if ($url === '' || $c_url === '')
\r
3210 throw new BadRequestException("Wrong parameters.");
\r
3212 $c_url = normalise_link($c_url);
\r
3214 // traditional DFRN
\r
3216 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
\r
3218 intval(api_user())
\r
3221 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
\r
3222 throw new BadRequestException("Unknown contact");
\r
3224 $cid = $r[0]['id'];
\r
3226 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
\r
3228 if($r[0]['duplex'] && $r[0]['issued-id']) {
\r
3229 $orig_id = $r[0]['issued-id'];
\r
3230 $dfrn_id = '1:' . $orig_id;
\r
3232 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
\r
3233 $orig_id = $r[0]['dfrn-id'];
\r
3234 $dfrn_id = '0:' . $orig_id;
\r
3237 $sec = random_string();
\r
3239 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
\r
3240 VALUES( %d, %s, '%s', '%s', %d )",
\r
3241 intval(api_user()),
\r
3245 intval(time() + 45)
\r
3248 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
\r
3249 $dest = (($url) ? '&destination_url=' . $url : '');
\r
3250 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
\r
3251 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
\r
3252 . '&type=profile&sec=' . $sec . $dest . $quiet );
\r
3254 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
\r
3257 * @brief Return the item shared, if the item contains only the [share] tag
\r
3259 * @param array $item Sharer item
\r
3260 * @return array Shared item or false if not a reshare
\r
3262 function api_share_as_retweet(&$item) {
\r
3263 $body = trim($item["body"]);
\r
3265 if (diaspora::is_reshare($body, false)===false) {
\r
3269 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
\r
3270 // Skip if there is no shared message in there
\r
3271 // we already checked this in diaspora::is_reshare()
\r
3272 // but better one more than one less...
\r
3273 if ($body == $attributes)
\r
3277 // build the fake reshared item
\r
3278 $reshared_item = $item;
\r
3281 preg_match("/author='(.*?)'/ism", $attributes, $matches);
\r
3282 if ($matches[1] != "")
\r
3283 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
\r
3285 preg_match('/author="(.*?)"/ism', $attributes, $matches);
\r
3286 if ($matches[1] != "")
\r
3287 $author = $matches[1];
\r
3290 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
\r
3291 if ($matches[1] != "")
\r
3292 $profile = $matches[1];
\r
3294 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
\r
3295 if ($matches[1] != "")
\r
3296 $profile = $matches[1];
\r
3299 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
\r
3300 if ($matches[1] != "")
\r
3301 $avatar = $matches[1];
\r
3303 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
\r
3304 if ($matches[1] != "")
\r
3305 $avatar = $matches[1];
\r
3308 preg_match("/link='(.*?)'/ism", $attributes, $matches);
\r
3309 if ($matches[1] != "")
\r
3310 $link = $matches[1];
\r
3312 preg_match('/link="(.*?)"/ism', $attributes, $matches);
\r
3313 if ($matches[1] != "")
\r
3314 $link = $matches[1];
\r
3317 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
\r
3318 if ($matches[1] != "")
\r
3319 $posted= $matches[1];
\r
3321 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
\r
3322 if ($matches[1] != "")
\r
3323 $posted = $matches[1];
\r
3325 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
\r
3327 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
\r
3332 $reshared_item["body"] = $shared_body;
\r
3333 $reshared_item["author-name"] = $author;
\r
3334 $reshared_item["author-link"] = $profile;
\r
3335 $reshared_item["author-avatar"] = $avatar;
\r
3336 $reshared_item["plink"] = $link;
\r
3337 $reshared_item["created"] = $posted;
\r
3338 $reshared_item["edited"] = $posted;
\r
3340 return $reshared_item;
\r
3344 function api_get_nick($profile) {
\r
3346 - remove trailing junk from profile url
\r
3347 - pump.io check has to check the website
\r
3352 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
\r
3353 dbesc(normalise_link($profile)));
\r
3355 $nick = $r[0]["nick"];
\r
3357 if (!$nick == "") {
\r
3358 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
\r
3359 dbesc(normalise_link($profile)));
\r
3361 $nick = $r[0]["nick"];
\r
3364 if (!$nick == "") {
\r
3365 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
\r
3366 if ($friendica != $profile)
\r
3367 $nick = $friendica;
\r
3370 if (!$nick == "") {
\r
3371 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
\r
3372 if ($diaspora != $profile)
\r
3373 $nick = $diaspora;
\r
3376 if (!$nick == "") {
\r
3377 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
\r
3378 if ($twitter != $profile)
\r
3383 if (!$nick == "") {
\r
3384 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
\r
3385 if ($StatusnetHost != $profile) {
\r
3386 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
\r
3387 if ($StatusnetUser != $profile) {
\r
3388 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
\r
3389 $user = json_decode($UserData);
\r
3391 $nick = $user->screen_name;
\r
3396 // To-Do: look at the page if its really a pumpio site
\r
3397 //if (!$nick == "") {
\r
3398 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
\r
3399 // if ($pumpio != $profile)
\r
3400 // $nick = $pumpio;
\r
3401 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
\r
3411 function api_clean_plain_items($Text) {
\r
3412 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
\r
3414 $Text = bb_CleanPictureLinks($Text);
\r
3415 $URLSearchString = "^\[\]";
\r
3417 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
\r
3419 if ($include_entities == "true") {
\r
3420 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
\r
3423 // Simplify "attachment" element
\r
3424 $Text = api_clean_attachments($Text);
\r
3430 * @brief Removes most sharing information for API text export
\r
3432 * @param string $body The original body
\r
3434 * @return string Cleaned body
\r
3436 function api_clean_attachments($body) {
\r
3437 $data = get_attachment_data($body);
\r
3444 if (isset($data["text"]))
\r
3445 $body = $data["text"];
\r
3447 if (($body == "") AND (isset($data["title"])))
\r
3448 $body = $data["title"];
\r
3450 if (isset($data["url"]))
\r
3451 $body .= "\n".$data["url"];
\r
3453 $body .= $data["after"];
\r
3458 function api_best_nickname(&$contacts) {
\r
3459 $best_contact = array();
\r
3461 if (count($contact) == 0)
\r
3464 foreach ($contacts AS $contact)
\r
3465 if ($contact["network"] == "") {
\r
3466 $contact["network"] = "dfrn";
\r
3467 $best_contact = array($contact);
\r
3470 if (sizeof($best_contact) == 0)
\r
3471 foreach ($contacts AS $contact)
\r
3472 if ($contact["network"] == "dfrn")
\r
3473 $best_contact = array($contact);
\r
3475 if (sizeof($best_contact) == 0)
\r
3476 foreach ($contacts AS $contact)
\r
3477 if ($contact["network"] == "dspr")
\r
3478 $best_contact = array($contact);
\r
3480 if (sizeof($best_contact) == 0)
\r
3481 foreach ($contacts AS $contact)
\r
3482 if ($contact["network"] == "stat")
\r
3483 $best_contact = array($contact);
\r
3485 if (sizeof($best_contact) == 0)
\r
3486 foreach ($contacts AS $contact)
\r
3487 if ($contact["network"] == "pump")
\r
3488 $best_contact = array($contact);
\r
3490 if (sizeof($best_contact) == 0)
\r
3491 foreach ($contacts AS $contact)
\r
3492 if ($contact["network"] == "twit")
\r
3493 $best_contact = array($contact);
\r
3495 if (sizeof($best_contact) == 1)
\r
3496 $contacts = $best_contact;
\r
3498 $contacts = array($contacts[0]);
\r
3501 // return all or a specified group of the user with the containing contacts
\r
3502 function api_friendica_group_show($type) {
\r
3506 if (api_user()===false) throw new ForbiddenException();
\r
3509 $user_info = api_get_user($a);
\r
3510 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
\r
3511 $uid = $user_info['uid'];
\r
3513 // get data of the specified group id or all groups if not specified
\r
3515 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
\r
3518 // error message if specified gid is not in database
\r
3519 if (count($r) == 0)
\r
3520 throw new BadRequestException("gid not available");
\r
3523 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
\r
3526 // loop through all groups and retrieve all members for adding data in the user array
\r
3527 foreach ($r as $rr) {
\r
3528 $members = group_get_members($rr['id']);
\r
3531 if ($type == "xml") {
\r
3532 $user_element = "users";
\r
3534 foreach ($members as $member) {
\r
3535 $user = api_get_user($a, $member['nurl']);
\r
3536 $users[$k++.":user"] = $user;
\r
3539 $user_element = "user";
\r
3540 foreach ($members as $member) {
\r
3541 $user = api_get_user($a, $member['nurl']);
\r
3545 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
\r
3547 return api_format_data("groups", $type, array('group' => $grps));
\r
3549 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
\r
3552 // delete the specified group of the user
\r
3553 function api_friendica_group_delete($type) {
\r
3557 if (api_user()===false) throw new ForbiddenException();
\r
3560 $user_info = api_get_user($a);
\r
3561 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
\r
3562 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
\r
3563 $uid = $user_info['uid'];
\r
3565 // error if no gid specified
\r
3566 if ($gid == 0 || $name == "")
\r
3567 throw new BadRequestException('gid or name not specified');
\r
3569 // get data of the specified group id
\r
3570 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
\r
3573 // error message if specified gid is not in database
\r
3574 if (count($r) == 0)
\r
3575 throw new BadRequestException('gid not available');
\r
3577 // get data of the specified group id and group name
\r
3578 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
\r
3582 // error message if specified gid is not in database
\r
3583 if (count($rname) == 0)
\r
3584 throw new BadRequestException('wrong group name');
\r
3587 $ret = group_rmv($uid, $name);
\r
3590 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
\r
3591 return api_format_data("group_delete", $type, array('result' => $success));
\r
3594 throw new BadRequestException('other API error');
\r
3596 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
\r
3599 // create the specified group with the posted array of contacts
\r
3600 function api_friendica_group_create($type) {
\r
3604 if (api_user()===false) throw new ForbiddenException();
\r
3607 $user_info = api_get_user($a);
\r
3608 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
\r
3609 $uid = $user_info['uid'];
\r
3610 $json = json_decode($_POST['json'], true);
\r
3611 $users = $json['user'];
\r
3613 // error if no name specified
\r
3615 throw new BadRequestException('group name not specified');
\r
3617 // get data of the specified group name
\r
3618 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
\r
3621 // error message if specified group name already exists
\r
3622 if (count($rname) != 0)
\r
3623 throw new BadRequestException('group name already exists');
\r
3625 // check if specified group name is a deleted group
\r
3626 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
\r
3629 // error message if specified group name already exists
\r
3630 if (count($rname) != 0)
\r
3631 $reactivate_group = true;
\r
3634 $ret = group_add($uid, $name);
\r
3636 $gid = group_byname($uid, $name);
\r
3638 throw new BadRequestException('other API error');
\r
3641 $erroraddinguser = false;
\r
3642 $errorusers = array();
\r
3643 foreach ($users as $user) {
\r
3644 $cid = $user['cid'];
\r
3645 // check if user really exists as contact
\r
3646 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
\r
3649 if (count($contact))
\r
3650 $result = group_add_member($uid, $name, $cid, $gid);
\r
3652 $erroraddinguser = true;
\r
3653 $errorusers[] = $cid;
\r
3657 // return success message incl. missing users in array
\r
3658 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
\r
3659 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
\r
3660 return api_format_data("group_create", $type, array('result' => $success));
\r
3662 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
\r
3665 // update the specified group with the posted array of contacts
\r
3666 function api_friendica_group_update($type) {
\r
3670 if (api_user()===false) throw new ForbiddenException();
\r
3673 $user_info = api_get_user($a);
\r
3674 $uid = $user_info['uid'];
\r
3675 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
\r
3676 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
\r
3677 $json = json_decode($_POST['json'], true);
\r
3678 $users = $json['user'];
\r
3680 // error if no name specified
\r
3682 throw new BadRequestException('group name not specified');
\r
3684 // error if no gid specified
\r
3686 throw new BadRequestException('gid not specified');
\r
3689 $members = group_get_members($gid);
\r
3690 foreach ($members as $member) {
\r
3691 $cid = $member['id'];
\r
3692 foreach ($users as $user) {
\r
3693 $found = ($user['cid'] == $cid ? true : false);
\r
3696 $ret = group_rmv_member($uid, $name, $cid);
\r
3701 $erroraddinguser = false;
\r
3702 $errorusers = array();
\r
3703 foreach ($users as $user) {
\r
3704 $cid = $user['cid'];
\r
3705 // check if user really exists as contact
\r
3706 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
\r
3709 if (count($contact))
\r
3710 $result = group_add_member($uid, $name, $cid, $gid);
\r
3712 $erroraddinguser = true;
\r
3713 $errorusers[] = $cid;
\r
3717 // return success message incl. missing users in array
\r
3718 $status = ($erroraddinguser ? "missing user" : "ok");
\r
3719 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
\r
3720 return api_format_data("group_update", $type, array('result' => $success));
\r
3722 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
\r
3725 function api_friendica_activity($type) {
\r
3729 if (api_user()===false) throw new ForbiddenException();
\r
3730 $verb = strtolower($a->argv[3]);
\r
3731 $verb = preg_replace("|\..*$|", "", $verb);
\r
3733 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
\r
3735 $res = do_like($id, $verb);
\r
3738 if ($type == "xml")
\r
3742 return api_format_data('ok', $type, array('ok' => $ok));
\r
3744 throw new BadRequestException('Error adding activity');
\r
3748 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
\r
3749 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
\r
3750 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
\r
3751 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
\r
3752 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
\r
3753 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
\r
3754 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
\r
3755 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
\r
3756 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
\r
3757 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
\r
3760 * @brief Returns notifications
\r
3762 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3765 function api_friendica_notification($type) {
\r
3769 if (api_user()===false) throw new ForbiddenException();
\r
3770 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
\r
3771 $nm = new NotificationsManager();
\r
3773 $notes = $nm->getAll(array(), "+seen -date", 50);
\r
3775 if ($type == "xml") {
\r
3776 $xmlnotes = array();
\r
3777 foreach ($notes AS $note)
\r
3778 $xmlnotes[] = array("@attributes" => $note);
\r
3780 $notes = $xmlnotes;
\r
3783 return api_format_data("notes", $type, array('note' => $notes));
\r
3787 * @brief Set notification as seen and returns associated item (if possible)
\r
3789 * POST request with 'id' param as notification id
\r
3791 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3794 function api_friendica_notification_seen($type){
\r
3798 if (api_user()===false) throw new ForbiddenException();
\r
3799 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
\r
3801 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
\r
3803 $nm = new NotificationsManager();
\r
3804 $note = $nm->getByID($id);
\r
3805 if (is_null($note)) throw new BadRequestException("Invalid argument");
\r
3807 $nm->setSeen($note);
\r
3808 if ($note['otype']=='item') {
\r
3809 // would be really better with an ItemsManager and $im->getByID() :-P
\r
3810 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
\r
3811 intval($note['iid']),
\r
3812 intval(local_user())
\r
3815 // we found the item, return it to the user
\r
3816 $user_info = api_get_user($a);
\r
3817 $ret = api_format_items($r,$user_info, false, $type);
\r
3818 $data = array('status' => $ret);
\r
3819 return api_format_data("status", $type, $data);
\r
3821 // the item can't be found, but we set the note as seen, so we count this as a success
\r
3823 return api_format_data('result', $type, array('result' => "success"));
\r
3826 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
\r
3827 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
\r
3831 * @brief update a direct_message to seen state
\r
3833 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3834 * @return string (success result=ok, error result=error with error message)
\r
3836 function api_friendica_direct_messages_setseen($type){
\r
3838 if (api_user()===false) throw new ForbiddenException();
\r
3841 $user_info = api_get_user($a);
\r
3842 $uid = $user_info['uid'];
\r
3843 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
\r
3845 // return error if id is zero
\r
3847 $answer = array('result' => 'error', 'message' => 'message id not specified');
\r
3848 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
\r
3851 // get data of the specified message id
\r
3852 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
\r
3855 // error message if specified id is not in database
\r
3856 if (!dbm::is_result($r)) {
\r
3857 $answer = array('result' => 'error', 'message' => 'message id not in database');
\r
3858 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
\r
3861 // update seen indicator
\r
3862 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
\r
3868 $answer = array('result' => 'ok', 'message' => 'message set to seen');
\r
3869 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
\r
3871 $answer = array('result' => 'error', 'message' => 'unknown error');
\r
3872 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
\r
3875 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
\r
3881 * @brief search for direct_messages containing a searchstring through api
\r
3883 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3884 * @return string (success: success=true if found and search_result contains found messages
\r
3885 * success=false if nothing was found, search_result='nothing found',
\r
3886 * error: result=error with error message)
\r
3888 function api_friendica_direct_messages_search($type){
\r
3891 if (api_user()===false) throw new ForbiddenException();
\r
3894 $user_info = api_get_user($a);
\r
3895 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");
\r
3896 $uid = $user_info['uid'];
\r
3898 // error if no searchstring specified
\r
3899 if ($searchstring == "") {
\r
3900 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
\r
3901 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
\r
3904 // get data for the specified searchstring
\r
3905 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
\r
3907 dbesc('%'.$searchstring.'%')
\r
3910 $profile_url = $user_info["url"];
\r
3911 // message if nothing was found
\r
3912 if (count($r) == 0)
\r
3913 $success = array('success' => false, 'search_results' => 'nothing found');
\r
3916 foreach($r as $item) {
\r
3917 if ($box == "inbox" || $item['from-url'] != $profile_url){
\r
3918 $recipient = $user_info;
\r
3919 $sender = api_get_user($a,normalise_link($item['contact-url']));
\r
3921 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
\r
3922 $recipient = api_get_user($a,normalise_link($item['contact-url']));
\r
3923 $sender = $user_info;
\r
3925 $ret[]=api_format_messages($item, $recipient, $sender);
\r
3927 $success = array('success' => true, 'search_results' => $ret);
\r
3930 return api_format_data("direct_message_search", $type, array('$result' => $success));
\r
3932 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
\r
3936 * @brief return data of all the profiles a user has to the client
\r
3938 * @param string $profile_id optional parameter to provide the id of the profile to be returned
\r
3939 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
\r
3942 function api_friendica_profile_show($type){
\r
3945 if (api_user()===false) throw new ForbiddenException();
\r
3948 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);
\r
3950 // retrieve general information about profiles for user
\r
3951 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
\r
3952 $directory = get_config('system', 'directory');
\r
3954 // get data of the specified profile id or all profiles of the user if not specified
\r
3955 if ($profileid != 0) {
\r
3956 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
\r
3957 intval(api_user()),
\r
3958 intval($profileid));
\r
3959 // error message if specified gid is not in database
\r
3960 if (count($r) == 0)
\r
3961 throw new BadRequestException("profile_id not available");
\r
3964 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
\r
3965 intval(api_user()));
\r
3967 // loop through all returned profiles and retrieve data and users
\r
3969 foreach ($r as $rr) {
\r
3970 $profile = api_format_items_profiles($rr, $type);
\r
3972 // select all users from contact table, loop and prepare standard return for user data
\r
3974 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
\r
3975 intval(api_user()),
\r
3976 intval($rr['profile_id']));
\r
3978 foreach ($r as $rr) {
\r
3979 $user = api_get_user($a, $rr['nurl']);
\r
3980 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;
\r
3982 $profile['users'] = $users;
\r
3984 // add prepared profile data to array for final return
\r
3985 if ($type == "xml") {
\r
3986 $profiles[$k++.":profile"] = $profile;
\r
3988 $profiles[] = $profile;
\r
3992 // return settings, authenticated user and profiles data
\r
3993 $result = array('multi_profiles' => $multi_profiles ? true : false,
\r
3994 'global_dir' => $directory,
\r
3995 'friendica_owner' => api_get_user($a, intval(api_user())),
\r
3996 'profiles' => $profiles);
\r
3997 return api_format_data("friendica_profiles", $type, array('$result' => $result));
\r
3999 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
\r
4003 [pagename] => api/1.1/statuses/lookup.json
\r
4004 [id] => 605138389168451584
\r
4005 [include_cards] => true
\r
4006 [cards_platform] => Android-12
\r
4007 [include_entities] => true
\r
4008 [include_my_retweet] => 1
\r
4009 [include_rts] => 1
\r
4010 [include_reply_count] => true
\r
4011 [include_descendent_reply_count] => true
\r
4015 Not implemented by now:
\r
4016 statuses/retweets_of_me
\r
4017 friendships/create
\r
4018 friendships/destroy
\r
4019 friendships/exists
\r
4021 account/update_location
\r
4022 account/update_profile_background_image
\r
4023 account/update_profile_image
\r
4026 friendica/profile/update
\r
4027 friendica/profile/create
\r
4028 friendica/profile/delete
\r
4030 Not implemented in status.net:
\r
4031 statuses/retweeted_to_me
\r
4032 statuses/retweeted_by_me
\r
4033 direct_messages/destroy
\r
4034 account/end_session
\r
4035 account/update_delivery_device
\r
4036 notifications/follow
\r
4037 notifications/leave
\r