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\System;
11 use Friendica\Core\Config;
13 require_once 'include/HTTPExceptions.php';
14 require_once 'include/bbcode.php';
15 require_once 'include/datetime.php';
16 require_once 'include/conversation.php';
17 require_once 'include/oauth.php';
18 require_once 'include/html2plain.php';
19 require_once 'mod/share.php';
20 require_once 'include/Photo.php';
21 require_once 'mod/item.php';
22 require_once 'include/security.php';
23 require_once 'include/contact_selectors.php';
24 require_once 'include/html2bbcode.php';
25 require_once 'mod/wall_upload.php';
26 require_once 'mod/proxy.php';
27 require_once 'include/message.php';
28 require_once 'include/group.php';
29 require_once 'include/like.php';
30 require_once 'include/NotificationsManager.php';
31 require_once 'include/plaintext.php';
32 require_once 'include/xml.php';
34 define('API_METHOD_ANY', '*');
35 define('API_METHOD_GET', 'GET');
36 define('API_METHOD_POST', 'POST,PUT');
37 define('API_METHOD_DELETE', 'POST,DELETE');
42 /// @TODO Fix intending
44 * @brief Auth API user
46 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
47 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
48 * into a page, and visitors will post something without noticing it).
51 if (x($_SESSION, 'allow_api')) {
59 * @brief Get source name from API client
61 * Clients can send 'source' parameter to be show in post metadata
62 * as "sent via <source>".
63 * Some clients doesn't send a source param, we support ones we know
67 * Client source name, default to "api" if unset/unknown
69 function api_source() {
70 if (requestdata('source')) {
71 return requestdata('source');
74 // Support for known clients that doesn't send a source name
75 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
79 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
85 * @brief Format date for API
87 * @param string $str Source date, as UTC
88 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
90 function api_date($str) {
91 // Wed May 23 06:01:13 +0000 2007
92 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
96 * @brief Register API endpoint
98 * Register a function to be the endpont for defined API path.
100 * @param string $path API URL path, relative to System::baseUrl()
101 * @param string $func Function name to call on path request
102 * @param bool $auth API need logged user
103 * @param string $method HTTP method reqiured to call this endpoint.
105 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
106 * Default to API_METHOD_ANY
108 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
117 // Workaround for hotot
118 $path = str_replace("api/", "api/1.1/", $path);
128 * @brief Login API user
130 * Log in user via OAuth1 or Simple HTTP Auth.
131 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
134 * @hook 'authenticate'
136 * 'username' => username from login form
137 * 'password' => password from login form
138 * 'authenticated' => return status,
139 * 'user_record' => return authenticated user record
141 * array $user logged user record
143 function api_login(App $a) {
146 $oauth = new FKOAuth1();
147 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
148 if (!is_null($token)) {
149 $oauth->loginUser($token->uid);
150 call_hooks('logged_in', $a->user);
153 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
154 var_dump($consumer, $token);
156 } catch (Exception $e) {
160 // workaround for HTTP-auth in CGI mode
161 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
162 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
163 if (strlen($userpass)) {
164 list($name, $password) = explode(':', $userpass);
165 $_SERVER['PHP_AUTH_USER'] = $name;
166 $_SERVER['PHP_AUTH_PW'] = $password;
170 if (!x($_SERVER, 'PHP_AUTH_USER')) {
171 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
172 header('WWW-Authenticate: Basic realm="Friendica"');
173 throw new UnauthorizedException("This API requires login");
176 $user = $_SERVER['PHP_AUTH_USER'];
177 $password = $_SERVER['PHP_AUTH_PW'];
178 $encrypted = hash('whirlpool', trim($password));
180 // allow "user@server" login (but ignore 'server' part)
181 $at = strstr($user, "@", true);
186 // next code from mod/auth.php. needs better solution
190 'username' => trim($user),
191 'password' => trim($password),
192 'authenticated' => 0,
193 'user_record' => null,
197 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
198 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
199 * and later plugins should not interfere with an earlier one that succeeded.
201 call_hooks('authenticate', $addon_auth);
203 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
204 $record = $addon_auth['user_record'];
206 // process normal login request
207 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
208 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
213 if (dbm::is_result($r)) {
218 if ((! $record) || (! count($record))) {
219 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
220 header('WWW-Authenticate: Basic realm="Friendica"');
221 //header('HTTP/1.0 401 Unauthorized');
222 //die('This api requires login');
223 throw new UnauthorizedException("This API requires login");
226 authenticate_success($record);
228 $_SESSION["allow_api"] = true;
230 call_hooks('logged_in', $a->user);
235 * @brief Check HTTP method of called API
237 * API endpoints can define which HTTP method to accept when called.
238 * This function check the current HTTP method agains endpoint
241 * @param string $method Required methods, uppercase, separated by comma
244 function api_check_method($method) {
245 if ($method == "*") {
248 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
252 * @brief Main API entry point
254 * Authenticate user, call registered API function, set HTTP headers
257 * @return string API call result
259 function api_call(App $a) {
260 global $API, $called_api;
263 if (strpos($a->query_string, ".xml") > 0) {
266 if (strpos($a->query_string, ".json") > 0) {
269 if (strpos($a->query_string, ".rss") > 0) {
272 if (strpos($a->query_string, ".atom") > 0) {
277 foreach ($API as $p => $info) {
278 if (strpos($a->query_string, $p) === 0) {
279 if (!api_check_method($info['method'])) {
280 throw new MethodNotAllowedException();
283 $called_api = explode("/", $p);
284 //unset($_SERVER['PHP_AUTH_USER']);
286 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
287 if ($info['auth'] === true && api_user() === false) {
291 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
292 logger('API parameters: ' . print_r($_REQUEST, true));
294 $stamp = microtime(true);
295 $r = call_user_func($info['func'], $type);
296 $duration = (float) (microtime(true) - $stamp);
297 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
299 if (get_config("system", "profiler")) {
300 $duration = microtime(true)-$a->performance["start"];
302 /// @TODO round() really everywhere?
303 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
304 round($a->performance["database"] - $a->performance["database_write"], 3),
305 round($a->performance["database_write"], 3),
306 round($a->performance["network"], 2),
307 round($a->performance["file"], 2),
308 round($duration - ($a->performance["database"] + $a->performance["network"]
309 + $a->performance["file"]), 2),
310 round($duration, 2)),
314 if (get_config("rendertime", "callstack")) {
315 $o = "Database Read:\n";
316 foreach ($a->callstack["database"] AS $func => $time) {
317 $time = round($time, 3);
319 $o .= $func . ": " . $time . "\n";
322 $o .= "\nDatabase Write:\n";
323 foreach ($a->callstack["database_write"] AS $func => $time) {
324 $time = round($time, 3);
326 $o .= $func . ": " . $time . "\n";
330 $o .= "\nNetwork:\n";
331 foreach ($a->callstack["network"] AS $func => $time) {
332 $time = round($time, 3);
334 $o .= $func . ": " . $time . "\n";
337 logger($o, LOGGER_DEBUG);
343 * api function returned false withour throw an
344 * exception. This should not happend, throw a 500
346 throw new InternalServerErrorException();
351 header ("Content-Type: text/xml");
355 header ("Content-Type: application/json");
357 $json = json_encode($rr);
358 if (x($_GET, 'callback')) {
359 $json = $_GET['callback'] . "(" . $json . ")";
364 header ("Content-Type: application/rss+xml");
365 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
368 header ("Content-Type: application/atom+xml");
369 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
375 logger('API call not implemented: ' . $a->query_string);
376 throw new NotImplementedException();
377 } catch (HTTPException $e) {
378 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
379 return api_error($type, $e);
384 * @brief Format API error string
386 * @param string $type Return type (xml, json, rss, as)
387 * @param HTTPException $error Error object
388 * @return strin error message formatted as $type
390 function api_error($type, $e) {
394 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
395 /// @TODO: https://dev.twitter.com/overview/api/response-codes
397 $error = array("error" => $error,
398 "code" => $e->httpcode . " " . $e->httpdesc,
399 "request" => $a->query_string);
401 $ret = api_format_data('status', $type, array('status' => $error));
405 header ("Content-Type: text/xml");
409 header ("Content-Type: application/json");
410 return json_encode($ret);
413 header ("Content-Type: application/rss+xml");
417 header ("Content-Type: application/atom+xml");
424 * @brief Set values for RSS template
427 * @param array $arr Array to be passed to template
428 * @param array $user_info
430 * @todo find proper type-hints
432 function api_rss_extra(App $a, $arr, $user_info) {
433 if (is_null($user_info)) {
434 $user_info = api_get_user($a);
437 $arr['$user'] = $user_info;
438 $arr['$rss'] = array(
439 'alternate' => $user_info['url'],
440 'self' => System::baseUrl() . "/" . $a->query_string,
441 'base' => System::baseUrl(),
442 'updated' => api_date(null),
443 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
444 'language' => $user_info['language'],
445 'logo' => System::baseUrl() . "/images/friendica-32.png",
453 * @brief Unique contact to contact url.
455 * @param int $id Contact id
456 * @return bool|string
457 * Contact url or False if contact id is unknown
459 function api_unique_id_to_url($id) {
460 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
462 if (dbm::is_result($r)) {
470 * @brief Get user info array.
473 * @param int|string $contact_id Contact ID or URL
474 * @param string $type Return type (for errors)
476 function api_get_user(App $a, $contact_id = null, $type = "json") {
484 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
486 // Searching for contact URL
487 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
488 $user = dbesc(normalise_link($contact_id));
490 $extra_query = "AND `contact`.`nurl` = '%s' ";
491 if (api_user() !== false) {
492 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
496 // Searching for contact id with uid = 0
497 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
498 $user = dbesc(api_unique_id_to_url($contact_id));
501 throw new BadRequestException("User not found.");
505 $extra_query = "AND `contact`.`nurl` = '%s' ";
506 if (api_user() !== false) {
507 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
511 if (is_null($user) && x($_GET, 'user_id')) {
512 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
515 throw new BadRequestException("User not found.");
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 if (is_null($user) && x($_GET, 'screen_name')) {
525 $user = dbesc($_GET['screen_name']);
527 $extra_query = "AND `contact`.`nick` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
533 if (is_null($user) && x($_GET, 'profileurl')) {
534 $user = dbesc(normalise_link($_GET['profileurl']));
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
542 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
543 $argid = count($called_api);
544 list($user, $null) = explode(".", $a->argv[$argid]);
545 if (is_numeric($user)) {
546 $user = dbesc(api_unique_id_to_url($user));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
558 $user = dbesc($user);
560 $extra_query = "AND `contact`.`nick` = '%s' ";
561 if (api_user() !== false) {
562 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 logger("api_get_user: user ".$user, LOGGER_DEBUG);
570 if (api_user() === false) {
574 $user = $_SESSION['uid'];
575 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
580 logger('api_user: ' . $extra_query . ', user: ' . $user);
583 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
589 // Selecting the id by priority, friendica first
590 api_best_nickname($uinfo);
592 // if the contact wasn't found, fetch it from the contacts with uid = 0
593 if (!dbm::is_result($uinfo)) {
597 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
600 if (dbm::is_result($r)) {
601 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
603 // If no nick where given, extract it from the address
604 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
605 $r[0]['nick'] = api_get_nick($r[0]["url"]);
610 'id_str' => (string) $r[0]["id"],
611 'name' => $r[0]["name"],
612 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
613 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
614 'description' => $r[0]["about"],
615 'profile_image_url' => $r[0]["micro"],
616 'profile_image_url_https' => $r[0]["micro"],
617 'url' => $r[0]["url"],
618 'protected' => false,
619 'followers_count' => 0,
620 'friends_count' => 0,
622 'created_at' => api_date($r[0]["created"]),
623 'favourites_count' => 0,
625 'time_zone' => 'UTC',
626 'geo_enabled' => false,
628 'statuses_count' => 0,
630 'contributors_enabled' => false,
631 'is_translator' => false,
632 'is_translation_enabled' => false,
633 'following' => false,
634 'follow_request_sent' => false,
635 'statusnet_blocking' => false,
636 'notifications' => false,
637 'statusnet_profile_url' => $r[0]["url"],
639 'cid' => get_contact($r[0]["url"], api_user(), true),
641 'network' => $r[0]["network"],
646 throw new BadRequestException("User not found.");
650 if ($uinfo[0]['self']) {
652 if ($uinfo[0]['network'] == "") {
653 $uinfo[0]['network'] = NETWORK_DFRN;
656 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
659 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
663 /// @TODO old-lost code? (twice)
664 // Counting is deactivated by now, due to performance issues
665 // count public wall messages
666 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
667 // intval($uinfo[0]['uid'])
669 //$countitms = $r[0]['count'];
672 // Counting is deactivated by now, due to performance issues
673 //$r = q("SELECT count(*) as `count` FROM `item`
674 // WHERE `contact-id` = %d",
675 // intval($uinfo[0]['id'])
677 //$countitms = $r[0]['count'];
681 /// @TODO old-lost code? (twice)
683 // Counting is deactivated by now, due to performance issues
685 $r = q("SELECT count(*) as `count` FROM `contact`
686 WHERE `uid` = %d AND `rel` IN ( %d, %d )
687 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
688 intval($uinfo[0]['uid']),
689 intval(CONTACT_IS_SHARING),
690 intval(CONTACT_IS_FRIEND)
692 $countfriends = $r[0]['count'];
694 $r = q("SELECT count(*) as `count` FROM `contact`
695 WHERE `uid` = %d AND `rel` IN ( %d, %d )
696 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
697 intval($uinfo[0]['uid']),
698 intval(CONTACT_IS_FOLLOWER),
699 intval(CONTACT_IS_FRIEND)
701 $countfollowers = $r[0]['count'];
703 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
704 intval($uinfo[0]['uid'])
706 $starred = $r[0]['count'];
709 if (! $uinfo[0]['self']) {
719 // Add a nick if it isn't present there
720 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
721 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
724 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
726 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
729 'id' => intval($pcontact_id),
730 'id_str' => (string) intval($pcontact_id),
731 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
732 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
733 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
734 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
735 'profile_image_url' => $uinfo[0]['micro'],
736 'profile_image_url_https' => $uinfo[0]['micro'],
737 'url' => $uinfo[0]['url'],
738 'protected' => false,
739 'followers_count' => intval($countfollowers),
740 'friends_count' => intval($countfriends),
742 'created_at' => api_date($uinfo[0]['created']),
743 'favourites_count' => intval($starred),
745 'time_zone' => 'UTC',
746 'geo_enabled' => false,
748 'statuses_count' => intval($countitms),
750 'contributors_enabled' => false,
751 'is_translator' => false,
752 'is_translation_enabled' => false,
753 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
754 'follow_request_sent' => false,
755 'statusnet_blocking' => false,
756 'notifications' => false,
758 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
759 'statusnet_profile_url' => $uinfo[0]['url'],
760 'uid' => intval($uinfo[0]['uid']),
761 'cid' => intval($uinfo[0]['cid']),
762 'self' => $uinfo[0]['self'],
763 'network' => $uinfo[0]['network'],
771 * @brief return api-formatted array for item's author and owner
774 * @param array $item : item from db
775 * @return array(array:author, array:owner)
777 function api_item_get_user(App $a, $item) {
779 $status_user = api_get_user($a, $item["author-link"]);
781 $status_user["protected"] = (($item["allow_cid"] != "") ||
782 ($item["allow_gid"] != "") ||
783 ($item["deny_cid"] != "") ||
784 ($item["deny_gid"] != "") ||
787 if ($item['thr-parent'] == $item['uri']) {
788 $owner_user = api_get_user($a, $item["owner-link"]);
790 $owner_user = $status_user;
793 return (array($status_user, $owner_user));
797 * @brief walks recursively through an array with the possibility to change value and key
799 * @param array $array The array to walk through
800 * @param string $callback The callback function
802 * @return array the transformed array
804 function api_walk_recursive(array &$array, callable $callback) {
806 $new_array = array();
808 foreach ($array as $k => $v) {
810 if ($callback($v, $k)) {
811 $new_array[$k] = api_walk_recursive($v, $callback);
814 if ($callback($v, $k)) {
825 * @brief Callback function to transform the array in an array that can be transformed in a XML file
827 * @param variant $item Array item value
828 * @param string $key Array key
830 * @return boolean Should the array item be deleted?
832 function api_reformat_xml(&$item, &$key) {
833 if (is_bool($item)) {
834 $item = ($item ? "true" : "false");
837 if (substr($key, 0, 10) == "statusnet_") {
838 $key = "statusnet:".substr($key, 10);
839 } elseif (substr($key, 0, 10) == "friendica_") {
840 $key = "friendica:".substr($key, 10);
842 /// @TODO old-lost code?
844 // $key = "default:".$key;
850 * @brief Creates the XML from a JSON style array
852 * @param array $data JSON style array
853 * @param string $root_element Name of the root element
855 * @return string The XML data
857 function api_create_xml($data, $root_element) {
858 $childname = key($data);
859 $data2 = array_pop($data);
862 $namespaces = array("" => "http://api.twitter.com",
863 "statusnet" => "http://status.net/schema/api/1/",
864 "friendica" => "http://friendi.ca/schema/api/1/",
865 "georss" => "http://www.georss.org/georss");
867 /// @todo Auto detection of needed namespaces
868 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
869 $namespaces = array();
872 if (is_array($data2)) {
873 api_walk_recursive($data2, "api_reformat_xml");
880 foreach ($data2 AS $item) {
881 $data4[$i++.":".$childname] = $item;
887 $data3 = array($root_element => $data2);
889 $ret = xml::from_array($data3, $xml, false, $namespaces);
894 * @brief Formats the data according to the data type
896 * @param string $root_element Name of the root element
897 * @param string $type Return type (atom, rss, xml, json)
898 * @param array $data JSON style array
900 * @return (string|object) XML data or JSON data
902 function api_format_data($root_element, $type, $data) {
910 $ret = api_create_xml($data, $root_element);
925 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
926 * returns a 401 status code and an error message if not.
927 * http://developer.twitter.com/doc/get/account/verify_credentials
929 function api_account_verify_credentials($type) {
933 if (api_user() === false) {
934 throw new ForbiddenException();
937 unset($_REQUEST["user_id"]);
938 unset($_GET["user_id"]);
940 unset($_REQUEST["screen_name"]);
941 unset($_GET["screen_name"]);
943 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
945 $user_info = api_get_user($a);
947 // "verified" isn't used here in the standard
948 unset($user_info["verified"]);
950 // - Adding last status
952 $user_info["status"] = api_status_show("raw");
953 if (!count($user_info["status"])) {
954 unset($user_info["status"]);
956 unset($user_info["status"]["user"]);
960 // "uid" and "self" are only needed for some internal stuff, so remove it from here
961 unset($user_info["uid"]);
962 unset($user_info["self"]);
964 return api_format_data("user", $type, array('user' => $user_info));
968 /// @TODO move to top of file or somwhere better
969 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
972 * get data from $_POST or $_GET
974 function requestdata($k) {
984 /*Waitman Gobble Mod*/
985 function api_statuses_mediap($type) {
989 if (api_user() === false) {
990 logger('api_statuses_update: no user');
991 throw new ForbiddenException();
993 $user_info = api_get_user($a);
995 $_REQUEST['type'] = 'wall';
996 $_REQUEST['profile_uid'] = api_user();
997 $_REQUEST['api_source'] = true;
998 $txt = requestdata('status');
999 /// @TODO old-lost code?
1000 //$txt = urldecode(requestdata('status'));
1002 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1004 $txt = html2bb_video($txt);
1005 $config = HTMLPurifier_Config::createDefault();
1006 $config->set('Cache.DefinitionImpl', null);
1007 $purifier = new HTMLPurifier($config);
1008 $txt = $purifier->purify($txt);
1010 $txt = html2bbcode($txt);
1012 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1014 // tell wall_upload function to return img info instead of echo
1015 $_REQUEST['hush'] = 'yeah';
1016 $bebop = wall_upload_post($a);
1018 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1019 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1022 // this should output the last post (the one we just posted).
1023 return api_status_show($type);
1026 /// @TODO move this to top of file or somewhere better!
1027 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1029 function api_statuses_update($type) {
1033 if (api_user() === false) {
1034 logger('api_statuses_update: no user');
1035 throw new ForbiddenException();
1038 $user_info = api_get_user($a);
1040 // convert $_POST array items to the form we use for web posts.
1042 // logger('api_post: ' . print_r($_POST,true));
1044 if (requestdata('htmlstatus')) {
1045 $txt = requestdata('htmlstatus');
1046 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1047 $txt = html2bb_video($txt);
1049 $config = HTMLPurifier_Config::createDefault();
1050 $config->set('Cache.DefinitionImpl', null);
1052 $purifier = new HTMLPurifier($config);
1053 $txt = $purifier->purify($txt);
1055 $_REQUEST['body'] = html2bbcode($txt);
1059 $_REQUEST['body'] = requestdata('status');
1062 $_REQUEST['title'] = requestdata('title');
1064 $parent = requestdata('in_reply_to_status_id');
1066 // Twidere sends "-1" if it is no reply ...
1067 if ($parent == -1) {
1071 if (ctype_digit($parent)) {
1072 $_REQUEST['parent'] = $parent;
1074 $_REQUEST['parent_uri'] = $parent;
1077 if (requestdata('lat') && requestdata('long')) {
1078 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1080 $_REQUEST['profile_uid'] = api_user();
1083 $_REQUEST['type'] = 'net-comment';
1085 // Check for throttling (maximum posts per day, week and month)
1086 $throttle_day = get_config('system','throttle_limit_day');
1087 if ($throttle_day > 0) {
1088 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1090 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1091 AND `created` > '%s' AND `id` = `parent`",
1092 intval(api_user()), dbesc($datefrom));
1094 if (dbm::is_result($r)) {
1095 $posts_day = $r[0]["posts_day"];
1100 if ($posts_day > $throttle_day) {
1101 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1102 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1103 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1107 $throttle_week = get_config('system','throttle_limit_week');
1108 if ($throttle_week > 0) {
1109 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1111 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1112 AND `created` > '%s' AND `id` = `parent`",
1113 intval(api_user()), dbesc($datefrom));
1115 if (dbm::is_result($r)) {
1116 $posts_week = $r[0]["posts_week"];
1121 if ($posts_week > $throttle_week) {
1122 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1123 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1124 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1128 $throttle_month = get_config('system','throttle_limit_month');
1129 if ($throttle_month > 0) {
1130 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1132 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1133 AND `created` > '%s' AND `id` = `parent`",
1134 intval(api_user()), dbesc($datefrom));
1136 if (dbm::is_result($r)) {
1137 $posts_month = $r[0]["posts_month"];
1142 if ($posts_month > $throttle_month) {
1143 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1144 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1145 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1149 $_REQUEST['type'] = 'wall';
1152 if (x($_FILES, 'media')) {
1153 // upload the image if we have one
1154 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1155 $media = wall_upload_post($a);
1156 if (strlen($media) > 0) {
1157 $_REQUEST['body'] .= "\n\n" . $media;
1161 // To-Do: Multiple IDs
1162 if (requestdata('media_ids')) {
1163 $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",
1164 intval(requestdata('media_ids')), api_user());
1165 if (dbm::is_result($r)) {
1166 $phototypes = Photo::supportedTypes();
1167 $ext = $phototypes[$r[0]['type']];
1168 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1169 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1173 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1175 $_REQUEST['api_source'] = true;
1177 if (!x($_REQUEST, "source")) {
1178 $_REQUEST["source"] = api_source();
1181 // call out normal post function
1184 // this should output the last post (the one we just posted).
1185 return api_status_show($type);
1188 /// @TODO move to top of file or somwhere better
1189 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1190 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1192 function api_media_upload($type) {
1196 if (api_user() === false) {
1198 throw new ForbiddenException();
1201 $user_info = api_get_user($a);
1203 if (!x($_FILES, 'media')) {
1205 throw new BadRequestException("No media.");
1208 $media = wall_upload_post($a, false);
1211 throw new InternalServerErrorException();
1214 $returndata = array();
1215 $returndata["media_id"] = $media["id"];
1216 $returndata["media_id_string"] = (string)$media["id"];
1217 $returndata["size"] = $media["size"];
1218 $returndata["image"] = array("w" => $media["width"],
1219 "h" => $media["height"],
1220 "image_type" => $media["type"]);
1222 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1224 return array("media" => $returndata);
1227 /// @TODO move to top of file or somwhere better
1228 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1230 function api_status_show($type) {
1234 $user_info = api_get_user($a);
1236 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1238 if ($type == "raw") {
1239 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1244 // get last public wall message
1245 $lastwall = q("SELECT `item`.*
1247 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1248 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1249 AND `item`.`type` != 'activity' $privacy_sql
1250 ORDER BY `item`.`id` DESC
1252 intval($user_info['cid']),
1254 dbesc($user_info['url']),
1255 dbesc(normalise_link($user_info['url'])),
1256 dbesc($user_info['url']),
1257 dbesc(normalise_link($user_info['url']))
1260 if (dbm::is_result($lastwall)) {
1261 $lastwall = $lastwall[0];
1263 $in_reply_to = api_in_reply_to($lastwall);
1265 $converted = api_convert_item($lastwall);
1267 if ($type == "xml") {
1268 $geo = "georss:point";
1273 $status_info = array(
1274 'created_at' => api_date($lastwall['created']),
1275 'id' => intval($lastwall['id']),
1276 'id_str' => (string) $lastwall['id'],
1277 'text' => $converted["text"],
1278 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1279 'truncated' => false,
1280 'in_reply_to_status_id' => $in_reply_to['status_id'],
1281 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1282 'in_reply_to_user_id' => $in_reply_to['user_id'],
1283 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1284 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1285 'user' => $user_info,
1287 'coordinates' => "",
1289 'contributors' => "",
1290 'is_quote_status' => false,
1291 'retweet_count' => 0,
1292 'favorite_count' => 0,
1293 'favorited' => $lastwall['starred'] ? true : false,
1294 'retweeted' => false,
1295 'possibly_sensitive' => false,
1297 'statusnet_html' => $converted["html"],
1298 'statusnet_conversation_id' => $lastwall['parent'],
1301 if (count($converted["attachments"]) > 0) {
1302 $status_info["attachments"] = $converted["attachments"];
1305 if (count($converted["entities"]) > 0) {
1306 $status_info["entities"] = $converted["entities"];
1309 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1310 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1311 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1312 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1315 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1316 unset($status_info["user"]["uid"]);
1317 unset($status_info["user"]["self"]);
1320 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1322 if ($type == "raw") {
1323 return $status_info;
1326 return api_format_data("statuses", $type, array('status' => $status_info));
1331 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1332 * The author's most recent status will be returned inline.
1333 * http://developer.twitter.com/doc/get/users/show
1335 function api_users_show($type) {
1339 $user_info = api_get_user($a);
1340 $lastwall = q("SELECT `item`.*
1342 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1343 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1344 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1345 AND `type`!='activity'
1346 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1350 dbesc(ACTIVITY_POST),
1351 intval($user_info['cid']),
1352 dbesc($user_info['url']),
1353 dbesc(normalise_link($user_info['url'])),
1354 dbesc($user_info['url']),
1355 dbesc(normalise_link($user_info['url']))
1358 if (dbm::is_result($lastwall)) {
1359 $lastwall = $lastwall[0];
1361 $in_reply_to = api_in_reply_to($lastwall);
1363 $converted = api_convert_item($lastwall);
1365 if ($type == "xml") {
1366 $geo = "georss:point";
1371 $user_info['status'] = array(
1372 'text' => $converted["text"],
1373 'truncated' => false,
1374 'created_at' => api_date($lastwall['created']),
1375 'in_reply_to_status_id' => $in_reply_to['status_id'],
1376 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1377 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1378 'id' => intval($lastwall['contact-id']),
1379 'id_str' => (string) $lastwall['contact-id'],
1380 'in_reply_to_user_id' => $in_reply_to['user_id'],
1381 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1382 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1384 'favorited' => $lastwall['starred'] ? true : false,
1385 'statusnet_html' => $converted["html"],
1386 'statusnet_conversation_id' => $lastwall['parent'],
1389 if (count($converted["attachments"]) > 0) {
1390 $user_info["status"]["attachments"] = $converted["attachments"];
1393 if (count($converted["entities"]) > 0) {
1394 $user_info["status"]["entities"] = $converted["entities"];
1397 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1398 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1401 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1402 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1407 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1408 unset($user_info["uid"]);
1409 unset($user_info["self"]);
1411 return api_format_data("user", $type, array('user' => $user_info));
1415 /// @TODO move to top of file or somewhere better
1416 api_register_func('api/users/show','api_users_show');
1417 api_register_func('api/externalprofile/show','api_users_show');
1419 function api_users_search($type) {
1423 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1425 $userlist = array();
1427 if (x($_GET, 'q')) {
1428 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1430 if (!dbm::is_result($r)) {
1431 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1434 if (dbm::is_result($r)) {
1436 foreach ($r AS $user) {
1437 $user_info = api_get_user($a, $user["id"], "json");
1439 if ($type == "xml") {
1440 $userlist[$k++.":user"] = $user_info;
1442 $userlist[] = $user_info;
1445 $userlist = array("users" => $userlist);
1447 throw new BadRequestException("User not found.");
1450 throw new BadRequestException("User not found.");
1452 return api_format_data("users", $type, $userlist);
1455 /// @TODO move to top of file or somewhere better
1456 api_register_func('api/users/search','api_users_search');
1460 * http://developer.twitter.com/doc/get/statuses/home_timeline
1462 * TODO: Optional parameters
1463 * TODO: Add reply info
1465 function api_statuses_home_timeline($type) {
1469 if (api_user() === false) {
1470 throw new ForbiddenException();
1473 unset($_REQUEST["user_id"]);
1474 unset($_GET["user_id"]);
1476 unset($_REQUEST["screen_name"]);
1477 unset($_GET["screen_name"]);
1479 $user_info = api_get_user($a);
1480 // get last newtork messages
1483 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1484 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1488 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1489 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1490 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1491 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1492 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1494 $start = $page * $count;
1498 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1500 if ($exclude_replies > 0) {
1501 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1503 if ($conversation_id > 0) {
1504 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1507 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1508 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1509 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1510 `contact`.`id` AS `cid`
1512 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1513 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1514 WHERE `item`.`uid` = %d AND `verb` = '%s'
1515 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1518 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1520 dbesc(ACTIVITY_POST),
1522 intval($start), intval($count)
1525 $ret = api_format_items($r, $user_info, false, $type);
1527 // Set all posts from the query above to seen
1529 foreach ($r AS $item) {
1530 $idarray[] = intval($item["id"]);
1533 $idlist = implode(",", $idarray);
1535 if ($idlist != "") {
1536 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1539 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1543 $data = array('status' => $ret);
1547 $data = api_rss_extra($a, $data, $user_info);
1551 return api_format_data("statuses", $type, $data);
1554 /// @TODO move to top of file or somewhere better
1555 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1556 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1558 function api_statuses_public_timeline($type) {
1562 if (api_user() === false) {
1563 throw new ForbiddenException();
1566 $user_info = api_get_user($a);
1567 // get last newtork messages
1570 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1571 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1575 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1576 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1577 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1578 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1579 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1581 $start = $page * $count;
1584 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1586 if ($exclude_replies > 0) {
1587 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1589 if ($conversation_id > 0) {
1590 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1593 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1594 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1595 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1596 `contact`.`id` AS `cid`,
1597 `user`.`nickname`, `user`.`hidewall`
1599 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1600 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1601 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1602 AND NOT `user`.`hidewall`
1603 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1604 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1605 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1606 AND NOT `item`.`private` AND `item`.`wall`
1609 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1610 dbesc(ACTIVITY_POST),
1615 $ret = api_format_items($r, $user_info, false, $type);
1617 $data = array('status' => $ret);
1621 $data = api_rss_extra($a, $data, $user_info);
1625 return api_format_data("statuses", $type, $data);
1628 /// @TODO move to top of file or somewhere better
1629 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1632 * @TODO nothing to say?
1634 function api_statuses_show($type) {
1638 if (api_user() === false) {
1639 throw new ForbiddenException();
1642 $user_info = api_get_user($a);
1645 $id = intval($a->argv[3]);
1648 $id = intval($_REQUEST["id"]);
1653 $id = intval($a->argv[4]);
1656 logger('API: api_statuses_show: ' . $id);
1658 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1661 if ($conversation) {
1662 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1664 $sql_extra .= " AND `item`.`id` = %d";
1667 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1668 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1669 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1670 `contact`.`id` AS `cid`
1672 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1673 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1674 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1675 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1678 dbesc(ACTIVITY_POST),
1682 /// @TODO How about copying this to above methods which don't check $r ?
1683 if (!dbm::is_result($r)) {
1684 throw new BadRequestException("There is no status with this id.");
1687 $ret = api_format_items($r,$user_info, false, $type);
1689 if ($conversation) {
1690 $data = array('status' => $ret);
1691 return api_format_data("statuses", $type, $data);
1693 $data = array('status' => $ret[0]);
1694 return api_format_data("status", $type, $data);
1698 /// @TODO move to top of file or somewhere better
1699 api_register_func('api/statuses/show','api_statuses_show', true);
1702 * @TODO nothing to say?
1704 function api_conversation_show($type) {
1708 if (api_user() === false) {
1709 throw new ForbiddenException();
1712 $user_info = api_get_user($a);
1715 $id = intval($a->argv[3]);
1716 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1717 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1721 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1722 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1724 $start = $page*$count;
1727 $id = intval($_REQUEST["id"]);
1732 $id = intval($a->argv[4]);
1735 logger('API: api_conversation_show: '.$id);
1737 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1738 if (dbm::is_result($r)) {
1739 $id = $r[0]["parent"];
1745 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1748 // Not sure why this query was so complicated. We should keep it here for a while,
1749 // just to make sure that we really don't need it.
1750 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1751 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1753 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1754 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1755 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1756 `contact`.`id` AS `cid`
1758 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1759 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1760 WHERE `item`.`parent` = %d AND `item`.`visible`
1761 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1762 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1763 AND `item`.`id`>%d $sql_extra
1764 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1765 intval($id), intval(api_user()),
1766 dbesc(ACTIVITY_POST),
1768 intval($start), intval($count)
1771 if (!dbm::is_result($r)) {
1772 throw new BadRequestException("There is no status with this id.");
1775 $ret = api_format_items($r, $user_info, false, $type);
1777 $data = array('status' => $ret);
1778 return api_format_data("statuses", $type, $data);
1781 /// @TODO move to top of file or somewhere better
1782 api_register_func('api/conversation/show','api_conversation_show', true);
1783 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1786 * @TODO nothing to say?
1788 function api_statuses_repeat($type) {
1793 if (api_user() === false) {
1794 throw new ForbiddenException();
1797 $user_info = api_get_user($a);
1800 $id = intval($a->argv[3]);
1803 $id = intval($_REQUEST["id"]);
1808 $id = intval($a->argv[4]);
1811 logger('API: api_statuses_repeat: '.$id);
1813 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1814 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1815 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1816 `contact`.`id` AS `cid`
1818 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1819 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1820 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1821 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1822 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1824 AND `item`.`id`=%d",
1828 /// @TODO other style than above functions!
1829 if (dbm::is_result($r) && $r[0]['body'] != "") {
1830 if (strpos($r[0]['body'], "[/share]") !== false) {
1831 $pos = strpos($r[0]['body'], "[share");
1832 $post = substr($r[0]['body'], $pos);
1834 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1836 $post .= $r[0]['body'];
1837 $post .= "[/share]";
1839 $_REQUEST['body'] = $post;
1840 $_REQUEST['profile_uid'] = api_user();
1841 $_REQUEST['type'] = 'wall';
1842 $_REQUEST['api_source'] = true;
1844 if (!x($_REQUEST, "source")) {
1845 $_REQUEST["source"] = api_source();
1850 throw new ForbiddenException();
1853 // this should output the last post (the one we just posted).
1855 return api_status_show($type);
1858 /// @TODO move to top of file or somewhere better
1859 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1862 * @TODO nothing to say?
1864 function api_statuses_destroy($type) {
1868 if (api_user() === false) {
1869 throw new ForbiddenException();
1872 $user_info = api_get_user($a);
1875 $id = intval($a->argv[3]);
1878 $id = intval($_REQUEST["id"]);
1883 $id = intval($a->argv[4]);
1886 logger('API: api_statuses_destroy: '.$id);
1888 $ret = api_statuses_show($type);
1890 drop_item($id, false);
1895 /// @TODO move to top of file or somewhere better
1896 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1899 * @TODO Nothing more than an URL to say?
1900 * http://developer.twitter.com/doc/get/statuses/mentions
1902 function api_statuses_mentions($type) {
1906 if (api_user() === false) {
1907 throw new ForbiddenException();
1910 unset($_REQUEST["user_id"]);
1911 unset($_GET["user_id"]);
1913 unset($_REQUEST["screen_name"]);
1914 unset($_GET["screen_name"]);
1916 $user_info = api_get_user($a);
1917 // get last newtork messages
1921 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1922 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1926 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1927 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1928 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1930 $start = $page * $count;
1932 // Ugly code - should be changed
1933 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1934 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1935 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1936 $myurl = str_replace('www.', '', $myurl);
1937 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1940 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1943 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1944 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1945 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1946 `contact`.`id` AS `cid`
1947 FROM `item` FORCE INDEX (`uid_id`)
1948 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1949 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1950 WHERE `item`.`uid` = %d AND `verb` = '%s'
1951 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1952 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1953 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1956 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1958 dbesc(ACTIVITY_POST),
1959 dbesc(protect_sprintf($myurl)),
1960 dbesc(protect_sprintf($myurl)),
1963 intval($start), intval($count)
1966 $ret = api_format_items($r, $user_info, false, $type);
1968 $data = array('status' => $ret);
1972 $data = api_rss_extra($a, $data, $user_info);
1976 return api_format_data("statuses", $type, $data);
1979 /// @TODO move to top of file or somewhere better
1980 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1981 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1983 function api_statuses_user_timeline($type) {
1987 if (api_user() === false) {
1988 throw new ForbiddenException();
1991 $user_info = api_get_user($a);
1992 // get last network messages
1994 logger("api_statuses_user_timeline: api_user: ". api_user() .
1995 "\nuser_info: ".print_r($user_info, true) .
1996 "\n_REQUEST: ".print_r($_REQUEST, true),
2000 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2001 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2005 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2006 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2007 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2008 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2010 $start = $page * $count;
2013 if ($user_info['self'] == 1) {
2014 $sql_extra .= " AND `item`.`wall` = 1 ";
2017 if ($exclude_replies > 0) {
2018 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2020 if ($conversation_id > 0) {
2021 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2024 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2025 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2026 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2027 `contact`.`id` AS `cid`
2028 FROM `item` FORCE INDEX (`uid_contactid_id`)
2029 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2030 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2031 WHERE `item`.`uid` = %d AND `verb` = '%s'
2032 AND `item`.`contact-id` = %d
2033 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2036 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2038 dbesc(ACTIVITY_POST),
2039 intval($user_info['cid']),
2041 intval($start), intval($count)
2044 $ret = api_format_items($r, $user_info, true, $type);
2046 $data = array('status' => $ret);
2050 $data = api_rss_extra($a, $data, $user_info);
2054 return api_format_data("statuses", $type, $data);
2057 /// @TODO move to top of file or somwhere better
2058 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2061 * Star/unstar an item
2062 * param: id : id of the item
2064 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2066 function api_favorites_create_destroy($type) {
2070 if (api_user() === false) {
2071 throw new ForbiddenException();
2074 // for versioned api.
2075 /// @TODO We need a better global soluton
2076 $action_argv_id = 2;
2077 if ($a->argv[1] == "1.1") {
2078 $action_argv_id = 3;
2081 if ($a->argc <= $action_argv_id) {
2082 throw new BadRequestException("Invalid request.");
2084 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2085 if ($a->argc == $action_argv_id + 2) {
2086 $itemid = intval($a->argv[$action_argv_id + 1]);
2088 /// @TODO use x() to check if _REQUEST contains 'id'
2089 $itemid = intval($_REQUEST['id']);
2092 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2093 $itemid, api_user());
2095 if (!dbm::is_result($item) || count($item) == 0) {
2096 throw new BadRequestException("Invalid item.");
2101 $item[0]['starred'] = 1;
2104 $item[0]['starred'] = 0;
2107 throw new BadRequestException("Invalid action ".$action);
2110 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2111 $item[0]['starred'], $itemid, api_user());
2113 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2114 $item[0]['starred'], $itemid, api_user());
2117 throw new InternalServerErrorException("DB error");
2121 $user_info = api_get_user($a);
2122 $rets = api_format_items($item, $user_info, false, $type);
2125 $data = array('status' => $ret);
2129 $data = api_rss_extra($a, $data, $user_info);
2132 return api_format_data("status", $type, $data);
2135 /// @TODO move to top of file or somwhere better
2136 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2137 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2139 function api_favorites($type) {
2144 if (api_user() === false) {
2145 throw new ForbiddenException();
2148 $called_api = array();
2150 $user_info = api_get_user($a);
2152 // in friendica starred item are private
2153 // return favorites only for self
2154 logger('api_favorites: self:' . $user_info['self']);
2156 if ($user_info['self'] == 0) {
2162 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2163 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2164 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2165 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2170 $start = $page*$count;
2173 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2176 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2177 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2178 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2179 `contact`.`id` AS `cid`
2180 FROM `item`, `contact`
2181 WHERE `item`.`uid` = %d
2182 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2183 AND `item`.`starred` = 1
2184 AND `contact`.`id` = `item`.`contact-id`
2185 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2188 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2191 intval($start), intval($count)
2194 $ret = api_format_items($r,$user_info, false, $type);
2198 $data = array('status' => $ret);
2202 $data = api_rss_extra($a, $data, $user_info);
2205 return api_format_data("statuses", $type, $data);
2208 /// @TODO move to top of file or somwhere better
2209 api_register_func('api/favorites','api_favorites', true);
2211 function api_format_messages($item, $recipient, $sender) {
2212 // standard meta information
2214 'id' => $item['id'],
2215 'sender_id' => $sender['id'] ,
2217 'recipient_id' => $recipient['id'],
2218 'created_at' => api_date($item['created']),
2219 'sender_screen_name' => $sender['screen_name'],
2220 'recipient_screen_name' => $recipient['screen_name'],
2221 'sender' => $sender,
2222 'recipient' => $recipient,
2224 'friendica_seen' => $item['seen'],
2225 'friendica_parent_uri' => $item['parent-uri'],
2228 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2229 unset($ret["sender"]["uid"]);
2230 unset($ret["sender"]["self"]);
2231 unset($ret["recipient"]["uid"]);
2232 unset($ret["recipient"]["self"]);
2234 //don't send title to regular StatusNET requests to avoid confusing these apps
2235 if (x($_GET, 'getText')) {
2236 $ret['title'] = $item['title'] ;
2237 if ($_GET['getText'] == 'html') {
2238 $ret['text'] = bbcode($item['body'], false, false);
2239 } elseif ($_GET['getText'] == 'plain') {
2240 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2241 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2244 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2246 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2247 unset($ret['sender']);
2248 unset($ret['recipient']);
2254 function api_convert_item($item) {
2255 $body = $item['body'];
2256 $attachments = api_get_attachments($body);
2258 // Workaround for ostatus messages where the title is identically to the body
2259 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2260 $statusbody = trim(html2plain($html, 0));
2262 // handle data: images
2263 $statusbody = api_format_items_embeded_images($item,$statusbody);
2265 $statustitle = trim($item['title']);
2267 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2268 $statustext = trim($statusbody);
2270 $statustext = trim($statustitle."\n\n".$statusbody);
2273 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2274 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2277 $statushtml = trim(bbcode($body, false, false));
2279 $search = array("<br>", "<blockquote>", "</blockquote>",
2280 "<h1>", "</h1>", "<h2>", "</h2>",
2281 "<h3>", "</h3>", "<h4>", "</h4>",
2282 "<h5>", "</h5>", "<h6>", "</h6>");
2283 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2284 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2285 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2286 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2287 $statushtml = str_replace($search, $replace, $statushtml);
2289 if ($item['title'] != "") {
2290 $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
2293 // feeds without body should contain the link
2294 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2295 $statushtml .= bbcode($item['plink']);
2298 $entities = api_get_entitities($statustext, $body);
2301 "text" => $statustext,
2302 "html" => $statushtml,
2303 "attachments" => $attachments,
2304 "entities" => $entities
2308 function api_get_attachments(&$body) {
2311 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2313 $URLSearchString = "^\[\]";
2314 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2320 $attachments = array();
2322 foreach ($images[1] AS $image) {
2323 $imagedata = get_photo_info($image);
2326 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2330 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2331 foreach ($images[0] AS $orig) {
2332 $body = str_replace($orig, "", $body);
2336 return $attachments;
2339 function api_get_entitities(&$text, $bbcode) {
2342 * Links at the first character of the post
2347 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2349 if ($include_entities != "true") {
2351 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2353 foreach ($images[1] AS $image) {
2354 $replace = proxy_url($image);
2355 $text = str_replace($image, $replace, $text);
2360 $bbcode = bb_CleanPictureLinks($bbcode);
2362 // Change pure links in text to bbcode uris
2363 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2365 $entities = array();
2366 $entities["hashtags"] = array();
2367 $entities["symbols"] = array();
2368 $entities["urls"] = array();
2369 $entities["user_mentions"] = array();
2371 $URLSearchString = "^\[\]";
2373 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2375 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2376 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2377 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2379 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2380 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2381 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2383 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2384 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2385 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2387 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2389 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2390 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2392 $ordered_urls = array();
2393 foreach ($urls[1] AS $id => $url) {
2394 //$start = strpos($text, $url, $offset);
2395 $start = iconv_strpos($text, $url, 0, "UTF-8");
2396 if (!($start === false)) {
2397 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2401 ksort($ordered_urls);
2404 //foreach ($urls[1] AS $id=>$url) {
2405 foreach ($ordered_urls AS $url) {
2406 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
2407 !strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
2408 $display_url = $url["title"];
2410 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2411 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2413 if (strlen($display_url) > 26)
2414 $display_url = substr($display_url, 0, 25)."…";
2417 //$start = strpos($text, $url, $offset);
2418 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2419 if (!($start === false)) {
2420 $entities["urls"][] = array("url" => $url["url"],
2421 "expanded_url" => $url["url"],
2422 "display_url" => $display_url,
2423 "indices" => array($start, $start+strlen($url["url"])));
2424 $offset = $start + 1;
2428 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2429 $ordered_images = array();
2430 foreach ($images[1] AS $image) {
2431 //$start = strpos($text, $url, $offset);
2432 $start = iconv_strpos($text, $image, 0, "UTF-8");
2433 if (!($start === false))
2434 $ordered_images[$start] = $image;
2436 //$entities["media"] = array();
2439 foreach ($ordered_images AS $url) {
2440 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2441 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2443 if (strlen($display_url) > 26)
2444 $display_url = substr($display_url, 0, 25)."…";
2446 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2447 if (!($start === false)) {
2448 $image = get_photo_info($url);
2450 // If image cache is activated, then use the following sizes:
2451 // thumb (150), small (340), medium (600) and large (1024)
2452 if (!get_config("system", "proxy_disabled")) {
2453 $media_url = proxy_url($url);
2456 $scale = scale_image($image[0], $image[1], 150);
2457 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2459 if (($image[0] > 150) || ($image[1] > 150)) {
2460 $scale = scale_image($image[0], $image[1], 340);
2461 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2464 $scale = scale_image($image[0], $image[1], 600);
2465 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2467 if (($image[0] > 600) || ($image[1] > 600)) {
2468 $scale = scale_image($image[0], $image[1], 1024);
2469 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2473 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2476 $entities["media"][] = array(
2478 "id_str" => (string)$start+1,
2479 "indices" => array($start, $start+strlen($url)),
2480 "media_url" => normalise_link($media_url),
2481 "media_url_https" => $media_url,
2483 "display_url" => $display_url,
2484 "expanded_url" => $url,
2488 $offset = $start + 1;
2494 function api_format_items_embeded_images(&$item, $text) {
2495 $text = preg_replace_callback(
2496 "|data:image/([^;]+)[^=]+=*|m",
2497 function($match) use ($item) {
2498 return System::baseUrl()."/display/".$item['guid'];
2506 * @brief return <a href='url'>name</a> as array
2508 * @param string $txt
2513 function api_contactlink_to_array($txt) {
2515 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2516 if ($r && count($match)==3) {
2518 'name' => $match[2],
2532 * @brief return likes, dislikes and attend status for item
2534 * @param array $item
2536 * likes => int count
2537 * dislikes => int count
2539 function api_format_items_activities(&$item, $type = "json") {
2543 $activities = array(
2545 'dislike' => array(),
2546 'attendyes' => array(),
2547 'attendno' => array(),
2548 'attendmaybe' => array(),
2551 $items = q('SELECT * FROM item
2552 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2553 intval($item['uid']),
2554 dbesc($item['uri']));
2556 foreach ($items as $i) {
2557 // not used as result should be structured like other user data
2558 //builtin_activity_puller($i, $activities);
2560 // get user data and add it to the array of the activity
2561 $user = api_get_user($a, $i['author-link']);
2562 switch ($i['verb']) {
2564 $activities['like'][] = $user;
2566 case ACTIVITY_DISLIKE:
2567 $activities['dislike'][] = $user;
2569 case ACTIVITY_ATTEND:
2570 $activities['attendyes'][] = $user;
2572 case ACTIVITY_ATTENDNO:
2573 $activities['attendno'][] = $user;
2575 case ACTIVITY_ATTENDMAYBE:
2576 $activities['attendmaybe'][] = $user;
2583 if ($type == "xml") {
2584 $xml_activities = array();
2585 foreach ($activities as $k => $v) {
2586 // change xml element from "like" to "friendica:like"
2587 $xml_activities["friendica:".$k] = $v;
2588 // add user data into xml output
2590 foreach ($v as $user)
2591 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2593 $activities = $xml_activities;
2602 * @brief return data from profiles
2604 * @param array $profile array containing data from db table 'profile'
2605 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2608 function api_format_items_profiles(&$profile = null, $type = "json") {
2609 if ($profile != null) {
2610 $profile = array('profile_id' => $profile['id'],
2611 'profile_name' => $profile['profile-name'],
2612 'is_default' => $profile['is-default'] ? true : false,
2613 'hide_friends'=> $profile['hide-friends'] ? true : false,
2614 'profile_photo' => $profile['photo'],
2615 'profile_thumb' => $profile['thumb'],
2616 'publish' => $profile['publish'] ? true : false,
2617 'net_publish' => $profile['net-publish'] ? true : false,
2618 'description' => $profile['pdesc'],
2619 'date_of_birth' => $profile['dob'],
2620 'address' => $profile['address'],
2621 'city' => $profile['locality'],
2622 'region' => $profile['region'],
2623 'postal_code' => $profile['postal-code'],
2624 'country' => $profile['country-name'],
2625 'hometown' => $profile['hometown'],
2626 'gender' => $profile['gender'],
2627 'marital' => $profile['marital'],
2628 'marital_with' => $profile['with'],
2629 'marital_since' => $profile['howlong'],
2630 'sexual' => $profile['sexual'],
2631 'politic' => $profile['politic'],
2632 'religion' => $profile['religion'],
2633 'public_keywords' => $profile['pub_keywords'],
2634 'private_keywords' => $profile['prv_keywords'],
2635 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2636 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2637 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2638 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2639 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2640 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2641 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2642 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2643 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2644 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2645 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2646 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2647 'homepage' => $profile['homepage'],
2654 * @brief format items to be returned by api
2656 * @param array $r array of items
2657 * @param array $user_info
2658 * @param bool $filter_user filter items by $user_info
2660 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2666 foreach ($r as $item) {
2668 localize_item($item);
2669 list($status_user, $owner_user) = api_item_get_user($a, $item);
2671 // Look if the posts are matching if they should be filtered by user id
2672 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2676 $in_reply_to = api_in_reply_to($item);
2678 $converted = api_convert_item($item);
2680 if ($type == "xml") {
2681 $geo = "georss:point";
2687 'text' => $converted["text"],
2688 'truncated' => False,
2689 'created_at'=> api_date($item['created']),
2690 'in_reply_to_status_id' => $in_reply_to['status_id'],
2691 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2692 'source' => (($item['app']) ? $item['app'] : 'web'),
2693 'id' => intval($item['id']),
2694 'id_str' => (string) intval($item['id']),
2695 'in_reply_to_user_id' => $in_reply_to['user_id'],
2696 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2697 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2699 'favorited' => $item['starred'] ? true : false,
2700 'user' => $status_user ,
2701 'friendica_owner' => $owner_user,
2702 //'entities' => NULL,
2703 'statusnet_html' => $converted["html"],
2704 'statusnet_conversation_id' => $item['parent'],
2705 'friendica_activities' => api_format_items_activities($item, $type),
2708 if (count($converted["attachments"]) > 0) {
2709 $status["attachments"] = $converted["attachments"];
2712 if (count($converted["entities"]) > 0) {
2713 $status["entities"] = $converted["entities"];
2716 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2717 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2718 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2719 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2723 // Retweets are only valid for top postings
2724 // It doesn't work reliable with the link if its a feed
2725 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2727 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2730 if ($item["id"] == $item["parent"]) {
2731 $retweeted_item = api_share_as_retweet($item);
2732 if ($retweeted_item !== false) {
2733 $retweeted_status = $status;
2735 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2736 } catch( BadRequestException $e ) {
2737 // user not found. should be found?
2738 /// @todo check if the user should be always found
2739 $retweeted_status["user"] = array();
2742 $rt_converted = api_convert_item($retweeted_item);
2744 $retweeted_status['text'] = $rt_converted["text"];
2745 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2746 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2747 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2748 $status['retweeted_status'] = $retweeted_status;
2752 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2753 unset($status["user"]["uid"]);
2754 unset($status["user"]["self"]);
2756 if ($item["coord"] != "") {
2757 $coords = explode(' ',$item["coord"]);
2758 if (count($coords) == 2) {
2759 if ($type == "json")
2760 $status["geo"] = array('type' => 'Point',
2761 'coordinates' => array((float) $coords[0],
2762 (float) $coords[1]));
2763 else // Not sure if this is the official format - if someone founds a documentation we can check
2764 $status["georss:point"] = $item["coord"];
2772 function api_account_rate_limit_status($type) {
2774 if ($type == "xml") {
2776 'remaining-hits' => '150',
2777 '@attributes' => array("type" => "integer"),
2778 'hourly-limit' => '150',
2779 '@attributes2' => array("type" => "integer"),
2780 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2781 '@attributes3' => array("type" => "datetime"),
2782 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2783 '@attributes4' => array("type" => "integer"),
2787 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2788 'remaining_hits' => '150',
2789 'hourly_limit' => '150',
2790 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2794 return api_format_data('hash', $type, array('hash' => $hash));
2797 /// @TODO move to top of file or somwhere better
2798 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2800 function api_help_test($type) {
2801 if ($type == 'xml') {
2807 return api_format_data('ok', $type, array("ok" => $ok));
2810 /// @TODO move to top of file or somwhere better
2811 api_register_func('api/help/test','api_help_test', false);
2813 function api_lists($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','api_lists',true);
2822 function api_lists_list($type) {
2824 /// @TODO $ret is not filled here?
2825 return api_format_data('lists', $type, array("lists_list" => $ret));
2828 /// @TODO move to top of file or somwhere better
2829 api_register_func('api/lists/list','api_lists_list',true);
2832 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2833 * This function is deprecated by Twitter
2834 * returns: json, xml
2836 function api_statuses_f($type, $qtype) {
2840 if (api_user() === false) {
2841 throw new ForbiddenException();
2844 $user_info = api_get_user($a);
2846 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2847 /* this is to stop Hotot to load friends multiple times
2848 * I'm not sure if I'm missing return something or
2849 * is a bug in hotot. Workaround, meantime
2853 return array('$users' => $ret);*/
2857 if ($qtype == 'friends') {
2858 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2860 if ($qtype == 'followers') {
2861 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2864 // friends and followers only for self
2865 if ($user_info['self'] == 0) {
2866 $sql_extra = " AND false ";
2869 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2874 foreach ($r as $cid) {
2875 $user = api_get_user($a, $cid['nurl']);
2876 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2877 unset($user["uid"]);
2878 unset($user["self"]);
2885 return array('user' => $ret);
2889 function api_statuses_friends($type) {
2890 $data = api_statuses_f($type, "friends");
2891 if ($data === false) {
2894 return api_format_data("users", $type, $data);
2897 function api_statuses_followers($type) {
2898 $data = api_statuses_f($type, "followers");
2899 if ($data === false) {
2902 return api_format_data("users", $type, $data);
2905 /// @TODO move to top of file or somewhere better
2906 api_register_func('api/statuses/friends','api_statuses_friends',true);
2907 api_register_func('api/statuses/followers','api_statuses_followers',true);
2909 function api_statusnet_config($type) {
2913 $name = $a->config['sitename'];
2914 $server = $a->get_hostname();
2915 $logo = System::baseUrl() . '/images/friendica-64.png';
2916 $email = $a->config['admin_email'];
2917 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2918 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2919 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2920 if ($a->config['api_import_size']) {
2921 $texlimit = string($a->config['api_import_size']);
2923 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2924 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',System::baseUrl()) : '');
2927 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2928 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2929 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2930 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2931 'shorturllength' => '30',
2932 'friendica' => array(
2933 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2934 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2935 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2936 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2941 return api_format_data('config', $type, array('config' => $config));
2945 /// @TODO move to top of file or somewhere better
2946 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2947 api_register_func('api/statusnet/config','api_statusnet_config', false);
2949 function api_statusnet_version($type) {
2951 $fake_statusnet_version = "0.9.7";
2953 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2956 /// @TODO move to top of file or somewhere better
2957 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2958 api_register_func('api/statusnet/version','api_statusnet_version', false);
2961 * @todo use api_format_data() to return data
2963 function api_ff_ids($type,$qtype) {
2968 throw new ForbiddenException();
2971 $user_info = api_get_user($a);
2973 if ($qtype == 'friends') {
2974 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2976 if ($qtype == 'followers') {
2977 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2980 if (!$user_info["self"]) {
2981 $sql_extra = " AND false ";
2984 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
2986 $r = q("SELECT `pcontact`.`id` FROM `contact`
2987 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2988 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2992 if (!dbm::is_result($r)) {
2997 foreach ($r as $rr) {
2998 if ($stringify_ids) {
3001 $ids[] = intval($rr['id']);
3005 return api_format_data("ids", $type, array('id' => $ids));
3008 function api_friends_ids($type) {
3009 return api_ff_ids($type,'friends');
3012 function api_followers_ids($type) {
3013 return api_ff_ids($type,'followers');
3016 /// @TODO move to top of file or somewhere better
3017 api_register_func('api/friends/ids','api_friends_ids',true);
3018 api_register_func('api/followers/ids','api_followers_ids',true);
3020 function api_direct_messages_new($type) {
3024 if (api_user() === false) throw new ForbiddenException();
3026 if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
3028 $sender = api_get_user($a);
3030 if ($_POST['screen_name']) {
3031 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3033 dbesc($_POST['screen_name']));
3035 // Selecting the id by priority, friendica first
3036 api_best_nickname($r);
3038 $recipient = api_get_user($a, $r[0]['nurl']);
3040 $recipient = api_get_user($a, $_POST['user_id']);
3045 if (x($_REQUEST, 'replyto')) {
3046 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3048 intval($_REQUEST['replyto']));
3049 $replyto = $r[0]['parent-uri'];
3050 $sub = $r[0]['title'];
3052 if (x($_REQUEST, 'title')) {
3053 $sub = $_REQUEST['title'];
3055 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3059 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3062 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3063 $ret = api_format_messages($r[0], $recipient, $sender);
3065 $ret = array("error"=>$id);
3068 $data = array('direct_message'=>$ret);
3073 $data = api_rss_extra($a, $data, $user_info);
3076 return api_format_data("direct-messages", $type, $data);
3080 /// @TODO move to top of file or somewhere better
3081 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3084 * @brief delete a direct_message from mail table through api
3086 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3089 function api_direct_messages_destroy($type) {
3092 if (api_user() === false) {
3093 throw new ForbiddenException();
3097 $user_info = api_get_user($a);
3099 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3101 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3102 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3103 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3105 $uid = $user_info['uid'];
3106 // error if no id or parenturi specified (for clients posting parent-uri as well)
3107 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3108 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3109 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3112 // BadRequestException if no id specified (for clients using Twitter API)
3114 throw new BadRequestException('Message id not specified');
3117 // add parent-uri to sql command if specified by calling app
3118 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3120 // get data of the specified message id
3121 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3125 // error message if specified id is not in database
3126 if (!dbm::is_result($r)) {
3127 if ($verbose == "true") {
3128 $answer = array('result' => 'error', 'message' => 'message id not in database');
3129 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3131 /// @todo BadRequestException ok for Twitter API clients?
3132 throw new BadRequestException('message id not in database');
3136 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3140 if ($verbose == "true") {
3143 $answer = array('result' => 'ok', 'message' => 'message deleted');
3144 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3146 $answer = array('result' => 'error', 'message' => 'unknown error');
3147 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3150 /// @todo return JSON data like Twitter API not yet implemented
3154 /// @TODO move to top of file or somewhere better
3155 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3157 function api_direct_messages_box($type, $box, $verbose) {
3161 if (api_user() === false) {
3162 throw new ForbiddenException();
3166 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3167 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3172 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3173 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3175 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3176 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3179 unset($_REQUEST["user_id"]);
3180 unset($_GET["user_id"]);
3182 unset($_REQUEST["screen_name"]);
3183 unset($_GET["screen_name"]);
3185 $user_info = api_get_user($a);
3186 $profile_url = $user_info["url"];
3189 $start = $page * $count;
3192 if ($box=="sentbox") {
3193 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3194 } elseif ($box == "conversation") {
3195 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3196 } elseif ($box == "all") {
3197 $sql_extra = "true";
3198 } elseif ($box == "inbox") {
3199 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3203 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3206 if ($user_id != "") {
3207 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3208 } elseif ($screen_name !="") {
3209 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3212 $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",
3215 intval($start), intval($count)
3217 if ($verbose == "true" && !dbm::is_result($r)) {
3218 $answer = array('result' => 'error', 'message' => 'no mails available');
3219 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3223 foreach ($r as $item) {
3224 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3225 $recipient = $user_info;
3226 $sender = api_get_user($a,normalise_link($item['contact-url']));
3227 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3228 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3229 $sender = $user_info;
3232 $ret[] = api_format_messages($item, $recipient, $sender);
3236 $data = array('direct_message' => $ret);
3240 $data = api_rss_extra($a, $data, $user_info);
3243 return api_format_data("direct-messages", $type, $data);
3247 function api_direct_messages_sentbox($type) {
3248 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3249 return api_direct_messages_box($type, "sentbox", $verbose);
3252 function api_direct_messages_inbox($type) {
3253 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3254 return api_direct_messages_box($type, "inbox", $verbose);
3257 function api_direct_messages_all($type) {
3258 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3259 return api_direct_messages_box($type, "all", $verbose);
3262 function api_direct_messages_conversation($type) {
3263 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3264 return api_direct_messages_box($type, "conversation", $verbose);
3267 /// @TODO move to top of file or somewhere better
3268 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3269 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3270 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3271 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3273 function api_oauth_request_token($type) {
3275 $oauth = new FKOAuth1();
3276 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3277 } catch (Exception $e) {
3278 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3285 function api_oauth_access_token($type) {
3287 $oauth = new FKOAuth1();
3288 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3289 } catch (Exception $e) {
3290 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3296 /// @TODO move to top of file or somewhere better
3297 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3298 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3302 * @brief delete a complete photoalbum with all containing photos from database through api
3304 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3307 function api_fr_photoalbum_delete($type) {
3308 if (api_user() === false) {
3309 throw new ForbiddenException();
3312 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3314 // we do not allow calls without album string
3316 throw new BadRequestException("no albumname specified");
3318 // check if album is existing
3319 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3322 if (!dbm::is_result($r))
3323 throw new BadRequestException("album not available");
3325 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3326 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3327 foreach ($r as $rr) {
3328 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3329 intval(local_user()),
3330 dbesc($rr['resource-id'])
3333 if (!dbm::is_result($photo_item)) {
3334 throw new InternalServerErrorException("problem with deleting items occured");
3336 drop_item($photo_item[0]['id'],false);
3339 // now let's delete all photos from the album
3340 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3344 // return success of deletion or error message
3346 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3347 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3349 throw new InternalServerErrorException("unknown error - deleting from database failed");
3355 * @brief update the name of the album for all photos of an album
3357 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3360 function api_fr_photoalbum_update($type) {
3361 if (api_user() === false) {
3362 throw new ForbiddenException();
3365 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3366 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3368 // we do not allow calls without album string
3370 throw new BadRequestException("no albumname specified");
3372 if ($album_new == "") {
3373 throw new BadRequestException("no new albumname specified");
3375 // check if album is existing
3376 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3379 if (!dbm::is_result($r)) {
3380 throw new BadRequestException("album not available");
3382 // now let's update all photos to the albumname
3383 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3388 // return success of updating or error message
3390 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3391 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3393 throw new InternalServerErrorException("unknown error - updating in database failed");
3399 * @brief list all photos of the authenticated user
3401 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3404 function api_fr_photos_list($type) {
3405 if (api_user() === false) {
3406 throw new ForbiddenException();
3408 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3409 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3410 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3411 intval(local_user())
3414 'image/jpeg' => 'jpg',
3415 'image/png' => 'png',
3416 'image/gif' => 'gif'
3418 $data = array('photo'=>array());
3419 if (dbm::is_result($r)) {
3420 foreach ($r as $rr) {
3422 $photo['id'] = $rr['resource-id'];
3423 $photo['album'] = $rr['album'];
3424 $photo['filename'] = $rr['filename'];
3425 $photo['type'] = $rr['type'];
3426 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3427 $photo['created'] = $rr['created'];
3428 $photo['edited'] = $rr['edited'];
3429 $photo['desc'] = $rr['desc'];
3431 if ($type == "xml") {
3432 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3434 $photo['thumb'] = $thumb;
3435 $data['photo'][] = $photo;
3439 return api_format_data("photos", $type, $data);
3443 * @brief upload a new photo or change an existing photo
3445 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3448 function api_fr_photo_create_update($type) {
3449 if (api_user() === false) {
3450 throw new ForbiddenException();
3453 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3454 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3455 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3456 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3457 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3458 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3459 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3460 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3461 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3463 // do several checks on input parameters
3464 // we do not allow calls without album string
3465 if ($album == null) {
3466 throw new BadRequestException("no albumname specified");
3468 // if photo_id == null --> we are uploading a new photo
3469 if ($photo_id == null) {
3472 // error if no media posted in create-mode
3473 if (!x($_FILES,'media')) {
3475 throw new BadRequestException("no media data submitted");
3478 // album_new will be ignored in create-mode
3483 // check if photo is existing in database
3484 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3488 if (!dbm::is_result($r)) {
3489 throw new BadRequestException("photo not available");
3493 // checks on acl strings provided by clients
3494 $acl_input_error = false;
3495 $acl_input_error |= check_acl_input($allow_cid);
3496 $acl_input_error |= check_acl_input($deny_cid);
3497 $acl_input_error |= check_acl_input($allow_gid);
3498 $acl_input_error |= check_acl_input($deny_gid);
3499 if ($acl_input_error) {
3500 throw new BadRequestException("acl data invalid");
3502 // now let's upload the new media in create-mode
3503 if ($mode == "create") {
3504 $media = $_FILES['media'];
3505 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3507 // return success of updating or error message
3508 if (!is_null($data)) {
3509 return api_format_data("photo_create", $type, $data);
3511 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3515 // now let's do the changes in update-mode
3516 if ($mode == "update") {
3519 if (!is_null($desc)) {
3520 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3523 if (!is_null($album_new)) {
3524 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3527 if (!is_null($allow_cid)) {
3528 $allow_cid = trim($allow_cid);
3529 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3532 if (!is_null($deny_cid)) {
3533 $deny_cid = trim($deny_cid);
3534 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3537 if (!is_null($allow_gid)) {
3538 $allow_gid = trim($allow_gid);
3539 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3542 if (!is_null($deny_gid)) {
3543 $deny_gid = trim($deny_gid);
3544 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3548 if ($sql_extra != "") {
3549 $nothingtodo = false;
3550 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3552 datetime_convert(), // update edited timestamp
3557 $nothingtodo = true;
3560 if (x($_FILES,'media')) {
3561 $nothingtodo = false;
3562 $media = $_FILES['media'];
3563 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3564 if (!is_null($data)) {
3565 return api_format_data("photo_update", $type, $data);
3569 // return success of updating or error message
3571 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3572 return api_format_data("photo_update", $type, array('$result' => $answer));
3575 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3576 return api_format_data("photo_update", $type, array('$result' => $answer));
3578 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3581 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3586 * @brief delete a single photo from the database through api
3588 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3591 function api_fr_photo_delete($type) {
3592 if (api_user() === false) {
3593 throw new ForbiddenException();
3596 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3598 // do several checks on input parameters
3599 // we do not allow calls without photo id
3600 if ($photo_id == null) {
3601 throw new BadRequestException("no photo_id specified");
3603 // check if photo is existing in database
3604 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3608 if (!dbm::is_result($r)) {
3609 throw new BadRequestException("photo not available");
3611 // now we can perform on the deletion of the photo
3612 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3616 // return success of deletion or error message
3618 // retrieve the id of the parent element (the photo element)
3619 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3620 intval(local_user()),
3624 if (!dbm::is_result($photo_item)) {
3625 throw new InternalServerErrorException("problem with deleting items occured");
3627 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3628 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3629 drop_item($photo_item[0]['id'], false);
3631 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3632 return api_format_data("photo_delete", $type, array('$result' => $answer));
3634 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3640 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3642 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3645 function api_fr_photo_detail($type) {
3646 if (api_user() === false) {
3647 throw new ForbiddenException();
3649 if (!x($_REQUEST, 'photo_id')) {
3650 throw new BadRequestException("No photo id.");
3653 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3654 $photo_id = $_REQUEST['photo_id'];
3656 // prepare json/xml output with data from database for the requested photo
3657 $data = prepare_photo_data($type, $scale, $photo_id);
3659 return api_format_data("photo_detail", $type, $data);
3664 * @brief updates the profile image for the user (either a specified profile or the default profile)
3666 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3669 function api_account_update_profile_image($type) {
3670 if (api_user() === false) {
3671 throw new ForbiddenException();
3674 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3676 // error if image data is missing
3677 if (!x($_FILES, 'image')) {
3678 throw new BadRequestException("no media data submitted");
3681 // check if specified profile id is valid
3682 if ($profileid != 0) {
3683 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3685 intval($profileid));
3686 // error message if specified profile id is not in database
3687 if (!dbm::is_result($r)) {
3688 throw new BadRequestException("profile_id not available");
3690 $is_default_profile = $r['profile'];
3692 $is_default_profile = 1;
3695 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3697 if (x($_FILES, 'image')) {
3698 $media = $_FILES['image'];
3699 } elseif (x($_FILES, 'media')) {
3700 $media = $_FILES['media'];
3702 // save new profile image
3703 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3706 if (is_array($media['type'])) {
3707 $filetype = $media['type'][0];
3709 $filetype = $media['type'];
3711 if ($filetype == "image/jpeg") {
3713 } elseif ($filetype == "image/png") {
3716 // change specified profile or all profiles to the new resource-id
3717 if ($is_default_profile) {
3718 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3719 dbesc($data['photo']['id']),
3720 intval(local_user())
3723 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3724 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3725 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3726 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3727 intval(local_user())
3730 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3731 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3732 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3733 intval($_REQUEST['profile']),
3734 intval(local_user())
3738 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3739 // so that browsers will do a cache update unconditionally
3741 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3742 dbesc(datetime_convert()),
3743 intval(local_user())
3746 // Update global directory in background
3747 //$user = api_get_user(get_app());
3748 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3749 if ($url && strlen(get_config('system', 'directory'))) {
3750 proc_run(PRIORITY_LOW, "include/directory.php", $url);
3753 proc_run(PRIORITY_LOW, 'include/profile_update.php', api_user());
3755 // output for client
3757 return api_account_verify_credentials($type);
3759 // SaveMediaToDatabase failed for some reason
3760 throw new InternalServerErrorException("image upload failed");
3764 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3765 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3766 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3767 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3768 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3769 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3770 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3771 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3772 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3775 function check_acl_input($acl_string) {
3776 if ($acl_string == null || $acl_string == " ") {
3779 $contact_not_found = false;
3781 // split <x><y><z> into array of cid's
3782 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3784 // check for each cid if it is available on server
3785 $cid_array = $array[0];
3786 foreach ($cid_array as $cid) {
3787 $cid = str_replace("<", "", $cid);
3788 $cid = str_replace(">", "", $cid);
3789 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3791 intval(api_user()));
3792 $contact_not_found |= !dbm::is_result($contact);
3794 return $contact_not_found;
3797 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null) {
3804 if (is_array($media)) {
3805 if (is_array($media['tmp_name'])) {
3806 $src = $media['tmp_name'][0];
3808 $src = $media['tmp_name'];
3810 if (is_array($media['name'])) {
3811 $filename = basename($media['name'][0]);
3813 $filename = basename($media['name']);
3815 if (is_array($media['size'])) {
3816 $filesize = intval($media['size'][0]);
3818 $filesize = intval($media['size']);
3820 if (is_array($media['type'])) {
3821 $filetype = $media['type'][0];
3823 $filetype = $media['type'];
3827 if ($filetype == "") {
3828 $filetype=guess_image_type($filename);
3830 $imagedata = getimagesize($src);
3832 $filetype = $imagedata['mime'];
3834 logger("File upload src: " . $src . " - filename: " . $filename .
3835 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3837 // check if there was a php upload error
3838 if ($filesize == 0 && $media['error'] == 1) {
3839 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3841 // check against max upload size within Friendica instance
3842 $maximagesize = get_config('system', 'maximagesize');
3843 if (($maximagesize) && ($filesize > $maximagesize)) {
3844 $formattedBytes = formatBytes($maximagesize);
3845 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3848 // create Photo instance with the data of the image
3849 $imagedata = @file_get_contents($src);
3850 $ph = new Photo($imagedata, $filetype);
3851 if (! $ph->is_valid()) {
3852 throw new InternalServerErrorException("unable to process image data");
3855 // check orientation of image
3859 // check max length of images on server
3860 $max_length = get_config('system', 'max_image_length');
3861 if (! $max_length) {
3862 $max_length = MAX_IMAGE_LENGTH;
3864 if ($max_length > 0) {
3865 $ph->scaleImage($max_length);
3866 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3868 $width = $ph->getWidth();
3869 $height = $ph->getHeight();
3871 // create a new resource-id if not already provided
3872 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3874 if ($mediatype == "photo") {
3875 // upload normal image (scales 0, 1, 2)
3876 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3878 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3880 logger("photo upload: image upload with scale 0 (original size) failed");
3882 if($width > 640 || $height > 640) {
3883 $ph->scaleImage(640);
3884 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3886 logger("photo upload: image upload with scale 1 (640x640) failed");
3890 if ($width > 320 || $height > 320) {
3891 $ph->scaleImage(320);
3892 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3894 logger("photo upload: image upload with scale 2 (320x320) failed");
3897 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3898 } elseif ($mediatype == "profileimage") {
3899 // upload profile image (scales 4, 5, 6)
3900 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3902 if ($width > 175 || $height > 175) {
3903 $ph->scaleImage(175);
3904 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3906 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3910 if ($width > 80 || $height > 80) {
3911 $ph->scaleImage(80);
3912 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3914 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3918 if ($width > 48 || $height > 48) {
3919 $ph->scaleImage(48);
3920 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3922 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3926 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3930 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3931 if ($photo_id == null && $mediatype == "photo") {
3932 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3934 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3935 return prepare_photo_data($type, false, $hash);
3937 throw new InternalServerErrorException("image upload failed");
3941 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3942 // get data about the api authenticated user
3943 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3944 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3947 $arr['guid'] = get_guid(32);
3948 $arr['uid'] = intval(api_user());
3950 $arr['parent-uri'] = $uri;
3951 $arr['type'] = 'photo';
3953 $arr['resource-id'] = $hash;
3954 $arr['contact-id'] = $owner_record[0]['id'];
3955 $arr['owner-name'] = $owner_record[0]['name'];
3956 $arr['owner-link'] = $owner_record[0]['url'];
3957 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3958 $arr['author-name'] = $owner_record[0]['name'];
3959 $arr['author-link'] = $owner_record[0]['url'];
3960 $arr['author-avatar'] = $owner_record[0]['thumb'];
3962 $arr['allow_cid'] = $allow_cid;
3963 $arr['allow_gid'] = $allow_gid;
3964 $arr['deny_cid'] = $deny_cid;
3965 $arr['deny_gid'] = $deny_gid;
3966 $arr['last-child'] = 1;
3967 $arr['visible'] = $visibility;
3971 'image/jpeg' => 'jpg',
3972 'image/png' => 'png',
3973 'image/gif' => 'gif'
3976 // adds link to the thumbnail scale photo
3977 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['name'] . '/image/' . $hash . ']'
3978 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3981 // do the magic for storing the item in the database and trigger the federation to other contacts
3985 function prepare_photo_data($type, $scale, $photo_id) {
3986 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3987 $data_sql = ($scale === false ? "" : "data, ");
3989 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3990 // clients needs to convert this in their way for further processing
3991 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3992 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3993 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3994 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
3996 intval(local_user()),
4002 'image/jpeg' => 'jpg',
4003 'image/png' => 'png',
4004 'image/gif' => 'gif'
4007 // prepare output data for photo
4008 if (dbm::is_result($r)) {
4009 $data = array('photo' => $r[0]);
4010 $data['photo']['id'] = $data['photo']['resource-id'];
4011 if ($scale !== false) {
4012 $data['photo']['data'] = base64_encode($data['photo']['data']);
4014 unset($data['photo']['datasize']); //needed only with scale param
4016 if ($type == "xml") {
4017 $data['photo']['links'] = array();
4018 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4019 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4021 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4024 $data['photo']['link'] = array();
4025 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4027 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4028 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4032 unset($data['photo']['resource-id']);
4033 unset($data['photo']['minscale']);
4034 unset($data['photo']['maxscale']);
4037 throw new NotFoundException();
4040 // retrieve item element for getting activities (like, dislike etc.) related to photo
4041 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4042 intval(local_user()),
4045 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4047 // retrieve comments on photo
4048 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4049 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4050 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4051 `contact`.`id` AS `cid`
4053 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4054 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4055 WHERE `item`.`parent` = %d AND `item`.`visible`
4056 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4057 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4058 intval($item[0]['parent']),
4060 dbesc(ACTIVITY_POST)
4063 // prepare output of comments
4064 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4065 $comments = array();
4066 if ($type == "xml") {
4068 foreach ($commentData as $comment) {
4069 $comments[$k++ . ":comment"] = $comment;
4072 foreach ($commentData as $comment) {
4073 $comments[] = $comment;
4076 $data['photo']['friendica_comments'] = $comments;
4078 // include info if rights on photo and rights on item are mismatching
4079 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4080 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4081 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4082 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4083 $data['photo']['rights_mismatch'] = $rights_mismatch;
4090 * similar as /mod/redir.php
4091 * redirect to 'url' after dfrn auth
4093 * why this when there is mod/redir.php already?
4094 * This use api_user() and api_login()
4097 * c_url: url of remote contact to auth to
4098 * url: string, url to redirect after auth
4100 function api_friendica_remoteauth() {
4101 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4102 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4104 if ($url === '' || $c_url === '') {
4105 throw new BadRequestException("Wrong parameters.");
4108 $c_url = normalise_link($c_url);
4112 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4117 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4118 throw new BadRequestException("Unknown contact");
4123 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4125 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4126 $orig_id = $r[0]['issued-id'];
4127 $dfrn_id = '1:' . $orig_id;
4129 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4130 $orig_id = $r[0]['dfrn-id'];
4131 $dfrn_id = '0:' . $orig_id;
4134 $sec = random_string();
4136 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4137 VALUES( %d, %s, '%s', '%s', %d )",
4145 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4146 $dest = (($url) ? '&destination_url=' . $url : '');
4147 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4148 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4149 . '&type=profile&sec=' . $sec . $dest . $quiet );
4151 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4154 * @brief Return the item shared, if the item contains only the [share] tag
4156 * @param array $item Sharer item
4157 * @return array Shared item or false if not a reshare
4159 function api_share_as_retweet(&$item) {
4160 $body = trim($item["body"]);
4162 if (Diaspora::is_reshare($body, false)===false) {
4166 /// @TODO "$1" should maybe mean '$1' ?
4167 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4169 * Skip if there is no shared message in there
4170 * we already checked this in diaspora::is_reshare()
4171 * but better one more than one less...
4173 if ($body == $attributes) {
4178 // build the fake reshared item
4179 $reshared_item = $item;
4182 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4183 if ($matches[1] != "") {
4184 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4187 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4188 if ($matches[1] != "") {
4189 $author = $matches[1];
4193 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4194 if ($matches[1] != "") {
4195 $profile = $matches[1];
4198 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4199 if ($matches[1] != "") {
4200 $profile = $matches[1];
4204 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4205 if ($matches[1] != "") {
4206 $avatar = $matches[1];
4209 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4210 if ($matches[1] != "") {
4211 $avatar = $matches[1];
4215 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4216 if ($matches[1] != "") {
4217 $link = $matches[1];
4220 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4221 if ($matches[1] != "") {
4222 $link = $matches[1];
4226 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4227 if ($matches[1] != "")
4228 $posted = $matches[1];
4230 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4231 if ($matches[1] != "") {
4232 $posted = $matches[1];
4235 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4237 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4241 $reshared_item["body"] = $shared_body;
4242 $reshared_item["author-name"] = $author;
4243 $reshared_item["author-link"] = $profile;
4244 $reshared_item["author-avatar"] = $avatar;
4245 $reshared_item["plink"] = $link;
4246 $reshared_item["created"] = $posted;
4247 $reshared_item["edited"] = $posted;
4249 return $reshared_item;
4253 function api_get_nick($profile) {
4255 - remove trailing junk from profile url
4256 - pump.io check has to check the website
4261 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4262 dbesc(normalise_link($profile)));
4264 if (dbm::is_result($r)) {
4265 $nick = $r[0]["nick"];
4269 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4270 dbesc(normalise_link($profile)));
4272 if (dbm::is_result($r)) {
4273 $nick = $r[0]["nick"];
4278 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4279 if ($friendica != $profile) {
4285 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4286 if ($diaspora != $profile) {
4292 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4293 if ($twitter != $profile) {
4300 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4301 if ($StatusnetHost != $profile) {
4302 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4303 if ($StatusnetUser != $profile) {
4304 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4305 $user = json_decode($UserData);
4307 $nick = $user->screen_name;
4313 // To-Do: look at the page if its really a pumpio site
4314 //if (!$nick == "") {
4315 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4316 // if ($pumpio != $profile)
4318 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4329 function api_in_reply_to($item) {
4330 $in_reply_to = array();
4332 $in_reply_to['status_id'] = NULL;
4333 $in_reply_to['user_id'] = NULL;
4334 $in_reply_to['status_id_str'] = NULL;
4335 $in_reply_to['user_id_str'] = NULL;
4336 $in_reply_to['screen_name'] = NULL;
4338 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4339 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4340 intval($item['uid']),
4341 dbesc($item['thr-parent']));
4343 if (dbm::is_result($r)) {
4344 $in_reply_to['status_id'] = intval($r[0]['id']);
4346 $in_reply_to['status_id'] = intval($item['parent']);
4349 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4351 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4352 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4353 WHERE `item`.`id` = %d LIMIT 1",
4354 intval($in_reply_to['status_id'])
4357 if (dbm::is_result($r)) {
4358 if ($r[0]['nick'] == "") {
4359 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4362 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4363 $in_reply_to['user_id'] = intval($r[0]['id']);
4364 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4367 // There seems to be situation, where both fields are identical:
4368 // https://github.com/friendica/friendica/issues/1010
4369 // This is a bugfix for that.
4370 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4371 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4372 $in_reply_to['status_id'] = NULL;
4373 $in_reply_to['user_id'] = NULL;
4374 $in_reply_to['status_id_str'] = NULL;
4375 $in_reply_to['user_id_str'] = NULL;
4376 $in_reply_to['screen_name'] = NULL;
4380 return $in_reply_to;
4383 function api_clean_plain_items($Text) {
4384 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4386 $Text = bb_CleanPictureLinks($Text);
4387 $URLSearchString = "^\[\]";
4389 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4391 if ($include_entities == "true") {
4392 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4395 // Simplify "attachment" element
4396 $Text = api_clean_attachments($Text);
4402 * @brief Removes most sharing information for API text export
4404 * @param string $body The original body
4406 * @return string Cleaned body
4408 function api_clean_attachments($body) {
4409 $data = get_attachment_data($body);
4416 if (isset($data["text"]))
4417 $body = $data["text"];
4419 if (($body == "") && (isset($data["title"])))
4420 $body = $data["title"];
4422 if (isset($data["url"]))
4423 $body .= "\n".$data["url"];
4425 $body .= $data["after"];
4430 function api_best_nickname(&$contacts) {
4431 $best_contact = array();
4433 if (count($contact) == 0)
4436 foreach ($contacts AS $contact)
4437 if ($contact["network"] == "") {
4438 $contact["network"] = "dfrn";
4439 $best_contact = array($contact);
4442 if (sizeof($best_contact) == 0)
4443 foreach ($contacts AS $contact)
4444 if ($contact["network"] == "dfrn")
4445 $best_contact = array($contact);
4447 if (sizeof($best_contact) == 0)
4448 foreach ($contacts AS $contact)
4449 if ($contact["network"] == "dspr")
4450 $best_contact = array($contact);
4452 if (sizeof($best_contact) == 0)
4453 foreach ($contacts AS $contact)
4454 if ($contact["network"] == "stat")
4455 $best_contact = array($contact);
4457 if (sizeof($best_contact) == 0)
4458 foreach ($contacts AS $contact)
4459 if ($contact["network"] == "pump")
4460 $best_contact = array($contact);
4462 if (sizeof($best_contact) == 0)
4463 foreach ($contacts AS $contact)
4464 if ($contact["network"] == "twit")
4465 $best_contact = array($contact);
4467 if (sizeof($best_contact) == 1)
4468 $contacts = $best_contact;
4470 $contacts = array($contacts[0]);
4473 // return all or a specified group of the user with the containing contacts
4474 function api_friendica_group_show($type) {
4478 if (api_user() === false) throw new ForbiddenException();
4481 $user_info = api_get_user($a);
4482 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4483 $uid = $user_info['uid'];
4485 // get data of the specified group id or all groups if not specified
4487 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4490 // error message if specified gid is not in database
4491 if (!dbm::is_result($r))
4492 throw new BadRequestException("gid not available");
4495 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4498 // loop through all groups and retrieve all members for adding data in the user array
4499 foreach ($r as $rr) {
4500 $members = group_get_members($rr['id']);
4503 if ($type == "xml") {
4504 $user_element = "users";
4506 foreach ($members as $member) {
4507 $user = api_get_user($a, $member['nurl']);
4508 $users[$k++.":user"] = $user;
4511 $user_element = "user";
4512 foreach ($members as $member) {
4513 $user = api_get_user($a, $member['nurl']);
4517 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4519 return api_format_data("groups", $type, array('group' => $grps));
4521 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4524 // delete the specified group of the user
4525 function api_friendica_group_delete($type) {
4529 if (api_user() === false) throw new ForbiddenException();
4532 $user_info = api_get_user($a);
4533 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4534 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4535 $uid = $user_info['uid'];
4537 // error if no gid specified
4538 if ($gid == 0 || $name == "")
4539 throw new BadRequestException('gid or name not specified');
4541 // get data of the specified group id
4542 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4545 // error message if specified gid is not in database
4546 if (!dbm::is_result($r))
4547 throw new BadRequestException('gid not available');
4549 // get data of the specified group id and group name
4550 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4554 // error message if specified gid is not in database
4555 if (!dbm::is_result($rname))
4556 throw new BadRequestException('wrong group name');
4559 $ret = group_rmv($uid, $name);
4562 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4563 return api_format_data("group_delete", $type, array('result' => $success));
4566 throw new BadRequestException('other API error');
4568 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4571 // create the specified group with the posted array of contacts
4572 function api_friendica_group_create($type) {
4576 if (api_user() === false) throw new ForbiddenException();
4579 $user_info = api_get_user($a);
4580 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4581 $uid = $user_info['uid'];
4582 $json = json_decode($_POST['json'], true);
4583 $users = $json['user'];
4585 // error if no name specified
4587 throw new BadRequestException('group name not specified');
4589 // get data of the specified group name
4590 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4593 // error message if specified group name already exists
4594 if (dbm::is_result($rname))
4595 throw new BadRequestException('group name already exists');
4597 // check if specified group name is a deleted group
4598 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4601 // error message if specified group name already exists
4602 if (dbm::is_result($rname))
4603 $reactivate_group = true;
4606 $ret = group_add($uid, $name);
4608 $gid = group_byname($uid, $name);
4610 throw new BadRequestException('other API error');
4613 $erroraddinguser = false;
4614 $errorusers = array();
4615 foreach ($users as $user) {
4616 $cid = $user['cid'];
4617 // check if user really exists as contact
4618 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4621 if (count($contact))
4622 $result = group_add_member($uid, $name, $cid, $gid);
4624 $erroraddinguser = true;
4625 $errorusers[] = $cid;
4629 // return success message incl. missing users in array
4630 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4631 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4632 return api_format_data("group_create", $type, array('result' => $success));
4634 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4637 // update the specified group with the posted array of contacts
4638 function api_friendica_group_update($type) {
4642 if (api_user() === false) throw new ForbiddenException();
4645 $user_info = api_get_user($a);
4646 $uid = $user_info['uid'];
4647 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4648 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4649 $json = json_decode($_POST['json'], true);
4650 $users = $json['user'];
4652 // error if no name specified
4654 throw new BadRequestException('group name not specified');
4656 // error if no gid specified
4658 throw new BadRequestException('gid not specified');
4661 $members = group_get_members($gid);
4662 foreach ($members as $member) {
4663 $cid = $member['id'];
4664 foreach ($users as $user) {
4665 $found = ($user['cid'] == $cid ? true : false);
4668 $ret = group_rmv_member($uid, $name, $cid);
4673 $erroraddinguser = false;
4674 $errorusers = array();
4675 foreach ($users as $user) {
4676 $cid = $user['cid'];
4677 // check if user really exists as contact
4678 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4681 if (count($contact))
4682 $result = group_add_member($uid, $name, $cid, $gid);
4684 $erroraddinguser = true;
4685 $errorusers[] = $cid;
4689 // return success message incl. missing users in array
4690 $status = ($erroraddinguser ? "missing user" : "ok");
4691 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4692 return api_format_data("group_update", $type, array('result' => $success));
4695 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4697 function api_friendica_activity($type) {
4701 if (api_user() === false) throw new ForbiddenException();
4702 $verb = strtolower($a->argv[3]);
4703 $verb = preg_replace("|\..*$|", "", $verb);
4705 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4707 $res = do_like($id, $verb);
4714 return api_format_data('ok', $type, array('ok' => $ok));
4716 throw new BadRequestException('Error adding activity');
4721 /// @TODO move to top of file or somwhere better
4722 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4723 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4724 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4725 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4726 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4727 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4728 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4729 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4730 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4731 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4734 * @brief Returns notifications
4736 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4739 function api_friendica_notification($type) {
4743 if (api_user() === false) throw new ForbiddenException();
4744 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4745 $nm = new NotificationsManager();
4747 $notes = $nm->getAll(array(), "+seen -date", 50);
4749 if ($type == "xml") {
4750 $xmlnotes = array();
4751 foreach ($notes AS $note)
4752 $xmlnotes[] = array("@attributes" => $note);
4757 return api_format_data("notes", $type, array('note' => $notes));
4761 * @brief Set notification as seen and returns associated item (if possible)
4763 * POST request with 'id' param as notification id
4765 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4768 function api_friendica_notification_seen($type) {
4772 if (api_user() === false) throw new ForbiddenException();
4773 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4775 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4777 $nm = new NotificationsManager();
4778 $note = $nm->getByID($id);
4779 if (is_null($note)) throw new BadRequestException("Invalid argument");
4781 $nm->setSeen($note);
4782 if ($note['otype']=='item') {
4783 // would be really better with an ItemsManager and $im->getByID() :-P
4784 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4785 intval($note['iid']),
4786 intval(local_user())
4789 // we found the item, return it to the user
4790 $user_info = api_get_user($a);
4791 $ret = api_format_items($r,$user_info, false, $type);
4792 $data = array('status' => $ret);
4793 return api_format_data("status", $type, $data);
4795 // the item can't be found, but we set the note as seen, so we count this as a success
4797 return api_format_data('result', $type, array('result' => "success"));
4800 /// @TODO move to top of file or somwhere better
4801 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4802 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4805 * @brief update a direct_message to seen state
4807 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4808 * @return string (success result=ok, error result=error with error message)
4810 function api_friendica_direct_messages_setseen($type) {
4812 if (api_user() === false) {
4813 throw new ForbiddenException();
4817 $user_info = api_get_user($a);
4818 $uid = $user_info['uid'];
4819 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4821 // return error if id is zero
4823 $answer = array('result' => 'error', 'message' => 'message id not specified');
4824 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4827 // get data of the specified message id
4828 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4832 // error message if specified id is not in database
4833 if (!dbm::is_result($r)) {
4834 $answer = array('result' => 'error', 'message' => 'message id not in database');
4835 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4838 // update seen indicator
4839 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4845 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4846 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4848 $answer = array('result' => 'error', 'message' => 'unknown error');
4849 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4853 /// @TODO move to top of file or somwhere better
4854 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4857 * @brief search for direct_messages containing a searchstring through api
4859 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4860 * @return string (success: success=true if found and search_result contains found messages
4861 * success=false if nothing was found, search_result='nothing found',
4862 * error: result=error with error message)
4864 function api_friendica_direct_messages_search($type) {
4867 if (api_user() === false) {
4868 throw new ForbiddenException();
4872 $user_info = api_get_user($a);
4873 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4874 $uid = $user_info['uid'];
4876 // error if no searchstring specified
4877 if ($searchstring == "") {
4878 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4879 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4882 // get data for the specified searchstring
4883 $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",
4885 dbesc('%'.$searchstring.'%')
4888 $profile_url = $user_info["url"];
4890 // message if nothing was found
4891 if (!dbm::is_result($r)) {
4892 $success = array('success' => false, 'search_results' => 'problem with query');
4893 } elseif (count($r) == 0) {
4894 $success = array('success' => false, 'search_results' => 'nothing found');
4897 foreach ($r as $item) {
4898 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4899 $recipient = $user_info;
4900 $sender = api_get_user($a,normalise_link($item['contact-url']));
4901 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4902 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4903 $sender = $user_info;
4906 $ret[] = api_format_messages($item, $recipient, $sender);
4908 $success = array('success' => true, 'search_results' => $ret);
4911 return api_format_data("direct_message_search", $type, array('$result' => $success));
4914 /// @TODO move to top of file or somwhere better
4915 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4918 * @brief return data of all the profiles a user has to the client
4920 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4923 function api_friendica_profile_show($type) {
4926 if (api_user() === false) {
4927 throw new ForbiddenException();
4931 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4933 // retrieve general information about profiles for user
4934 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4935 $directory = get_config('system', 'directory');
4937 // get data of the specified profile id or all profiles of the user if not specified
4938 if ($profileid != 0) {
4939 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4941 intval($profileid));
4943 // error message if specified gid is not in database
4944 if (!dbm::is_result($r)) {
4945 throw new BadRequestException("profile_id not available");
4948 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4949 intval(api_user()));
4951 // loop through all returned profiles and retrieve data and users
4953 foreach ($r as $rr) {
4954 $profile = api_format_items_profiles($rr, $type);
4956 // select all users from contact table, loop and prepare standard return for user data
4958 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4960 intval($rr['profile_id']));
4962 foreach ($r as $rr) {
4963 $user = api_get_user($a, $rr['nurl']);
4964 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4966 $profile['users'] = $users;
4968 // add prepared profile data to array for final return
4969 if ($type == "xml") {
4970 $profiles[$k++ . ":profile"] = $profile;
4972 $profiles[] = $profile;
4976 // return settings, authenticated user and profiles data
4977 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4979 $result = array('multi_profiles' => $multi_profiles ? true : false,
4980 'global_dir' => $directory,
4981 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4982 'profiles' => $profiles);
4983 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4985 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4988 @TODO Maybe open to implement?
4990 [pagename] => api/1.1/statuses/lookup.json
4991 [id] => 605138389168451584
4992 [include_cards] => true
4993 [cards_platform] => Android-12
4994 [include_entities] => true
4995 [include_my_retweet] => 1
4997 [include_reply_count] => true
4998 [include_descendent_reply_count] => true
5002 Not implemented by now:
5003 statuses/retweets_of_me
5008 account/update_location
5009 account/update_profile_background_image
5012 friendica/profile/update
5013 friendica/profile/create
5014 friendica/profile/delete
5016 Not implemented in status.net:
5017 statuses/retweeted_to_me
5018 statuses/retweeted_by_me
5019 direct_messages/destroy
5021 account/update_delivery_device
5022 notifications/follow