3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Core\Config;
12 require_once 'include/HTTPExceptions.php';
13 require_once 'include/bbcode.php';
14 require_once 'include/datetime.php';
15 require_once 'include/conversation.php';
16 require_once 'include/oauth.php';
17 require_once 'include/html2plain.php';
18 require_once 'mod/share.php';
19 require_once 'include/Photo.php';
20 require_once 'mod/item.php';
21 require_once 'include/security.php';
22 require_once 'include/contact_selectors.php';
23 require_once 'include/html2bbcode.php';
24 require_once 'mod/wall_upload.php';
25 require_once 'mod/proxy.php';
26 require_once 'include/message.php';
27 require_once 'include/group.php';
28 require_once 'include/like.php';
29 require_once 'include/NotificationsManager.php';
30 require_once 'include/plaintext.php';
31 require_once 'include/xml.php';
33 define('API_METHOD_ANY', '*');
34 define('API_METHOD_GET', 'GET');
35 define('API_METHOD_POST', 'POST,PUT');
36 define('API_METHOD_DELETE', 'POST,DELETE');
41 /// @TODO Fix intending
43 * @brief Auth API user
45 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
46 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
47 * into a page, and visitors will post something without noticing it).
50 if (x($_SESSION, 'allow_api')) {
58 * @brief Get source name from API client
60 * Clients can send 'source' parameter to be show in post metadata
61 * as "sent via <source>".
62 * Some clients doesn't send a source param, we support ones we know
66 * Client source name, default to "api" if unset/unknown
68 function api_source() {
69 if (requestdata('source')) {
70 return requestdata('source');
73 // Support for known clients that doesn't send a source name
74 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
78 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
84 * @brief Format date for API
86 * @param string $str Source date, as UTC
87 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
89 function api_date($str) {
90 // Wed May 23 06:01:13 +0000 2007
91 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
95 * @brief Register API endpoint
97 * Register a function to be the endpont for defined API path.
99 * @param string $path API URL path, relative to App::get_baseurl()
100 * @param string $func Function name to call on path request
101 * @param bool $auth API need logged user
102 * @param string $method HTTP method reqiured to call this endpoint.
104 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
105 * Default to API_METHOD_ANY
107 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
116 // Workaround for hotot
117 $path = str_replace("api/", "api/1.1/", $path);
127 * @brief Login API user
129 * Log in user via OAuth1 or Simple HTTP Auth.
130 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
133 * @hook 'authenticate'
135 * 'username' => username from login form
136 * 'password' => password from login form
137 * 'authenticated' => return status,
138 * 'user_record' => return authenticated user record
140 * array $user logged user record
142 function api_login(App $a) {
145 $oauth = new FKOAuth1();
146 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
147 if (!is_null($token)) {
148 $oauth->loginUser($token->uid);
149 call_hooks('logged_in', $a->user);
152 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
153 var_dump($consumer, $token);
155 } catch (Exception $e) {
159 // workaround for HTTP-auth in CGI mode
160 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
161 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
162 if (strlen($userpass)) {
163 list($name, $password) = explode(':', $userpass);
164 $_SERVER['PHP_AUTH_USER'] = $name;
165 $_SERVER['PHP_AUTH_PW'] = $password;
169 if (!x($_SERVER, 'PHP_AUTH_USER')) {
170 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
171 header('WWW-Authenticate: Basic realm="Friendica"');
172 throw new UnauthorizedException("This API requires login");
175 $user = $_SERVER['PHP_AUTH_USER'];
176 $password = $_SERVER['PHP_AUTH_PW'];
177 $encrypted = hash('whirlpool', trim($password));
179 // allow "user@server" login (but ignore 'server' part)
180 $at = strstr($user, "@", true);
185 // next code from mod/auth.php. needs better solution
189 'username' => trim($user),
190 'password' => trim($password),
191 'authenticated' => 0,
192 'user_record' => null,
196 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
197 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
198 * and later plugins should not interfere with an earlier one that succeeded.
200 call_hooks('authenticate', $addon_auth);
202 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
203 $record = $addon_auth['user_record'];
205 // process normal login request
206 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
207 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
212 if (dbm::is_result($r)) {
217 if ((! $record) || (! count($record))) {
218 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
219 header('WWW-Authenticate: Basic realm="Friendica"');
220 //header('HTTP/1.0 401 Unauthorized');
221 //die('This api requires login');
222 throw new UnauthorizedException("This API requires login");
225 authenticate_success($record);
227 $_SESSION["allow_api"] = true;
229 call_hooks('logged_in', $a->user);
234 * @brief Check HTTP method of called API
236 * API endpoints can define which HTTP method to accept when called.
237 * This function check the current HTTP method agains endpoint
240 * @param string $method Required methods, uppercase, separated by comma
243 function api_check_method($method) {
244 if ($method == "*") {
247 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
251 * @brief Main API entry point
253 * Authenticate user, call registered API function, set HTTP headers
256 * @return string API call result
258 function api_call(App $a) {
259 global $API, $called_api;
262 if (strpos($a->query_string, ".xml") > 0) {
265 if (strpos($a->query_string, ".json") > 0) {
268 if (strpos($a->query_string, ".rss") > 0) {
271 if (strpos($a->query_string, ".atom") > 0) {
276 foreach ($API as $p => $info) {
277 if (strpos($a->query_string, $p) === 0) {
278 if (!api_check_method($info['method'])) {
279 throw new MethodNotAllowedException();
282 $called_api = explode("/", $p);
283 //unset($_SERVER['PHP_AUTH_USER']);
285 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
286 if ($info['auth'] === true && api_user() === false) {
290 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
291 logger('API parameters: ' . print_r($_REQUEST, true));
293 $stamp = microtime(true);
294 $r = call_user_func($info['func'], $type);
295 $duration = (float) (microtime(true) - $stamp);
296 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
298 if (get_config("system", "profiler")) {
299 $duration = microtime(true)-$a->performance["start"];
301 /// @TODO round() really everywhere?
302 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
303 round($a->performance["database"] - $a->performance["database_write"], 3),
304 round($a->performance["database_write"], 3),
305 round($a->performance["network"], 2),
306 round($a->performance["file"], 2),
307 round($duration - ($a->performance["database"] + $a->performance["network"]
308 + $a->performance["file"]), 2),
309 round($duration, 2)),
313 if (get_config("rendertime", "callstack")) {
314 $o = "Database Read:\n";
315 foreach ($a->callstack["database"] AS $func => $time) {
316 $time = round($time, 3);
318 $o .= $func . ": " . $time . "\n";
321 $o .= "\nDatabase Write:\n";
322 foreach ($a->callstack["database_write"] AS $func => $time) {
323 $time = round($time, 3);
325 $o .= $func . ": " . $time . "\n";
329 $o .= "\nNetwork:\n";
330 foreach ($a->callstack["network"] AS $func => $time) {
331 $time = round($time, 3);
333 $o .= $func . ": " . $time . "\n";
336 logger($o, LOGGER_DEBUG);
342 * api function returned false withour throw an
343 * exception. This should not happend, throw a 500
345 throw new InternalServerErrorException();
350 header ("Content-Type: text/xml");
354 header ("Content-Type: application/json");
356 $json = json_encode($rr);
357 if (x($_GET, 'callback')) {
358 $json = $_GET['callback'] . "(" . $json . ")";
363 header ("Content-Type: application/rss+xml");
364 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
367 header ("Content-Type: application/atom+xml");
368 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
374 logger('API call not implemented: ' . $a->query_string);
375 throw new NotImplementedException();
376 } catch (HTTPException $e) {
377 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
378 return api_error($type, $e);
383 * @brief Format API error string
385 * @param string $type Return type (xml, json, rss, as)
386 * @param HTTPException $error Error object
387 * @return strin error message formatted as $type
389 function api_error($type, $e) {
393 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
394 /// @TODO: https://dev.twitter.com/overview/api/response-codes
396 $error = array("error" => $error,
397 "code" => $e->httpcode . " " . $e->httpdesc,
398 "request" => $a->query_string);
400 $ret = api_format_data('status', $type, array('status' => $error));
404 header ("Content-Type: text/xml");
408 header ("Content-Type: application/json");
409 return json_encode($ret);
412 header ("Content-Type: application/rss+xml");
416 header ("Content-Type: application/atom+xml");
423 * @brief Set values for RSS template
426 * @param array $arr Array to be passed to template
427 * @param array $user_info
429 * @todo find proper type-hints
431 function api_rss_extra(App $a, $arr, $user_info) {
432 if (is_null($user_info)) {
433 $user_info = api_get_user($a);
436 $arr['$user'] = $user_info;
437 $arr['$rss'] = array(
438 'alternate' => $user_info['url'],
439 'self' => App::get_baseurl() . "/" . $a->query_string,
440 'base' => App::get_baseurl(),
441 'updated' => api_date(null),
442 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
443 'language' => $user_info['language'],
444 'logo' => App::get_baseurl() . "/images/friendica-32.png",
452 * @brief Unique contact to contact url.
454 * @param int $id Contact id
455 * @return bool|string
456 * Contact url or False if contact id is unknown
458 function api_unique_id_to_url($id) {
459 $r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
462 return (dbm::is_result($r) && $r[0]["url"]);
466 * @brief Get user info array.
469 * @param int|string $contact_id Contact ID or URL
470 * @param string $type Return type (for errors)
472 function api_get_user(App $a, $contact_id = null, $type = "json") {
480 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
482 // Searching for contact URL
483 if (!is_null($contact_id) AND (intval($contact_id) == 0)) {
484 $user = dbesc(normalise_link($contact_id));
486 $extra_query = "AND `contact`.`nurl` = '%s' ";
487 if (api_user() !== false) {
488 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
492 // Searching for contact id with uid = 0
493 if (!is_null($contact_id) AND (intval($contact_id) != 0)) {
494 $user = dbesc(api_unique_id_to_url($contact_id));
497 throw new BadRequestException("User not found.");
501 $extra_query = "AND `contact`.`nurl` = '%s' ";
502 if (api_user() !== false) {
503 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
507 if (is_null($user) && x($_GET, 'user_id')) {
508 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
511 throw new BadRequestException("User not found.");
515 $extra_query = "AND `contact`.`nurl` = '%s' ";
516 if (api_user() !== false) {
517 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
520 if (is_null($user) && x($_GET, 'screen_name')) {
521 $user = dbesc($_GET['screen_name']);
523 $extra_query = "AND `contact`.`nick` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
529 if (is_null($user) AND ($a->argc > (count($called_api) - 1)) AND (count($called_api) > 0)) {
530 $argid = count($called_api);
531 list($user, $null) = explode(".", $a->argv[$argid]);
532 if (is_numeric($user)) {
533 $user = dbesc(api_unique_id_to_url($user));
540 $extra_query = "AND `contact`.`nurl` = '%s' ";
541 if (api_user() !== false) {
542 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
545 $user = dbesc($user);
547 $extra_query = "AND `contact`.`nick` = '%s' ";
548 if (api_user() !== false) {
549 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
554 logger("api_get_user: user ".$user, LOGGER_DEBUG);
557 if (api_user() === false) {
561 $user = $_SESSION['uid'];
562 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
567 logger('api_user: ' . $extra_query . ', user: ' . $user);
570 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
576 // Selecting the id by priority, friendica first
577 api_best_nickname($uinfo);
579 // if the contact wasn't found, fetch it from the contacts with uid = 0
580 if (!dbm::is_result($uinfo)) {
584 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
587 if (dbm::is_result($r)) {
588 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
590 // If no nick where given, extract it from the address
591 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick'])) {
592 $r[0]['nick'] = api_get_nick($r[0]["url"]);
597 'id_str' => (string) $r[0]["id"],
598 'name' => $r[0]["name"],
599 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
600 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
601 'description' => $r[0]["about"],
602 'profile_image_url' => $r[0]["micro"],
603 'profile_image_url_https' => $r[0]["micro"],
604 'url' => $r[0]["url"],
605 'protected' => false,
606 'followers_count' => 0,
607 'friends_count' => 0,
609 'created_at' => api_date($r[0]["created"]),
610 'favourites_count' => 0,
612 'time_zone' => 'UTC',
613 'geo_enabled' => false,
615 'statuses_count' => 0,
617 'contributors_enabled' => false,
618 'is_translator' => false,
619 'is_translation_enabled' => false,
620 'following' => false,
621 'follow_request_sent' => false,
622 'statusnet_blocking' => false,
623 'notifications' => false,
624 'statusnet_profile_url' => $r[0]["url"],
626 'cid' => get_contact($r[0]["url"], api_user(), true),
628 'network' => $r[0]["network"],
633 throw new BadRequestException("User not found.");
637 if ($uinfo[0]['self']) {
639 if ($uinfo[0]['network'] == "") {
640 $uinfo[0]['network'] = NETWORK_DFRN;
643 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
646 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
650 /// @TODO old-lost code? (twice)
651 // Counting is deactivated by now, due to performance issues
652 // count public wall messages
653 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
654 // intval($uinfo[0]['uid'])
656 //$countitms = $r[0]['count'];
659 // Counting is deactivated by now, due to performance issues
660 //$r = q("SELECT count(*) as `count` FROM `item`
661 // WHERE `contact-id` = %d",
662 // intval($uinfo[0]['id'])
664 //$countitms = $r[0]['count'];
668 /// @TODO old-lost code? (twice)
670 // Counting is deactivated by now, due to performance issues
672 $r = q("SELECT count(*) as `count` FROM `contact`
673 WHERE `uid` = %d AND `rel` IN ( %d, %d )
674 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
675 intval($uinfo[0]['uid']),
676 intval(CONTACT_IS_SHARING),
677 intval(CONTACT_IS_FRIEND)
679 $countfriends = $r[0]['count'];
681 $r = q("SELECT count(*) as `count` FROM `contact`
682 WHERE `uid` = %d AND `rel` IN ( %d, %d )
683 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
684 intval($uinfo[0]['uid']),
685 intval(CONTACT_IS_FOLLOWER),
686 intval(CONTACT_IS_FRIEND)
688 $countfollowers = $r[0]['count'];
690 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
691 intval($uinfo[0]['uid'])
693 $starred = $r[0]['count'];
696 if (! $uinfo[0]['self']) {
706 // Add a nick if it isn't present there
707 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
708 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
711 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
713 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
716 'id' => intval($pcontact_id),
717 'id_str' => (string) intval($pcontact_id),
718 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
719 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
720 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
721 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
722 'profile_image_url' => $uinfo[0]['micro'],
723 'profile_image_url_https' => $uinfo[0]['micro'],
724 'url' => $uinfo[0]['url'],
725 'protected' => false,
726 'followers_count' => intval($countfollowers),
727 'friends_count' => intval($countfriends),
729 'created_at' => api_date($uinfo[0]['created']),
730 'favourites_count' => intval($starred),
732 'time_zone' => 'UTC',
733 'geo_enabled' => false,
735 'statuses_count' => intval($countitms),
737 'contributors_enabled' => false,
738 'is_translator' => false,
739 'is_translation_enabled' => false,
740 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
741 'follow_request_sent' => false,
742 'statusnet_blocking' => false,
743 'notifications' => false,
745 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
746 'statusnet_profile_url' => $uinfo[0]['url'],
747 'uid' => intval($uinfo[0]['uid']),
748 'cid' => intval($uinfo[0]['cid']),
749 'self' => $uinfo[0]['self'],
750 'network' => $uinfo[0]['network'],
758 * @brief return api-formatted array for item's author and owner
761 * @param array $item : item from db
762 * @return array(array:author, array:owner)
764 function api_item_get_user(App $a, $item) {
766 $status_user = api_get_user($a, $item["author-link"]);
768 $status_user["protected"] = (($item["allow_cid"] != "") OR
769 ($item["allow_gid"] != "") OR
770 ($item["deny_cid"] != "") OR
771 ($item["deny_gid"] != "") OR
774 if ($item['thr-parent'] == $item['uri']) {
775 $owner_user = api_get_user($a, $item["owner-link"]);
777 $owner_user = $status_user;
780 return (array($status_user, $owner_user));
784 * @brief walks recursively through an array with the possibility to change value and key
786 * @param array $array The array to walk through
787 * @param string $callback The callback function
789 * @return array the transformed array
791 function api_walk_recursive(array &$array, callable $callback) {
793 $new_array = array();
795 foreach ($array as $k => $v) {
797 if ($callback($v, $k)) {
798 $new_array[$k] = api_walk_recursive($v, $callback);
801 if ($callback($v, $k)) {
812 * @brief Callback function to transform the array in an array that can be transformed in a XML file
814 * @param variant $item Array item value
815 * @param string $key Array key
817 * @return boolean Should the array item be deleted?
819 function api_reformat_xml(&$item, &$key) {
820 if (is_bool($item)) {
821 $item = ($item ? "true" : "false");
824 if (substr($key, 0, 10) == "statusnet_") {
825 $key = "statusnet:".substr($key, 10);
826 } elseif (substr($key, 0, 10) == "friendica_") {
827 $key = "friendica:".substr($key, 10);
829 /// @TODO old-lost code?
831 // $key = "default:".$key;
837 * @brief Creates the XML from a JSON style array
839 * @param array $data JSON style array
840 * @param string $root_element Name of the root element
842 * @return string The XML data
844 function api_create_xml($data, $root_element) {
845 $childname = key($data);
846 $data2 = array_pop($data);
849 $namespaces = array("" => "http://api.twitter.com",
850 "statusnet" => "http://status.net/schema/api/1/",
851 "friendica" => "http://friendi.ca/schema/api/1/",
852 "georss" => "http://www.georss.org/georss");
854 /// @todo Auto detection of needed namespaces
855 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
856 $namespaces = array();
859 if (is_array($data2)) {
860 api_walk_recursive($data2, "api_reformat_xml");
867 foreach ($data2 AS $item) {
868 $data4[$i++.":".$childname] = $item;
874 $data3 = array($root_element => $data2);
876 $ret = xml::from_array($data3, $xml, false, $namespaces);
881 * @brief Formats the data according to the data type
883 * @param string $root_element Name of the root element
884 * @param string $type Return type (atom, rss, xml, json)
885 * @param array $data JSON style array
887 * @return (string|object) XML data or JSON data
889 function api_format_data($root_element, $type, $data) {
897 $ret = api_create_xml($data, $root_element);
912 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
913 * returns a 401 status code and an error message if not.
914 * http://developer.twitter.com/doc/get/account/verify_credentials
916 function api_account_verify_credentials($type) {
920 if (api_user() === false) {
921 throw new ForbiddenException();
924 unset($_REQUEST["user_id"]);
925 unset($_GET["user_id"]);
927 unset($_REQUEST["screen_name"]);
928 unset($_GET["screen_name"]);
930 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
932 $user_info = api_get_user($a);
934 // "verified" isn't used here in the standard
935 unset($user_info["verified"]);
937 // - Adding last status
939 $user_info["status"] = api_status_show("raw");
940 if (!count($user_info["status"])) {
941 unset($user_info["status"]);
943 unset($user_info["status"]["user"]);
947 // "uid" and "self" are only needed for some internal stuff, so remove it from here
948 unset($user_info["uid"]);
949 unset($user_info["self"]);
951 return api_format_data("user", $type, array('user' => $user_info));
955 /// @TODO move to top of file or somwhere better
956 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
959 * get data from $_POST or $_GET
961 function requestdata($k) {
971 /*Waitman Gobble Mod*/
972 function api_statuses_mediap($type) {
976 if (api_user() === false) {
977 logger('api_statuses_update: no user');
978 throw new ForbiddenException();
980 $user_info = api_get_user($a);
982 $_REQUEST['type'] = 'wall';
983 $_REQUEST['profile_uid'] = api_user();
984 $_REQUEST['api_source'] = true;
985 $txt = requestdata('status');
986 /// @TODO old-lost code?
987 //$txt = urldecode(requestdata('status'));
989 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
991 $txt = html2bb_video($txt);
992 $config = HTMLPurifier_Config::createDefault();
993 $config->set('Cache.DefinitionImpl', null);
994 $purifier = new HTMLPurifier($config);
995 $txt = $purifier->purify($txt);
997 $txt = html2bbcode($txt);
999 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1001 // tell wall_upload function to return img info instead of echo
1002 $_REQUEST['hush'] = 'yeah';
1003 $bebop = wall_upload_post($a);
1005 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1006 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1009 // this should output the last post (the one we just posted).
1010 return api_status_show($type);
1013 /// @TODO move this to top of file or somewhere better!
1014 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1016 function api_statuses_update($type) {
1020 if (api_user() === false) {
1021 logger('api_statuses_update: no user');
1022 throw new ForbiddenException();
1025 $user_info = api_get_user($a);
1027 // convert $_POST array items to the form we use for web posts.
1029 // logger('api_post: ' . print_r($_POST,true));
1031 if (requestdata('htmlstatus')) {
1032 $txt = requestdata('htmlstatus');
1033 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1034 $txt = html2bb_video($txt);
1036 $config = HTMLPurifier_Config::createDefault();
1037 $config->set('Cache.DefinitionImpl', null);
1039 $purifier = new HTMLPurifier($config);
1040 $txt = $purifier->purify($txt);
1042 $_REQUEST['body'] = html2bbcode($txt);
1046 $_REQUEST['body'] = requestdata('status');
1049 $_REQUEST['title'] = requestdata('title');
1051 $parent = requestdata('in_reply_to_status_id');
1053 // Twidere sends "-1" if it is no reply ...
1054 if ($parent == -1) {
1058 if (ctype_digit($parent)) {
1059 $_REQUEST['parent'] = $parent;
1061 $_REQUEST['parent_uri'] = $parent;
1064 if (requestdata('lat') && requestdata('long')) {
1065 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1067 $_REQUEST['profile_uid'] = api_user();
1070 $_REQUEST['type'] = 'net-comment';
1072 // Check for throttling (maximum posts per day, week and month)
1073 $throttle_day = get_config('system','throttle_limit_day');
1074 if ($throttle_day > 0) {
1075 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1077 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1078 AND `created` > '%s' AND `id` = `parent`",
1079 intval(api_user()), dbesc($datefrom));
1081 if (dbm::is_result($r)) {
1082 $posts_day = $r[0]["posts_day"];
1087 if ($posts_day > $throttle_day) {
1088 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1089 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1090 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1094 $throttle_week = get_config('system','throttle_limit_week');
1095 if ($throttle_week > 0) {
1096 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1098 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1099 AND `created` > '%s' AND `id` = `parent`",
1100 intval(api_user()), dbesc($datefrom));
1102 if (dbm::is_result($r)) {
1103 $posts_week = $r[0]["posts_week"];
1108 if ($posts_week > $throttle_week) {
1109 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1110 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1111 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1115 $throttle_month = get_config('system','throttle_limit_month');
1116 if ($throttle_month > 0) {
1117 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1119 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1120 AND `created` > '%s' AND `id` = `parent`",
1121 intval(api_user()), dbesc($datefrom));
1123 if (dbm::is_result($r)) {
1124 $posts_month = $r[0]["posts_month"];
1129 if ($posts_month > $throttle_month) {
1130 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1131 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1132 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1136 $_REQUEST['type'] = 'wall';
1139 if (x($_FILES, 'media')) {
1140 // upload the image if we have one
1141 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1142 $media = wall_upload_post($a);
1143 if (strlen($media) > 0) {
1144 $_REQUEST['body'] .= "\n\n" . $media;
1148 // To-Do: Multiple IDs
1149 if (requestdata('media_ids')) {
1150 $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",
1151 intval(requestdata('media_ids')), api_user());
1152 if (dbm::is_result($r)) {
1153 $phototypes = Photo::supportedTypes();
1154 $ext = $phototypes[$r[0]['type']];
1155 $_REQUEST['body'] .= "\n\n" . '[url=' . App::get_baseurl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1156 $_REQUEST['body'] .= '[img]' . App::get_baseurl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1160 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1162 $_REQUEST['api_source'] = true;
1164 if (!x($_REQUEST, "source")) {
1165 $_REQUEST["source"] = api_source();
1168 // call out normal post function
1171 // this should output the last post (the one we just posted).
1172 return api_status_show($type);
1175 /// @TODO move to top of file or somwhere better
1176 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1177 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1179 function api_media_upload($type) {
1183 if (api_user() === false) {
1185 throw new ForbiddenException();
1188 $user_info = api_get_user($a);
1190 if (!x($_FILES, 'media')) {
1192 throw new BadRequestException("No media.");
1195 $media = wall_upload_post($a, false);
1198 throw new InternalServerErrorException();
1201 $returndata = array();
1202 $returndata["media_id"] = $media["id"];
1203 $returndata["media_id_string"] = (string)$media["id"];
1204 $returndata["size"] = $media["size"];
1205 $returndata["image"] = array("w" => $media["width"],
1206 "h" => $media["height"],
1207 "image_type" => $media["type"]);
1209 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1211 return array("media" => $returndata);
1214 /// @TODO move to top of file or somwhere better
1215 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1217 function api_status_show($type) {
1221 $user_info = api_get_user($a);
1223 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1225 if ($type == "raw") {
1226 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1231 // get last public wall message
1232 $lastwall = q("SELECT `item`.*
1234 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1235 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1236 AND `item`.`type` != 'activity' $privacy_sql
1237 ORDER BY `item`.`id` DESC
1239 intval($user_info['cid']),
1241 dbesc($user_info['url']),
1242 dbesc(normalise_link($user_info['url'])),
1243 dbesc($user_info['url']),
1244 dbesc(normalise_link($user_info['url']))
1247 if (dbm::is_result($lastwall)) {
1248 $lastwall = $lastwall[0];
1250 $in_reply_to = api_in_reply_to($lastwall);
1252 $converted = api_convert_item($lastwall);
1254 if ($type == "xml") {
1255 $geo = "georss:point";
1260 $status_info = array(
1261 'created_at' => api_date($lastwall['created']),
1262 'id' => intval($lastwall['id']),
1263 'id_str' => (string) $lastwall['id'],
1264 'text' => $converted["text"],
1265 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1266 'truncated' => false,
1267 'in_reply_to_status_id' => $in_reply_to['status_id'],
1268 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1269 'in_reply_to_user_id' => $in_reply_to['user_id'],
1270 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1271 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1272 'user' => $user_info,
1274 'coordinates' => "",
1276 'contributors' => "",
1277 'is_quote_status' => false,
1278 'retweet_count' => 0,
1279 'favorite_count' => 0,
1280 'favorited' => $lastwall['starred'] ? true : false,
1281 'retweeted' => false,
1282 'possibly_sensitive' => false,
1284 'statusnet_html' => $converted["html"],
1285 'statusnet_conversation_id' => $lastwall['parent'],
1288 if (count($converted["attachments"]) > 0) {
1289 $status_info["attachments"] = $converted["attachments"];
1292 if (count($converted["entities"]) > 0) {
1293 $status_info["entities"] = $converted["entities"];
1296 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web')) {
1297 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1298 } elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1299 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1302 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1303 unset($status_info["user"]["uid"]);
1304 unset($status_info["user"]["self"]);
1307 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1309 if ($type == "raw") {
1310 return $status_info;
1313 return api_format_data("statuses", $type, array('status' => $status_info));
1318 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1319 * The author's most recent status will be returned inline.
1320 * http://developer.twitter.com/doc/get/users/show
1322 function api_users_show($type) {
1326 $user_info = api_get_user($a);
1327 $lastwall = q("SELECT `item`.*
1329 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1330 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1331 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1332 AND `type`!='activity'
1333 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1337 dbesc(ACTIVITY_POST),
1338 intval($user_info['cid']),
1339 dbesc($user_info['url']),
1340 dbesc(normalise_link($user_info['url'])),
1341 dbesc($user_info['url']),
1342 dbesc(normalise_link($user_info['url']))
1345 if (dbm::is_result($lastwall)) {
1346 $lastwall = $lastwall[0];
1348 $in_reply_to = api_in_reply_to($lastwall);
1350 $converted = api_convert_item($lastwall);
1352 if ($type == "xml") {
1353 $geo = "georss:point";
1358 $user_info['status'] = array(
1359 'text' => $converted["text"],
1360 'truncated' => false,
1361 'created_at' => api_date($lastwall['created']),
1362 'in_reply_to_status_id' => $in_reply_to['status_id'],
1363 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1364 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1365 'id' => intval($lastwall['contact-id']),
1366 'id_str' => (string) $lastwall['contact-id'],
1367 'in_reply_to_user_id' => $in_reply_to['user_id'],
1368 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1369 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1371 'favorited' => $lastwall['starred'] ? true : false,
1372 'statusnet_html' => $converted["html"],
1373 'statusnet_conversation_id' => $lastwall['parent'],
1376 if (count($converted["attachments"]) > 0) {
1377 $user_info["status"]["attachments"] = $converted["attachments"];
1380 if (count($converted["entities"]) > 0) {
1381 $user_info["status"]["entities"] = $converted["entities"];
1384 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web')) {
1385 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1388 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1389 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1394 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1395 unset($user_info["uid"]);
1396 unset($user_info["self"]);
1398 return api_format_data("user", $type, array('user' => $user_info));
1402 /// @TODO move to top of file or somewhere better
1403 api_register_func('api/users/show','api_users_show');
1405 function api_users_search($type) {
1409 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1411 $userlist = array();
1413 if (x($_GET, 'q')) {
1414 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1416 if (!dbm::is_result($r)) {
1417 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1420 if (dbm::is_result($r)) {
1422 foreach ($r AS $user) {
1423 $user_info = api_get_user($a, $user["id"], "json");
1425 if ($type == "xml") {
1426 $userlist[$k++.":user"] = $user_info;
1428 $userlist[] = $user_info;
1431 $userlist = array("users" => $userlist);
1433 throw new BadRequestException("User not found.");
1436 throw new BadRequestException("User not found.");
1438 return api_format_data("users", $type, $userlist);
1441 /// @TODO move to top of file or somewhere better
1442 api_register_func('api/users/search','api_users_search');
1446 * http://developer.twitter.com/doc/get/statuses/home_timeline
1448 * TODO: Optional parameters
1449 * TODO: Add reply info
1451 function api_statuses_home_timeline($type) {
1455 if (api_user() === false) {
1456 throw new ForbiddenException();
1459 unset($_REQUEST["user_id"]);
1460 unset($_GET["user_id"]);
1462 unset($_REQUEST["screen_name"]);
1463 unset($_GET["screen_name"]);
1465 $user_info = api_get_user($a);
1466 // get last newtork messages
1469 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1470 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1474 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1475 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1476 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1477 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1478 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1480 $start = $page * $count;
1484 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1486 if ($exclude_replies > 0) {
1487 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1489 if ($conversation_id > 0) {
1490 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1493 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1494 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1495 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1496 `contact`.`id` AS `cid`
1498 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1499 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1500 WHERE `item`.`uid` = %d AND `verb` = '%s'
1501 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1504 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1506 dbesc(ACTIVITY_POST),
1508 intval($start), intval($count)
1511 $ret = api_format_items($r, $user_info, false, $type);
1513 // Set all posts from the query above to seen
1515 foreach ($r AS $item) {
1516 $idarray[] = intval($item["id"]);
1519 $idlist = implode(",", $idarray);
1521 if ($idlist != "") {
1522 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1525 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1529 $data = array('status' => $ret);
1533 $data = api_rss_extra($a, $data, $user_info);
1537 return api_format_data("statuses", $type, $data);
1540 /// @TODO move to top of file or somewhere better
1541 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1542 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1544 function api_statuses_public_timeline($type) {
1548 if (api_user() === false) {
1549 throw new ForbiddenException();
1552 $user_info = api_get_user($a);
1553 // get last newtork messages
1556 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1557 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1561 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1562 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1563 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1564 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1565 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1567 $start = $page * $count;
1570 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1572 if ($exclude_replies > 0) {
1573 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1575 if ($conversation_id > 0) {
1576 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1579 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1580 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1581 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1582 `contact`.`id` AS `cid`,
1583 `user`.`nickname`, `user`.`hidewall`
1585 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1586 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1587 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1588 AND NOT `user`.`hidewall`
1589 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1590 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1591 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1592 AND NOT `item`.`private` AND `item`.`wall`
1595 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1596 dbesc(ACTIVITY_POST),
1601 $ret = api_format_items($r, $user_info, false, $type);
1603 $data = array('status' => $ret);
1607 $data = api_rss_extra($a, $data, $user_info);
1611 return api_format_data("statuses", $type, $data);
1614 /// @TODO move to top of file or somewhere better
1615 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1618 * @TODO nothing to say?
1620 function api_statuses_show($type) {
1624 if (api_user() === false) {
1625 throw new ForbiddenException();
1628 $user_info = api_get_user($a);
1631 $id = intval($a->argv[3]);
1634 $id = intval($_REQUEST["id"]);
1639 $id = intval($a->argv[4]);
1642 logger('API: api_statuses_show: ' . $id);
1644 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1647 if ($conversation) {
1648 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1650 $sql_extra .= " AND `item`.`id` = %d";
1653 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1654 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1655 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1656 `contact`.`id` AS `cid`
1658 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1659 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1660 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1661 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1664 dbesc(ACTIVITY_POST),
1668 /// @TODO How about copying this to above methods which don't check $r ?
1669 if (!dbm::is_result($r)) {
1670 throw new BadRequestException("There is no status with this id.");
1673 $ret = api_format_items($r,$user_info, false, $type);
1675 if ($conversation) {
1676 $data = array('status' => $ret);
1677 return api_format_data("statuses", $type, $data);
1679 $data = array('status' => $ret[0]);
1680 return api_format_data("status", $type, $data);
1684 /// @TODO move to top of file or somewhere better
1685 api_register_func('api/statuses/show','api_statuses_show', true);
1688 * @TODO nothing to say?
1690 function api_conversation_show($type) {
1694 if (api_user() === false) {
1695 throw new ForbiddenException();
1698 $user_info = api_get_user($a);
1701 $id = intval($a->argv[3]);
1702 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1703 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1707 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1708 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1710 $start = $page*$count;
1713 $id = intval($_REQUEST["id"]);
1718 $id = intval($a->argv[4]);
1721 logger('API: api_conversation_show: '.$id);
1723 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1724 if (dbm::is_result($r)) {
1725 $id = $r[0]["parent"];
1731 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1734 // Not sure why this query was so complicated. We should keep it here for a while,
1735 // just to make sure that we really don't need it.
1736 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1737 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1739 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1740 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1741 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1742 `contact`.`id` AS `cid`
1744 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1745 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1746 WHERE `item`.`parent` = %d AND `item`.`visible`
1747 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1748 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1749 AND `item`.`id`>%d $sql_extra
1750 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1751 intval($id), intval(api_user()),
1752 dbesc(ACTIVITY_POST),
1754 intval($start), intval($count)
1757 if (!dbm::is_result($r)) {
1758 throw new BadRequestException("There is no status with this id.");
1761 $ret = api_format_items($r, $user_info, false, $type);
1763 $data = array('status' => $ret);
1764 return api_format_data("statuses", $type, $data);
1767 /// @TODO move to top of file or somewhere better
1768 api_register_func('api/conversation/show','api_conversation_show', true);
1769 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1772 * @TODO nothing to say?
1774 function api_statuses_repeat($type) {
1779 if (api_user() === false) {
1780 throw new ForbiddenException();
1783 $user_info = api_get_user($a);
1786 $id = intval($a->argv[3]);
1789 $id = intval($_REQUEST["id"]);
1794 $id = intval($a->argv[4]);
1797 logger('API: api_statuses_repeat: '.$id);
1799 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1800 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1801 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1802 `contact`.`id` AS `cid`
1804 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1805 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1806 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1807 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1808 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1810 AND `item`.`id`=%d",
1814 /// @TODO other style than above functions!
1815 if (dbm::is_result($r) && $r[0]['body'] != "") {
1816 if (strpos($r[0]['body'], "[/share]") !== false) {
1817 $pos = strpos($r[0]['body'], "[share");
1818 $post = substr($r[0]['body'], $pos);
1820 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1822 $post .= $r[0]['body'];
1823 $post .= "[/share]";
1825 $_REQUEST['body'] = $post;
1826 $_REQUEST['profile_uid'] = api_user();
1827 $_REQUEST['type'] = 'wall';
1828 $_REQUEST['api_source'] = true;
1830 if (!x($_REQUEST, "source")) {
1831 $_REQUEST["source"] = api_source();
1836 throw new ForbiddenException();
1839 // this should output the last post (the one we just posted).
1841 return api_status_show($type);
1844 /// @TODO move to top of file or somewhere better
1845 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1848 * @TODO nothing to say?
1850 function api_statuses_destroy($type) {
1854 if (api_user() === false) {
1855 throw new ForbiddenException();
1858 $user_info = api_get_user($a);
1861 $id = intval($a->argv[3]);
1864 $id = intval($_REQUEST["id"]);
1869 $id = intval($a->argv[4]);
1872 logger('API: api_statuses_destroy: '.$id);
1874 $ret = api_statuses_show($type);
1876 drop_item($id, false);
1881 /// @TODO move to top of file or somewhere better
1882 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1885 * @TODO Nothing more than an URL to say?
1886 * http://developer.twitter.com/doc/get/statuses/mentions
1888 function api_statuses_mentions($type) {
1892 if (api_user() === false) {
1893 throw new ForbiddenException();
1896 unset($_REQUEST["user_id"]);
1897 unset($_GET["user_id"]);
1899 unset($_REQUEST["screen_name"]);
1900 unset($_GET["screen_name"]);
1902 $user_info = api_get_user($a);
1903 // get last newtork messages
1907 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1908 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1912 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1913 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1914 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1916 $start = $page * $count;
1918 // Ugly code - should be changed
1919 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1920 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1921 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1922 $myurl = str_replace('www.', '', $myurl);
1923 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1926 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1929 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1930 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1931 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1932 `contact`.`id` AS `cid`
1933 FROM `item` FORCE INDEX (`uid_id`)
1934 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1935 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1936 WHERE `item`.`uid` = %d AND `verb` = '%s'
1937 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1938 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1939 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1942 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1944 dbesc(ACTIVITY_POST),
1945 dbesc(protect_sprintf($myurl)),
1946 dbesc(protect_sprintf($myurl)),
1949 intval($start), intval($count)
1952 $ret = api_format_items($r, $user_info, false, $type);
1954 $data = array('status' => $ret);
1958 $data = api_rss_extra($a, $data, $user_info);
1962 return api_format_data("statuses", $type, $data);
1965 /// @TODO move to top of file or somewhere better
1966 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1967 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1969 function api_statuses_user_timeline($type) {
1973 if (api_user() === false) {
1974 throw new ForbiddenException();
1977 $user_info = api_get_user($a);
1978 // get last network messages
1980 logger("api_statuses_user_timeline: api_user: ". api_user() .
1981 "\nuser_info: ".print_r($user_info, true) .
1982 "\n_REQUEST: ".print_r($_REQUEST, true),
1986 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1987 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1991 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1992 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1993 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1994 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1996 $start = $page * $count;
1999 if ($user_info['self'] == 1) {
2000 $sql_extra .= " AND `item`.`wall` = 1 ";
2003 if ($exclude_replies > 0) {
2004 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2006 if ($conversation_id > 0) {
2007 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2010 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2011 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2012 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2013 `contact`.`id` AS `cid`
2014 FROM `item` FORCE INDEX (`uid_contactid_id`)
2015 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2016 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2017 WHERE `item`.`uid` = %d AND `verb` = '%s'
2018 AND `item`.`contact-id` = %d
2019 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2022 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2024 dbesc(ACTIVITY_POST),
2025 intval($user_info['cid']),
2027 intval($start), intval($count)
2030 $ret = api_format_items($r, $user_info, true, $type);
2032 $data = array('status' => $ret);
2036 $data = api_rss_extra($a, $data, $user_info);
2040 return api_format_data("statuses", $type, $data);
2043 /// @TODO move to top of file or somwhere better
2044 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2047 * Star/unstar an item
2048 * param: id : id of the item
2050 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2052 function api_favorites_create_destroy($type) {
2056 if (api_user() === false) {
2057 throw new ForbiddenException();
2060 // for versioned api.
2061 /// @TODO We need a better global soluton
2062 $action_argv_id = 2;
2063 if ($a->argv[1] == "1.1") {
2064 $action_argv_id = 3;
2067 if ($a->argc <= $action_argv_id) {
2068 throw new BadRequestException("Invalid request.");
2070 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2071 if ($a->argc == $action_argv_id + 2) {
2072 $itemid = intval($a->argv[$action_argv_id + 1]);
2074 /// @TODO use x() to check if _REQUEST contains 'id'
2075 $itemid = intval($_REQUEST['id']);
2078 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2079 $itemid, api_user());
2081 if (!dbm::is_result($item) || count($item) == 0) {
2082 throw new BadRequestException("Invalid item.");
2087 $item[0]['starred'] = 1;
2090 $item[0]['starred'] = 0;
2093 throw new BadRequestException("Invalid action ".$action);
2096 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2097 $item[0]['starred'], $itemid, api_user());
2099 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2100 $item[0]['starred'], $itemid, api_user());
2103 throw new InternalServerErrorException("DB error");
2107 $user_info = api_get_user($a);
2108 $rets = api_format_items($item, $user_info, false, $type);
2111 $data = array('status' => $ret);
2115 $data = api_rss_extra($a, $data, $user_info);
2118 return api_format_data("status", $type, $data);
2121 /// @TODO move to top of file or somwhere better
2122 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2123 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2125 function api_favorites($type) {
2130 if (api_user() === false) {
2131 throw new ForbiddenException();
2134 $called_api = array();
2136 $user_info = api_get_user($a);
2138 // in friendica starred item are private
2139 // return favorites only for self
2140 logger('api_favorites: self:' . $user_info['self']);
2142 if ($user_info['self'] == 0) {
2148 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2149 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2150 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2151 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2156 $start = $page*$count;
2159 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2162 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2163 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2164 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2165 `contact`.`id` AS `cid`
2166 FROM `item`, `contact`
2167 WHERE `item`.`uid` = %d
2168 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2169 AND `item`.`starred` = 1
2170 AND `contact`.`id` = `item`.`contact-id`
2171 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2174 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2177 intval($start), intval($count)
2180 $ret = api_format_items($r,$user_info, false, $type);
2184 $data = array('status' => $ret);
2188 $data = api_rss_extra($a, $data, $user_info);
2191 return api_format_data("statuses", $type, $data);
2194 /// @TODO move to top of file or somwhere better
2195 api_register_func('api/favorites','api_favorites', true);
2197 function api_format_messages($item, $recipient, $sender) {
2198 // standard meta information
2200 'id' => $item['id'],
2201 'sender_id' => $sender['id'] ,
2203 'recipient_id' => $recipient['id'],
2204 'created_at' => api_date($item['created']),
2205 'sender_screen_name' => $sender['screen_name'],
2206 'recipient_screen_name' => $recipient['screen_name'],
2207 'sender' => $sender,
2208 'recipient' => $recipient,
2210 'friendica_seen' => $item['seen'],
2211 'friendica_parent_uri' => $item['parent-uri'],
2214 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2215 unset($ret["sender"]["uid"]);
2216 unset($ret["sender"]["self"]);
2217 unset($ret["recipient"]["uid"]);
2218 unset($ret["recipient"]["self"]);
2220 //don't send title to regular StatusNET requests to avoid confusing these apps
2221 if (x($_GET, 'getText')) {
2222 $ret['title'] = $item['title'] ;
2223 if ($_GET['getText'] == 'html') {
2224 $ret['text'] = bbcode($item['body'], false, false);
2225 } elseif ($_GET['getText'] == 'plain') {
2226 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2227 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2230 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2232 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2233 unset($ret['sender']);
2234 unset($ret['recipient']);
2240 function api_convert_item($item) {
2241 $body = $item['body'];
2242 $attachments = api_get_attachments($body);
2244 // Workaround for ostatus messages where the title is identically to the body
2245 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2246 $statusbody = trim(html2plain($html, 0));
2248 // handle data: images
2249 $statusbody = api_format_items_embeded_images($item,$statusbody);
2251 $statustitle = trim($item['title']);
2253 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false)) {
2254 $statustext = trim($statusbody);
2256 $statustext = trim($statustitle."\n\n".$statusbody);
2259 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000)) {
2260 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2263 $statushtml = trim(bbcode($body, false, false));
2265 $search = array("<br>", "<blockquote>", "</blockquote>",
2266 "<h1>", "</h1>", "<h2>", "</h2>",
2267 "<h3>", "</h3>", "<h4>", "</h4>",
2268 "<h5>", "</h5>", "<h6>", "</h6>");
2269 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2270 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2271 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2272 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2273 $statushtml = str_replace($search, $replace, $statushtml);
2275 if ($item['title'] != "") {
2276 $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
2279 $entities = api_get_entitities($statustext, $body);
2282 "text" => $statustext,
2283 "html" => $statushtml,
2284 "attachments" => $attachments,
2285 "entities" => $entities
2289 function api_get_attachments(&$body) {
2292 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2294 $URLSearchString = "^\[\]";
2295 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2301 $attachments = array();
2303 foreach ($images[1] AS $image) {
2304 $imagedata = get_photo_info($image);
2307 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2311 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2312 foreach ($images[0] AS $orig) {
2313 $body = str_replace($orig, "", $body);
2317 return $attachments;
2320 function api_get_entitities(&$text, $bbcode) {
2323 * Links at the first character of the post
2328 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2330 if ($include_entities != "true") {
2332 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2334 foreach ($images[1] AS $image) {
2335 $replace = proxy_url($image);
2336 $text = str_replace($image, $replace, $text);
2341 $bbcode = bb_CleanPictureLinks($bbcode);
2343 // Change pure links in text to bbcode uris
2344 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2346 $entities = array();
2347 $entities["hashtags"] = array();
2348 $entities["symbols"] = array();
2349 $entities["urls"] = array();
2350 $entities["user_mentions"] = array();
2352 $URLSearchString = "^\[\]";
2354 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2356 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2357 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2358 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2360 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2361 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2362 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2364 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2365 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2366 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2368 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2370 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2371 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2373 $ordered_urls = array();
2374 foreach ($urls[1] AS $id => $url) {
2375 //$start = strpos($text, $url, $offset);
2376 $start = iconv_strpos($text, $url, 0, "UTF-8");
2377 if (!($start === false)) {
2378 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2382 ksort($ordered_urls);
2385 //foreach ($urls[1] AS $id=>$url) {
2386 foreach ($ordered_urls AS $url) {
2387 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2388 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2389 $display_url = $url["title"];
2391 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2392 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2394 if (strlen($display_url) > 26)
2395 $display_url = substr($display_url, 0, 25)."…";
2398 //$start = strpos($text, $url, $offset);
2399 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2400 if (!($start === false)) {
2401 $entities["urls"][] = array("url" => $url["url"],
2402 "expanded_url" => $url["url"],
2403 "display_url" => $display_url,
2404 "indices" => array($start, $start+strlen($url["url"])));
2405 $offset = $start + 1;
2409 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2410 $ordered_images = array();
2411 foreach ($images[1] AS $image) {
2412 //$start = strpos($text, $url, $offset);
2413 $start = iconv_strpos($text, $image, 0, "UTF-8");
2414 if (!($start === false))
2415 $ordered_images[$start] = $image;
2417 //$entities["media"] = array();
2420 foreach ($ordered_images AS $url) {
2421 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2422 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2424 if (strlen($display_url) > 26)
2425 $display_url = substr($display_url, 0, 25)."…";
2427 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2428 if (!($start === false)) {
2429 $image = get_photo_info($url);
2431 // If image cache is activated, then use the following sizes:
2432 // thumb (150), small (340), medium (600) and large (1024)
2433 if (!get_config("system", "proxy_disabled")) {
2434 $media_url = proxy_url($url);
2437 $scale = scale_image($image[0], $image[1], 150);
2438 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2440 if (($image[0] > 150) OR ($image[1] > 150)) {
2441 $scale = scale_image($image[0], $image[1], 340);
2442 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2445 $scale = scale_image($image[0], $image[1], 600);
2446 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2448 if (($image[0] > 600) OR ($image[1] > 600)) {
2449 $scale = scale_image($image[0], $image[1], 1024);
2450 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2454 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2457 $entities["media"][] = array(
2459 "id_str" => (string)$start+1,
2460 "indices" => array($start, $start+strlen($url)),
2461 "media_url" => normalise_link($media_url),
2462 "media_url_https" => $media_url,
2464 "display_url" => $display_url,
2465 "expanded_url" => $url,
2469 $offset = $start + 1;
2475 function api_format_items_embeded_images(&$item, $text) {
2476 $text = preg_replace_callback(
2477 "|data:image/([^;]+)[^=]+=*|m",
2478 function($match) use ($item) {
2479 return App::get_baseurl()."/display/".$item['guid'];
2487 * @brief return <a href='url'>name</a> as array
2489 * @param string $txt
2494 function api_contactlink_to_array($txt) {
2496 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2497 if ($r && count($match)==3) {
2499 'name' => $match[2],
2513 * @brief return likes, dislikes and attend status for item
2515 * @param array $item
2517 * likes => int count
2518 * dislikes => int count
2520 function api_format_items_activities(&$item, $type = "json") {
2524 $activities = array(
2526 'dislike' => array(),
2527 'attendyes' => array(),
2528 'attendno' => array(),
2529 'attendmaybe' => array(),
2532 $items = q('SELECT * FROM item
2533 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2534 intval($item['uid']),
2535 dbesc($item['uri']));
2537 foreach ($items as $i) {
2538 // not used as result should be structured like other user data
2539 //builtin_activity_puller($i, $activities);
2541 // get user data and add it to the array of the activity
2542 $user = api_get_user($a, $i['author-link']);
2543 switch ($i['verb']) {
2545 $activities['like'][] = $user;
2547 case ACTIVITY_DISLIKE:
2548 $activities['dislike'][] = $user;
2550 case ACTIVITY_ATTEND:
2551 $activities['attendyes'][] = $user;
2553 case ACTIVITY_ATTENDNO:
2554 $activities['attendno'][] = $user;
2556 case ACTIVITY_ATTENDMAYBE:
2557 $activities['attendmaybe'][] = $user;
2564 if ($type == "xml") {
2565 $xml_activities = array();
2566 foreach ($activities as $k => $v) {
2567 // change xml element from "like" to "friendica:like"
2568 $xml_activities["friendica:".$k] = $v;
2569 // add user data into xml output
2571 foreach ($v as $user)
2572 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2574 $activities = $xml_activities;
2583 * @brief return data from profiles
2585 * @param array $profile array containing data from db table 'profile'
2586 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2589 function api_format_items_profiles(&$profile = null, $type = "json") {
2590 if ($profile != null) {
2591 $profile = array('profile_id' => $profile['id'],
2592 'profile_name' => $profile['profile-name'],
2593 'is_default' => $profile['is-default'] ? true : false,
2594 'hide_friends'=> $profile['hide-friends'] ? true : false,
2595 'profile_photo' => $profile['photo'],
2596 'profile_thumb' => $profile['thumb'],
2597 'publish' => $profile['publish'] ? true : false,
2598 'net_publish' => $profile['net-publish'] ? true : false,
2599 'description' => $profile['pdesc'],
2600 'date_of_birth' => $profile['dob'],
2601 'address' => $profile['address'],
2602 'city' => $profile['locality'],
2603 'region' => $profile['region'],
2604 'postal_code' => $profile['postal-code'],
2605 'country' => $profile['country-name'],
2606 'hometown' => $profile['hometown'],
2607 'gender' => $profile['gender'],
2608 'marital' => $profile['marital'],
2609 'marital_with' => $profile['with'],
2610 'marital_since' => $profile['howlong'],
2611 'sexual' => $profile['sexual'],
2612 'politic' => $profile['politic'],
2613 'religion' => $profile['religion'],
2614 'public_keywords' => $profile['pub_keywords'],
2615 'private_keywords' => $profile['prv_keywords'],
2616 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2617 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2618 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2619 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2620 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2621 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2622 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2623 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2624 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2625 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2626 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2627 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2628 'homepage' => $profile['homepage'],
2635 * @brief format items to be returned by api
2637 * @param array $r array of items
2638 * @param array $user_info
2639 * @param bool $filter_user filter items by $user_info
2641 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2647 foreach ($r as $item) {
2649 localize_item($item);
2650 list($status_user, $owner_user) = api_item_get_user($a, $item);
2652 // Look if the posts are matching if they should be filtered by user id
2653 if ($filter_user AND ($status_user["id"] != $user_info["id"])) {
2657 $in_reply_to = api_in_reply_to($item);
2659 $converted = api_convert_item($item);
2661 if ($type == "xml") {
2662 $geo = "georss:point";
2668 'text' => $converted["text"],
2669 'truncated' => False,
2670 'created_at'=> api_date($item['created']),
2671 'in_reply_to_status_id' => $in_reply_to['status_id'],
2672 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2673 'source' => (($item['app']) ? $item['app'] : 'web'),
2674 'id' => intval($item['id']),
2675 'id_str' => (string) intval($item['id']),
2676 'in_reply_to_user_id' => $in_reply_to['user_id'],
2677 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2678 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2680 'favorited' => $item['starred'] ? true : false,
2681 'user' => $status_user ,
2682 'friendica_owner' => $owner_user,
2683 //'entities' => NULL,
2684 'statusnet_html' => $converted["html"],
2685 'statusnet_conversation_id' => $item['parent'],
2686 'friendica_activities' => api_format_items_activities($item, $type),
2689 if (count($converted["attachments"]) > 0) {
2690 $status["attachments"] = $converted["attachments"];
2693 if (count($converted["entities"]) > 0) {
2694 $status["entities"] = $converted["entities"];
2697 if (($item['item_network'] != "") AND ($status["source"] == 'web')) {
2698 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2699 } elseif (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2700 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2704 // Retweets are only valid for top postings
2705 // It doesn't work reliable with the link if its a feed
2706 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2708 // $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2711 if ($item["id"] == $item["parent"]) {
2712 $retweeted_item = api_share_as_retweet($item);
2713 if ($retweeted_item !== false) {
2714 $retweeted_status = $status;
2716 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2717 } catch( BadRequestException $e ) {
2718 // user not found. should be found?
2719 /// @todo check if the user should be always found
2720 $retweeted_status["user"] = array();
2723 $rt_converted = api_convert_item($retweeted_item);
2725 $retweeted_status['text'] = $rt_converted["text"];
2726 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2727 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2728 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2729 $status['retweeted_status'] = $retweeted_status;
2733 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2734 unset($status["user"]["uid"]);
2735 unset($status["user"]["self"]);
2737 if ($item["coord"] != "") {
2738 $coords = explode(' ',$item["coord"]);
2739 if (count($coords) == 2) {
2740 if ($type == "json")
2741 $status["geo"] = array('type' => 'Point',
2742 'coordinates' => array((float) $coords[0],
2743 (float) $coords[1]));
2744 else // Not sure if this is the official format - if someone founds a documentation we can check
2745 $status["georss:point"] = $item["coord"];
2753 function api_account_rate_limit_status($type) {
2755 if ($type == "xml") {
2757 'remaining-hits' => '150',
2758 '@attributes' => array("type" => "integer"),
2759 'hourly-limit' => '150',
2760 '@attributes2' => array("type" => "integer"),
2761 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2762 '@attributes3' => array("type" => "datetime"),
2763 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2764 '@attributes4' => array("type" => "integer"),
2768 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2769 'remaining_hits' => '150',
2770 'hourly_limit' => '150',
2771 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2775 return api_format_data('hash', $type, array('hash' => $hash));
2778 /// @TODO move to top of file or somwhere better
2779 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2781 function api_help_test($type) {
2782 if ($type == 'xml') {
2788 return api_format_data('ok', $type, array("ok" => $ok));
2791 /// @TODO move to top of file or somwhere better
2792 api_register_func('api/help/test','api_help_test', false);
2794 function api_lists($type) {
2796 /// @TODO $ret is not filled here?
2797 return api_format_data('lists', $type, array("lists_list" => $ret));
2800 /// @TODO move to top of file or somwhere better
2801 api_register_func('api/lists','api_lists',true);
2803 function api_lists_list($type) {
2805 /// @TODO $ret is not filled here?
2806 return api_format_data('lists', $type, array("lists_list" => $ret));
2809 /// @TODO move to top of file or somwhere better
2810 api_register_func('api/lists/list','api_lists_list',true);
2813 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2814 * This function is deprecated by Twitter
2815 * returns: json, xml
2817 function api_statuses_f($type, $qtype) {
2821 if (api_user() === false) {
2822 throw new ForbiddenException();
2825 $user_info = api_get_user($a);
2827 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2828 /* this is to stop Hotot to load friends multiple times
2829 * I'm not sure if I'm missing return something or
2830 * is a bug in hotot. Workaround, meantime
2834 return array('$users' => $ret);*/
2838 if ($qtype == 'friends') {
2839 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2841 if ($qtype == 'followers') {
2842 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2845 // friends and followers only for self
2846 if ($user_info['self'] == 0) {
2847 $sql_extra = " AND false ";
2850 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2855 foreach ($r as $cid) {
2856 $user = api_get_user($a, $cid['nurl']);
2857 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2858 unset($user["uid"]);
2859 unset($user["self"]);
2866 return array('user' => $ret);
2870 function api_statuses_friends($type) {
2871 $data = api_statuses_f($type, "friends");
2872 if ($data === false) {
2875 return api_format_data("users", $type, $data);
2878 function api_statuses_followers($type) {
2879 $data = api_statuses_f($type, "followers");
2880 if ($data === false) {
2883 return api_format_data("users", $type, $data);
2886 /// @TODO move to top of file or somewhere better
2887 api_register_func('api/statuses/friends','api_statuses_friends',true);
2888 api_register_func('api/statuses/followers','api_statuses_followers',true);
2890 function api_statusnet_config($type) {
2894 $name = $a->config['sitename'];
2895 $server = $a->get_hostname();
2896 $logo = App::get_baseurl() . '/images/friendica-64.png';
2897 $email = $a->config['admin_email'];
2898 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2899 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2900 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2901 if ($a->config['api_import_size']) {
2902 $texlimit = string($a->config['api_import_size']);
2904 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2905 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2908 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2909 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2910 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2911 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2912 'shorturllength' => '30',
2913 'friendica' => array(
2914 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2915 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2916 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2917 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2922 return api_format_data('config', $type, array('config' => $config));
2926 /// @TODO move to top of file or somewhere better
2927 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2928 api_register_func('api/statusnet/config','api_statusnet_config', false);
2930 function api_statusnet_version($type) {
2932 $fake_statusnet_version = "0.9.7";
2934 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2937 /// @TODO move to top of file or somewhere better
2938 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2939 api_register_func('api/statusnet/version','api_statusnet_version', false);
2942 * @todo use api_format_data() to return data
2944 function api_ff_ids($type,$qtype) {
2949 throw new ForbiddenException();
2952 $user_info = api_get_user($a);
2954 if ($qtype == 'friends') {
2955 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2957 if ($qtype == 'followers') {
2958 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2961 if (!$user_info["self"]) {
2962 $sql_extra = " AND false ";
2965 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
2967 $r = q("SELECT `pcontact`.`id` FROM `contact`
2968 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2969 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2973 if (!dbm::is_result($r)) {
2978 foreach ($r as $rr) {
2979 if ($stringify_ids) {
2982 $ids[] = intval($rr['id']);
2986 return api_format_data("ids", $type, array('id' => $ids));
2989 function api_friends_ids($type) {
2990 return api_ff_ids($type,'friends');
2993 function api_followers_ids($type) {
2994 return api_ff_ids($type,'followers');
2997 /// @TODO move to top of file or somewhere better
2998 api_register_func('api/friends/ids','api_friends_ids',true);
2999 api_register_func('api/followers/ids','api_followers_ids',true);
3001 function api_direct_messages_new($type) {
3005 if (api_user() === false) throw new ForbiddenException();
3007 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
3009 $sender = api_get_user($a);
3011 if ($_POST['screen_name']) {
3012 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3014 dbesc($_POST['screen_name']));
3016 // Selecting the id by priority, friendica first
3017 api_best_nickname($r);
3019 $recipient = api_get_user($a, $r[0]['nurl']);
3021 $recipient = api_get_user($a, $_POST['user_id']);
3025 if (x($_REQUEST, 'replyto')) {
3026 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3028 intval($_REQUEST['replyto']));
3029 $replyto = $r[0]['parent-uri'];
3030 $sub = $r[0]['title'];
3032 if (x($_REQUEST, 'title')) {
3033 $sub = $_REQUEST['title'];
3035 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3039 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3042 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3043 $ret = api_format_messages($r[0], $recipient, $sender);
3045 $ret = array("error"=>$id);
3048 $data = array('direct_message'=>$ret);
3053 $data = api_rss_extra($a, $data, $user_info);
3056 return api_format_data("direct-messages", $type, $data);
3060 /// @TODO move to top of file or somewhere better
3061 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3064 * @brief delete a direct_message from mail table through api
3066 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3069 function api_direct_messages_destroy($type) {
3072 if (api_user() === false) {
3073 throw new ForbiddenException();
3077 $user_info = api_get_user($a);
3079 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3081 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3082 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3083 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3085 $uid = $user_info['uid'];
3086 // error if no id or parenturi specified (for clients posting parent-uri as well)
3087 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3088 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3089 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3092 // BadRequestException if no id specified (for clients using Twitter API)
3094 throw new BadRequestException('Message id not specified');
3097 // add parent-uri to sql command if specified by calling app
3098 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3100 // get data of the specified message id
3101 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3105 // error message if specified id is not in database
3106 if (!dbm::is_result($r)) {
3107 if ($verbose == "true") {
3108 $answer = array('result' => 'error', 'message' => 'message id not in database');
3109 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3111 /// @todo BadRequestException ok for Twitter API clients?
3112 throw new BadRequestException('message id not in database');
3116 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3120 if ($verbose == "true") {
3123 $answer = array('result' => 'ok', 'message' => 'message deleted');
3124 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3126 $answer = array('result' => 'error', 'message' => 'unknown error');
3127 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3130 /// @todo return JSON data like Twitter API not yet implemented
3134 /// @TODO move to top of file or somewhere better
3135 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3137 function api_direct_messages_box($type, $box, $verbose) {
3141 if (api_user() === false) {
3142 throw new ForbiddenException();
3146 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3147 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3152 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3153 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3155 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3156 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3159 unset($_REQUEST["user_id"]);
3160 unset($_GET["user_id"]);
3162 unset($_REQUEST["screen_name"]);
3163 unset($_GET["screen_name"]);
3165 $user_info = api_get_user($a);
3166 $profile_url = $user_info["url"];
3169 $start = $page * $count;
3172 if ($box=="sentbox") {
3173 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3174 } elseif ($box == "conversation") {
3175 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3176 } elseif ($box == "all") {
3177 $sql_extra = "true";
3178 } elseif ($box == "inbox") {
3179 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3183 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3186 if ($user_id != "") {
3187 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3188 } elseif ($screen_name !="") {
3189 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3192 $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",
3195 intval($start), intval($count)
3197 if ($verbose == "true" && !dbm::is_result($r)) {
3198 $answer = array('result' => 'error', 'message' => 'no mails available');
3199 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3203 foreach ($r as $item) {
3204 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3205 $recipient = $user_info;
3206 $sender = api_get_user($a,normalise_link($item['contact-url']));
3207 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3208 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3209 $sender = $user_info;
3212 $ret[] = api_format_messages($item, $recipient, $sender);
3216 $data = array('direct_message' => $ret);
3220 $data = api_rss_extra($a, $data, $user_info);
3223 return api_format_data("direct-messages", $type, $data);
3227 function api_direct_messages_sentbox($type) {
3228 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3229 return api_direct_messages_box($type, "sentbox", $verbose);
3232 function api_direct_messages_inbox($type) {
3233 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3234 return api_direct_messages_box($type, "inbox", $verbose);
3237 function api_direct_messages_all($type) {
3238 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3239 return api_direct_messages_box($type, "all", $verbose);
3242 function api_direct_messages_conversation($type) {
3243 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3244 return api_direct_messages_box($type, "conversation", $verbose);
3247 /// @TODO move to top of file or somewhere better
3248 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3249 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3250 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3251 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3253 function api_oauth_request_token($type) {
3255 $oauth = new FKOAuth1();
3256 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3257 } catch (Exception $e) {
3258 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3265 function api_oauth_access_token($type) {
3267 $oauth = new FKOAuth1();
3268 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3269 } catch (Exception $e) {
3270 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3276 /// @TODO move to top of file or somewhere better
3277 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3278 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3280 function api_fr_photos_list($type) {
3281 if (api_user() === false) {
3282 throw new ForbiddenException();
3285 $r = q("SELECT `resource-id`, MAX(`scale`) AS `scale`, `album`, `filename`, `type`
3287 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
3288 intval(local_user())
3291 'image/jpeg' => 'jpg',
3292 'image/png' => 'png',
3293 'image/gif' => 'gif'
3295 $data = array('photo' => array());
3296 if (dbm::is_result($r)) {
3297 foreach ($r as $rr) {
3299 $photo['id'] = $rr['resource-id'];
3300 $photo['album'] = $rr['album'];
3301 $photo['filename'] = $rr['filename'];
3302 $photo['type'] = $rr['type'];
3303 $thumb = App::get_baseurl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3305 if ($type == "xml") {
3306 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3308 $photo['thumb'] = $thumb;
3309 $data['photo'][] = $photo;
3313 return api_format_data("photos", $type, $data);
3316 function api_fr_photo_detail($type) {
3317 if (api_user() === false) {
3318 throw new ForbiddenException();
3319 } elseif (!x($_REQUEST, 'photo_id')) {
3320 throw new BadRequestException("No photo id.");
3323 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3324 $scale_sql = ($scale === false ? "" : sprintf("AND `scale`=%d",intval($scale)));
3325 $data_sql = ($scale === false ? "" : "ANY_VALUE(`data`) AS data`,");
3327 $r = q("SELECT %s ANY_VALUE(`resource-id`) AS `resource-id`, ANY_VALUE(`created`) AS `created`,
3328 ANY_VALUE(`edited`) AS `edited`, ANY_VALUE(`title`) AS `title`, ANY_VALUE(`desc`) AS `desc`,
3329 ANY_VALUE(`album`) AS `album`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
3330 ANY_VALUE(`height`) AS `height`, ANY_VALUE(`width`) AS `width`, ANY_VALUE(`datasize`) AS `datasize`,
3331 ANY_VALUE(`profile`) AS `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
3332 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s",
3334 intval(local_user()),
3335 dbesc($_REQUEST['photo_id']),
3340 'image/jpeg' => 'jpg',
3341 'image/png' => 'png',
3342 'image/gif' => 'gif'
3345 if (dbm::is_result($r)) {
3346 $data = array('photo' => $r[0]);
3347 $data['photo']['id'] = $data['photo']['resource-id'];
3348 if ($scale !== false) {
3349 $data['photo']['data'] = base64_encode($data['photo']['data']);
3351 unset($data['photo']['datasize']); //needed only with scale param
3353 if ($type == "xml") {
3354 $data['photo']['links'] = array();
3355 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3356 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
3358 "href" => App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
3361 $data['photo']['link'] = array();
3362 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3363 $data['photo']['link'][$k] = App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3366 unset($data['photo']['resource-id']);
3367 unset($data['photo']['minscale']);
3368 unset($data['photo']['maxscale']);
3371 throw new NotFoundException();
3374 return api_format_data("photo_detail", $type, $data);
3377 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3378 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3383 * similar as /mod/redir.php
3384 * redirect to 'url' after dfrn auth
3386 * why this when there is mod/redir.php already?
3387 * This use api_user() and api_login()
3390 * c_url: url of remote contact to auth to
3391 * url: string, url to redirect after auth
3393 function api_friendica_remoteauth() {
3394 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
3395 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
3397 if ($url === '' || $c_url === '') {
3398 throw new BadRequestException("Wrong parameters.");
3401 $c_url = normalise_link($c_url);
3405 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3410 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
3411 throw new BadRequestException("Unknown contact");
3416 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3418 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3419 $orig_id = $r[0]['issued-id'];
3420 $dfrn_id = '1:' . $orig_id;
3422 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3423 $orig_id = $r[0]['dfrn-id'];
3424 $dfrn_id = '0:' . $orig_id;
3427 $sec = random_string();
3429 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3430 VALUES( %d, %s, '%s', '%s', %d )",
3438 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3439 $dest = (($url) ? '&destination_url=' . $url : '');
3440 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3441 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3442 . '&type=profile&sec=' . $sec . $dest . $quiet );
3444 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3447 * @brief Return the item shared, if the item contains only the [share] tag
3449 * @param array $item Sharer item
3450 * @return array Shared item or false if not a reshare
3452 function api_share_as_retweet(&$item) {
3453 $body = trim($item["body"]);
3455 if (Diaspora::is_reshare($body, false)===false) {
3459 /// @TODO "$1" should maybe mean '$1' ?
3460 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3462 * Skip if there is no shared message in there
3463 * we already checked this in diaspora::is_reshare()
3464 * but better one more than one less...
3466 if ($body == $attributes) {
3471 // build the fake reshared item
3472 $reshared_item = $item;
3475 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3476 if ($matches[1] != "") {
3477 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
3480 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3481 if ($matches[1] != "") {
3482 $author = $matches[1];
3486 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3487 if ($matches[1] != "") {
3488 $profile = $matches[1];
3491 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3492 if ($matches[1] != "") {
3493 $profile = $matches[1];
3497 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3498 if ($matches[1] != "") {
3499 $avatar = $matches[1];
3502 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3503 if ($matches[1] != "") {
3504 $avatar = $matches[1];
3508 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3509 if ($matches[1] != "") {
3510 $link = $matches[1];
3513 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3514 if ($matches[1] != "") {
3515 $link = $matches[1];
3519 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3520 if ($matches[1] != "")
3521 $posted = $matches[1];
3523 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3524 if ($matches[1] != "") {
3525 $posted = $matches[1];
3528 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3530 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
3534 $reshared_item["body"] = $shared_body;
3535 $reshared_item["author-name"] = $author;
3536 $reshared_item["author-link"] = $profile;
3537 $reshared_item["author-avatar"] = $avatar;
3538 $reshared_item["plink"] = $link;
3539 $reshared_item["created"] = $posted;
3540 $reshared_item["edited"] = $posted;
3542 return $reshared_item;
3546 function api_get_nick($profile) {
3548 - remove trailing junk from profile url
3549 - pump.io check has to check the website
3554 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3555 dbesc(normalise_link($profile)));
3557 if (dbm::is_result($r)) {
3558 $nick = $r[0]["nick"];
3562 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3563 dbesc(normalise_link($profile)));
3565 if (dbm::is_result($r)) {
3566 $nick = $r[0]["nick"];
3571 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3572 if ($friendica != $profile) {
3578 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3579 if ($diaspora != $profile) {
3585 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3586 if ($twitter != $profile) {
3593 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3594 if ($StatusnetHost != $profile) {
3595 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3596 if ($StatusnetUser != $profile) {
3597 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3598 $user = json_decode($UserData);
3600 $nick = $user->screen_name;
3606 // To-Do: look at the page if its really a pumpio site
3607 //if (!$nick == "") {
3608 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3609 // if ($pumpio != $profile)
3611 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3622 function api_in_reply_to($item) {
3623 $in_reply_to = array();
3625 $in_reply_to['status_id'] = NULL;
3626 $in_reply_to['user_id'] = NULL;
3627 $in_reply_to['status_id_str'] = NULL;
3628 $in_reply_to['user_id_str'] = NULL;
3629 $in_reply_to['screen_name'] = NULL;
3631 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
3632 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
3633 intval($item['uid']),
3634 dbesc($item['thr-parent']));
3636 if (dbm::is_result($r)) {
3637 $in_reply_to['status_id'] = intval($r[0]['id']);
3639 $in_reply_to['status_id'] = intval($item['parent']);
3642 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3644 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
3645 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
3646 WHERE `item`.`id` = %d LIMIT 1",
3647 intval($in_reply_to['status_id'])
3650 if (dbm::is_result($r)) {
3651 if ($r[0]['nick'] == "") {
3652 $r[0]['nick'] = api_get_nick($r[0]["url"]);
3655 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
3656 $in_reply_to['user_id'] = intval($r[0]['id']);
3657 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
3660 // There seems to be situation, where both fields are identical:
3661 // https://github.com/friendica/friendica/issues/1010
3662 // This is a bugfix for that.
3663 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3664 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
3665 $in_reply_to['status_id'] = NULL;
3666 $in_reply_to['user_id'] = NULL;
3667 $in_reply_to['status_id_str'] = NULL;
3668 $in_reply_to['user_id_str'] = NULL;
3669 $in_reply_to['screen_name'] = NULL;
3673 return $in_reply_to;
3676 function api_clean_plain_items($Text) {
3677 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
3679 $Text = bb_CleanPictureLinks($Text);
3680 $URLSearchString = "^\[\]";
3682 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3684 if ($include_entities == "true") {
3685 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3688 // Simplify "attachment" element
3689 $Text = api_clean_attachments($Text);
3695 * @brief Removes most sharing information for API text export
3697 * @param string $body The original body
3699 * @return string Cleaned body
3701 function api_clean_attachments($body) {
3702 $data = get_attachment_data($body);
3709 if (isset($data["text"]))
3710 $body = $data["text"];
3712 if (($body == "") AND (isset($data["title"])))
3713 $body = $data["title"];
3715 if (isset($data["url"]))
3716 $body .= "\n".$data["url"];
3718 $body .= $data["after"];
3723 function api_best_nickname(&$contacts) {
3724 $best_contact = array();
3726 if (count($contact) == 0)
3729 foreach ($contacts AS $contact)
3730 if ($contact["network"] == "") {
3731 $contact["network"] = "dfrn";
3732 $best_contact = array($contact);
3735 if (sizeof($best_contact) == 0)
3736 foreach ($contacts AS $contact)
3737 if ($contact["network"] == "dfrn")
3738 $best_contact = array($contact);
3740 if (sizeof($best_contact) == 0)
3741 foreach ($contacts AS $contact)
3742 if ($contact["network"] == "dspr")
3743 $best_contact = array($contact);
3745 if (sizeof($best_contact) == 0)
3746 foreach ($contacts AS $contact)
3747 if ($contact["network"] == "stat")
3748 $best_contact = array($contact);
3750 if (sizeof($best_contact) == 0)
3751 foreach ($contacts AS $contact)
3752 if ($contact["network"] == "pump")
3753 $best_contact = array($contact);
3755 if (sizeof($best_contact) == 0)
3756 foreach ($contacts AS $contact)
3757 if ($contact["network"] == "twit")
3758 $best_contact = array($contact);
3760 if (sizeof($best_contact) == 1)
3761 $contacts = $best_contact;
3763 $contacts = array($contacts[0]);
3766 // return all or a specified group of the user with the containing contacts
3767 function api_friendica_group_show($type) {
3771 if (api_user() === false) throw new ForbiddenException();
3774 $user_info = api_get_user($a);
3775 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3776 $uid = $user_info['uid'];
3778 // get data of the specified group id or all groups if not specified
3780 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3783 // error message if specified gid is not in database
3784 if (!dbm::is_result($r))
3785 throw new BadRequestException("gid not available");
3788 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3791 // loop through all groups and retrieve all members for adding data in the user array
3792 foreach ($r as $rr) {
3793 $members = group_get_members($rr['id']);
3796 if ($type == "xml") {
3797 $user_element = "users";
3799 foreach ($members as $member) {
3800 $user = api_get_user($a, $member['nurl']);
3801 $users[$k++.":user"] = $user;
3804 $user_element = "user";
3805 foreach ($members as $member) {
3806 $user = api_get_user($a, $member['nurl']);
3810 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3812 return api_format_data("groups", $type, array('group' => $grps));
3814 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3817 // delete the specified group of the user
3818 function api_friendica_group_delete($type) {
3822 if (api_user() === false) throw new ForbiddenException();
3825 $user_info = api_get_user($a);
3826 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3827 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3828 $uid = $user_info['uid'];
3830 // error if no gid specified
3831 if ($gid == 0 || $name == "")
3832 throw new BadRequestException('gid or name not specified');
3834 // get data of the specified group id
3835 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3838 // error message if specified gid is not in database
3839 if (!dbm::is_result($r))
3840 throw new BadRequestException('gid not available');
3842 // get data of the specified group id and group name
3843 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3847 // error message if specified gid is not in database
3848 if (!dbm::is_result($rname))
3849 throw new BadRequestException('wrong group name');
3852 $ret = group_rmv($uid, $name);
3855 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3856 return api_format_data("group_delete", $type, array('result' => $success));
3859 throw new BadRequestException('other API error');
3861 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3864 // create the specified group with the posted array of contacts
3865 function api_friendica_group_create($type) {
3869 if (api_user() === false) throw new ForbiddenException();
3872 $user_info = api_get_user($a);
3873 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3874 $uid = $user_info['uid'];
3875 $json = json_decode($_POST['json'], true);
3876 $users = $json['user'];
3878 // error if no name specified
3880 throw new BadRequestException('group name not specified');
3882 // get data of the specified group name
3883 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3886 // error message if specified group name already exists
3887 if (dbm::is_result($rname))
3888 throw new BadRequestException('group name already exists');
3890 // check if specified group name is a deleted group
3891 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3894 // error message if specified group name already exists
3895 if (dbm::is_result($rname))
3896 $reactivate_group = true;
3899 $ret = group_add($uid, $name);
3901 $gid = group_byname($uid, $name);
3903 throw new BadRequestException('other API error');
3906 $erroraddinguser = false;
3907 $errorusers = array();
3908 foreach ($users as $user) {
3909 $cid = $user['cid'];
3910 // check if user really exists as contact
3911 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3914 if (count($contact))
3915 $result = group_add_member($uid, $name, $cid, $gid);
3917 $erroraddinguser = true;
3918 $errorusers[] = $cid;
3922 // return success message incl. missing users in array
3923 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3924 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3925 return api_format_data("group_create", $type, array('result' => $success));
3927 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3930 // update the specified group with the posted array of contacts
3931 function api_friendica_group_update($type) {
3935 if (api_user() === false) throw new ForbiddenException();
3938 $user_info = api_get_user($a);
3939 $uid = $user_info['uid'];
3940 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3941 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3942 $json = json_decode($_POST['json'], true);
3943 $users = $json['user'];
3945 // error if no name specified
3947 throw new BadRequestException('group name not specified');
3949 // error if no gid specified
3951 throw new BadRequestException('gid not specified');
3954 $members = group_get_members($gid);
3955 foreach ($members as $member) {
3956 $cid = $member['id'];
3957 foreach ($users as $user) {
3958 $found = ($user['cid'] == $cid ? true : false);
3961 $ret = group_rmv_member($uid, $name, $cid);
3966 $erroraddinguser = false;
3967 $errorusers = array();
3968 foreach ($users as $user) {
3969 $cid = $user['cid'];
3970 // check if user really exists as contact
3971 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3974 if (count($contact))
3975 $result = group_add_member($uid, $name, $cid, $gid);
3977 $erroraddinguser = true;
3978 $errorusers[] = $cid;
3982 // return success message incl. missing users in array
3983 $status = ($erroraddinguser ? "missing user" : "ok");
3984 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3985 return api_format_data("group_update", $type, array('result' => $success));
3988 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3990 function api_friendica_activity($type) {
3994 if (api_user() === false) throw new ForbiddenException();
3995 $verb = strtolower($a->argv[3]);
3996 $verb = preg_replace("|\..*$|", "", $verb);
3998 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4000 $res = do_like($id, $verb);
4007 return api_format_data('ok', $type, array('ok' => $ok));
4009 throw new BadRequestException('Error adding activity');
4014 /// @TODO move to top of file or somwhere better
4015 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4016 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4017 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4018 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4019 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4020 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4021 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4022 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4023 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4024 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4027 * @brief Returns notifications
4029 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4032 function api_friendica_notification($type) {
4036 if (api_user() === false) throw new ForbiddenException();
4037 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4038 $nm = new NotificationsManager();
4040 $notes = $nm->getAll(array(), "+seen -date", 50);
4042 if ($type == "xml") {
4043 $xmlnotes = array();
4044 foreach ($notes AS $note)
4045 $xmlnotes[] = array("@attributes" => $note);
4050 return api_format_data("notes", $type, array('note' => $notes));
4054 * @brief Set notification as seen and returns associated item (if possible)
4056 * POST request with 'id' param as notification id
4058 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4061 function api_friendica_notification_seen($type) {
4065 if (api_user() === false) throw new ForbiddenException();
4066 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4068 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4070 $nm = new NotificationsManager();
4071 $note = $nm->getByID($id);
4072 if (is_null($note)) throw new BadRequestException("Invalid argument");
4074 $nm->setSeen($note);
4075 if ($note['otype']=='item') {
4076 // would be really better with an ItemsManager and $im->getByID() :-P
4077 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4078 intval($note['iid']),
4079 intval(local_user())
4082 // we found the item, return it to the user
4083 $user_info = api_get_user($a);
4084 $ret = api_format_items($r,$user_info, false, $type);
4085 $data = array('status' => $ret);
4086 return api_format_data("status", $type, $data);
4088 // the item can't be found, but we set the note as seen, so we count this as a success
4090 return api_format_data('result', $type, array('result' => "success"));
4093 /// @TODO move to top of file or somwhere better
4094 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4095 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4098 * @brief update a direct_message to seen state
4100 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4101 * @return string (success result=ok, error result=error with error message)
4103 function api_friendica_direct_messages_setseen($type) {
4105 if (api_user() === false) {
4106 throw new ForbiddenException();
4110 $user_info = api_get_user($a);
4111 $uid = $user_info['uid'];
4112 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4114 // return error if id is zero
4116 $answer = array('result' => 'error', 'message' => 'message id not specified');
4117 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4120 // get data of the specified message id
4121 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4125 // error message if specified id is not in database
4126 if (!dbm::is_result($r)) {
4127 $answer = array('result' => 'error', 'message' => 'message id not in database');
4128 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4131 // update seen indicator
4132 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4138 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4139 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4141 $answer = array('result' => 'error', 'message' => 'unknown error');
4142 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4146 /// @TODO move to top of file or somwhere better
4147 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4150 * @brief search for direct_messages containing a searchstring through api
4152 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4153 * @return string (success: success=true if found and search_result contains found messages
4154 * success=false if nothing was found, search_result='nothing found',
4155 * error: result=error with error message)
4157 function api_friendica_direct_messages_search($type) {
4160 if (api_user() === false) {
4161 throw new ForbiddenException();
4165 $user_info = api_get_user($a);
4166 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4167 $uid = $user_info['uid'];
4169 // error if no searchstring specified
4170 if ($searchstring == "") {
4171 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4172 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4175 // get data for the specified searchstring
4176 $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",
4178 dbesc('%'.$searchstring.'%')
4181 $profile_url = $user_info["url"];
4183 // message if nothing was found
4184 if (!dbm::is_result($r)) {
4185 $success = array('success' => false, 'search_results' => 'problem with query');
4186 } elseif (count($r) == 0) {
4187 $success = array('success' => false, 'search_results' => 'nothing found');
4190 foreach ($r as $item) {
4191 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4192 $recipient = $user_info;
4193 $sender = api_get_user($a,normalise_link($item['contact-url']));
4194 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4195 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4196 $sender = $user_info;
4199 $ret[] = api_format_messages($item, $recipient, $sender);
4201 $success = array('success' => true, 'search_results' => $ret);
4204 return api_format_data("direct_message_search", $type, array('$result' => $success));
4207 /// @TODO move to top of file or somwhere better
4208 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4211 * @brief return data of all the profiles a user has to the client
4213 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4216 function api_friendica_profile_show($type) {
4219 if (api_user() === false) {
4220 throw new ForbiddenException();
4224 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4226 // retrieve general information about profiles for user
4227 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4228 $directory = get_config('system', 'directory');
4230 // get data of the specified profile id or all profiles of the user if not specified
4231 if ($profileid != 0) {
4232 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4234 intval($profileid));
4236 // error message if specified gid is not in database
4237 if (!dbm::is_result($r)) {
4238 throw new BadRequestException("profile_id not available");
4241 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4242 intval(api_user()));
4244 // loop through all returned profiles and retrieve data and users
4246 foreach ($r as $rr) {
4247 $profile = api_format_items_profiles($rr, $type);
4249 // select all users from contact table, loop and prepare standard return for user data
4251 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4253 intval($rr['profile_id']));
4255 foreach ($r as $rr) {
4256 $user = api_get_user($a, $rr['nurl']);
4257 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4259 $profile['users'] = $users;
4261 // add prepared profile data to array for final return
4262 if ($type == "xml") {
4263 $profiles[$k++ . ":profile"] = $profile;
4265 $profiles[] = $profile;
4269 // return settings, authenticated user and profiles data
4270 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4272 $result = array('multi_profiles' => $multi_profiles ? true : false,
4273 'global_dir' => $directory,
4274 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4275 'profiles' => $profiles);
4276 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4278 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4281 @TODO Maybe open to implement?
4283 [pagename] => api/1.1/statuses/lookup.json
4284 [id] => 605138389168451584
4285 [include_cards] => true
4286 [cards_platform] => Android-12
4287 [include_entities] => true
4288 [include_my_retweet] => 1
4290 [include_reply_count] => true
4291 [include_descendent_reply_count] => true
4295 Not implemented by now:
4296 statuses/retweets_of_me
4301 account/update_location
4302 account/update_profile_background_image
4303 account/update_profile_image
4306 friendica/profile/update
4307 friendica/profile/create
4308 friendica/profile/delete
4310 Not implemented in status.net:
4311 statuses/retweeted_to_me
4312 statuses/retweeted_by_me
4313 direct_messages/destroy
4315 account/update_delivery_device
4316 notifications/follow