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) && x($_GET, 'profileurl')) {
530 $user = dbesc(normalise_link($_GET['profileurl']));
532 $extra_query = "AND `contact`.`nurl` = '%s' ";
533 if (api_user() !== false) {
534 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
538 if (is_null($user) AND ($a->argc > (count($called_api) - 1)) AND (count($called_api) > 0)) {
539 $argid = count($called_api);
540 list($user, $null) = explode(".", $a->argv[$argid]);
541 if (is_numeric($user)) {
542 $user = dbesc(api_unique_id_to_url($user));
549 $extra_query = "AND `contact`.`nurl` = '%s' ";
550 if (api_user() !== false) {
551 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
554 $user = dbesc($user);
556 $extra_query = "AND `contact`.`nick` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
563 logger("api_get_user: user ".$user, LOGGER_DEBUG);
566 if (api_user() === false) {
570 $user = $_SESSION['uid'];
571 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
576 logger('api_user: ' . $extra_query . ', user: ' . $user);
579 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
585 // Selecting the id by priority, friendica first
586 api_best_nickname($uinfo);
588 // if the contact wasn't found, fetch it from the contacts with uid = 0
589 if (!dbm::is_result($uinfo)) {
593 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
596 if (dbm::is_result($r)) {
597 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
599 // If no nick where given, extract it from the address
600 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick'])) {
601 $r[0]['nick'] = api_get_nick($r[0]["url"]);
606 'id_str' => (string) $r[0]["id"],
607 'name' => $r[0]["name"],
608 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
609 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
610 'description' => $r[0]["about"],
611 'profile_image_url' => $r[0]["micro"],
612 'profile_image_url_https' => $r[0]["micro"],
613 'url' => $r[0]["url"],
614 'protected' => false,
615 'followers_count' => 0,
616 'friends_count' => 0,
618 'created_at' => api_date($r[0]["created"]),
619 'favourites_count' => 0,
621 'time_zone' => 'UTC',
622 'geo_enabled' => false,
624 'statuses_count' => 0,
626 'contributors_enabled' => false,
627 'is_translator' => false,
628 'is_translation_enabled' => false,
629 'following' => false,
630 'follow_request_sent' => false,
631 'statusnet_blocking' => false,
632 'notifications' => false,
633 'statusnet_profile_url' => $r[0]["url"],
635 'cid' => get_contact($r[0]["url"], api_user(), true),
637 'network' => $r[0]["network"],
642 throw new BadRequestException("User not found.");
646 if ($uinfo[0]['self']) {
648 if ($uinfo[0]['network'] == "") {
649 $uinfo[0]['network'] = NETWORK_DFRN;
652 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
655 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
659 /// @TODO old-lost code? (twice)
660 // Counting is deactivated by now, due to performance issues
661 // count public wall messages
662 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
663 // intval($uinfo[0]['uid'])
665 //$countitms = $r[0]['count'];
668 // Counting is deactivated by now, due to performance issues
669 //$r = q("SELECT count(*) as `count` FROM `item`
670 // WHERE `contact-id` = %d",
671 // intval($uinfo[0]['id'])
673 //$countitms = $r[0]['count'];
677 /// @TODO old-lost code? (twice)
679 // Counting is deactivated by now, due to performance issues
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_SHARING),
686 intval(CONTACT_IS_FRIEND)
688 $countfriends = $r[0]['count'];
690 $r = q("SELECT count(*) as `count` FROM `contact`
691 WHERE `uid` = %d AND `rel` IN ( %d, %d )
692 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
693 intval($uinfo[0]['uid']),
694 intval(CONTACT_IS_FOLLOWER),
695 intval(CONTACT_IS_FRIEND)
697 $countfollowers = $r[0]['count'];
699 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
700 intval($uinfo[0]['uid'])
702 $starred = $r[0]['count'];
705 if (! $uinfo[0]['self']) {
715 // Add a nick if it isn't present there
716 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
717 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
720 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
722 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
725 'id' => intval($pcontact_id),
726 'id_str' => (string) intval($pcontact_id),
727 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
728 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
729 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
730 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
731 'profile_image_url' => $uinfo[0]['micro'],
732 'profile_image_url_https' => $uinfo[0]['micro'],
733 'url' => $uinfo[0]['url'],
734 'protected' => false,
735 'followers_count' => intval($countfollowers),
736 'friends_count' => intval($countfriends),
738 'created_at' => api_date($uinfo[0]['created']),
739 'favourites_count' => intval($starred),
741 'time_zone' => 'UTC',
742 'geo_enabled' => false,
744 'statuses_count' => intval($countitms),
746 'contributors_enabled' => false,
747 'is_translator' => false,
748 'is_translation_enabled' => false,
749 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
750 'follow_request_sent' => false,
751 'statusnet_blocking' => false,
752 'notifications' => false,
754 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
755 'statusnet_profile_url' => $uinfo[0]['url'],
756 'uid' => intval($uinfo[0]['uid']),
757 'cid' => intval($uinfo[0]['cid']),
758 'self' => $uinfo[0]['self'],
759 'network' => $uinfo[0]['network'],
767 * @brief return api-formatted array for item's author and owner
770 * @param array $item : item from db
771 * @return array(array:author, array:owner)
773 function api_item_get_user(App $a, $item) {
775 $status_user = api_get_user($a, $item["author-link"]);
777 $status_user["protected"] = (($item["allow_cid"] != "") OR
778 ($item["allow_gid"] != "") OR
779 ($item["deny_cid"] != "") OR
780 ($item["deny_gid"] != "") OR
783 if ($item['thr-parent'] == $item['uri']) {
784 $owner_user = api_get_user($a, $item["owner-link"]);
786 $owner_user = $status_user;
789 return (array($status_user, $owner_user));
793 * @brief walks recursively through an array with the possibility to change value and key
795 * @param array $array The array to walk through
796 * @param string $callback The callback function
798 * @return array the transformed array
800 function api_walk_recursive(array &$array, callable $callback) {
802 $new_array = array();
804 foreach ($array as $k => $v) {
806 if ($callback($v, $k)) {
807 $new_array[$k] = api_walk_recursive($v, $callback);
810 if ($callback($v, $k)) {
821 * @brief Callback function to transform the array in an array that can be transformed in a XML file
823 * @param variant $item Array item value
824 * @param string $key Array key
826 * @return boolean Should the array item be deleted?
828 function api_reformat_xml(&$item, &$key) {
829 if (is_bool($item)) {
830 $item = ($item ? "true" : "false");
833 if (substr($key, 0, 10) == "statusnet_") {
834 $key = "statusnet:".substr($key, 10);
835 } elseif (substr($key, 0, 10) == "friendica_") {
836 $key = "friendica:".substr($key, 10);
838 /// @TODO old-lost code?
840 // $key = "default:".$key;
846 * @brief Creates the XML from a JSON style array
848 * @param array $data JSON style array
849 * @param string $root_element Name of the root element
851 * @return string The XML data
853 function api_create_xml($data, $root_element) {
854 $childname = key($data);
855 $data2 = array_pop($data);
858 $namespaces = array("" => "http://api.twitter.com",
859 "statusnet" => "http://status.net/schema/api/1/",
860 "friendica" => "http://friendi.ca/schema/api/1/",
861 "georss" => "http://www.georss.org/georss");
863 /// @todo Auto detection of needed namespaces
864 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
865 $namespaces = array();
868 if (is_array($data2)) {
869 api_walk_recursive($data2, "api_reformat_xml");
876 foreach ($data2 AS $item) {
877 $data4[$i++.":".$childname] = $item;
883 $data3 = array($root_element => $data2);
885 $ret = xml::from_array($data3, $xml, false, $namespaces);
890 * @brief Formats the data according to the data type
892 * @param string $root_element Name of the root element
893 * @param string $type Return type (atom, rss, xml, json)
894 * @param array $data JSON style array
896 * @return (string|object) XML data or JSON data
898 function api_format_data($root_element, $type, $data) {
906 $ret = api_create_xml($data, $root_element);
921 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
922 * returns a 401 status code and an error message if not.
923 * http://developer.twitter.com/doc/get/account/verify_credentials
925 function api_account_verify_credentials($type) {
929 if (api_user() === false) {
930 throw new ForbiddenException();
933 unset($_REQUEST["user_id"]);
934 unset($_GET["user_id"]);
936 unset($_REQUEST["screen_name"]);
937 unset($_GET["screen_name"]);
939 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
941 $user_info = api_get_user($a);
943 // "verified" isn't used here in the standard
944 unset($user_info["verified"]);
946 // - Adding last status
948 $user_info["status"] = api_status_show("raw");
949 if (!count($user_info["status"])) {
950 unset($user_info["status"]);
952 unset($user_info["status"]["user"]);
956 // "uid" and "self" are only needed for some internal stuff, so remove it from here
957 unset($user_info["uid"]);
958 unset($user_info["self"]);
960 return api_format_data("user", $type, array('user' => $user_info));
964 /// @TODO move to top of file or somwhere better
965 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
968 * get data from $_POST or $_GET
970 function requestdata($k) {
980 /*Waitman Gobble Mod*/
981 function api_statuses_mediap($type) {
985 if (api_user() === false) {
986 logger('api_statuses_update: no user');
987 throw new ForbiddenException();
989 $user_info = api_get_user($a);
991 $_REQUEST['type'] = 'wall';
992 $_REQUEST['profile_uid'] = api_user();
993 $_REQUEST['api_source'] = true;
994 $txt = requestdata('status');
995 /// @TODO old-lost code?
996 //$txt = urldecode(requestdata('status'));
998 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1000 $txt = html2bb_video($txt);
1001 $config = HTMLPurifier_Config::createDefault();
1002 $config->set('Cache.DefinitionImpl', null);
1003 $purifier = new HTMLPurifier($config);
1004 $txt = $purifier->purify($txt);
1006 $txt = html2bbcode($txt);
1008 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1010 // tell wall_upload function to return img info instead of echo
1011 $_REQUEST['hush'] = 'yeah';
1012 $bebop = wall_upload_post($a);
1014 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1015 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1018 // this should output the last post (the one we just posted).
1019 return api_status_show($type);
1022 /// @TODO move this to top of file or somewhere better!
1023 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1025 function api_statuses_update($type) {
1029 if (api_user() === false) {
1030 logger('api_statuses_update: no user');
1031 throw new ForbiddenException();
1034 $user_info = api_get_user($a);
1036 // convert $_POST array items to the form we use for web posts.
1038 // logger('api_post: ' . print_r($_POST,true));
1040 if (requestdata('htmlstatus')) {
1041 $txt = requestdata('htmlstatus');
1042 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1043 $txt = html2bb_video($txt);
1045 $config = HTMLPurifier_Config::createDefault();
1046 $config->set('Cache.DefinitionImpl', null);
1048 $purifier = new HTMLPurifier($config);
1049 $txt = $purifier->purify($txt);
1051 $_REQUEST['body'] = html2bbcode($txt);
1055 $_REQUEST['body'] = requestdata('status');
1058 $_REQUEST['title'] = requestdata('title');
1060 $parent = requestdata('in_reply_to_status_id');
1062 // Twidere sends "-1" if it is no reply ...
1063 if ($parent == -1) {
1067 if (ctype_digit($parent)) {
1068 $_REQUEST['parent'] = $parent;
1070 $_REQUEST['parent_uri'] = $parent;
1073 if (requestdata('lat') && requestdata('long')) {
1074 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1076 $_REQUEST['profile_uid'] = api_user();
1079 $_REQUEST['type'] = 'net-comment';
1081 // Check for throttling (maximum posts per day, week and month)
1082 $throttle_day = get_config('system','throttle_limit_day');
1083 if ($throttle_day > 0) {
1084 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1086 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1087 AND `created` > '%s' AND `id` = `parent`",
1088 intval(api_user()), dbesc($datefrom));
1090 if (dbm::is_result($r)) {
1091 $posts_day = $r[0]["posts_day"];
1096 if ($posts_day > $throttle_day) {
1097 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1098 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1099 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1103 $throttle_week = get_config('system','throttle_limit_week');
1104 if ($throttle_week > 0) {
1105 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1107 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1108 AND `created` > '%s' AND `id` = `parent`",
1109 intval(api_user()), dbesc($datefrom));
1111 if (dbm::is_result($r)) {
1112 $posts_week = $r[0]["posts_week"];
1117 if ($posts_week > $throttle_week) {
1118 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1119 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1120 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1124 $throttle_month = get_config('system','throttle_limit_month');
1125 if ($throttle_month > 0) {
1126 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1128 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1129 AND `created` > '%s' AND `id` = `parent`",
1130 intval(api_user()), dbesc($datefrom));
1132 if (dbm::is_result($r)) {
1133 $posts_month = $r[0]["posts_month"];
1138 if ($posts_month > $throttle_month) {
1139 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1140 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1141 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1145 $_REQUEST['type'] = 'wall';
1148 if (x($_FILES, 'media')) {
1149 // upload the image if we have one
1150 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1151 $media = wall_upload_post($a);
1152 if (strlen($media) > 0) {
1153 $_REQUEST['body'] .= "\n\n" . $media;
1157 // To-Do: Multiple IDs
1158 if (requestdata('media_ids')) {
1159 $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",
1160 intval(requestdata('media_ids')), api_user());
1161 if (dbm::is_result($r)) {
1162 $phototypes = Photo::supportedTypes();
1163 $ext = $phototypes[$r[0]['type']];
1164 $_REQUEST['body'] .= "\n\n" . '[url=' . App::get_baseurl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1165 $_REQUEST['body'] .= '[img]' . App::get_baseurl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1169 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1171 $_REQUEST['api_source'] = true;
1173 if (!x($_REQUEST, "source")) {
1174 $_REQUEST["source"] = api_source();
1177 // call out normal post function
1180 // this should output the last post (the one we just posted).
1181 return api_status_show($type);
1184 /// @TODO move to top of file or somwhere better
1185 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1186 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1188 function api_media_upload($type) {
1192 if (api_user() === false) {
1194 throw new ForbiddenException();
1197 $user_info = api_get_user($a);
1199 if (!x($_FILES, 'media')) {
1201 throw new BadRequestException("No media.");
1204 $media = wall_upload_post($a, false);
1207 throw new InternalServerErrorException();
1210 $returndata = array();
1211 $returndata["media_id"] = $media["id"];
1212 $returndata["media_id_string"] = (string)$media["id"];
1213 $returndata["size"] = $media["size"];
1214 $returndata["image"] = array("w" => $media["width"],
1215 "h" => $media["height"],
1216 "image_type" => $media["type"]);
1218 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1220 return array("media" => $returndata);
1223 /// @TODO move to top of file or somwhere better
1224 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1226 function api_status_show($type) {
1230 $user_info = api_get_user($a);
1232 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1234 if ($type == "raw") {
1235 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1240 // get last public wall message
1241 $lastwall = q("SELECT `item`.*
1243 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1244 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1245 AND `item`.`type` != 'activity' $privacy_sql
1246 ORDER BY `item`.`id` DESC
1248 intval($user_info['cid']),
1250 dbesc($user_info['url']),
1251 dbesc(normalise_link($user_info['url'])),
1252 dbesc($user_info['url']),
1253 dbesc(normalise_link($user_info['url']))
1256 if (dbm::is_result($lastwall)) {
1257 $lastwall = $lastwall[0];
1259 $in_reply_to = api_in_reply_to($lastwall);
1261 $converted = api_convert_item($lastwall);
1263 if ($type == "xml") {
1264 $geo = "georss:point";
1269 $status_info = array(
1270 'created_at' => api_date($lastwall['created']),
1271 'id' => intval($lastwall['id']),
1272 'id_str' => (string) $lastwall['id'],
1273 'text' => $converted["text"],
1274 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1275 'truncated' => false,
1276 'in_reply_to_status_id' => $in_reply_to['status_id'],
1277 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1278 'in_reply_to_user_id' => $in_reply_to['user_id'],
1279 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1280 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1281 'user' => $user_info,
1283 'coordinates' => "",
1285 'contributors' => "",
1286 'is_quote_status' => false,
1287 'retweet_count' => 0,
1288 'favorite_count' => 0,
1289 'favorited' => $lastwall['starred'] ? true : false,
1290 'retweeted' => false,
1291 'possibly_sensitive' => false,
1293 'statusnet_html' => $converted["html"],
1294 'statusnet_conversation_id' => $lastwall['parent'],
1297 if (count($converted["attachments"]) > 0) {
1298 $status_info["attachments"] = $converted["attachments"];
1301 if (count($converted["entities"]) > 0) {
1302 $status_info["entities"] = $converted["entities"];
1305 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web')) {
1306 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1307 } elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1308 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1311 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1312 unset($status_info["user"]["uid"]);
1313 unset($status_info["user"]["self"]);
1316 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1318 if ($type == "raw") {
1319 return $status_info;
1322 return api_format_data("statuses", $type, array('status' => $status_info));
1327 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1328 * The author's most recent status will be returned inline.
1329 * http://developer.twitter.com/doc/get/users/show
1331 function api_users_show($type) {
1335 $user_info = api_get_user($a);
1336 $lastwall = q("SELECT `item`.*
1338 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1339 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1340 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1341 AND `type`!='activity'
1342 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1346 dbesc(ACTIVITY_POST),
1347 intval($user_info['cid']),
1348 dbesc($user_info['url']),
1349 dbesc(normalise_link($user_info['url'])),
1350 dbesc($user_info['url']),
1351 dbesc(normalise_link($user_info['url']))
1354 if (dbm::is_result($lastwall)) {
1355 $lastwall = $lastwall[0];
1357 $in_reply_to = api_in_reply_to($lastwall);
1359 $converted = api_convert_item($lastwall);
1361 if ($type == "xml") {
1362 $geo = "georss:point";
1367 $user_info['status'] = array(
1368 'text' => $converted["text"],
1369 'truncated' => false,
1370 'created_at' => api_date($lastwall['created']),
1371 'in_reply_to_status_id' => $in_reply_to['status_id'],
1372 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1373 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1374 'id' => intval($lastwall['contact-id']),
1375 'id_str' => (string) $lastwall['contact-id'],
1376 'in_reply_to_user_id' => $in_reply_to['user_id'],
1377 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1378 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1380 'favorited' => $lastwall['starred'] ? true : false,
1381 'statusnet_html' => $converted["html"],
1382 'statusnet_conversation_id' => $lastwall['parent'],
1385 if (count($converted["attachments"]) > 0) {
1386 $user_info["status"]["attachments"] = $converted["attachments"];
1389 if (count($converted["entities"]) > 0) {
1390 $user_info["status"]["entities"] = $converted["entities"];
1393 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web')) {
1394 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1397 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1398 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1403 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1404 unset($user_info["uid"]);
1405 unset($user_info["self"]);
1407 return api_format_data("user", $type, array('user' => $user_info));
1411 /// @TODO move to top of file or somewhere better
1412 api_register_func('api/users/show','api_users_show');
1413 api_register_func('api/externalprofile/show','api_users_show');
1415 function api_users_search($type) {
1419 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1421 $userlist = array();
1423 if (x($_GET, 'q')) {
1424 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1426 if (!dbm::is_result($r)) {
1427 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1430 if (dbm::is_result($r)) {
1432 foreach ($r AS $user) {
1433 $user_info = api_get_user($a, $user["id"], "json");
1435 if ($type == "xml") {
1436 $userlist[$k++.":user"] = $user_info;
1438 $userlist[] = $user_info;
1441 $userlist = array("users" => $userlist);
1443 throw new BadRequestException("User not found.");
1446 throw new BadRequestException("User not found.");
1448 return api_format_data("users", $type, $userlist);
1451 /// @TODO move to top of file or somewhere better
1452 api_register_func('api/users/search','api_users_search');
1456 * http://developer.twitter.com/doc/get/statuses/home_timeline
1458 * TODO: Optional parameters
1459 * TODO: Add reply info
1461 function api_statuses_home_timeline($type) {
1465 if (api_user() === false) {
1466 throw new ForbiddenException();
1469 unset($_REQUEST["user_id"]);
1470 unset($_GET["user_id"]);
1472 unset($_REQUEST["screen_name"]);
1473 unset($_GET["screen_name"]);
1475 $user_info = api_get_user($a);
1476 // get last newtork messages
1479 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1480 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1484 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1485 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1486 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1487 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1488 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1490 $start = $page * $count;
1494 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1496 if ($exclude_replies > 0) {
1497 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1499 if ($conversation_id > 0) {
1500 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1503 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1504 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1505 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1506 `contact`.`id` AS `cid`
1508 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1509 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1510 WHERE `item`.`uid` = %d AND `verb` = '%s'
1511 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1514 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1516 dbesc(ACTIVITY_POST),
1518 intval($start), intval($count)
1521 $ret = api_format_items($r, $user_info, false, $type);
1523 // Set all posts from the query above to seen
1525 foreach ($r AS $item) {
1526 $idarray[] = intval($item["id"]);
1529 $idlist = implode(",", $idarray);
1531 if ($idlist != "") {
1532 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1535 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1539 $data = array('status' => $ret);
1543 $data = api_rss_extra($a, $data, $user_info);
1547 return api_format_data("statuses", $type, $data);
1550 /// @TODO move to top of file or somewhere better
1551 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1552 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1554 function api_statuses_public_timeline($type) {
1558 if (api_user() === false) {
1559 throw new ForbiddenException();
1562 $user_info = api_get_user($a);
1563 // get last newtork messages
1566 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1567 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1571 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1572 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1573 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1574 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1575 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1577 $start = $page * $count;
1580 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1582 if ($exclude_replies > 0) {
1583 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1585 if ($conversation_id > 0) {
1586 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1589 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1590 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1591 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1592 `contact`.`id` AS `cid`,
1593 `user`.`nickname`, `user`.`hidewall`
1595 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1596 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1597 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1598 AND NOT `user`.`hidewall`
1599 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1600 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1601 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1602 AND NOT `item`.`private` AND `item`.`wall`
1605 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1606 dbesc(ACTIVITY_POST),
1611 $ret = api_format_items($r, $user_info, false, $type);
1613 $data = array('status' => $ret);
1617 $data = api_rss_extra($a, $data, $user_info);
1621 return api_format_data("statuses", $type, $data);
1624 /// @TODO move to top of file or somewhere better
1625 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1628 * @TODO nothing to say?
1630 function api_statuses_show($type) {
1634 if (api_user() === false) {
1635 throw new ForbiddenException();
1638 $user_info = api_get_user($a);
1641 $id = intval($a->argv[3]);
1644 $id = intval($_REQUEST["id"]);
1649 $id = intval($a->argv[4]);
1652 logger('API: api_statuses_show: ' . $id);
1654 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1657 if ($conversation) {
1658 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1660 $sql_extra .= " AND `item`.`id` = %d";
1663 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1664 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1665 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1666 `contact`.`id` AS `cid`
1668 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1669 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1670 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1671 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1674 dbesc(ACTIVITY_POST),
1678 /// @TODO How about copying this to above methods which don't check $r ?
1679 if (!dbm::is_result($r)) {
1680 throw new BadRequestException("There is no status with this id.");
1683 $ret = api_format_items($r,$user_info, false, $type);
1685 if ($conversation) {
1686 $data = array('status' => $ret);
1687 return api_format_data("statuses", $type, $data);
1689 $data = array('status' => $ret[0]);
1690 return api_format_data("status", $type, $data);
1694 /// @TODO move to top of file or somewhere better
1695 api_register_func('api/statuses/show','api_statuses_show', true);
1698 * @TODO nothing to say?
1700 function api_conversation_show($type) {
1704 if (api_user() === false) {
1705 throw new ForbiddenException();
1708 $user_info = api_get_user($a);
1711 $id = intval($a->argv[3]);
1712 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1713 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1717 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1718 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1720 $start = $page*$count;
1723 $id = intval($_REQUEST["id"]);
1728 $id = intval($a->argv[4]);
1731 logger('API: api_conversation_show: '.$id);
1733 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1734 if (dbm::is_result($r)) {
1735 $id = $r[0]["parent"];
1741 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1744 // Not sure why this query was so complicated. We should keep it here for a while,
1745 // just to make sure that we really don't need it.
1746 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1747 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1749 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1750 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1751 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1752 `contact`.`id` AS `cid`
1754 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1755 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1756 WHERE `item`.`parent` = %d AND `item`.`visible`
1757 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1758 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1759 AND `item`.`id`>%d $sql_extra
1760 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1761 intval($id), intval(api_user()),
1762 dbesc(ACTIVITY_POST),
1764 intval($start), intval($count)
1767 if (!dbm::is_result($r)) {
1768 throw new BadRequestException("There is no status with this id.");
1771 $ret = api_format_items($r, $user_info, false, $type);
1773 $data = array('status' => $ret);
1774 return api_format_data("statuses", $type, $data);
1777 /// @TODO move to top of file or somewhere better
1778 api_register_func('api/conversation/show','api_conversation_show', true);
1779 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1782 * @TODO nothing to say?
1784 function api_statuses_repeat($type) {
1789 if (api_user() === false) {
1790 throw new ForbiddenException();
1793 $user_info = api_get_user($a);
1796 $id = intval($a->argv[3]);
1799 $id = intval($_REQUEST["id"]);
1804 $id = intval($a->argv[4]);
1807 logger('API: api_statuses_repeat: '.$id);
1809 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1810 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1811 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1812 `contact`.`id` AS `cid`
1814 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1815 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1816 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1817 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1818 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1820 AND `item`.`id`=%d",
1824 /// @TODO other style than above functions!
1825 if (dbm::is_result($r) && $r[0]['body'] != "") {
1826 if (strpos($r[0]['body'], "[/share]") !== false) {
1827 $pos = strpos($r[0]['body'], "[share");
1828 $post = substr($r[0]['body'], $pos);
1830 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1832 $post .= $r[0]['body'];
1833 $post .= "[/share]";
1835 $_REQUEST['body'] = $post;
1836 $_REQUEST['profile_uid'] = api_user();
1837 $_REQUEST['type'] = 'wall';
1838 $_REQUEST['api_source'] = true;
1840 if (!x($_REQUEST, "source")) {
1841 $_REQUEST["source"] = api_source();
1846 throw new ForbiddenException();
1849 // this should output the last post (the one we just posted).
1851 return api_status_show($type);
1854 /// @TODO move to top of file or somewhere better
1855 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1858 * @TODO nothing to say?
1860 function api_statuses_destroy($type) {
1864 if (api_user() === false) {
1865 throw new ForbiddenException();
1868 $user_info = api_get_user($a);
1871 $id = intval($a->argv[3]);
1874 $id = intval($_REQUEST["id"]);
1879 $id = intval($a->argv[4]);
1882 logger('API: api_statuses_destroy: '.$id);
1884 $ret = api_statuses_show($type);
1886 drop_item($id, false);
1891 /// @TODO move to top of file or somewhere better
1892 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1895 * @TODO Nothing more than an URL to say?
1896 * http://developer.twitter.com/doc/get/statuses/mentions
1898 function api_statuses_mentions($type) {
1902 if (api_user() === false) {
1903 throw new ForbiddenException();
1906 unset($_REQUEST["user_id"]);
1907 unset($_GET["user_id"]);
1909 unset($_REQUEST["screen_name"]);
1910 unset($_GET["screen_name"]);
1912 $user_info = api_get_user($a);
1913 // get last newtork messages
1917 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1918 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1922 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1923 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1924 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1926 $start = $page * $count;
1928 // Ugly code - should be changed
1929 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1930 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1931 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1932 $myurl = str_replace('www.', '', $myurl);
1933 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1936 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1939 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1940 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1941 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1942 `contact`.`id` AS `cid`
1943 FROM `item` FORCE INDEX (`uid_id`)
1944 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1945 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1946 WHERE `item`.`uid` = %d AND `verb` = '%s'
1947 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1948 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1949 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1952 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1954 dbesc(ACTIVITY_POST),
1955 dbesc(protect_sprintf($myurl)),
1956 dbesc(protect_sprintf($myurl)),
1959 intval($start), intval($count)
1962 $ret = api_format_items($r, $user_info, false, $type);
1964 $data = array('status' => $ret);
1968 $data = api_rss_extra($a, $data, $user_info);
1972 return api_format_data("statuses", $type, $data);
1975 /// @TODO move to top of file or somewhere better
1976 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1977 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1979 function api_statuses_user_timeline($type) {
1983 if (api_user() === false) {
1984 throw new ForbiddenException();
1987 $user_info = api_get_user($a);
1988 // get last network messages
1990 logger("api_statuses_user_timeline: api_user: ". api_user() .
1991 "\nuser_info: ".print_r($user_info, true) .
1992 "\n_REQUEST: ".print_r($_REQUEST, true),
1996 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1997 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2001 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2002 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2003 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2004 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2006 $start = $page * $count;
2009 if ($user_info['self'] == 1) {
2010 $sql_extra .= " AND `item`.`wall` = 1 ";
2013 if ($exclude_replies > 0) {
2014 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2016 if ($conversation_id > 0) {
2017 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2020 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2021 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2022 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2023 `contact`.`id` AS `cid`
2024 FROM `item` FORCE INDEX (`uid_contactid_id`)
2025 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2026 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2027 WHERE `item`.`uid` = %d AND `verb` = '%s'
2028 AND `item`.`contact-id` = %d
2029 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2032 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2034 dbesc(ACTIVITY_POST),
2035 intval($user_info['cid']),
2037 intval($start), intval($count)
2040 $ret = api_format_items($r, $user_info, true, $type);
2042 $data = array('status' => $ret);
2046 $data = api_rss_extra($a, $data, $user_info);
2050 return api_format_data("statuses", $type, $data);
2053 /// @TODO move to top of file or somwhere better
2054 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2057 * Star/unstar an item
2058 * param: id : id of the item
2060 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2062 function api_favorites_create_destroy($type) {
2066 if (api_user() === false) {
2067 throw new ForbiddenException();
2070 // for versioned api.
2071 /// @TODO We need a better global soluton
2072 $action_argv_id = 2;
2073 if ($a->argv[1] == "1.1") {
2074 $action_argv_id = 3;
2077 if ($a->argc <= $action_argv_id) {
2078 throw new BadRequestException("Invalid request.");
2080 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2081 if ($a->argc == $action_argv_id + 2) {
2082 $itemid = intval($a->argv[$action_argv_id + 1]);
2084 /// @TODO use x() to check if _REQUEST contains 'id'
2085 $itemid = intval($_REQUEST['id']);
2088 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2089 $itemid, api_user());
2091 if (!dbm::is_result($item) || count($item) == 0) {
2092 throw new BadRequestException("Invalid item.");
2097 $item[0]['starred'] = 1;
2100 $item[0]['starred'] = 0;
2103 throw new BadRequestException("Invalid action ".$action);
2106 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2107 $item[0]['starred'], $itemid, api_user());
2109 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2110 $item[0]['starred'], $itemid, api_user());
2113 throw new InternalServerErrorException("DB error");
2117 $user_info = api_get_user($a);
2118 $rets = api_format_items($item, $user_info, false, $type);
2121 $data = array('status' => $ret);
2125 $data = api_rss_extra($a, $data, $user_info);
2128 return api_format_data("status", $type, $data);
2131 /// @TODO move to top of file or somwhere better
2132 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2133 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2135 function api_favorites($type) {
2140 if (api_user() === false) {
2141 throw new ForbiddenException();
2144 $called_api = array();
2146 $user_info = api_get_user($a);
2148 // in friendica starred item are private
2149 // return favorites only for self
2150 logger('api_favorites: self:' . $user_info['self']);
2152 if ($user_info['self'] == 0) {
2158 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2159 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2160 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2161 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2166 $start = $page*$count;
2169 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2172 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2173 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2174 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2175 `contact`.`id` AS `cid`
2176 FROM `item`, `contact`
2177 WHERE `item`.`uid` = %d
2178 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2179 AND `item`.`starred` = 1
2180 AND `contact`.`id` = `item`.`contact-id`
2181 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2184 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2187 intval($start), intval($count)
2190 $ret = api_format_items($r,$user_info, false, $type);
2194 $data = array('status' => $ret);
2198 $data = api_rss_extra($a, $data, $user_info);
2201 return api_format_data("statuses", $type, $data);
2204 /// @TODO move to top of file or somwhere better
2205 api_register_func('api/favorites','api_favorites', true);
2207 function api_format_messages($item, $recipient, $sender) {
2208 // standard meta information
2210 'id' => $item['id'],
2211 'sender_id' => $sender['id'] ,
2213 'recipient_id' => $recipient['id'],
2214 'created_at' => api_date($item['created']),
2215 'sender_screen_name' => $sender['screen_name'],
2216 'recipient_screen_name' => $recipient['screen_name'],
2217 'sender' => $sender,
2218 'recipient' => $recipient,
2220 'friendica_seen' => $item['seen'],
2221 'friendica_parent_uri' => $item['parent-uri'],
2224 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2225 unset($ret["sender"]["uid"]);
2226 unset($ret["sender"]["self"]);
2227 unset($ret["recipient"]["uid"]);
2228 unset($ret["recipient"]["self"]);
2230 //don't send title to regular StatusNET requests to avoid confusing these apps
2231 if (x($_GET, 'getText')) {
2232 $ret['title'] = $item['title'] ;
2233 if ($_GET['getText'] == 'html') {
2234 $ret['text'] = bbcode($item['body'], false, false);
2235 } elseif ($_GET['getText'] == 'plain') {
2236 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2237 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2240 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2242 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2243 unset($ret['sender']);
2244 unset($ret['recipient']);
2250 function api_convert_item($item) {
2251 $body = $item['body'];
2252 $attachments = api_get_attachments($body);
2254 // Workaround for ostatus messages where the title is identically to the body
2255 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2256 $statusbody = trim(html2plain($html, 0));
2258 // handle data: images
2259 $statusbody = api_format_items_embeded_images($item,$statusbody);
2261 $statustitle = trim($item['title']);
2263 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false)) {
2264 $statustext = trim($statusbody);
2266 $statustext = trim($statustitle."\n\n".$statusbody);
2269 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000)) {
2270 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2273 $statushtml = trim(bbcode($body, false, false));
2275 $search = array("<br>", "<blockquote>", "</blockquote>",
2276 "<h1>", "</h1>", "<h2>", "</h2>",
2277 "<h3>", "</h3>", "<h4>", "</h4>",
2278 "<h5>", "</h5>", "<h6>", "</h6>");
2279 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2280 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2281 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2282 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2283 $statushtml = str_replace($search, $replace, $statushtml);
2285 if ($item['title'] != "") {
2286 $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
2289 $entities = api_get_entitities($statustext, $body);
2292 "text" => $statustext,
2293 "html" => $statushtml,
2294 "attachments" => $attachments,
2295 "entities" => $entities
2299 function api_get_attachments(&$body) {
2302 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2304 $URLSearchString = "^\[\]";
2305 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2311 $attachments = array();
2313 foreach ($images[1] AS $image) {
2314 $imagedata = get_photo_info($image);
2317 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2321 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2322 foreach ($images[0] AS $orig) {
2323 $body = str_replace($orig, "", $body);
2327 return $attachments;
2330 function api_get_entitities(&$text, $bbcode) {
2333 * Links at the first character of the post
2338 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2340 if ($include_entities != "true") {
2342 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2344 foreach ($images[1] AS $image) {
2345 $replace = proxy_url($image);
2346 $text = str_replace($image, $replace, $text);
2351 $bbcode = bb_CleanPictureLinks($bbcode);
2353 // Change pure links in text to bbcode uris
2354 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2356 $entities = array();
2357 $entities["hashtags"] = array();
2358 $entities["symbols"] = array();
2359 $entities["urls"] = array();
2360 $entities["user_mentions"] = array();
2362 $URLSearchString = "^\[\]";
2364 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2366 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2367 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2368 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2370 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2371 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2372 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2374 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2375 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2376 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2378 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2380 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2381 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2383 $ordered_urls = array();
2384 foreach ($urls[1] AS $id => $url) {
2385 //$start = strpos($text, $url, $offset);
2386 $start = iconv_strpos($text, $url, 0, "UTF-8");
2387 if (!($start === false)) {
2388 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2392 ksort($ordered_urls);
2395 //foreach ($urls[1] AS $id=>$url) {
2396 foreach ($ordered_urls AS $url) {
2397 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2398 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2399 $display_url = $url["title"];
2401 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2402 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2404 if (strlen($display_url) > 26)
2405 $display_url = substr($display_url, 0, 25)."…";
2408 //$start = strpos($text, $url, $offset);
2409 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2410 if (!($start === false)) {
2411 $entities["urls"][] = array("url" => $url["url"],
2412 "expanded_url" => $url["url"],
2413 "display_url" => $display_url,
2414 "indices" => array($start, $start+strlen($url["url"])));
2415 $offset = $start + 1;
2419 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2420 $ordered_images = array();
2421 foreach ($images[1] AS $image) {
2422 //$start = strpos($text, $url, $offset);
2423 $start = iconv_strpos($text, $image, 0, "UTF-8");
2424 if (!($start === false))
2425 $ordered_images[$start] = $image;
2427 //$entities["media"] = array();
2430 foreach ($ordered_images AS $url) {
2431 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2432 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2434 if (strlen($display_url) > 26)
2435 $display_url = substr($display_url, 0, 25)."…";
2437 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2438 if (!($start === false)) {
2439 $image = get_photo_info($url);
2441 // If image cache is activated, then use the following sizes:
2442 // thumb (150), small (340), medium (600) and large (1024)
2443 if (!get_config("system", "proxy_disabled")) {
2444 $media_url = proxy_url($url);
2447 $scale = scale_image($image[0], $image[1], 150);
2448 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2450 if (($image[0] > 150) OR ($image[1] > 150)) {
2451 $scale = scale_image($image[0], $image[1], 340);
2452 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2455 $scale = scale_image($image[0], $image[1], 600);
2456 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2458 if (($image[0] > 600) OR ($image[1] > 600)) {
2459 $scale = scale_image($image[0], $image[1], 1024);
2460 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2464 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2467 $entities["media"][] = array(
2469 "id_str" => (string)$start+1,
2470 "indices" => array($start, $start+strlen($url)),
2471 "media_url" => normalise_link($media_url),
2472 "media_url_https" => $media_url,
2474 "display_url" => $display_url,
2475 "expanded_url" => $url,
2479 $offset = $start + 1;
2485 function api_format_items_embeded_images(&$item, $text) {
2486 $text = preg_replace_callback(
2487 "|data:image/([^;]+)[^=]+=*|m",
2488 function($match) use ($item) {
2489 return App::get_baseurl()."/display/".$item['guid'];
2497 * @brief return <a href='url'>name</a> as array
2499 * @param string $txt
2504 function api_contactlink_to_array($txt) {
2506 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2507 if ($r && count($match)==3) {
2509 'name' => $match[2],
2523 * @brief return likes, dislikes and attend status for item
2525 * @param array $item
2527 * likes => int count
2528 * dislikes => int count
2530 function api_format_items_activities(&$item, $type = "json") {
2534 $activities = array(
2536 'dislike' => array(),
2537 'attendyes' => array(),
2538 'attendno' => array(),
2539 'attendmaybe' => array(),
2542 $items = q('SELECT * FROM item
2543 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2544 intval($item['uid']),
2545 dbesc($item['uri']));
2547 foreach ($items as $i) {
2548 // not used as result should be structured like other user data
2549 //builtin_activity_puller($i, $activities);
2551 // get user data and add it to the array of the activity
2552 $user = api_get_user($a, $i['author-link']);
2553 switch ($i['verb']) {
2555 $activities['like'][] = $user;
2557 case ACTIVITY_DISLIKE:
2558 $activities['dislike'][] = $user;
2560 case ACTIVITY_ATTEND:
2561 $activities['attendyes'][] = $user;
2563 case ACTIVITY_ATTENDNO:
2564 $activities['attendno'][] = $user;
2566 case ACTIVITY_ATTENDMAYBE:
2567 $activities['attendmaybe'][] = $user;
2574 if ($type == "xml") {
2575 $xml_activities = array();
2576 foreach ($activities as $k => $v) {
2577 // change xml element from "like" to "friendica:like"
2578 $xml_activities["friendica:".$k] = $v;
2579 // add user data into xml output
2581 foreach ($v as $user)
2582 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2584 $activities = $xml_activities;
2593 * @brief return data from profiles
2595 * @param array $profile array containing data from db table 'profile'
2596 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2599 function api_format_items_profiles(&$profile = null, $type = "json") {
2600 if ($profile != null) {
2601 $profile = array('profile_id' => $profile['id'],
2602 'profile_name' => $profile['profile-name'],
2603 'is_default' => $profile['is-default'] ? true : false,
2604 'hide_friends'=> $profile['hide-friends'] ? true : false,
2605 'profile_photo' => $profile['photo'],
2606 'profile_thumb' => $profile['thumb'],
2607 'publish' => $profile['publish'] ? true : false,
2608 'net_publish' => $profile['net-publish'] ? true : false,
2609 'description' => $profile['pdesc'],
2610 'date_of_birth' => $profile['dob'],
2611 'address' => $profile['address'],
2612 'city' => $profile['locality'],
2613 'region' => $profile['region'],
2614 'postal_code' => $profile['postal-code'],
2615 'country' => $profile['country-name'],
2616 'hometown' => $profile['hometown'],
2617 'gender' => $profile['gender'],
2618 'marital' => $profile['marital'],
2619 'marital_with' => $profile['with'],
2620 'marital_since' => $profile['howlong'],
2621 'sexual' => $profile['sexual'],
2622 'politic' => $profile['politic'],
2623 'religion' => $profile['religion'],
2624 'public_keywords' => $profile['pub_keywords'],
2625 'private_keywords' => $profile['prv_keywords'],
2626 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2627 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2628 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2629 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2630 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2631 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2632 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2633 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2634 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2635 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2636 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2637 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2638 'homepage' => $profile['homepage'],
2645 * @brief format items to be returned by api
2647 * @param array $r array of items
2648 * @param array $user_info
2649 * @param bool $filter_user filter items by $user_info
2651 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2657 foreach ($r as $item) {
2659 localize_item($item);
2660 list($status_user, $owner_user) = api_item_get_user($a, $item);
2662 // Look if the posts are matching if they should be filtered by user id
2663 if ($filter_user AND ($status_user["id"] != $user_info["id"])) {
2667 $in_reply_to = api_in_reply_to($item);
2669 $converted = api_convert_item($item);
2671 if ($type == "xml") {
2672 $geo = "georss:point";
2678 'text' => $converted["text"],
2679 'truncated' => False,
2680 'created_at'=> api_date($item['created']),
2681 'in_reply_to_status_id' => $in_reply_to['status_id'],
2682 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2683 'source' => (($item['app']) ? $item['app'] : 'web'),
2684 'id' => intval($item['id']),
2685 'id_str' => (string) intval($item['id']),
2686 'in_reply_to_user_id' => $in_reply_to['user_id'],
2687 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2688 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2690 'favorited' => $item['starred'] ? true : false,
2691 'user' => $status_user ,
2692 'friendica_owner' => $owner_user,
2693 //'entities' => NULL,
2694 'statusnet_html' => $converted["html"],
2695 'statusnet_conversation_id' => $item['parent'],
2696 'friendica_activities' => api_format_items_activities($item, $type),
2699 if (count($converted["attachments"]) > 0) {
2700 $status["attachments"] = $converted["attachments"];
2703 if (count($converted["entities"]) > 0) {
2704 $status["entities"] = $converted["entities"];
2707 if (($item['item_network'] != "") AND ($status["source"] == 'web')) {
2708 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2709 } elseif (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2710 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2714 // Retweets are only valid for top postings
2715 // It doesn't work reliable with the link if its a feed
2716 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2718 // $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2721 if ($item["id"] == $item["parent"]) {
2722 $retweeted_item = api_share_as_retweet($item);
2723 if ($retweeted_item !== false) {
2724 $retweeted_status = $status;
2726 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2727 } catch( BadRequestException $e ) {
2728 // user not found. should be found?
2729 /// @todo check if the user should be always found
2730 $retweeted_status["user"] = array();
2733 $rt_converted = api_convert_item($retweeted_item);
2735 $retweeted_status['text'] = $rt_converted["text"];
2736 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2737 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2738 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2739 $status['retweeted_status'] = $retweeted_status;
2743 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2744 unset($status["user"]["uid"]);
2745 unset($status["user"]["self"]);
2747 if ($item["coord"] != "") {
2748 $coords = explode(' ',$item["coord"]);
2749 if (count($coords) == 2) {
2750 if ($type == "json")
2751 $status["geo"] = array('type' => 'Point',
2752 'coordinates' => array((float) $coords[0],
2753 (float) $coords[1]));
2754 else // Not sure if this is the official format - if someone founds a documentation we can check
2755 $status["georss:point"] = $item["coord"];
2763 function api_account_rate_limit_status($type) {
2765 if ($type == "xml") {
2767 'remaining-hits' => '150',
2768 '@attributes' => array("type" => "integer"),
2769 'hourly-limit' => '150',
2770 '@attributes2' => array("type" => "integer"),
2771 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2772 '@attributes3' => array("type" => "datetime"),
2773 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2774 '@attributes4' => array("type" => "integer"),
2778 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2779 'remaining_hits' => '150',
2780 'hourly_limit' => '150',
2781 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2785 return api_format_data('hash', $type, array('hash' => $hash));
2788 /// @TODO move to top of file or somwhere better
2789 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2791 function api_help_test($type) {
2792 if ($type == 'xml') {
2798 return api_format_data('ok', $type, array("ok" => $ok));
2801 /// @TODO move to top of file or somwhere better
2802 api_register_func('api/help/test','api_help_test', false);
2804 function api_lists($type) {
2806 /// @TODO $ret is not filled here?
2807 return api_format_data('lists', $type, array("lists_list" => $ret));
2810 /// @TODO move to top of file or somwhere better
2811 api_register_func('api/lists','api_lists',true);
2813 function api_lists_list($type) {
2815 /// @TODO $ret is not filled here?
2816 return api_format_data('lists', $type, array("lists_list" => $ret));
2819 /// @TODO move to top of file or somwhere better
2820 api_register_func('api/lists/list','api_lists_list',true);
2823 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2824 * This function is deprecated by Twitter
2825 * returns: json, xml
2827 function api_statuses_f($type, $qtype) {
2831 if (api_user() === false) {
2832 throw new ForbiddenException();
2835 $user_info = api_get_user($a);
2837 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2838 /* this is to stop Hotot to load friends multiple times
2839 * I'm not sure if I'm missing return something or
2840 * is a bug in hotot. Workaround, meantime
2844 return array('$users' => $ret);*/
2848 if ($qtype == 'friends') {
2849 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2851 if ($qtype == 'followers') {
2852 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2855 // friends and followers only for self
2856 if ($user_info['self'] == 0) {
2857 $sql_extra = " AND false ";
2860 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2865 foreach ($r as $cid) {
2866 $user = api_get_user($a, $cid['nurl']);
2867 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2868 unset($user["uid"]);
2869 unset($user["self"]);
2876 return array('user' => $ret);
2880 function api_statuses_friends($type) {
2881 $data = api_statuses_f($type, "friends");
2882 if ($data === false) {
2885 return api_format_data("users", $type, $data);
2888 function api_statuses_followers($type) {
2889 $data = api_statuses_f($type, "followers");
2890 if ($data === false) {
2893 return api_format_data("users", $type, $data);
2896 /// @TODO move to top of file or somewhere better
2897 api_register_func('api/statuses/friends','api_statuses_friends',true);
2898 api_register_func('api/statuses/followers','api_statuses_followers',true);
2900 function api_statusnet_config($type) {
2904 $name = $a->config['sitename'];
2905 $server = $a->get_hostname();
2906 $logo = App::get_baseurl() . '/images/friendica-64.png';
2907 $email = $a->config['admin_email'];
2908 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2909 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2910 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2911 if ($a->config['api_import_size']) {
2912 $texlimit = string($a->config['api_import_size']);
2914 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2915 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2918 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2919 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2920 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2921 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2922 'shorturllength' => '30',
2923 'friendica' => array(
2924 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2925 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2926 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2927 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2932 return api_format_data('config', $type, array('config' => $config));
2936 /// @TODO move to top of file or somewhere better
2937 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2938 api_register_func('api/statusnet/config','api_statusnet_config', false);
2940 function api_statusnet_version($type) {
2942 $fake_statusnet_version = "0.9.7";
2944 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2947 /// @TODO move to top of file or somewhere better
2948 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2949 api_register_func('api/statusnet/version','api_statusnet_version', false);
2952 * @todo use api_format_data() to return data
2954 function api_ff_ids($type,$qtype) {
2959 throw new ForbiddenException();
2962 $user_info = api_get_user($a);
2964 if ($qtype == 'friends') {
2965 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2967 if ($qtype == 'followers') {
2968 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2971 if (!$user_info["self"]) {
2972 $sql_extra = " AND false ";
2975 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
2977 $r = q("SELECT `pcontact`.`id` FROM `contact`
2978 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2979 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2983 if (!dbm::is_result($r)) {
2988 foreach ($r as $rr) {
2989 if ($stringify_ids) {
2992 $ids[] = intval($rr['id']);
2996 return api_format_data("ids", $type, array('id' => $ids));
2999 function api_friends_ids($type) {
3000 return api_ff_ids($type,'friends');
3003 function api_followers_ids($type) {
3004 return api_ff_ids($type,'followers');
3007 /// @TODO move to top of file or somewhere better
3008 api_register_func('api/friends/ids','api_friends_ids',true);
3009 api_register_func('api/followers/ids','api_followers_ids',true);
3011 function api_direct_messages_new($type) {
3015 if (api_user() === false) throw new ForbiddenException();
3017 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
3019 $sender = api_get_user($a);
3021 if ($_POST['screen_name']) {
3022 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3024 dbesc($_POST['screen_name']));
3026 // Selecting the id by priority, friendica first
3027 api_best_nickname($r);
3029 $recipient = api_get_user($a, $r[0]['nurl']);
3031 $recipient = api_get_user($a, $_POST['user_id']);
3035 if (x($_REQUEST, 'replyto')) {
3036 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3038 intval($_REQUEST['replyto']));
3039 $replyto = $r[0]['parent-uri'];
3040 $sub = $r[0]['title'];
3042 if (x($_REQUEST, 'title')) {
3043 $sub = $_REQUEST['title'];
3045 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3049 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3052 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3053 $ret = api_format_messages($r[0], $recipient, $sender);
3055 $ret = array("error"=>$id);
3058 $data = array('direct_message'=>$ret);
3063 $data = api_rss_extra($a, $data, $user_info);
3066 return api_format_data("direct-messages", $type, $data);
3070 /// @TODO move to top of file or somewhere better
3071 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3074 * @brief delete a direct_message from mail table through api
3076 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3079 function api_direct_messages_destroy($type) {
3082 if (api_user() === false) {
3083 throw new ForbiddenException();
3087 $user_info = api_get_user($a);
3089 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3091 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3092 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3093 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3095 $uid = $user_info['uid'];
3096 // error if no id or parenturi specified (for clients posting parent-uri as well)
3097 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3098 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3099 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3102 // BadRequestException if no id specified (for clients using Twitter API)
3104 throw new BadRequestException('Message id not specified');
3107 // add parent-uri to sql command if specified by calling app
3108 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3110 // get data of the specified message id
3111 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3115 // error message if specified id is not in database
3116 if (!dbm::is_result($r)) {
3117 if ($verbose == "true") {
3118 $answer = array('result' => 'error', 'message' => 'message id not in database');
3119 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3121 /// @todo BadRequestException ok for Twitter API clients?
3122 throw new BadRequestException('message id not in database');
3126 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3130 if ($verbose == "true") {
3133 $answer = array('result' => 'ok', 'message' => 'message deleted');
3134 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3136 $answer = array('result' => 'error', 'message' => 'unknown error');
3137 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3140 /// @todo return JSON data like Twitter API not yet implemented
3144 /// @TODO move to top of file or somewhere better
3145 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3147 function api_direct_messages_box($type, $box, $verbose) {
3151 if (api_user() === false) {
3152 throw new ForbiddenException();
3156 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3157 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3162 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3163 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3165 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3166 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3169 unset($_REQUEST["user_id"]);
3170 unset($_GET["user_id"]);
3172 unset($_REQUEST["screen_name"]);
3173 unset($_GET["screen_name"]);
3175 $user_info = api_get_user($a);
3176 $profile_url = $user_info["url"];
3179 $start = $page * $count;
3182 if ($box=="sentbox") {
3183 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3184 } elseif ($box == "conversation") {
3185 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3186 } elseif ($box == "all") {
3187 $sql_extra = "true";
3188 } elseif ($box == "inbox") {
3189 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3193 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3196 if ($user_id != "") {
3197 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3198 } elseif ($screen_name !="") {
3199 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3202 $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",
3205 intval($start), intval($count)
3207 if ($verbose == "true" && !dbm::is_result($r)) {
3208 $answer = array('result' => 'error', 'message' => 'no mails available');
3209 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3213 foreach ($r as $item) {
3214 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3215 $recipient = $user_info;
3216 $sender = api_get_user($a,normalise_link($item['contact-url']));
3217 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3218 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3219 $sender = $user_info;
3222 $ret[] = api_format_messages($item, $recipient, $sender);
3226 $data = array('direct_message' => $ret);
3230 $data = api_rss_extra($a, $data, $user_info);
3233 return api_format_data("direct-messages", $type, $data);
3237 function api_direct_messages_sentbox($type) {
3238 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3239 return api_direct_messages_box($type, "sentbox", $verbose);
3242 function api_direct_messages_inbox($type) {
3243 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3244 return api_direct_messages_box($type, "inbox", $verbose);
3247 function api_direct_messages_all($type) {
3248 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3249 return api_direct_messages_box($type, "all", $verbose);
3252 function api_direct_messages_conversation($type) {
3253 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3254 return api_direct_messages_box($type, "conversation", $verbose);
3257 /// @TODO move to top of file or somewhere better
3258 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3259 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3260 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3261 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3263 function api_oauth_request_token($type) {
3265 $oauth = new FKOAuth1();
3266 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3267 } catch (Exception $e) {
3268 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3275 function api_oauth_access_token($type) {
3277 $oauth = new FKOAuth1();
3278 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3279 } catch (Exception $e) {
3280 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3286 /// @TODO move to top of file or somewhere better
3287 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3288 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3290 function api_fr_photos_list($type) {
3291 if (api_user() === false) {
3292 throw new ForbiddenException();
3295 $r = q("SELECT `resource-id`, MAX(`scale`) AS `scale`, `album`, `filename`, `type`
3297 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
3298 intval(local_user())
3301 'image/jpeg' => 'jpg',
3302 'image/png' => 'png',
3303 'image/gif' => 'gif'
3305 $data = array('photo' => array());
3306 if (dbm::is_result($r)) {
3307 foreach ($r as $rr) {
3309 $photo['id'] = $rr['resource-id'];
3310 $photo['album'] = $rr['album'];
3311 $photo['filename'] = $rr['filename'];
3312 $photo['type'] = $rr['type'];
3313 $thumb = App::get_baseurl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3315 if ($type == "xml") {
3316 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3318 $photo['thumb'] = $thumb;
3319 $data['photo'][] = $photo;
3323 return api_format_data("photos", $type, $data);
3326 function api_fr_photo_detail($type) {
3327 if (api_user() === false) {
3328 throw new ForbiddenException();
3329 } elseif (!x($_REQUEST, 'photo_id')) {
3330 throw new BadRequestException("No photo id.");
3333 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3334 $scale_sql = ($scale === false ? "" : sprintf("AND `scale`=%d",intval($scale)));
3335 $data_sql = ($scale === false ? "" : "ANY_VALUE(`data`) AS data`,");
3337 $r = q("SELECT %s ANY_VALUE(`resource-id`) AS `resource-id`, ANY_VALUE(`created`) AS `created`,
3338 ANY_VALUE(`edited`) AS `edited`, ANY_VALUE(`title`) AS `title`, ANY_VALUE(`desc`) AS `desc`,
3339 ANY_VALUE(`album`) AS `album`, ANY_VALUE(`filename`) AS `filename`, ANY_VALUE(`type`) AS `type`,
3340 ANY_VALUE(`height`) AS `height`, ANY_VALUE(`width`) AS `width`, ANY_VALUE(`datasize`) AS `datasize`,
3341 ANY_VALUE(`profile`) AS `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
3342 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s",
3344 intval(local_user()),
3345 dbesc($_REQUEST['photo_id']),
3350 'image/jpeg' => 'jpg',
3351 'image/png' => 'png',
3352 'image/gif' => 'gif'
3355 if (dbm::is_result($r)) {
3356 $data = array('photo' => $r[0]);
3357 $data['photo']['id'] = $data['photo']['resource-id'];
3358 if ($scale !== false) {
3359 $data['photo']['data'] = base64_encode($data['photo']['data']);
3361 unset($data['photo']['datasize']); //needed only with scale param
3363 if ($type == "xml") {
3364 $data['photo']['links'] = array();
3365 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3366 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
3368 "href" => App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
3371 $data['photo']['link'] = array();
3372 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3373 $data['photo']['link'][$k] = App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3376 unset($data['photo']['resource-id']);
3377 unset($data['photo']['minscale']);
3378 unset($data['photo']['maxscale']);
3381 throw new NotFoundException();
3384 return api_format_data("photo_detail", $type, $data);
3387 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3388 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3393 * similar as /mod/redir.php
3394 * redirect to 'url' after dfrn auth
3396 * why this when there is mod/redir.php already?
3397 * This use api_user() and api_login()
3400 * c_url: url of remote contact to auth to
3401 * url: string, url to redirect after auth
3403 function api_friendica_remoteauth() {
3404 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
3405 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
3407 if ($url === '' || $c_url === '') {
3408 throw new BadRequestException("Wrong parameters.");
3411 $c_url = normalise_link($c_url);
3415 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3420 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
3421 throw new BadRequestException("Unknown contact");
3426 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3428 if ($r[0]['duplex'] && $r[0]['issued-id']) {
3429 $orig_id = $r[0]['issued-id'];
3430 $dfrn_id = '1:' . $orig_id;
3432 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3433 $orig_id = $r[0]['dfrn-id'];
3434 $dfrn_id = '0:' . $orig_id;
3437 $sec = random_string();
3439 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3440 VALUES( %d, %s, '%s', '%s', %d )",
3448 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3449 $dest = (($url) ? '&destination_url=' . $url : '');
3450 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3451 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3452 . '&type=profile&sec=' . $sec . $dest . $quiet );
3454 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3457 * @brief Return the item shared, if the item contains only the [share] tag
3459 * @param array $item Sharer item
3460 * @return array Shared item or false if not a reshare
3462 function api_share_as_retweet(&$item) {
3463 $body = trim($item["body"]);
3465 if (Diaspora::is_reshare($body, false)===false) {
3469 /// @TODO "$1" should maybe mean '$1' ?
3470 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3472 * Skip if there is no shared message in there
3473 * we already checked this in diaspora::is_reshare()
3474 * but better one more than one less...
3476 if ($body == $attributes) {
3481 // build the fake reshared item
3482 $reshared_item = $item;
3485 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3486 if ($matches[1] != "") {
3487 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
3490 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3491 if ($matches[1] != "") {
3492 $author = $matches[1];
3496 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3497 if ($matches[1] != "") {
3498 $profile = $matches[1];
3501 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3502 if ($matches[1] != "") {
3503 $profile = $matches[1];
3507 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3508 if ($matches[1] != "") {
3509 $avatar = $matches[1];
3512 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3513 if ($matches[1] != "") {
3514 $avatar = $matches[1];
3518 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3519 if ($matches[1] != "") {
3520 $link = $matches[1];
3523 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3524 if ($matches[1] != "") {
3525 $link = $matches[1];
3529 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3530 if ($matches[1] != "")
3531 $posted = $matches[1];
3533 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3534 if ($matches[1] != "") {
3535 $posted = $matches[1];
3538 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3540 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
3544 $reshared_item["body"] = $shared_body;
3545 $reshared_item["author-name"] = $author;
3546 $reshared_item["author-link"] = $profile;
3547 $reshared_item["author-avatar"] = $avatar;
3548 $reshared_item["plink"] = $link;
3549 $reshared_item["created"] = $posted;
3550 $reshared_item["edited"] = $posted;
3552 return $reshared_item;
3556 function api_get_nick($profile) {
3558 - remove trailing junk from profile url
3559 - pump.io check has to check the website
3564 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3565 dbesc(normalise_link($profile)));
3567 if (dbm::is_result($r)) {
3568 $nick = $r[0]["nick"];
3572 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3573 dbesc(normalise_link($profile)));
3575 if (dbm::is_result($r)) {
3576 $nick = $r[0]["nick"];
3581 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3582 if ($friendica != $profile) {
3588 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3589 if ($diaspora != $profile) {
3595 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3596 if ($twitter != $profile) {
3603 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3604 if ($StatusnetHost != $profile) {
3605 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3606 if ($StatusnetUser != $profile) {
3607 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3608 $user = json_decode($UserData);
3610 $nick = $user->screen_name;
3616 // To-Do: look at the page if its really a pumpio site
3617 //if (!$nick == "") {
3618 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3619 // if ($pumpio != $profile)
3621 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3632 function api_in_reply_to($item) {
3633 $in_reply_to = array();
3635 $in_reply_to['status_id'] = NULL;
3636 $in_reply_to['user_id'] = NULL;
3637 $in_reply_to['status_id_str'] = NULL;
3638 $in_reply_to['user_id_str'] = NULL;
3639 $in_reply_to['screen_name'] = NULL;
3641 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
3642 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
3643 intval($item['uid']),
3644 dbesc($item['thr-parent']));
3646 if (dbm::is_result($r)) {
3647 $in_reply_to['status_id'] = intval($r[0]['id']);
3649 $in_reply_to['status_id'] = intval($item['parent']);
3652 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3654 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
3655 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
3656 WHERE `item`.`id` = %d LIMIT 1",
3657 intval($in_reply_to['status_id'])
3660 if (dbm::is_result($r)) {
3661 if ($r[0]['nick'] == "") {
3662 $r[0]['nick'] = api_get_nick($r[0]["url"]);
3665 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
3666 $in_reply_to['user_id'] = intval($r[0]['id']);
3667 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
3670 // There seems to be situation, where both fields are identical:
3671 // https://github.com/friendica/friendica/issues/1010
3672 // This is a bugfix for that.
3673 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3674 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
3675 $in_reply_to['status_id'] = NULL;
3676 $in_reply_to['user_id'] = NULL;
3677 $in_reply_to['status_id_str'] = NULL;
3678 $in_reply_to['user_id_str'] = NULL;
3679 $in_reply_to['screen_name'] = NULL;
3683 return $in_reply_to;
3686 function api_clean_plain_items($Text) {
3687 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
3689 $Text = bb_CleanPictureLinks($Text);
3690 $URLSearchString = "^\[\]";
3692 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3694 if ($include_entities == "true") {
3695 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3698 // Simplify "attachment" element
3699 $Text = api_clean_attachments($Text);
3705 * @brief Removes most sharing information for API text export
3707 * @param string $body The original body
3709 * @return string Cleaned body
3711 function api_clean_attachments($body) {
3712 $data = get_attachment_data($body);
3719 if (isset($data["text"]))
3720 $body = $data["text"];
3722 if (($body == "") AND (isset($data["title"])))
3723 $body = $data["title"];
3725 if (isset($data["url"]))
3726 $body .= "\n".$data["url"];
3728 $body .= $data["after"];
3733 function api_best_nickname(&$contacts) {
3734 $best_contact = array();
3736 if (count($contact) == 0)
3739 foreach ($contacts AS $contact)
3740 if ($contact["network"] == "") {
3741 $contact["network"] = "dfrn";
3742 $best_contact = array($contact);
3745 if (sizeof($best_contact) == 0)
3746 foreach ($contacts AS $contact)
3747 if ($contact["network"] == "dfrn")
3748 $best_contact = array($contact);
3750 if (sizeof($best_contact) == 0)
3751 foreach ($contacts AS $contact)
3752 if ($contact["network"] == "dspr")
3753 $best_contact = array($contact);
3755 if (sizeof($best_contact) == 0)
3756 foreach ($contacts AS $contact)
3757 if ($contact["network"] == "stat")
3758 $best_contact = array($contact);
3760 if (sizeof($best_contact) == 0)
3761 foreach ($contacts AS $contact)
3762 if ($contact["network"] == "pump")
3763 $best_contact = array($contact);
3765 if (sizeof($best_contact) == 0)
3766 foreach ($contacts AS $contact)
3767 if ($contact["network"] == "twit")
3768 $best_contact = array($contact);
3770 if (sizeof($best_contact) == 1)
3771 $contacts = $best_contact;
3773 $contacts = array($contacts[0]);
3776 // return all or a specified group of the user with the containing contacts
3777 function api_friendica_group_show($type) {
3781 if (api_user() === false) throw new ForbiddenException();
3784 $user_info = api_get_user($a);
3785 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3786 $uid = $user_info['uid'];
3788 // get data of the specified group id or all groups if not specified
3790 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3793 // error message if specified gid is not in database
3794 if (!dbm::is_result($r))
3795 throw new BadRequestException("gid not available");
3798 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3801 // loop through all groups and retrieve all members for adding data in the user array
3802 foreach ($r as $rr) {
3803 $members = group_get_members($rr['id']);
3806 if ($type == "xml") {
3807 $user_element = "users";
3809 foreach ($members as $member) {
3810 $user = api_get_user($a, $member['nurl']);
3811 $users[$k++.":user"] = $user;
3814 $user_element = "user";
3815 foreach ($members as $member) {
3816 $user = api_get_user($a, $member['nurl']);
3820 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3822 return api_format_data("groups", $type, array('group' => $grps));
3824 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3827 // delete the specified group of the user
3828 function api_friendica_group_delete($type) {
3832 if (api_user() === false) throw new ForbiddenException();
3835 $user_info = api_get_user($a);
3836 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3837 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3838 $uid = $user_info['uid'];
3840 // error if no gid specified
3841 if ($gid == 0 || $name == "")
3842 throw new BadRequestException('gid or name not specified');
3844 // get data of the specified group id
3845 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3848 // error message if specified gid is not in database
3849 if (!dbm::is_result($r))
3850 throw new BadRequestException('gid not available');
3852 // get data of the specified group id and group name
3853 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3857 // error message if specified gid is not in database
3858 if (!dbm::is_result($rname))
3859 throw new BadRequestException('wrong group name');
3862 $ret = group_rmv($uid, $name);
3865 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3866 return api_format_data("group_delete", $type, array('result' => $success));
3869 throw new BadRequestException('other API error');
3871 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3874 // create the specified group with the posted array of contacts
3875 function api_friendica_group_create($type) {
3879 if (api_user() === false) throw new ForbiddenException();
3882 $user_info = api_get_user($a);
3883 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3884 $uid = $user_info['uid'];
3885 $json = json_decode($_POST['json'], true);
3886 $users = $json['user'];
3888 // error if no name specified
3890 throw new BadRequestException('group name not specified');
3892 // get data of the specified group name
3893 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3896 // error message if specified group name already exists
3897 if (dbm::is_result($rname))
3898 throw new BadRequestException('group name already exists');
3900 // check if specified group name is a deleted group
3901 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3904 // error message if specified group name already exists
3905 if (dbm::is_result($rname))
3906 $reactivate_group = true;
3909 $ret = group_add($uid, $name);
3911 $gid = group_byname($uid, $name);
3913 throw new BadRequestException('other API error');
3916 $erroraddinguser = false;
3917 $errorusers = array();
3918 foreach ($users as $user) {
3919 $cid = $user['cid'];
3920 // check if user really exists as contact
3921 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3924 if (count($contact))
3925 $result = group_add_member($uid, $name, $cid, $gid);
3927 $erroraddinguser = true;
3928 $errorusers[] = $cid;
3932 // return success message incl. missing users in array
3933 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3934 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3935 return api_format_data("group_create", $type, array('result' => $success));
3937 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3940 // update the specified group with the posted array of contacts
3941 function api_friendica_group_update($type) {
3945 if (api_user() === false) throw new ForbiddenException();
3948 $user_info = api_get_user($a);
3949 $uid = $user_info['uid'];
3950 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3951 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3952 $json = json_decode($_POST['json'], true);
3953 $users = $json['user'];
3955 // error if no name specified
3957 throw new BadRequestException('group name not specified');
3959 // error if no gid specified
3961 throw new BadRequestException('gid not specified');
3964 $members = group_get_members($gid);
3965 foreach ($members as $member) {
3966 $cid = $member['id'];
3967 foreach ($users as $user) {
3968 $found = ($user['cid'] == $cid ? true : false);
3971 $ret = group_rmv_member($uid, $name, $cid);
3976 $erroraddinguser = false;
3977 $errorusers = array();
3978 foreach ($users as $user) {
3979 $cid = $user['cid'];
3980 // check if user really exists as contact
3981 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3984 if (count($contact))
3985 $result = group_add_member($uid, $name, $cid, $gid);
3987 $erroraddinguser = true;
3988 $errorusers[] = $cid;
3992 // return success message incl. missing users in array
3993 $status = ($erroraddinguser ? "missing user" : "ok");
3994 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3995 return api_format_data("group_update", $type, array('result' => $success));
3998 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4000 function api_friendica_activity($type) {
4004 if (api_user() === false) throw new ForbiddenException();
4005 $verb = strtolower($a->argv[3]);
4006 $verb = preg_replace("|\..*$|", "", $verb);
4008 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4010 $res = do_like($id, $verb);
4017 return api_format_data('ok', $type, array('ok' => $ok));
4019 throw new BadRequestException('Error adding activity');
4024 /// @TODO move to top of file or somwhere better
4025 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4026 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4027 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4028 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4029 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4030 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4031 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4032 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4033 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4034 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4037 * @brief Returns notifications
4039 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4042 function api_friendica_notification($type) {
4046 if (api_user() === false) throw new ForbiddenException();
4047 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4048 $nm = new NotificationsManager();
4050 $notes = $nm->getAll(array(), "+seen -date", 50);
4052 if ($type == "xml") {
4053 $xmlnotes = array();
4054 foreach ($notes AS $note)
4055 $xmlnotes[] = array("@attributes" => $note);
4060 return api_format_data("notes", $type, array('note' => $notes));
4064 * @brief Set notification as seen and returns associated item (if possible)
4066 * POST request with 'id' param as notification id
4068 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4071 function api_friendica_notification_seen($type) {
4075 if (api_user() === false) throw new ForbiddenException();
4076 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4078 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4080 $nm = new NotificationsManager();
4081 $note = $nm->getByID($id);
4082 if (is_null($note)) throw new BadRequestException("Invalid argument");
4084 $nm->setSeen($note);
4085 if ($note['otype']=='item') {
4086 // would be really better with an ItemsManager and $im->getByID() :-P
4087 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4088 intval($note['iid']),
4089 intval(local_user())
4092 // we found the item, return it to the user
4093 $user_info = api_get_user($a);
4094 $ret = api_format_items($r,$user_info, false, $type);
4095 $data = array('status' => $ret);
4096 return api_format_data("status", $type, $data);
4098 // the item can't be found, but we set the note as seen, so we count this as a success
4100 return api_format_data('result', $type, array('result' => "success"));
4103 /// @TODO move to top of file or somwhere better
4104 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4105 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4108 * @brief update a direct_message to seen state
4110 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4111 * @return string (success result=ok, error result=error with error message)
4113 function api_friendica_direct_messages_setseen($type) {
4115 if (api_user() === false) {
4116 throw new ForbiddenException();
4120 $user_info = api_get_user($a);
4121 $uid = $user_info['uid'];
4122 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4124 // return error if id is zero
4126 $answer = array('result' => 'error', 'message' => 'message id not specified');
4127 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4130 // get data of the specified message id
4131 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4135 // error message if specified id is not in database
4136 if (!dbm::is_result($r)) {
4137 $answer = array('result' => 'error', 'message' => 'message id not in database');
4138 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4141 // update seen indicator
4142 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4148 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4149 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4151 $answer = array('result' => 'error', 'message' => 'unknown error');
4152 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4156 /// @TODO move to top of file or somwhere better
4157 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4160 * @brief search for direct_messages containing a searchstring through api
4162 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4163 * @return string (success: success=true if found and search_result contains found messages
4164 * success=false if nothing was found, search_result='nothing found',
4165 * error: result=error with error message)
4167 function api_friendica_direct_messages_search($type) {
4170 if (api_user() === false) {
4171 throw new ForbiddenException();
4175 $user_info = api_get_user($a);
4176 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4177 $uid = $user_info['uid'];
4179 // error if no searchstring specified
4180 if ($searchstring == "") {
4181 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4182 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4185 // get data for the specified searchstring
4186 $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",
4188 dbesc('%'.$searchstring.'%')
4191 $profile_url = $user_info["url"];
4193 // message if nothing was found
4194 if (!dbm::is_result($r)) {
4195 $success = array('success' => false, 'search_results' => 'problem with query');
4196 } elseif (count($r) == 0) {
4197 $success = array('success' => false, 'search_results' => 'nothing found');
4200 foreach ($r as $item) {
4201 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4202 $recipient = $user_info;
4203 $sender = api_get_user($a,normalise_link($item['contact-url']));
4204 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4205 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4206 $sender = $user_info;
4209 $ret[] = api_format_messages($item, $recipient, $sender);
4211 $success = array('success' => true, 'search_results' => $ret);
4214 return api_format_data("direct_message_search", $type, array('$result' => $success));
4217 /// @TODO move to top of file or somwhere better
4218 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4221 * @brief return data of all the profiles a user has to the client
4223 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4226 function api_friendica_profile_show($type) {
4229 if (api_user() === false) {
4230 throw new ForbiddenException();
4234 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4236 // retrieve general information about profiles for user
4237 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4238 $directory = get_config('system', 'directory');
4240 // get data of the specified profile id or all profiles of the user if not specified
4241 if ($profileid != 0) {
4242 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4244 intval($profileid));
4246 // error message if specified gid is not in database
4247 if (!dbm::is_result($r)) {
4248 throw new BadRequestException("profile_id not available");
4251 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4252 intval(api_user()));
4254 // loop through all returned profiles and retrieve data and users
4256 foreach ($r as $rr) {
4257 $profile = api_format_items_profiles($rr, $type);
4259 // select all users from contact table, loop and prepare standard return for user data
4261 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4263 intval($rr['profile_id']));
4265 foreach ($r as $rr) {
4266 $user = api_get_user($a, $rr['nurl']);
4267 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4269 $profile['users'] = $users;
4271 // add prepared profile data to array for final return
4272 if ($type == "xml") {
4273 $profiles[$k++ . ":profile"] = $profile;
4275 $profiles[] = $profile;
4279 // return settings, authenticated user and profiles data
4280 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4282 $result = array('multi_profiles' => $multi_profiles ? true : false,
4283 'global_dir' => $directory,
4284 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4285 'profiles' => $profiles);
4286 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4288 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4291 @TODO Maybe open to implement?
4293 [pagename] => api/1.1/statuses/lookup.json
4294 [id] => 605138389168451584
4295 [include_cards] => true
4296 [cards_platform] => Android-12
4297 [include_entities] => true
4298 [include_my_retweet] => 1
4300 [include_reply_count] => true
4301 [include_descendent_reply_count] => true
4305 Not implemented by now:
4306 statuses/retweets_of_me
4311 account/update_location
4312 account/update_profile_background_image
4313 account/update_profile_image
4316 friendica/profile/update
4317 friendica/profile/create
4318 friendica/profile/delete
4320 Not implemented in status.net:
4321 statuses/retweeted_to_me
4322 statuses/retweeted_by_me
4323 direct_messages/destroy
4325 account/update_delivery_device
4326 notifications/follow