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 // Workaround for clients with limited HTML parser functionality
2280 $search = array("<br>", "<blockquote>", "</blockquote>",
2281 "<h1>", "</h1>", "<h2>", "</h2>",
2282 "<h3>", "</h3>", "<h4>", "</h4>",
2283 "<h5>", "</h5>", "<h6>", "</h6>");
2284 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2285 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2286 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2287 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2288 $statushtml = str_replace($search, $replace, $statushtml);
2290 if ($item['title'] != "") {
2291 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2295 $oldtext = $statushtml;
2296 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2297 } while ($oldtext != $statushtml);
2299 if (substr($statushtml, 0, 4) == '<br>') {
2300 $statushtml = substr($statushtml, 4);
2303 if (substr($statushtml, 0, -4) == '<br>') {
2304 $statushtml = substr($statushtml, -4);
2307 // feeds without body should contain the link
2308 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2309 $statushtml .= bbcode($item['plink']);
2312 $entities = api_get_entitities($statustext, $body);
2315 "text" => $statustext,
2316 "html" => $statushtml,
2317 "attachments" => $attachments,
2318 "entities" => $entities
2322 function api_get_attachments(&$body) {
2325 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2327 $URLSearchString = "^\[\]";
2328 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2334 $attachments = array();
2336 foreach ($images[1] AS $image) {
2337 $imagedata = get_photo_info($image);
2340 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2344 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2345 foreach ($images[0] AS $orig) {
2346 $body = str_replace($orig, "", $body);
2350 return $attachments;
2353 function api_get_entitities(&$text, $bbcode) {
2356 * Links at the first character of the post
2361 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2363 if ($include_entities != "true") {
2365 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2367 foreach ($images[1] AS $image) {
2368 $replace = proxy_url($image);
2369 $text = str_replace($image, $replace, $text);
2374 $bbcode = bb_CleanPictureLinks($bbcode);
2376 // Change pure links in text to bbcode uris
2377 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2379 $entities = array();
2380 $entities["hashtags"] = array();
2381 $entities["symbols"] = array();
2382 $entities["urls"] = array();
2383 $entities["user_mentions"] = array();
2385 $URLSearchString = "^\[\]";
2387 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2389 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2390 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2391 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2393 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2394 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2395 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2397 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2398 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2399 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2401 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2403 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2404 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2406 $ordered_urls = array();
2407 foreach ($urls[1] AS $id => $url) {
2408 //$start = strpos($text, $url, $offset);
2409 $start = iconv_strpos($text, $url, 0, "UTF-8");
2410 if (!($start === false)) {
2411 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2415 ksort($ordered_urls);
2418 //foreach ($urls[1] AS $id=>$url) {
2419 foreach ($ordered_urls AS $url) {
2420 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
2421 !strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
2422 $display_url = $url["title"];
2424 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2425 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2427 if (strlen($display_url) > 26)
2428 $display_url = substr($display_url, 0, 25)."…";
2431 //$start = strpos($text, $url, $offset);
2432 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2433 if (!($start === false)) {
2434 $entities["urls"][] = array("url" => $url["url"],
2435 "expanded_url" => $url["url"],
2436 "display_url" => $display_url,
2437 "indices" => array($start, $start+strlen($url["url"])));
2438 $offset = $start + 1;
2442 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2443 $ordered_images = array();
2444 foreach ($images[1] AS $image) {
2445 //$start = strpos($text, $url, $offset);
2446 $start = iconv_strpos($text, $image, 0, "UTF-8");
2447 if (!($start === false))
2448 $ordered_images[$start] = $image;
2450 //$entities["media"] = array();
2453 foreach ($ordered_images AS $url) {
2454 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2455 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2457 if (strlen($display_url) > 26)
2458 $display_url = substr($display_url, 0, 25)."…";
2460 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2461 if (!($start === false)) {
2462 $image = get_photo_info($url);
2464 // If image cache is activated, then use the following sizes:
2465 // thumb (150), small (340), medium (600) and large (1024)
2466 if (!get_config("system", "proxy_disabled")) {
2467 $media_url = proxy_url($url);
2470 $scale = scale_image($image[0], $image[1], 150);
2471 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2473 if (($image[0] > 150) || ($image[1] > 150)) {
2474 $scale = scale_image($image[0], $image[1], 340);
2475 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2478 $scale = scale_image($image[0], $image[1], 600);
2479 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2481 if (($image[0] > 600) || ($image[1] > 600)) {
2482 $scale = scale_image($image[0], $image[1], 1024);
2483 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2487 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2490 $entities["media"][] = array(
2492 "id_str" => (string)$start+1,
2493 "indices" => array($start, $start+strlen($url)),
2494 "media_url" => normalise_link($media_url),
2495 "media_url_https" => $media_url,
2497 "display_url" => $display_url,
2498 "expanded_url" => $url,
2502 $offset = $start + 1;
2508 function api_format_items_embeded_images(&$item, $text) {
2509 $text = preg_replace_callback(
2510 "|data:image/([^;]+)[^=]+=*|m",
2511 function($match) use ($item) {
2512 return System::baseUrl()."/display/".$item['guid'];
2520 * @brief return <a href='url'>name</a> as array
2522 * @param string $txt
2527 function api_contactlink_to_array($txt) {
2529 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2530 if ($r && count($match)==3) {
2532 'name' => $match[2],
2546 * @brief return likes, dislikes and attend status for item
2548 * @param array $item
2550 * likes => int count
2551 * dislikes => int count
2553 function api_format_items_activities(&$item, $type = "json") {
2557 $activities = array(
2559 'dislike' => array(),
2560 'attendyes' => array(),
2561 'attendno' => array(),
2562 'attendmaybe' => array(),
2565 $items = q('SELECT * FROM item
2566 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2567 intval($item['uid']),
2568 dbesc($item['uri']));
2570 foreach ($items as $i) {
2571 // not used as result should be structured like other user data
2572 //builtin_activity_puller($i, $activities);
2574 // get user data and add it to the array of the activity
2575 $user = api_get_user($a, $i['author-link']);
2576 switch ($i['verb']) {
2578 $activities['like'][] = $user;
2580 case ACTIVITY_DISLIKE:
2581 $activities['dislike'][] = $user;
2583 case ACTIVITY_ATTEND:
2584 $activities['attendyes'][] = $user;
2586 case ACTIVITY_ATTENDNO:
2587 $activities['attendno'][] = $user;
2589 case ACTIVITY_ATTENDMAYBE:
2590 $activities['attendmaybe'][] = $user;
2597 if ($type == "xml") {
2598 $xml_activities = array();
2599 foreach ($activities as $k => $v) {
2600 // change xml element from "like" to "friendica:like"
2601 $xml_activities["friendica:".$k] = $v;
2602 // add user data into xml output
2604 foreach ($v as $user)
2605 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2607 $activities = $xml_activities;
2616 * @brief return data from profiles
2618 * @param array $profile array containing data from db table 'profile'
2619 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2622 function api_format_items_profiles(&$profile = null, $type = "json") {
2623 if ($profile != null) {
2624 $profile = array('profile_id' => $profile['id'],
2625 'profile_name' => $profile['profile-name'],
2626 'is_default' => $profile['is-default'] ? true : false,
2627 'hide_friends'=> $profile['hide-friends'] ? true : false,
2628 'profile_photo' => $profile['photo'],
2629 'profile_thumb' => $profile['thumb'],
2630 'publish' => $profile['publish'] ? true : false,
2631 'net_publish' => $profile['net-publish'] ? true : false,
2632 'description' => $profile['pdesc'],
2633 'date_of_birth' => $profile['dob'],
2634 'address' => $profile['address'],
2635 'city' => $profile['locality'],
2636 'region' => $profile['region'],
2637 'postal_code' => $profile['postal-code'],
2638 'country' => $profile['country-name'],
2639 'hometown' => $profile['hometown'],
2640 'gender' => $profile['gender'],
2641 'marital' => $profile['marital'],
2642 'marital_with' => $profile['with'],
2643 'marital_since' => $profile['howlong'],
2644 'sexual' => $profile['sexual'],
2645 'politic' => $profile['politic'],
2646 'religion' => $profile['religion'],
2647 'public_keywords' => $profile['pub_keywords'],
2648 'private_keywords' => $profile['prv_keywords'],
2649 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2650 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2651 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2652 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2653 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2654 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2655 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2656 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2657 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2658 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2659 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2660 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2661 'homepage' => $profile['homepage'],
2668 * @brief format items to be returned by api
2670 * @param array $r array of items
2671 * @param array $user_info
2672 * @param bool $filter_user filter items by $user_info
2674 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2680 foreach ($r as $item) {
2682 localize_item($item);
2683 list($status_user, $owner_user) = api_item_get_user($a, $item);
2685 // Look if the posts are matching if they should be filtered by user id
2686 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2690 $in_reply_to = api_in_reply_to($item);
2692 $converted = api_convert_item($item);
2694 if ($type == "xml") {
2695 $geo = "georss:point";
2701 'text' => $converted["text"],
2702 'truncated' => False,
2703 'created_at'=> api_date($item['created']),
2704 'in_reply_to_status_id' => $in_reply_to['status_id'],
2705 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2706 'source' => (($item['app']) ? $item['app'] : 'web'),
2707 'id' => intval($item['id']),
2708 'id_str' => (string) intval($item['id']),
2709 'in_reply_to_user_id' => $in_reply_to['user_id'],
2710 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2711 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2713 'favorited' => $item['starred'] ? true : false,
2714 'user' => $status_user ,
2715 'friendica_owner' => $owner_user,
2716 //'entities' => NULL,
2717 'statusnet_html' => $converted["html"],
2718 'statusnet_conversation_id' => $item['parent'],
2719 'friendica_activities' => api_format_items_activities($item, $type),
2722 if (count($converted["attachments"]) > 0) {
2723 $status["attachments"] = $converted["attachments"];
2726 if (count($converted["entities"]) > 0) {
2727 $status["entities"] = $converted["entities"];
2730 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2731 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2732 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2733 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2737 // Retweets are only valid for top postings
2738 // It doesn't work reliable with the link if its a feed
2739 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2741 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2744 if ($item["id"] == $item["parent"]) {
2745 $retweeted_item = api_share_as_retweet($item);
2746 if ($retweeted_item !== false) {
2747 $retweeted_status = $status;
2749 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2750 } catch( BadRequestException $e ) {
2751 // user not found. should be found?
2752 /// @todo check if the user should be always found
2753 $retweeted_status["user"] = array();
2756 $rt_converted = api_convert_item($retweeted_item);
2758 $retweeted_status['text'] = $rt_converted["text"];
2759 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2760 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2761 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2762 $status['retweeted_status'] = $retweeted_status;
2766 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2767 unset($status["user"]["uid"]);
2768 unset($status["user"]["self"]);
2770 if ($item["coord"] != "") {
2771 $coords = explode(' ',$item["coord"]);
2772 if (count($coords) == 2) {
2773 if ($type == "json")
2774 $status["geo"] = array('type' => 'Point',
2775 'coordinates' => array((float) $coords[0],
2776 (float) $coords[1]));
2777 else // Not sure if this is the official format - if someone founds a documentation we can check
2778 $status["georss:point"] = $item["coord"];
2786 function api_account_rate_limit_status($type) {
2788 if ($type == "xml") {
2790 'remaining-hits' => '150',
2791 '@attributes' => array("type" => "integer"),
2792 'hourly-limit' => '150',
2793 '@attributes2' => array("type" => "integer"),
2794 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2795 '@attributes3' => array("type" => "datetime"),
2796 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2797 '@attributes4' => array("type" => "integer"),
2801 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2802 'remaining_hits' => '150',
2803 'hourly_limit' => '150',
2804 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2808 return api_format_data('hash', $type, array('hash' => $hash));
2811 /// @TODO move to top of file or somwhere better
2812 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2814 function api_help_test($type) {
2815 if ($type == 'xml') {
2821 return api_format_data('ok', $type, array("ok" => $ok));
2824 /// @TODO move to top of file or somwhere better
2825 api_register_func('api/help/test','api_help_test', false);
2827 function api_lists($type) {
2829 /// @TODO $ret is not filled here?
2830 return api_format_data('lists', $type, array("lists_list" => $ret));
2833 /// @TODO move to top of file or somwhere better
2834 api_register_func('api/lists','api_lists',true);
2836 function api_lists_list($type) {
2838 /// @TODO $ret is not filled here?
2839 return api_format_data('lists', $type, array("lists_list" => $ret));
2842 /// @TODO move to top of file or somwhere better
2843 api_register_func('api/lists/list','api_lists_list',true);
2846 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2847 * This function is deprecated by Twitter
2848 * returns: json, xml
2850 function api_statuses_f($type, $qtype) {
2854 if (api_user() === false) {
2855 throw new ForbiddenException();
2858 $user_info = api_get_user($a);
2860 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2861 /* this is to stop Hotot to load friends multiple times
2862 * I'm not sure if I'm missing return something or
2863 * is a bug in hotot. Workaround, meantime
2867 return array('$users' => $ret);*/
2871 if ($qtype == 'friends') {
2872 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2874 if ($qtype == 'followers') {
2875 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2878 // friends and followers only for self
2879 if ($user_info['self'] == 0) {
2880 $sql_extra = " AND false ";
2883 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2888 foreach ($r as $cid) {
2889 $user = api_get_user($a, $cid['nurl']);
2890 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2891 unset($user["uid"]);
2892 unset($user["self"]);
2899 return array('user' => $ret);
2903 function api_statuses_friends($type) {
2904 $data = api_statuses_f($type, "friends");
2905 if ($data === false) {
2908 return api_format_data("users", $type, $data);
2911 function api_statuses_followers($type) {
2912 $data = api_statuses_f($type, "followers");
2913 if ($data === false) {
2916 return api_format_data("users", $type, $data);
2919 /// @TODO move to top of file or somewhere better
2920 api_register_func('api/statuses/friends','api_statuses_friends',true);
2921 api_register_func('api/statuses/followers','api_statuses_followers',true);
2923 function api_statusnet_config($type) {
2927 $name = $a->config['sitename'];
2928 $server = $a->get_hostname();
2929 $logo = System::baseUrl() . '/images/friendica-64.png';
2930 $email = $a->config['admin_email'];
2931 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2932 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2933 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2934 if ($a->config['api_import_size']) {
2935 $texlimit = string($a->config['api_import_size']);
2937 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2938 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',System::baseUrl()) : '');
2941 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2942 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2943 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2944 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2945 'shorturllength' => '30',
2946 'friendica' => array(
2947 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2948 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2949 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2950 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2955 return api_format_data('config', $type, array('config' => $config));
2959 /// @TODO move to top of file or somewhere better
2960 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2961 api_register_func('api/statusnet/config','api_statusnet_config', false);
2963 function api_statusnet_version($type) {
2965 $fake_statusnet_version = "0.9.7";
2967 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2970 /// @TODO move to top of file or somewhere better
2971 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2972 api_register_func('api/statusnet/version','api_statusnet_version', false);
2975 * @todo use api_format_data() to return data
2977 function api_ff_ids($type,$qtype) {
2982 throw new ForbiddenException();
2985 $user_info = api_get_user($a);
2987 if ($qtype == 'friends') {
2988 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2990 if ($qtype == 'followers') {
2991 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2994 if (!$user_info["self"]) {
2995 $sql_extra = " AND false ";
2998 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3000 $r = q("SELECT `pcontact`.`id` FROM `contact`
3001 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3002 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3006 if (!dbm::is_result($r)) {
3011 foreach ($r as $rr) {
3012 if ($stringify_ids) {
3015 $ids[] = intval($rr['id']);
3019 return api_format_data("ids", $type, array('id' => $ids));
3022 function api_friends_ids($type) {
3023 return api_ff_ids($type,'friends');
3026 function api_followers_ids($type) {
3027 return api_ff_ids($type,'followers');
3030 /// @TODO move to top of file or somewhere better
3031 api_register_func('api/friends/ids','api_friends_ids',true);
3032 api_register_func('api/followers/ids','api_followers_ids',true);
3034 function api_direct_messages_new($type) {
3038 if (api_user() === false) throw new ForbiddenException();
3040 if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
3042 $sender = api_get_user($a);
3044 if ($_POST['screen_name']) {
3045 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3047 dbesc($_POST['screen_name']));
3049 // Selecting the id by priority, friendica first
3050 api_best_nickname($r);
3052 $recipient = api_get_user($a, $r[0]['nurl']);
3054 $recipient = api_get_user($a, $_POST['user_id']);
3059 if (x($_REQUEST, 'replyto')) {
3060 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3062 intval($_REQUEST['replyto']));
3063 $replyto = $r[0]['parent-uri'];
3064 $sub = $r[0]['title'];
3066 if (x($_REQUEST, 'title')) {
3067 $sub = $_REQUEST['title'];
3069 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3073 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3076 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3077 $ret = api_format_messages($r[0], $recipient, $sender);
3079 $ret = array("error"=>$id);
3082 $data = array('direct_message'=>$ret);
3087 $data = api_rss_extra($a, $data, $user_info);
3090 return api_format_data("direct-messages", $type, $data);
3094 /// @TODO move to top of file or somewhere better
3095 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3098 * @brief delete a direct_message from mail table through api
3100 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3103 function api_direct_messages_destroy($type) {
3106 if (api_user() === false) {
3107 throw new ForbiddenException();
3111 $user_info = api_get_user($a);
3113 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3115 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3116 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3117 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3119 $uid = $user_info['uid'];
3120 // error if no id or parenturi specified (for clients posting parent-uri as well)
3121 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3122 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3123 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3126 // BadRequestException if no id specified (for clients using Twitter API)
3128 throw new BadRequestException('Message id not specified');
3131 // add parent-uri to sql command if specified by calling app
3132 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3134 // get data of the specified message id
3135 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3139 // error message if specified id is not in database
3140 if (!dbm::is_result($r)) {
3141 if ($verbose == "true") {
3142 $answer = array('result' => 'error', 'message' => 'message id not in database');
3143 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3145 /// @todo BadRequestException ok for Twitter API clients?
3146 throw new BadRequestException('message id not in database');
3150 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3154 if ($verbose == "true") {
3157 $answer = array('result' => 'ok', 'message' => 'message deleted');
3158 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3160 $answer = array('result' => 'error', 'message' => 'unknown error');
3161 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3164 /// @todo return JSON data like Twitter API not yet implemented
3168 /// @TODO move to top of file or somewhere better
3169 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3171 function api_direct_messages_box($type, $box, $verbose) {
3175 if (api_user() === false) {
3176 throw new ForbiddenException();
3180 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3181 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3186 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3187 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3189 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3190 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3193 unset($_REQUEST["user_id"]);
3194 unset($_GET["user_id"]);
3196 unset($_REQUEST["screen_name"]);
3197 unset($_GET["screen_name"]);
3199 $user_info = api_get_user($a);
3200 $profile_url = $user_info["url"];
3203 $start = $page * $count;
3206 if ($box=="sentbox") {
3207 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3208 } elseif ($box == "conversation") {
3209 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3210 } elseif ($box == "all") {
3211 $sql_extra = "true";
3212 } elseif ($box == "inbox") {
3213 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3217 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3220 if ($user_id != "") {
3221 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3222 } elseif ($screen_name !="") {
3223 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3226 $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",
3229 intval($start), intval($count)
3231 if ($verbose == "true" && !dbm::is_result($r)) {
3232 $answer = array('result' => 'error', 'message' => 'no mails available');
3233 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3237 foreach ($r as $item) {
3238 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3239 $recipient = $user_info;
3240 $sender = api_get_user($a,normalise_link($item['contact-url']));
3241 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3242 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3243 $sender = $user_info;
3246 $ret[] = api_format_messages($item, $recipient, $sender);
3250 $data = array('direct_message' => $ret);
3254 $data = api_rss_extra($a, $data, $user_info);
3257 return api_format_data("direct-messages", $type, $data);
3261 function api_direct_messages_sentbox($type) {
3262 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3263 return api_direct_messages_box($type, "sentbox", $verbose);
3266 function api_direct_messages_inbox($type) {
3267 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3268 return api_direct_messages_box($type, "inbox", $verbose);
3271 function api_direct_messages_all($type) {
3272 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3273 return api_direct_messages_box($type, "all", $verbose);
3276 function api_direct_messages_conversation($type) {
3277 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3278 return api_direct_messages_box($type, "conversation", $verbose);
3281 /// @TODO move to top of file or somewhere better
3282 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3283 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3284 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3285 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3287 function api_oauth_request_token($type) {
3289 $oauth = new FKOAuth1();
3290 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3291 } catch (Exception $e) {
3292 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3299 function api_oauth_access_token($type) {
3301 $oauth = new FKOAuth1();
3302 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3303 } catch (Exception $e) {
3304 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3310 /// @TODO move to top of file or somewhere better
3311 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3312 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3316 * @brief delete a complete photoalbum with all containing photos from database through api
3318 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3321 function api_fr_photoalbum_delete($type) {
3322 if (api_user() === false) {
3323 throw new ForbiddenException();
3326 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3328 // we do not allow calls without album string
3330 throw new BadRequestException("no albumname specified");
3332 // check if album is existing
3333 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3336 if (!dbm::is_result($r))
3337 throw new BadRequestException("album not available");
3339 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3340 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3341 foreach ($r as $rr) {
3342 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3343 intval(local_user()),
3344 dbesc($rr['resource-id'])
3347 if (!dbm::is_result($photo_item)) {
3348 throw new InternalServerErrorException("problem with deleting items occured");
3350 drop_item($photo_item[0]['id'],false);
3353 // now let's delete all photos from the album
3354 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3358 // return success of deletion or error message
3360 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3361 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3363 throw new InternalServerErrorException("unknown error - deleting from database failed");
3369 * @brief update the name of the album for all photos of an album
3371 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3374 function api_fr_photoalbum_update($type) {
3375 if (api_user() === false) {
3376 throw new ForbiddenException();
3379 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3380 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3382 // we do not allow calls without album string
3384 throw new BadRequestException("no albumname specified");
3386 if ($album_new == "") {
3387 throw new BadRequestException("no new albumname specified");
3389 // check if album is existing
3390 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3393 if (!dbm::is_result($r)) {
3394 throw new BadRequestException("album not available");
3396 // now let's update all photos to the albumname
3397 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3402 // return success of updating or error message
3404 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3405 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3407 throw new InternalServerErrorException("unknown error - updating in database failed");
3413 * @brief list all photos of the authenticated user
3415 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3418 function api_fr_photos_list($type) {
3419 if (api_user() === false) {
3420 throw new ForbiddenException();
3422 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3423 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3424 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3425 intval(local_user())
3428 'image/jpeg' => 'jpg',
3429 'image/png' => 'png',
3430 'image/gif' => 'gif'
3432 $data = array('photo'=>array());
3433 if (dbm::is_result($r)) {
3434 foreach ($r as $rr) {
3436 $photo['id'] = $rr['resource-id'];
3437 $photo['album'] = $rr['album'];
3438 $photo['filename'] = $rr['filename'];
3439 $photo['type'] = $rr['type'];
3440 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3441 $photo['created'] = $rr['created'];
3442 $photo['edited'] = $rr['edited'];
3443 $photo['desc'] = $rr['desc'];
3445 if ($type == "xml") {
3446 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3448 $photo['thumb'] = $thumb;
3449 $data['photo'][] = $photo;
3453 return api_format_data("photos", $type, $data);
3457 * @brief upload a new photo or change an existing photo
3459 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3462 function api_fr_photo_create_update($type) {
3463 if (api_user() === false) {
3464 throw new ForbiddenException();
3467 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3468 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3469 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3470 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3471 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3472 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3473 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3474 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3475 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3477 // do several checks on input parameters
3478 // we do not allow calls without album string
3479 if ($album == null) {
3480 throw new BadRequestException("no albumname specified");
3482 // if photo_id == null --> we are uploading a new photo
3483 if ($photo_id == null) {
3486 // error if no media posted in create-mode
3487 if (!x($_FILES,'media')) {
3489 throw new BadRequestException("no media data submitted");
3492 // album_new will be ignored in create-mode
3497 // check if photo is existing in database
3498 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3502 if (!dbm::is_result($r)) {
3503 throw new BadRequestException("photo not available");
3507 // checks on acl strings provided by clients
3508 $acl_input_error = false;
3509 $acl_input_error |= check_acl_input($allow_cid);
3510 $acl_input_error |= check_acl_input($deny_cid);
3511 $acl_input_error |= check_acl_input($allow_gid);
3512 $acl_input_error |= check_acl_input($deny_gid);
3513 if ($acl_input_error) {
3514 throw new BadRequestException("acl data invalid");
3516 // now let's upload the new media in create-mode
3517 if ($mode == "create") {
3518 $media = $_FILES['media'];
3519 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3521 // return success of updating or error message
3522 if (!is_null($data)) {
3523 return api_format_data("photo_create", $type, $data);
3525 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3529 // now let's do the changes in update-mode
3530 if ($mode == "update") {
3533 if (!is_null($desc)) {
3534 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3537 if (!is_null($album_new)) {
3538 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3541 if (!is_null($allow_cid)) {
3542 $allow_cid = trim($allow_cid);
3543 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3546 if (!is_null($deny_cid)) {
3547 $deny_cid = trim($deny_cid);
3548 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3551 if (!is_null($allow_gid)) {
3552 $allow_gid = trim($allow_gid);
3553 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3556 if (!is_null($deny_gid)) {
3557 $deny_gid = trim($deny_gid);
3558 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3562 if ($sql_extra != "") {
3563 $nothingtodo = false;
3564 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3566 datetime_convert(), // update edited timestamp
3571 $nothingtodo = true;
3574 if (x($_FILES,'media')) {
3575 $nothingtodo = false;
3576 $media = $_FILES['media'];
3577 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3578 if (!is_null($data)) {
3579 return api_format_data("photo_update", $type, $data);
3583 // return success of updating or error message
3585 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3586 return api_format_data("photo_update", $type, array('$result' => $answer));
3589 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3590 return api_format_data("photo_update", $type, array('$result' => $answer));
3592 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3595 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3600 * @brief delete a single photo from the database through api
3602 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3605 function api_fr_photo_delete($type) {
3606 if (api_user() === false) {
3607 throw new ForbiddenException();
3610 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3612 // do several checks on input parameters
3613 // we do not allow calls without photo id
3614 if ($photo_id == null) {
3615 throw new BadRequestException("no photo_id specified");
3617 // check if photo is existing in database
3618 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3622 if (!dbm::is_result($r)) {
3623 throw new BadRequestException("photo not available");
3625 // now we can perform on the deletion of the photo
3626 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3630 // return success of deletion or error message
3632 // retrieve the id of the parent element (the photo element)
3633 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3634 intval(local_user()),
3638 if (!dbm::is_result($photo_item)) {
3639 throw new InternalServerErrorException("problem with deleting items occured");
3641 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3642 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3643 drop_item($photo_item[0]['id'], false);
3645 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3646 return api_format_data("photo_delete", $type, array('$result' => $answer));
3648 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3654 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3656 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3659 function api_fr_photo_detail($type) {
3660 if (api_user() === false) {
3661 throw new ForbiddenException();
3663 if (!x($_REQUEST, 'photo_id')) {
3664 throw new BadRequestException("No photo id.");
3667 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3668 $photo_id = $_REQUEST['photo_id'];
3670 // prepare json/xml output with data from database for the requested photo
3671 $data = prepare_photo_data($type, $scale, $photo_id);
3673 return api_format_data("photo_detail", $type, $data);
3678 * @brief updates the profile image for the user (either a specified profile or the default profile)
3680 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3683 function api_account_update_profile_image($type) {
3684 if (api_user() === false) {
3685 throw new ForbiddenException();
3688 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3690 // error if image data is missing
3691 if (!x($_FILES, 'image')) {
3692 throw new BadRequestException("no media data submitted");
3695 // check if specified profile id is valid
3696 if ($profileid != 0) {
3697 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3699 intval($profileid));
3700 // error message if specified profile id is not in database
3701 if (!dbm::is_result($r)) {
3702 throw new BadRequestException("profile_id not available");
3704 $is_default_profile = $r['profile'];
3706 $is_default_profile = 1;
3709 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3711 if (x($_FILES, 'image')) {
3712 $media = $_FILES['image'];
3713 } elseif (x($_FILES, 'media')) {
3714 $media = $_FILES['media'];
3716 // save new profile image
3717 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3720 if (is_array($media['type'])) {
3721 $filetype = $media['type'][0];
3723 $filetype = $media['type'];
3725 if ($filetype == "image/jpeg") {
3727 } elseif ($filetype == "image/png") {
3730 // change specified profile or all profiles to the new resource-id
3731 if ($is_default_profile) {
3732 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3733 dbesc($data['photo']['id']),
3734 intval(local_user())
3737 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3738 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3739 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3740 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3741 intval(local_user())
3744 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3745 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3746 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3747 intval($_REQUEST['profile']),
3748 intval(local_user())
3752 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3753 // so that browsers will do a cache update unconditionally
3755 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3756 dbesc(datetime_convert()),
3757 intval(local_user())
3760 // Update global directory in background
3761 //$user = api_get_user(get_app());
3762 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3763 if ($url && strlen(get_config('system', 'directory'))) {
3764 proc_run(PRIORITY_LOW, "include/directory.php", $url);
3767 proc_run(PRIORITY_LOW, 'include/profile_update.php', api_user());
3769 // output for client
3771 return api_account_verify_credentials($type);
3773 // SaveMediaToDatabase failed for some reason
3774 throw new InternalServerErrorException("image upload failed");
3778 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3779 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3780 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3781 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3782 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3783 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3784 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3785 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3786 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3789 function check_acl_input($acl_string) {
3790 if ($acl_string == null || $acl_string == " ") {
3793 $contact_not_found = false;
3795 // split <x><y><z> into array of cid's
3796 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3798 // check for each cid if it is available on server
3799 $cid_array = $array[0];
3800 foreach ($cid_array as $cid) {
3801 $cid = str_replace("<", "", $cid);
3802 $cid = str_replace(">", "", $cid);
3803 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3805 intval(api_user()));
3806 $contact_not_found |= !dbm::is_result($contact);
3808 return $contact_not_found;
3811 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) {
3818 if (is_array($media)) {
3819 if (is_array($media['tmp_name'])) {
3820 $src = $media['tmp_name'][0];
3822 $src = $media['tmp_name'];
3824 if (is_array($media['name'])) {
3825 $filename = basename($media['name'][0]);
3827 $filename = basename($media['name']);
3829 if (is_array($media['size'])) {
3830 $filesize = intval($media['size'][0]);
3832 $filesize = intval($media['size']);
3834 if (is_array($media['type'])) {
3835 $filetype = $media['type'][0];
3837 $filetype = $media['type'];
3841 if ($filetype == "") {
3842 $filetype=guess_image_type($filename);
3844 $imagedata = getimagesize($src);
3846 $filetype = $imagedata['mime'];
3848 logger("File upload src: " . $src . " - filename: " . $filename .
3849 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3851 // check if there was a php upload error
3852 if ($filesize == 0 && $media['error'] == 1) {
3853 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3855 // check against max upload size within Friendica instance
3856 $maximagesize = get_config('system', 'maximagesize');
3857 if (($maximagesize) && ($filesize > $maximagesize)) {
3858 $formattedBytes = formatBytes($maximagesize);
3859 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3862 // create Photo instance with the data of the image
3863 $imagedata = @file_get_contents($src);
3864 $ph = new Photo($imagedata, $filetype);
3865 if (! $ph->is_valid()) {
3866 throw new InternalServerErrorException("unable to process image data");
3869 // check orientation of image
3873 // check max length of images on server
3874 $max_length = get_config('system', 'max_image_length');
3875 if (! $max_length) {
3876 $max_length = MAX_IMAGE_LENGTH;
3878 if ($max_length > 0) {
3879 $ph->scaleImage($max_length);
3880 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3882 $width = $ph->getWidth();
3883 $height = $ph->getHeight();
3885 // create a new resource-id if not already provided
3886 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3888 if ($mediatype == "photo") {
3889 // upload normal image (scales 0, 1, 2)
3890 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3892 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3894 logger("photo upload: image upload with scale 0 (original size) failed");
3896 if($width > 640 || $height > 640) {
3897 $ph->scaleImage(640);
3898 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3900 logger("photo upload: image upload with scale 1 (640x640) failed");
3904 if ($width > 320 || $height > 320) {
3905 $ph->scaleImage(320);
3906 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3908 logger("photo upload: image upload with scale 2 (320x320) failed");
3911 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3912 } elseif ($mediatype == "profileimage") {
3913 // upload profile image (scales 4, 5, 6)
3914 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3916 if ($width > 175 || $height > 175) {
3917 $ph->scaleImage(175);
3918 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3920 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3924 if ($width > 80 || $height > 80) {
3925 $ph->scaleImage(80);
3926 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3928 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3932 if ($width > 48 || $height > 48) {
3933 $ph->scaleImage(48);
3934 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3936 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3940 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3944 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3945 if ($photo_id == null && $mediatype == "photo") {
3946 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3948 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3949 return prepare_photo_data($type, false, $hash);
3951 throw new InternalServerErrorException("image upload failed");
3955 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3956 // get data about the api authenticated user
3957 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3958 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3961 $arr['guid'] = get_guid(32);
3962 $arr['uid'] = intval(api_user());
3964 $arr['parent-uri'] = $uri;
3965 $arr['type'] = 'photo';
3967 $arr['resource-id'] = $hash;
3968 $arr['contact-id'] = $owner_record[0]['id'];
3969 $arr['owner-name'] = $owner_record[0]['name'];
3970 $arr['owner-link'] = $owner_record[0]['url'];
3971 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3972 $arr['author-name'] = $owner_record[0]['name'];
3973 $arr['author-link'] = $owner_record[0]['url'];
3974 $arr['author-avatar'] = $owner_record[0]['thumb'];
3976 $arr['allow_cid'] = $allow_cid;
3977 $arr['allow_gid'] = $allow_gid;
3978 $arr['deny_cid'] = $deny_cid;
3979 $arr['deny_gid'] = $deny_gid;
3980 $arr['last-child'] = 1;
3981 $arr['visible'] = $visibility;
3985 'image/jpeg' => 'jpg',
3986 'image/png' => 'png',
3987 'image/gif' => 'gif'
3990 // adds link to the thumbnail scale photo
3991 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
3992 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3995 // do the magic for storing the item in the database and trigger the federation to other contacts
3999 function prepare_photo_data($type, $scale, $photo_id) {
4000 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4001 $data_sql = ($scale === false ? "" : "data, ");
4003 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4004 // clients needs to convert this in their way for further processing
4005 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4006 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4007 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4008 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4010 intval(local_user()),
4016 'image/jpeg' => 'jpg',
4017 'image/png' => 'png',
4018 'image/gif' => 'gif'
4021 // prepare output data for photo
4022 if (dbm::is_result($r)) {
4023 $data = array('photo' => $r[0]);
4024 $data['photo']['id'] = $data['photo']['resource-id'];
4025 if ($scale !== false) {
4026 $data['photo']['data'] = base64_encode($data['photo']['data']);
4028 unset($data['photo']['datasize']); //needed only with scale param
4030 if ($type == "xml") {
4031 $data['photo']['links'] = array();
4032 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4033 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4035 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4038 $data['photo']['link'] = array();
4039 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4041 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4042 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4046 unset($data['photo']['resource-id']);
4047 unset($data['photo']['minscale']);
4048 unset($data['photo']['maxscale']);
4051 throw new NotFoundException();
4054 // retrieve item element for getting activities (like, dislike etc.) related to photo
4055 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4056 intval(local_user()),
4059 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4061 // retrieve comments on photo
4062 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4063 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4064 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4065 `contact`.`id` AS `cid`
4067 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4068 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4069 WHERE `item`.`parent` = %d AND `item`.`visible`
4070 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4071 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4072 intval($item[0]['parent']),
4074 dbesc(ACTIVITY_POST)
4077 // prepare output of comments
4078 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4079 $comments = array();
4080 if ($type == "xml") {
4082 foreach ($commentData as $comment) {
4083 $comments[$k++ . ":comment"] = $comment;
4086 foreach ($commentData as $comment) {
4087 $comments[] = $comment;
4090 $data['photo']['friendica_comments'] = $comments;
4092 // include info if rights on photo and rights on item are mismatching
4093 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4094 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4095 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4096 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4097 $data['photo']['rights_mismatch'] = $rights_mismatch;
4104 * similar as /mod/redir.php
4105 * redirect to 'url' after dfrn auth
4107 * why this when there is mod/redir.php already?
4108 * This use api_user() and api_login()
4111 * c_url: url of remote contact to auth to
4112 * url: string, url to redirect after auth
4114 function api_friendica_remoteauth() {
4115 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4116 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4118 if ($url === '' || $c_url === '') {
4119 throw new BadRequestException("Wrong parameters.");
4122 $c_url = normalise_link($c_url);
4126 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4131 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4132 throw new BadRequestException("Unknown contact");
4137 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4139 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4140 $orig_id = $r[0]['issued-id'];
4141 $dfrn_id = '1:' . $orig_id;
4143 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4144 $orig_id = $r[0]['dfrn-id'];
4145 $dfrn_id = '0:' . $orig_id;
4148 $sec = random_string();
4150 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4151 VALUES( %d, %s, '%s', '%s', %d )",
4159 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4160 $dest = (($url) ? '&destination_url=' . $url : '');
4161 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4162 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4163 . '&type=profile&sec=' . $sec . $dest . $quiet );
4165 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4168 * @brief Return the item shared, if the item contains only the [share] tag
4170 * @param array $item Sharer item
4171 * @return array Shared item or false if not a reshare
4173 function api_share_as_retweet(&$item) {
4174 $body = trim($item["body"]);
4176 if (Diaspora::is_reshare($body, false)===false) {
4180 /// @TODO "$1" should maybe mean '$1' ?
4181 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4183 * Skip if there is no shared message in there
4184 * we already checked this in diaspora::is_reshare()
4185 * but better one more than one less...
4187 if ($body == $attributes) {
4192 // build the fake reshared item
4193 $reshared_item = $item;
4196 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4197 if ($matches[1] != "") {
4198 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4201 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4202 if ($matches[1] != "") {
4203 $author = $matches[1];
4207 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4208 if ($matches[1] != "") {
4209 $profile = $matches[1];
4212 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4213 if ($matches[1] != "") {
4214 $profile = $matches[1];
4218 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4219 if ($matches[1] != "") {
4220 $avatar = $matches[1];
4223 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4224 if ($matches[1] != "") {
4225 $avatar = $matches[1];
4229 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4230 if ($matches[1] != "") {
4231 $link = $matches[1];
4234 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4235 if ($matches[1] != "") {
4236 $link = $matches[1];
4240 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4241 if ($matches[1] != "")
4242 $posted = $matches[1];
4244 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4245 if ($matches[1] != "") {
4246 $posted = $matches[1];
4249 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4251 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4255 $reshared_item["body"] = $shared_body;
4256 $reshared_item["author-name"] = $author;
4257 $reshared_item["author-link"] = $profile;
4258 $reshared_item["author-avatar"] = $avatar;
4259 $reshared_item["plink"] = $link;
4260 $reshared_item["created"] = $posted;
4261 $reshared_item["edited"] = $posted;
4263 return $reshared_item;
4267 function api_get_nick($profile) {
4269 - remove trailing junk from profile url
4270 - pump.io check has to check the website
4275 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4276 dbesc(normalise_link($profile)));
4278 if (dbm::is_result($r)) {
4279 $nick = $r[0]["nick"];
4283 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4284 dbesc(normalise_link($profile)));
4286 if (dbm::is_result($r)) {
4287 $nick = $r[0]["nick"];
4292 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4293 if ($friendica != $profile) {
4299 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4300 if ($diaspora != $profile) {
4306 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4307 if ($twitter != $profile) {
4314 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4315 if ($StatusnetHost != $profile) {
4316 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4317 if ($StatusnetUser != $profile) {
4318 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4319 $user = json_decode($UserData);
4321 $nick = $user->screen_name;
4327 // To-Do: look at the page if its really a pumpio site
4328 //if (!$nick == "") {
4329 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4330 // if ($pumpio != $profile)
4332 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4343 function api_in_reply_to($item) {
4344 $in_reply_to = array();
4346 $in_reply_to['status_id'] = NULL;
4347 $in_reply_to['user_id'] = NULL;
4348 $in_reply_to['status_id_str'] = NULL;
4349 $in_reply_to['user_id_str'] = NULL;
4350 $in_reply_to['screen_name'] = NULL;
4352 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4353 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4354 intval($item['uid']),
4355 dbesc($item['thr-parent']));
4357 if (dbm::is_result($r)) {
4358 $in_reply_to['status_id'] = intval($r[0]['id']);
4360 $in_reply_to['status_id'] = intval($item['parent']);
4363 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4365 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4366 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4367 WHERE `item`.`id` = %d LIMIT 1",
4368 intval($in_reply_to['status_id'])
4371 if (dbm::is_result($r)) {
4372 if ($r[0]['nick'] == "") {
4373 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4376 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4377 $in_reply_to['user_id'] = intval($r[0]['id']);
4378 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4381 // There seems to be situation, where both fields are identical:
4382 // https://github.com/friendica/friendica/issues/1010
4383 // This is a bugfix for that.
4384 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4385 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4386 $in_reply_to['status_id'] = NULL;
4387 $in_reply_to['user_id'] = NULL;
4388 $in_reply_to['status_id_str'] = NULL;
4389 $in_reply_to['user_id_str'] = NULL;
4390 $in_reply_to['screen_name'] = NULL;
4394 return $in_reply_to;
4397 function api_clean_plain_items($Text) {
4398 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4400 $Text = bb_CleanPictureLinks($Text);
4401 $URLSearchString = "^\[\]";
4403 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4405 if ($include_entities == "true") {
4406 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4409 // Simplify "attachment" element
4410 $Text = api_clean_attachments($Text);
4416 * @brief Removes most sharing information for API text export
4418 * @param string $body The original body
4420 * @return string Cleaned body
4422 function api_clean_attachments($body) {
4423 $data = get_attachment_data($body);
4430 if (isset($data["text"]))
4431 $body = $data["text"];
4433 if (($body == "") && (isset($data["title"])))
4434 $body = $data["title"];
4436 if (isset($data["url"]))
4437 $body .= "\n".$data["url"];
4439 $body .= $data["after"];
4444 function api_best_nickname(&$contacts) {
4445 $best_contact = array();
4447 if (count($contact) == 0)
4450 foreach ($contacts AS $contact)
4451 if ($contact["network"] == "") {
4452 $contact["network"] = "dfrn";
4453 $best_contact = array($contact);
4456 if (sizeof($best_contact) == 0)
4457 foreach ($contacts AS $contact)
4458 if ($contact["network"] == "dfrn")
4459 $best_contact = array($contact);
4461 if (sizeof($best_contact) == 0)
4462 foreach ($contacts AS $contact)
4463 if ($contact["network"] == "dspr")
4464 $best_contact = array($contact);
4466 if (sizeof($best_contact) == 0)
4467 foreach ($contacts AS $contact)
4468 if ($contact["network"] == "stat")
4469 $best_contact = array($contact);
4471 if (sizeof($best_contact) == 0)
4472 foreach ($contacts AS $contact)
4473 if ($contact["network"] == "pump")
4474 $best_contact = array($contact);
4476 if (sizeof($best_contact) == 0)
4477 foreach ($contacts AS $contact)
4478 if ($contact["network"] == "twit")
4479 $best_contact = array($contact);
4481 if (sizeof($best_contact) == 1)
4482 $contacts = $best_contact;
4484 $contacts = array($contacts[0]);
4487 // return all or a specified group of the user with the containing contacts
4488 function api_friendica_group_show($type) {
4492 if (api_user() === false) throw new ForbiddenException();
4495 $user_info = api_get_user($a);
4496 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4497 $uid = $user_info['uid'];
4499 // get data of the specified group id or all groups if not specified
4501 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4504 // error message if specified gid is not in database
4505 if (!dbm::is_result($r))
4506 throw new BadRequestException("gid not available");
4509 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4512 // loop through all groups and retrieve all members for adding data in the user array
4513 foreach ($r as $rr) {
4514 $members = group_get_members($rr['id']);
4517 if ($type == "xml") {
4518 $user_element = "users";
4520 foreach ($members as $member) {
4521 $user = api_get_user($a, $member['nurl']);
4522 $users[$k++.":user"] = $user;
4525 $user_element = "user";
4526 foreach ($members as $member) {
4527 $user = api_get_user($a, $member['nurl']);
4531 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4533 return api_format_data("groups", $type, array('group' => $grps));
4535 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4538 // delete the specified group of the user
4539 function api_friendica_group_delete($type) {
4543 if (api_user() === false) throw new ForbiddenException();
4546 $user_info = api_get_user($a);
4547 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4548 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4549 $uid = $user_info['uid'];
4551 // error if no gid specified
4552 if ($gid == 0 || $name == "")
4553 throw new BadRequestException('gid or name not specified');
4555 // get data of the specified group id
4556 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4559 // error message if specified gid is not in database
4560 if (!dbm::is_result($r))
4561 throw new BadRequestException('gid not available');
4563 // get data of the specified group id and group name
4564 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4568 // error message if specified gid is not in database
4569 if (!dbm::is_result($rname))
4570 throw new BadRequestException('wrong group name');
4573 $ret = group_rmv($uid, $name);
4576 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4577 return api_format_data("group_delete", $type, array('result' => $success));
4580 throw new BadRequestException('other API error');
4582 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4585 // create the specified group with the posted array of contacts
4586 function api_friendica_group_create($type) {
4590 if (api_user() === false) throw new ForbiddenException();
4593 $user_info = api_get_user($a);
4594 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4595 $uid = $user_info['uid'];
4596 $json = json_decode($_POST['json'], true);
4597 $users = $json['user'];
4599 // error if no name specified
4601 throw new BadRequestException('group name not specified');
4603 // get data of the specified group name
4604 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4607 // error message if specified group name already exists
4608 if (dbm::is_result($rname))
4609 throw new BadRequestException('group name already exists');
4611 // check if specified group name is a deleted group
4612 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4615 // error message if specified group name already exists
4616 if (dbm::is_result($rname))
4617 $reactivate_group = true;
4620 $ret = group_add($uid, $name);
4622 $gid = group_byname($uid, $name);
4624 throw new BadRequestException('other API error');
4627 $erroraddinguser = false;
4628 $errorusers = array();
4629 foreach ($users as $user) {
4630 $cid = $user['cid'];
4631 // check if user really exists as contact
4632 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4635 if (count($contact))
4636 $result = group_add_member($uid, $name, $cid, $gid);
4638 $erroraddinguser = true;
4639 $errorusers[] = $cid;
4643 // return success message incl. missing users in array
4644 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4645 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4646 return api_format_data("group_create", $type, array('result' => $success));
4648 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4651 // update the specified group with the posted array of contacts
4652 function api_friendica_group_update($type) {
4656 if (api_user() === false) throw new ForbiddenException();
4659 $user_info = api_get_user($a);
4660 $uid = $user_info['uid'];
4661 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4662 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4663 $json = json_decode($_POST['json'], true);
4664 $users = $json['user'];
4666 // error if no name specified
4668 throw new BadRequestException('group name not specified');
4670 // error if no gid specified
4672 throw new BadRequestException('gid not specified');
4675 $members = group_get_members($gid);
4676 foreach ($members as $member) {
4677 $cid = $member['id'];
4678 foreach ($users as $user) {
4679 $found = ($user['cid'] == $cid ? true : false);
4682 $ret = group_rmv_member($uid, $name, $cid);
4687 $erroraddinguser = false;
4688 $errorusers = array();
4689 foreach ($users as $user) {
4690 $cid = $user['cid'];
4691 // check if user really exists as contact
4692 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4695 if (count($contact))
4696 $result = group_add_member($uid, $name, $cid, $gid);
4698 $erroraddinguser = true;
4699 $errorusers[] = $cid;
4703 // return success message incl. missing users in array
4704 $status = ($erroraddinguser ? "missing user" : "ok");
4705 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4706 return api_format_data("group_update", $type, array('result' => $success));
4709 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4711 function api_friendica_activity($type) {
4715 if (api_user() === false) throw new ForbiddenException();
4716 $verb = strtolower($a->argv[3]);
4717 $verb = preg_replace("|\..*$|", "", $verb);
4719 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4721 $res = do_like($id, $verb);
4728 return api_format_data('ok', $type, array('ok' => $ok));
4730 throw new BadRequestException('Error adding activity');
4735 /// @TODO move to top of file or somwhere better
4736 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4737 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4738 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4739 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4740 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4741 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4742 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4743 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4744 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4745 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4748 * @brief Returns notifications
4750 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4753 function api_friendica_notification($type) {
4757 if (api_user() === false) throw new ForbiddenException();
4758 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4759 $nm = new NotificationsManager();
4761 $notes = $nm->getAll(array(), "+seen -date", 50);
4763 if ($type == "xml") {
4764 $xmlnotes = array();
4765 foreach ($notes AS $note)
4766 $xmlnotes[] = array("@attributes" => $note);
4771 return api_format_data("notes", $type, array('note' => $notes));
4775 * @brief Set notification as seen and returns associated item (if possible)
4777 * POST request with 'id' param as notification id
4779 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4782 function api_friendica_notification_seen($type) {
4786 if (api_user() === false) throw new ForbiddenException();
4787 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4789 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4791 $nm = new NotificationsManager();
4792 $note = $nm->getByID($id);
4793 if (is_null($note)) throw new BadRequestException("Invalid argument");
4795 $nm->setSeen($note);
4796 if ($note['otype']=='item') {
4797 // would be really better with an ItemsManager and $im->getByID() :-P
4798 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4799 intval($note['iid']),
4800 intval(local_user())
4803 // we found the item, return it to the user
4804 $user_info = api_get_user($a);
4805 $ret = api_format_items($r,$user_info, false, $type);
4806 $data = array('status' => $ret);
4807 return api_format_data("status", $type, $data);
4809 // the item can't be found, but we set the note as seen, so we count this as a success
4811 return api_format_data('result', $type, array('result' => "success"));
4814 /// @TODO move to top of file or somwhere better
4815 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4816 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4819 * @brief update a direct_message to seen state
4821 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4822 * @return string (success result=ok, error result=error with error message)
4824 function api_friendica_direct_messages_setseen($type) {
4826 if (api_user() === false) {
4827 throw new ForbiddenException();
4831 $user_info = api_get_user($a);
4832 $uid = $user_info['uid'];
4833 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4835 // return error if id is zero
4837 $answer = array('result' => 'error', 'message' => 'message id not specified');
4838 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4841 // get data of the specified message id
4842 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4846 // error message if specified id is not in database
4847 if (!dbm::is_result($r)) {
4848 $answer = array('result' => 'error', 'message' => 'message id not in database');
4849 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4852 // update seen indicator
4853 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4859 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4860 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4862 $answer = array('result' => 'error', 'message' => 'unknown error');
4863 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4867 /// @TODO move to top of file or somwhere better
4868 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4871 * @brief search for direct_messages containing a searchstring through api
4873 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4874 * @return string (success: success=true if found and search_result contains found messages
4875 * success=false if nothing was found, search_result='nothing found',
4876 * error: result=error with error message)
4878 function api_friendica_direct_messages_search($type) {
4881 if (api_user() === false) {
4882 throw new ForbiddenException();
4886 $user_info = api_get_user($a);
4887 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4888 $uid = $user_info['uid'];
4890 // error if no searchstring specified
4891 if ($searchstring == "") {
4892 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4893 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4896 // get data for the specified searchstring
4897 $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",
4899 dbesc('%'.$searchstring.'%')
4902 $profile_url = $user_info["url"];
4904 // message if nothing was found
4905 if (!dbm::is_result($r)) {
4906 $success = array('success' => false, 'search_results' => 'problem with query');
4907 } elseif (count($r) == 0) {
4908 $success = array('success' => false, 'search_results' => 'nothing found');
4911 foreach ($r as $item) {
4912 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4913 $recipient = $user_info;
4914 $sender = api_get_user($a,normalise_link($item['contact-url']));
4915 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4916 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4917 $sender = $user_info;
4920 $ret[] = api_format_messages($item, $recipient, $sender);
4922 $success = array('success' => true, 'search_results' => $ret);
4925 return api_format_data("direct_message_search", $type, array('$result' => $success));
4928 /// @TODO move to top of file or somwhere better
4929 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4932 * @brief return data of all the profiles a user has to the client
4934 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4937 function api_friendica_profile_show($type) {
4940 if (api_user() === false) {
4941 throw new ForbiddenException();
4945 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4947 // retrieve general information about profiles for user
4948 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4949 $directory = get_config('system', 'directory');
4951 // get data of the specified profile id or all profiles of the user if not specified
4952 if ($profileid != 0) {
4953 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4955 intval($profileid));
4957 // error message if specified gid is not in database
4958 if (!dbm::is_result($r)) {
4959 throw new BadRequestException("profile_id not available");
4962 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4963 intval(api_user()));
4965 // loop through all returned profiles and retrieve data and users
4967 foreach ($r as $rr) {
4968 $profile = api_format_items_profiles($rr, $type);
4970 // select all users from contact table, loop and prepare standard return for user data
4972 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4974 intval($rr['profile_id']));
4976 foreach ($r as $rr) {
4977 $user = api_get_user($a, $rr['nurl']);
4978 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4980 $profile['users'] = $users;
4982 // add prepared profile data to array for final return
4983 if ($type == "xml") {
4984 $profiles[$k++ . ":profile"] = $profile;
4986 $profiles[] = $profile;
4990 // return settings, authenticated user and profiles data
4991 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4993 $result = array('multi_profiles' => $multi_profiles ? true : false,
4994 'global_dir' => $directory,
4995 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4996 'profiles' => $profiles);
4997 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4999 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5002 @TODO Maybe open to implement?
5004 [pagename] => api/1.1/statuses/lookup.json
5005 [id] => 605138389168451584
5006 [include_cards] => true
5007 [cards_platform] => Android-12
5008 [include_entities] => true
5009 [include_my_retweet] => 1
5011 [include_reply_count] => true
5012 [include_descendent_reply_count] => true
5016 Not implemented by now:
5017 statuses/retweets_of_me
5022 account/update_location
5023 account/update_profile_background_image
5026 friendica/profile/update
5027 friendica/profile/create
5028 friendica/profile/delete
5030 Not implemented in status.net:
5031 statuses/retweeted_to_me
5032 statuses/retweeted_by_me
5033 direct_messages/destroy
5035 account/update_delivery_device
5036 notifications/follow