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;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
16 require_once 'include/HTTPExceptions.php';
17 require_once 'include/bbcode.php';
18 require_once 'include/datetime.php';
19 require_once 'include/conversation.php';
20 require_once 'include/oauth.php';
21 require_once 'include/html2plain.php';
22 require_once 'mod/share.php';
23 require_once 'include/Photo.php';
24 require_once 'mod/item.php';
25 require_once 'include/security.php';
26 require_once 'include/contact_selectors.php';
27 require_once 'include/html2bbcode.php';
28 require_once 'mod/wall_upload.php';
29 require_once 'mod/proxy.php';
30 require_once 'include/message.php';
31 require_once 'include/group.php';
32 require_once 'include/like.php';
33 require_once 'include/plaintext.php';
34 require_once 'include/xml.php';
36 define('API_METHOD_ANY', '*');
37 define('API_METHOD_GET', 'GET');
38 define('API_METHOD_POST', 'POST,PUT');
39 define('API_METHOD_DELETE', 'POST,DELETE');
44 /// @TODO Fix intending
46 * @brief Auth API user
48 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
49 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
50 * into a page, and visitors will post something without noticing it).
53 if (x($_SESSION, 'allow_api')) {
61 * @brief Get source name from API client
63 * Clients can send 'source' parameter to be show in post metadata
64 * as "sent via <source>".
65 * Some clients doesn't send a source param, we support ones we know
69 * Client source name, default to "api" if unset/unknown
71 function api_source() {
72 if (requestdata('source')) {
73 return requestdata('source');
76 // Support for known clients that doesn't send a source name
77 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
81 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
87 * @brief Format date for API
89 * @param string $str Source date, as UTC
90 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
92 function api_date($str) {
93 // Wed May 23 06:01:13 +0000 2007
94 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
98 * @brief Register API endpoint
100 * Register a function to be the endpont for defined API path.
102 * @param string $path API URL path, relative to System::baseUrl()
103 * @param string $func Function name to call on path request
104 * @param bool $auth API need logged user
105 * @param string $method HTTP method reqiured to call this endpoint.
107 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
108 * Default to API_METHOD_ANY
110 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
119 // Workaround for hotot
120 $path = str_replace("api/", "api/1.1/", $path);
130 * @brief Login API user
132 * Log in user via OAuth1 or Simple HTTP Auth.
133 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
136 * @hook 'authenticate'
138 * 'username' => username from login form
139 * 'password' => password from login form
140 * 'authenticated' => return status,
141 * 'user_record' => return authenticated user record
143 * array $user logged user record
145 function api_login(App $a) {
148 $oauth = new FKOAuth1();
149 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
150 if (!is_null($token)) {
151 $oauth->loginUser($token->uid);
152 call_hooks('logged_in', $a->user);
155 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
156 var_dump($consumer, $token);
158 } catch (Exception $e) {
162 // workaround for HTTP-auth in CGI mode
163 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
164 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
165 if (strlen($userpass)) {
166 list($name, $password) = explode(':', $userpass);
167 $_SERVER['PHP_AUTH_USER'] = $name;
168 $_SERVER['PHP_AUTH_PW'] = $password;
172 if (!x($_SERVER, 'PHP_AUTH_USER')) {
173 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
174 header('WWW-Authenticate: Basic realm="Friendica"');
175 throw new UnauthorizedException("This API requires login");
178 $user = $_SERVER['PHP_AUTH_USER'];
179 $password = $_SERVER['PHP_AUTH_PW'];
180 $encrypted = hash('whirlpool', trim($password));
182 // allow "user@server" login (but ignore 'server' part)
183 $at = strstr($user, "@", true);
188 // next code from mod/auth.php. needs better solution
192 'username' => trim($user),
193 'password' => trim($password),
194 'authenticated' => 0,
195 'user_record' => null,
199 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
200 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
201 * and later plugins should not interfere with an earlier one that succeeded.
203 call_hooks('authenticate', $addon_auth);
205 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
206 $record = $addon_auth['user_record'];
208 // process normal login request
209 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
210 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
215 if (DBM::is_result($r)) {
220 if ((! $record) || (! count($record))) {
221 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
222 header('WWW-Authenticate: Basic realm="Friendica"');
223 //header('HTTP/1.0 401 Unauthorized');
224 //die('This api requires login');
225 throw new UnauthorizedException("This API requires login");
228 authenticate_success($record);
230 $_SESSION["allow_api"] = true;
232 call_hooks('logged_in', $a->user);
237 * @brief Check HTTP method of called API
239 * API endpoints can define which HTTP method to accept when called.
240 * This function check the current HTTP method agains endpoint
243 * @param string $method Required methods, uppercase, separated by comma
246 function api_check_method($method) {
247 if ($method == "*") {
250 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
254 * @brief Main API entry point
256 * Authenticate user, call registered API function, set HTTP headers
259 * @return string API call result
261 function api_call(App $a) {
262 global $API, $called_api;
265 if (strpos($a->query_string, ".xml") > 0) {
268 if (strpos($a->query_string, ".json") > 0) {
271 if (strpos($a->query_string, ".rss") > 0) {
274 if (strpos($a->query_string, ".atom") > 0) {
279 foreach ($API as $p => $info) {
280 if (strpos($a->query_string, $p) === 0) {
281 if (!api_check_method($info['method'])) {
282 throw new MethodNotAllowedException();
285 $called_api = explode("/", $p);
286 //unset($_SERVER['PHP_AUTH_USER']);
288 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
289 if ($info['auth'] === true && api_user() === false) {
293 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
294 logger('API parameters: ' . print_r($_REQUEST, true));
296 $stamp = microtime(true);
297 $r = call_user_func($info['func'], $type);
298 $duration = (float) (microtime(true) - $stamp);
299 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
301 if (Config::get("system", "profiler")) {
302 $duration = microtime(true)-$a->performance["start"];
304 /// @TODO round() really everywhere?
305 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
306 round($a->performance["database"] - $a->performance["database_write"], 3),
307 round($a->performance["database_write"], 3),
308 round($a->performance["network"], 2),
309 round($a->performance["file"], 2),
310 round($duration - ($a->performance["database"] + $a->performance["network"]
311 + $a->performance["file"]), 2),
312 round($duration, 2)),
316 if (Config::get("rendertime", "callstack")) {
317 $o = "Database Read:\n";
318 foreach ($a->callstack["database"] AS $func => $time) {
319 $time = round($time, 3);
321 $o .= $func . ": " . $time . "\n";
324 $o .= "\nDatabase Write:\n";
325 foreach ($a->callstack["database_write"] AS $func => $time) {
326 $time = round($time, 3);
328 $o .= $func . ": " . $time . "\n";
332 $o .= "\nNetwork:\n";
333 foreach ($a->callstack["network"] AS $func => $time) {
334 $time = round($time, 3);
336 $o .= $func . ": " . $time . "\n";
339 logger($o, LOGGER_DEBUG);
345 * api function returned false withour throw an
346 * exception. This should not happend, throw a 500
348 throw new InternalServerErrorException();
353 header ("Content-Type: text/xml");
357 header ("Content-Type: application/json");
359 $json = json_encode($rr);
360 if (x($_GET, 'callback')) {
361 $json = $_GET['callback'] . "(" . $json . ")";
366 header ("Content-Type: application/rss+xml");
367 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
370 header ("Content-Type: application/atom+xml");
371 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
377 logger('API call not implemented: ' . $a->query_string);
378 throw new NotImplementedException();
379 } catch (HTTPException $e) {
380 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
381 return api_error($type, $e);
386 * @brief Format API error string
388 * @param string $type Return type (xml, json, rss, as)
389 * @param HTTPException $error Error object
390 * @return strin error message formatted as $type
392 function api_error($type, $e) {
396 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
397 /// @TODO: https://dev.twitter.com/overview/api/response-codes
399 $error = array("error" => $error,
400 "code" => $e->httpcode . " " . $e->httpdesc,
401 "request" => $a->query_string);
403 $ret = api_format_data('status', $type, array('status' => $error));
407 header ("Content-Type: text/xml");
411 header ("Content-Type: application/json");
412 return json_encode($ret);
415 header ("Content-Type: application/rss+xml");
419 header ("Content-Type: application/atom+xml");
426 * @brief Set values for RSS template
429 * @param array $arr Array to be passed to template
430 * @param array $user_info
432 * @todo find proper type-hints
434 function api_rss_extra(App $a, $arr, $user_info) {
435 if (is_null($user_info)) {
436 $user_info = api_get_user($a);
439 $arr['$user'] = $user_info;
440 $arr['$rss'] = array(
441 'alternate' => $user_info['url'],
442 'self' => System::baseUrl() . "/" . $a->query_string,
443 'base' => System::baseUrl(),
444 'updated' => api_date(null),
445 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
446 'language' => $user_info['language'],
447 'logo' => System::baseUrl() . "/images/friendica-32.png",
455 * @brief Unique contact to contact url.
457 * @param int $id Contact id
458 * @return bool|string
459 * Contact url or False if contact id is unknown
461 function api_unique_id_to_url($id) {
462 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
464 if (DBM::is_result($r)) {
472 * @brief Get user info array.
475 * @param int|string $contact_id Contact ID or URL
476 * @param string $type Return type (for errors)
478 function api_get_user(App $a, $contact_id = null, $type = "json") {
486 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
488 // Searching for contact URL
489 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
490 $user = dbesc(normalise_link($contact_id));
492 $extra_query = "AND `contact`.`nurl` = '%s' ";
493 if (api_user() !== false) {
494 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
498 // Searching for contact id with uid = 0
499 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
500 $user = dbesc(api_unique_id_to_url($contact_id));
503 throw new BadRequestException("User not found.");
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 if (is_null($user) && x($_GET, 'user_id')) {
514 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
517 throw new BadRequestException("User not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
526 if (is_null($user) && x($_GET, 'screen_name')) {
527 $user = dbesc($_GET['screen_name']);
529 $extra_query = "AND `contact`.`nick` = '%s' ";
530 if (api_user() !== false) {
531 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
535 if (is_null($user) && x($_GET, 'profileurl')) {
536 $user = dbesc(normalise_link($_GET['profileurl']));
538 $extra_query = "AND `contact`.`nurl` = '%s' ";
539 if (api_user() !== false) {
540 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
544 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
545 $argid = count($called_api);
546 list($user, $null) = explode(".", $a->argv[$argid]);
547 if (is_numeric($user)) {
548 $user = dbesc(api_unique_id_to_url($user));
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 $user = dbesc($user);
562 $extra_query = "AND `contact`.`nick` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
569 logger("api_get_user: user ".$user, LOGGER_DEBUG);
572 if (api_user() === false) {
576 $user = $_SESSION['uid'];
577 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
582 logger('api_user: ' . $extra_query . ', user: ' . $user);
585 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
591 // Selecting the id by priority, friendica first
592 api_best_nickname($uinfo);
594 // if the contact wasn't found, fetch it from the contacts with uid = 0
595 if (!DBM::is_result($uinfo)) {
599 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
602 if (DBM::is_result($r)) {
603 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
605 // If no nick where given, extract it from the address
606 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
607 $r[0]['nick'] = api_get_nick($r[0]["url"]);
612 'id_str' => (string) $r[0]["id"],
613 'name' => $r[0]["name"],
614 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
615 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
616 'description' => $r[0]["about"],
617 'profile_image_url' => $r[0]["micro"],
618 'profile_image_url_https' => $r[0]["micro"],
619 'url' => $r[0]["url"],
620 'protected' => false,
621 'followers_count' => 0,
622 'friends_count' => 0,
624 'created_at' => api_date($r[0]["created"]),
625 'favourites_count' => 0,
627 'time_zone' => 'UTC',
628 'geo_enabled' => false,
630 'statuses_count' => 0,
632 'contributors_enabled' => false,
633 'is_translator' => false,
634 'is_translation_enabled' => false,
635 'following' => false,
636 'follow_request_sent' => false,
637 'statusnet_blocking' => false,
638 'notifications' => false,
639 'statusnet_profile_url' => $r[0]["url"],
641 'cid' => get_contact($r[0]["url"], api_user(), true),
643 'network' => $r[0]["network"],
648 throw new BadRequestException("User not found.");
652 if ($uinfo[0]['self']) {
654 if ($uinfo[0]['network'] == "") {
655 $uinfo[0]['network'] = NETWORK_DFRN;
658 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
661 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
665 /// @TODO old-lost code? (twice)
666 // Counting is deactivated by now, due to performance issues
667 // count public wall messages
668 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
669 // intval($uinfo[0]['uid'])
671 //$countitms = $r[0]['count'];
674 // Counting is deactivated by now, due to performance issues
675 //$r = q("SELECT count(*) as `count` FROM `item`
676 // WHERE `contact-id` = %d",
677 // intval($uinfo[0]['id'])
679 //$countitms = $r[0]['count'];
683 /// @TODO old-lost code? (twice)
685 // Counting is deactivated by now, due to performance issues
687 $r = q("SELECT count(*) as `count` FROM `contact`
688 WHERE `uid` = %d AND `rel` IN ( %d, %d )
689 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
690 intval($uinfo[0]['uid']),
691 intval(CONTACT_IS_SHARING),
692 intval(CONTACT_IS_FRIEND)
694 $countfriends = $r[0]['count'];
696 $r = q("SELECT count(*) as `count` FROM `contact`
697 WHERE `uid` = %d AND `rel` IN ( %d, %d )
698 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
699 intval($uinfo[0]['uid']),
700 intval(CONTACT_IS_FOLLOWER),
701 intval(CONTACT_IS_FRIEND)
703 $countfollowers = $r[0]['count'];
705 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
706 intval($uinfo[0]['uid'])
708 $starred = $r[0]['count'];
711 if (! $uinfo[0]['self']) {
721 // Add a nick if it isn't present there
722 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
723 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
726 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
728 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
731 'id' => intval($pcontact_id),
732 'id_str' => (string) intval($pcontact_id),
733 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
734 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
735 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
736 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
737 'profile_image_url' => $uinfo[0]['micro'],
738 'profile_image_url_https' => $uinfo[0]['micro'],
739 'url' => $uinfo[0]['url'],
740 'protected' => false,
741 'followers_count' => intval($countfollowers),
742 'friends_count' => intval($countfriends),
744 'created_at' => api_date($uinfo[0]['created']),
745 'favourites_count' => intval($starred),
747 'time_zone' => 'UTC',
748 'geo_enabled' => false,
750 'statuses_count' => intval($countitms),
752 'contributors_enabled' => false,
753 'is_translator' => false,
754 'is_translation_enabled' => false,
755 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
756 'follow_request_sent' => false,
757 'statusnet_blocking' => false,
758 'notifications' => false,
760 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
761 'statusnet_profile_url' => $uinfo[0]['url'],
762 'uid' => intval($uinfo[0]['uid']),
763 'cid' => intval($uinfo[0]['cid']),
764 'self' => $uinfo[0]['self'],
765 'network' => $uinfo[0]['network'],
773 * @brief return api-formatted array for item's author and owner
776 * @param array $item : item from db
777 * @return array(array:author, array:owner)
779 function api_item_get_user(App $a, $item) {
781 $status_user = api_get_user($a, $item["author-link"]);
783 $status_user["protected"] = (($item["allow_cid"] != "") ||
784 ($item["allow_gid"] != "") ||
785 ($item["deny_cid"] != "") ||
786 ($item["deny_gid"] != "") ||
789 if ($item['thr-parent'] == $item['uri']) {
790 $owner_user = api_get_user($a, $item["owner-link"]);
792 $owner_user = $status_user;
795 return (array($status_user, $owner_user));
799 * @brief walks recursively through an array with the possibility to change value and key
801 * @param array $array The array to walk through
802 * @param string $callback The callback function
804 * @return array the transformed array
806 function api_walk_recursive(array &$array, callable $callback) {
808 $new_array = array();
810 foreach ($array as $k => $v) {
812 if ($callback($v, $k)) {
813 $new_array[$k] = api_walk_recursive($v, $callback);
816 if ($callback($v, $k)) {
827 * @brief Callback function to transform the array in an array that can be transformed in a XML file
829 * @param variant $item Array item value
830 * @param string $key Array key
832 * @return boolean Should the array item be deleted?
834 function api_reformat_xml(&$item, &$key) {
835 if (is_bool($item)) {
836 $item = ($item ? "true" : "false");
839 if (substr($key, 0, 10) == "statusnet_") {
840 $key = "statusnet:".substr($key, 10);
841 } elseif (substr($key, 0, 10) == "friendica_") {
842 $key = "friendica:".substr($key, 10);
844 /// @TODO old-lost code?
846 // $key = "default:".$key;
852 * @brief Creates the XML from a JSON style array
854 * @param array $data JSON style array
855 * @param string $root_element Name of the root element
857 * @return string The XML data
859 function api_create_xml($data, $root_element) {
860 $childname = key($data);
861 $data2 = array_pop($data);
864 $namespaces = array("" => "http://api.twitter.com",
865 "statusnet" => "http://status.net/schema/api/1/",
866 "friendica" => "http://friendi.ca/schema/api/1/",
867 "georss" => "http://www.georss.org/georss");
869 /// @todo Auto detection of needed namespaces
870 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
871 $namespaces = array();
874 if (is_array($data2)) {
875 api_walk_recursive($data2, "api_reformat_xml");
882 foreach ($data2 AS $item) {
883 $data4[$i++.":".$childname] = $item;
889 $data3 = array($root_element => $data2);
891 $ret = xml::from_array($data3, $xml, false, $namespaces);
896 * @brief Formats the data according to the data type
898 * @param string $root_element Name of the root element
899 * @param string $type Return type (atom, rss, xml, json)
900 * @param array $data JSON style array
902 * @return (string|object) XML data or JSON data
904 function api_format_data($root_element, $type, $data) {
912 $ret = api_create_xml($data, $root_element);
927 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
928 * returns a 401 status code and an error message if not.
929 * http://developer.twitter.com/doc/get/account/verify_credentials
931 function api_account_verify_credentials($type) {
935 if (api_user() === false) {
936 throw new ForbiddenException();
939 unset($_REQUEST["user_id"]);
940 unset($_GET["user_id"]);
942 unset($_REQUEST["screen_name"]);
943 unset($_GET["screen_name"]);
945 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
947 $user_info = api_get_user($a);
949 // "verified" isn't used here in the standard
950 unset($user_info["verified"]);
952 // - Adding last status
954 $user_info["status"] = api_status_show("raw");
955 if (!count($user_info["status"])) {
956 unset($user_info["status"]);
958 unset($user_info["status"]["user"]);
962 // "uid" and "self" are only needed for some internal stuff, so remove it from here
963 unset($user_info["uid"]);
964 unset($user_info["self"]);
966 return api_format_data("user", $type, array('user' => $user_info));
970 /// @TODO move to top of file or somwhere better
971 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
974 * get data from $_POST or $_GET
976 function requestdata($k) {
986 /*Waitman Gobble Mod*/
987 function api_statuses_mediap($type) {
991 if (api_user() === false) {
992 logger('api_statuses_update: no user');
993 throw new ForbiddenException();
995 $user_info = api_get_user($a);
997 $_REQUEST['type'] = 'wall';
998 $_REQUEST['profile_uid'] = api_user();
999 $_REQUEST['api_source'] = true;
1000 $txt = requestdata('status');
1001 /// @TODO old-lost code?
1002 //$txt = urldecode(requestdata('status'));
1004 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1006 $txt = html2bb_video($txt);
1007 $config = HTMLPurifier_Config::createDefault();
1008 $config->set('Cache.DefinitionImpl', null);
1009 $purifier = new HTMLPurifier($config);
1010 $txt = $purifier->purify($txt);
1012 $txt = html2bbcode($txt);
1014 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1016 // tell wall_upload function to return img info instead of echo
1017 $_REQUEST['hush'] = 'yeah';
1018 $bebop = wall_upload_post($a);
1020 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1021 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1024 // this should output the last post (the one we just posted).
1025 return api_status_show($type);
1028 /// @TODO move this to top of file or somewhere better!
1029 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1031 function api_statuses_update($type) {
1035 if (api_user() === false) {
1036 logger('api_statuses_update: no user');
1037 throw new ForbiddenException();
1040 $user_info = api_get_user($a);
1042 // convert $_POST array items to the form we use for web posts.
1044 // logger('api_post: ' . print_r($_POST,true));
1046 if (requestdata('htmlstatus')) {
1047 $txt = requestdata('htmlstatus');
1048 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1049 $txt = html2bb_video($txt);
1051 $config = HTMLPurifier_Config::createDefault();
1052 $config->set('Cache.DefinitionImpl', null);
1054 $purifier = new HTMLPurifier($config);
1055 $txt = $purifier->purify($txt);
1057 $_REQUEST['body'] = html2bbcode($txt);
1061 $_REQUEST['body'] = requestdata('status');
1064 $_REQUEST['title'] = requestdata('title');
1066 $parent = requestdata('in_reply_to_status_id');
1068 // Twidere sends "-1" if it is no reply ...
1069 if ($parent == -1) {
1073 if (ctype_digit($parent)) {
1074 $_REQUEST['parent'] = $parent;
1076 $_REQUEST['parent_uri'] = $parent;
1079 if (requestdata('lat') && requestdata('long')) {
1080 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1082 $_REQUEST['profile_uid'] = api_user();
1085 $_REQUEST['type'] = 'net-comment';
1087 // Check for throttling (maximum posts per day, week and month)
1088 $throttle_day = Config::get('system','throttle_limit_day');
1089 if ($throttle_day > 0) {
1090 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1092 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1093 AND `created` > '%s' AND `id` = `parent`",
1094 intval(api_user()), dbesc($datefrom));
1096 if (DBM::is_result($r)) {
1097 $posts_day = $r[0]["posts_day"];
1102 if ($posts_day > $throttle_day) {
1103 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1104 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1105 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1109 $throttle_week = Config::get('system','throttle_limit_week');
1110 if ($throttle_week > 0) {
1111 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1113 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1114 AND `created` > '%s' AND `id` = `parent`",
1115 intval(api_user()), dbesc($datefrom));
1117 if (DBM::is_result($r)) {
1118 $posts_week = $r[0]["posts_week"];
1123 if ($posts_week > $throttle_week) {
1124 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1125 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1126 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1130 $throttle_month = Config::get('system','throttle_limit_month');
1131 if ($throttle_month > 0) {
1132 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1134 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1135 AND `created` > '%s' AND `id` = `parent`",
1136 intval(api_user()), dbesc($datefrom));
1138 if (DBM::is_result($r)) {
1139 $posts_month = $r[0]["posts_month"];
1144 if ($posts_month > $throttle_month) {
1145 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1146 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1147 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1151 $_REQUEST['type'] = 'wall';
1154 if (x($_FILES, 'media')) {
1155 // upload the image if we have one
1156 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1157 $media = wall_upload_post($a);
1158 if (strlen($media) > 0) {
1159 $_REQUEST['body'] .= "\n\n" . $media;
1163 // To-Do: Multiple IDs
1164 if (requestdata('media_ids')) {
1165 $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",
1166 intval(requestdata('media_ids')), api_user());
1167 if (DBM::is_result($r)) {
1168 $phototypes = Photo::supportedTypes();
1169 $ext = $phototypes[$r[0]['type']];
1170 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1171 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1175 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1177 $_REQUEST['api_source'] = true;
1179 if (!x($_REQUEST, "source")) {
1180 $_REQUEST["source"] = api_source();
1183 // call out normal post function
1186 // this should output the last post (the one we just posted).
1187 return api_status_show($type);
1190 /// @TODO move to top of file or somwhere better
1191 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1192 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1194 function api_media_upload($type) {
1198 if (api_user() === false) {
1200 throw new ForbiddenException();
1203 $user_info = api_get_user($a);
1205 if (!x($_FILES, 'media')) {
1207 throw new BadRequestException("No media.");
1210 $media = wall_upload_post($a, false);
1213 throw new InternalServerErrorException();
1216 $returndata = array();
1217 $returndata["media_id"] = $media["id"];
1218 $returndata["media_id_string"] = (string)$media["id"];
1219 $returndata["size"] = $media["size"];
1220 $returndata["image"] = array("w" => $media["width"],
1221 "h" => $media["height"],
1222 "image_type" => $media["type"]);
1224 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1226 return array("media" => $returndata);
1229 /// @TODO move to top of file or somwhere better
1230 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1232 function api_status_show($type) {
1236 $user_info = api_get_user($a);
1238 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1240 if ($type == "raw") {
1241 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1246 // get last public wall message
1247 $lastwall = q("SELECT `item`.*
1249 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1250 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1251 AND `item`.`type` != 'activity' $privacy_sql
1252 ORDER BY `item`.`id` DESC
1254 intval($user_info['cid']),
1256 dbesc($user_info['url']),
1257 dbesc(normalise_link($user_info['url'])),
1258 dbesc($user_info['url']),
1259 dbesc(normalise_link($user_info['url']))
1262 if (DBM::is_result($lastwall)) {
1263 $lastwall = $lastwall[0];
1265 $in_reply_to = api_in_reply_to($lastwall);
1267 $converted = api_convert_item($lastwall);
1269 if ($type == "xml") {
1270 $geo = "georss:point";
1275 $status_info = array(
1276 'created_at' => api_date($lastwall['created']),
1277 'id' => intval($lastwall['id']),
1278 'id_str' => (string) $lastwall['id'],
1279 'text' => $converted["text"],
1280 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1281 'truncated' => false,
1282 'in_reply_to_status_id' => $in_reply_to['status_id'],
1283 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1284 'in_reply_to_user_id' => $in_reply_to['user_id'],
1285 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1286 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1287 'user' => $user_info,
1289 'coordinates' => "",
1291 'contributors' => "",
1292 'is_quote_status' => false,
1293 'retweet_count' => 0,
1294 'favorite_count' => 0,
1295 'favorited' => $lastwall['starred'] ? true : false,
1296 'retweeted' => false,
1297 'possibly_sensitive' => false,
1299 'statusnet_html' => $converted["html"],
1300 'statusnet_conversation_id' => $lastwall['parent'],
1303 if (count($converted["attachments"]) > 0) {
1304 $status_info["attachments"] = $converted["attachments"];
1307 if (count($converted["entities"]) > 0) {
1308 $status_info["entities"] = $converted["entities"];
1311 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1312 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1313 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1314 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1317 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1318 unset($status_info["user"]["uid"]);
1319 unset($status_info["user"]["self"]);
1322 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1324 if ($type == "raw") {
1325 return $status_info;
1328 return api_format_data("statuses", $type, array('status' => $status_info));
1333 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1334 * The author's most recent status will be returned inline.
1335 * http://developer.twitter.com/doc/get/users/show
1337 function api_users_show($type) {
1341 $user_info = api_get_user($a);
1342 $lastwall = q("SELECT `item`.*
1344 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1345 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1346 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1347 AND `type`!='activity'
1348 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1352 dbesc(ACTIVITY_POST),
1353 intval($user_info['cid']),
1354 dbesc($user_info['url']),
1355 dbesc(normalise_link($user_info['url'])),
1356 dbesc($user_info['url']),
1357 dbesc(normalise_link($user_info['url']))
1360 if (DBM::is_result($lastwall)) {
1361 $lastwall = $lastwall[0];
1363 $in_reply_to = api_in_reply_to($lastwall);
1365 $converted = api_convert_item($lastwall);
1367 if ($type == "xml") {
1368 $geo = "georss:point";
1373 $user_info['status'] = array(
1374 'text' => $converted["text"],
1375 'truncated' => false,
1376 'created_at' => api_date($lastwall['created']),
1377 'in_reply_to_status_id' => $in_reply_to['status_id'],
1378 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1379 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1380 'id' => intval($lastwall['contact-id']),
1381 'id_str' => (string) $lastwall['contact-id'],
1382 'in_reply_to_user_id' => $in_reply_to['user_id'],
1383 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1384 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1386 'favorited' => $lastwall['starred'] ? true : false,
1387 'statusnet_html' => $converted["html"],
1388 'statusnet_conversation_id' => $lastwall['parent'],
1391 if (count($converted["attachments"]) > 0) {
1392 $user_info["status"]["attachments"] = $converted["attachments"];
1395 if (count($converted["entities"]) > 0) {
1396 $user_info["status"]["entities"] = $converted["entities"];
1399 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1400 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1403 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1404 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1409 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1410 unset($user_info["uid"]);
1411 unset($user_info["self"]);
1413 return api_format_data("user", $type, array('user' => $user_info));
1417 /// @TODO move to top of file or somewhere better
1418 api_register_func('api/users/show','api_users_show');
1419 api_register_func('api/externalprofile/show','api_users_show');
1421 function api_users_search($type) {
1425 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1427 $userlist = array();
1429 if (x($_GET, 'q')) {
1430 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1432 if (!DBM::is_result($r)) {
1433 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1436 if (DBM::is_result($r)) {
1438 foreach ($r AS $user) {
1439 $user_info = api_get_user($a, $user["id"], "json");
1441 if ($type == "xml") {
1442 $userlist[$k++.":user"] = $user_info;
1444 $userlist[] = $user_info;
1447 $userlist = array("users" => $userlist);
1449 throw new BadRequestException("User not found.");
1452 throw new BadRequestException("User not found.");
1454 return api_format_data("users", $type, $userlist);
1457 /// @TODO move to top of file or somewhere better
1458 api_register_func('api/users/search','api_users_search');
1462 * http://developer.twitter.com/doc/get/statuses/home_timeline
1464 * TODO: Optional parameters
1465 * TODO: Add reply info
1467 function api_statuses_home_timeline($type) {
1471 if (api_user() === false) {
1472 throw new ForbiddenException();
1475 unset($_REQUEST["user_id"]);
1476 unset($_GET["user_id"]);
1478 unset($_REQUEST["screen_name"]);
1479 unset($_GET["screen_name"]);
1481 $user_info = api_get_user($a);
1482 // get last newtork messages
1485 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1486 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1490 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1491 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1492 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1493 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1494 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1496 $start = $page * $count;
1500 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1502 if ($exclude_replies > 0) {
1503 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1505 if ($conversation_id > 0) {
1506 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1509 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1510 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1511 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1512 `contact`.`id` AS `cid`
1514 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1515 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1516 WHERE `item`.`uid` = %d AND `verb` = '%s'
1517 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1520 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1522 dbesc(ACTIVITY_POST),
1524 intval($start), intval($count)
1527 $ret = api_format_items($r, $user_info, false, $type);
1529 // Set all posts from the query above to seen
1531 foreach ($r AS $item) {
1532 $idarray[] = intval($item["id"]);
1535 $idlist = implode(",", $idarray);
1537 if ($idlist != "") {
1538 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1541 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1545 $data = array('status' => $ret);
1549 $data = api_rss_extra($a, $data, $user_info);
1553 return api_format_data("statuses", $type, $data);
1556 /// @TODO move to top of file or somewhere better
1557 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1558 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1560 function api_statuses_public_timeline($type) {
1564 if (api_user() === false) {
1565 throw new ForbiddenException();
1568 $user_info = api_get_user($a);
1569 // get last newtork messages
1572 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1573 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1577 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1578 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1579 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1580 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1581 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1583 $start = $page * $count;
1586 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1588 if ($exclude_replies > 0) {
1589 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1591 if ($conversation_id > 0) {
1592 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1595 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1596 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1597 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1598 `contact`.`id` AS `cid`,
1599 `user`.`nickname`, `user`.`hidewall`
1601 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1602 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1603 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1604 AND NOT `user`.`hidewall`
1605 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1606 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1607 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1608 AND NOT `item`.`private` AND `item`.`wall`
1611 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1612 dbesc(ACTIVITY_POST),
1617 $ret = api_format_items($r, $user_info, false, $type);
1619 $data = array('status' => $ret);
1623 $data = api_rss_extra($a, $data, $user_info);
1627 return api_format_data("statuses", $type, $data);
1630 /// @TODO move to top of file or somewhere better
1631 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1634 * @TODO nothing to say?
1636 function api_statuses_show($type) {
1640 if (api_user() === false) {
1641 throw new ForbiddenException();
1644 $user_info = api_get_user($a);
1647 $id = intval($a->argv[3]);
1650 $id = intval($_REQUEST["id"]);
1655 $id = intval($a->argv[4]);
1658 logger('API: api_statuses_show: ' . $id);
1660 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1663 if ($conversation) {
1664 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1666 $sql_extra .= " AND `item`.`id` = %d";
1669 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1670 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1671 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1672 `contact`.`id` AS `cid`
1674 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1675 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1676 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1677 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1680 dbesc(ACTIVITY_POST),
1684 /// @TODO How about copying this to above methods which don't check $r ?
1685 if (!DBM::is_result($r)) {
1686 throw new BadRequestException("There is no status with this id.");
1689 $ret = api_format_items($r,$user_info, false, $type);
1691 if ($conversation) {
1692 $data = array('status' => $ret);
1693 return api_format_data("statuses", $type, $data);
1695 $data = array('status' => $ret[0]);
1696 return api_format_data("status", $type, $data);
1700 /// @TODO move to top of file or somewhere better
1701 api_register_func('api/statuses/show','api_statuses_show', true);
1704 * @TODO nothing to say?
1706 function api_conversation_show($type) {
1710 if (api_user() === false) {
1711 throw new ForbiddenException();
1714 $user_info = api_get_user($a);
1717 $id = intval($a->argv[3]);
1718 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1719 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1723 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1724 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1726 $start = $page*$count;
1729 $id = intval($_REQUEST["id"]);
1734 $id = intval($a->argv[4]);
1737 logger('API: api_conversation_show: '.$id);
1739 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1740 if (DBM::is_result($r)) {
1741 $id = $r[0]["parent"];
1747 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1750 // Not sure why this query was so complicated. We should keep it here for a while,
1751 // just to make sure that we really don't need it.
1752 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1753 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1755 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1756 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1757 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1758 `contact`.`id` AS `cid`
1760 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1761 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1762 WHERE `item`.`parent` = %d AND `item`.`visible`
1763 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1764 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1765 AND `item`.`id`>%d $sql_extra
1766 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1767 intval($id), intval(api_user()),
1768 dbesc(ACTIVITY_POST),
1770 intval($start), intval($count)
1773 if (!DBM::is_result($r)) {
1774 throw new BadRequestException("There is no status with this id.");
1777 $ret = api_format_items($r, $user_info, false, $type);
1779 $data = array('status' => $ret);
1780 return api_format_data("statuses", $type, $data);
1783 /// @TODO move to top of file or somewhere better
1784 api_register_func('api/conversation/show','api_conversation_show', true);
1785 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1788 * @TODO nothing to say?
1790 function api_statuses_repeat($type) {
1795 if (api_user() === false) {
1796 throw new ForbiddenException();
1799 $user_info = api_get_user($a);
1802 $id = intval($a->argv[3]);
1805 $id = intval($_REQUEST["id"]);
1810 $id = intval($a->argv[4]);
1813 logger('API: api_statuses_repeat: '.$id);
1815 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1816 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1817 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1818 `contact`.`id` AS `cid`
1820 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1821 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1822 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1823 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1824 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1826 AND `item`.`id`=%d",
1830 /// @TODO other style than above functions!
1831 if (DBM::is_result($r) && $r[0]['body'] != "") {
1832 if (strpos($r[0]['body'], "[/share]") !== false) {
1833 $pos = strpos($r[0]['body'], "[share");
1834 $post = substr($r[0]['body'], $pos);
1836 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1838 $post .= $r[0]['body'];
1839 $post .= "[/share]";
1841 $_REQUEST['body'] = $post;
1842 $_REQUEST['profile_uid'] = api_user();
1843 $_REQUEST['type'] = 'wall';
1844 $_REQUEST['api_source'] = true;
1846 if (!x($_REQUEST, "source")) {
1847 $_REQUEST["source"] = api_source();
1852 throw new ForbiddenException();
1855 // this should output the last post (the one we just posted).
1857 return api_status_show($type);
1860 /// @TODO move to top of file or somewhere better
1861 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1864 * @TODO nothing to say?
1866 function api_statuses_destroy($type) {
1870 if (api_user() === false) {
1871 throw new ForbiddenException();
1874 $user_info = api_get_user($a);
1877 $id = intval($a->argv[3]);
1880 $id = intval($_REQUEST["id"]);
1885 $id = intval($a->argv[4]);
1888 logger('API: api_statuses_destroy: '.$id);
1890 $ret = api_statuses_show($type);
1892 drop_item($id, false);
1897 /// @TODO move to top of file or somewhere better
1898 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1901 * @TODO Nothing more than an URL to say?
1902 * http://developer.twitter.com/doc/get/statuses/mentions
1904 function api_statuses_mentions($type) {
1908 if (api_user() === false) {
1909 throw new ForbiddenException();
1912 unset($_REQUEST["user_id"]);
1913 unset($_GET["user_id"]);
1915 unset($_REQUEST["screen_name"]);
1916 unset($_GET["screen_name"]);
1918 $user_info = api_get_user($a);
1919 // get last newtork messages
1923 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1924 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1928 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1929 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1930 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1932 $start = $page * $count;
1934 // Ugly code - should be changed
1935 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1936 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1937 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1938 $myurl = str_replace('www.', '', $myurl);
1939 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1942 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1945 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1946 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1947 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1948 `contact`.`id` AS `cid`
1949 FROM `item` FORCE INDEX (`uid_id`)
1950 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1951 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1952 WHERE `item`.`uid` = %d AND `verb` = '%s'
1953 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1954 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1955 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1958 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1960 dbesc(ACTIVITY_POST),
1961 dbesc(protect_sprintf($myurl)),
1962 dbesc(protect_sprintf($myurl)),
1965 intval($start), intval($count)
1968 $ret = api_format_items($r, $user_info, false, $type);
1970 $data = array('status' => $ret);
1974 $data = api_rss_extra($a, $data, $user_info);
1978 return api_format_data("statuses", $type, $data);
1981 /// @TODO move to top of file or somewhere better
1982 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1983 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1985 function api_statuses_user_timeline($type) {
1989 if (api_user() === false) {
1990 throw new ForbiddenException();
1993 $user_info = api_get_user($a);
1994 // get last network messages
1996 logger("api_statuses_user_timeline: api_user: ". api_user() .
1997 "\nuser_info: ".print_r($user_info, true) .
1998 "\n_REQUEST: ".print_r($_REQUEST, true),
2002 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2003 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2007 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2008 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2009 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2010 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2012 $start = $page * $count;
2015 if ($user_info['self'] == 1) {
2016 $sql_extra .= " AND `item`.`wall` = 1 ";
2019 if ($exclude_replies > 0) {
2020 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2022 if ($conversation_id > 0) {
2023 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2026 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2027 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2028 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2029 `contact`.`id` AS `cid`
2030 FROM `item` FORCE INDEX (`uid_contactid_id`)
2031 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2032 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2033 WHERE `item`.`uid` = %d AND `verb` = '%s'
2034 AND `item`.`contact-id` = %d
2035 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2038 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2040 dbesc(ACTIVITY_POST),
2041 intval($user_info['cid']),
2043 intval($start), intval($count)
2046 $ret = api_format_items($r, $user_info, true, $type);
2048 $data = array('status' => $ret);
2052 $data = api_rss_extra($a, $data, $user_info);
2056 return api_format_data("statuses", $type, $data);
2059 /// @TODO move to top of file or somwhere better
2060 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2063 * Star/unstar an item
2064 * param: id : id of the item
2066 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2068 function api_favorites_create_destroy($type) {
2072 if (api_user() === false) {
2073 throw new ForbiddenException();
2076 // for versioned api.
2077 /// @TODO We need a better global soluton
2078 $action_argv_id = 2;
2079 if ($a->argv[1] == "1.1") {
2080 $action_argv_id = 3;
2083 if ($a->argc <= $action_argv_id) {
2084 throw new BadRequestException("Invalid request.");
2086 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2087 if ($a->argc == $action_argv_id + 2) {
2088 $itemid = intval($a->argv[$action_argv_id + 1]);
2090 /// @TODO use x() to check if _REQUEST contains 'id'
2091 $itemid = intval($_REQUEST['id']);
2094 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2095 $itemid, api_user());
2097 if (!DBM::is_result($item) || count($item) == 0) {
2098 throw new BadRequestException("Invalid item.");
2103 $item[0]['starred'] = 1;
2106 $item[0]['starred'] = 0;
2109 throw new BadRequestException("Invalid action ".$action);
2112 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2113 $item[0]['starred'], $itemid, api_user());
2115 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2116 $item[0]['starred'], $itemid, api_user());
2119 throw new InternalServerErrorException("DB error");
2123 $user_info = api_get_user($a);
2124 $rets = api_format_items($item, $user_info, false, $type);
2127 $data = array('status' => $ret);
2131 $data = api_rss_extra($a, $data, $user_info);
2134 return api_format_data("status", $type, $data);
2137 /// @TODO move to top of file or somwhere better
2138 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2139 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2141 function api_favorites($type) {
2146 if (api_user() === false) {
2147 throw new ForbiddenException();
2150 $called_api = array();
2152 $user_info = api_get_user($a);
2154 // in friendica starred item are private
2155 // return favorites only for self
2156 logger('api_favorites: self:' . $user_info['self']);
2158 if ($user_info['self'] == 0) {
2164 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2165 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2166 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2167 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2172 $start = $page*$count;
2175 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2178 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2179 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2180 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2181 `contact`.`id` AS `cid`
2182 FROM `item`, `contact`
2183 WHERE `item`.`uid` = %d
2184 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2185 AND `item`.`starred` = 1
2186 AND `contact`.`id` = `item`.`contact-id`
2187 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2190 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2193 intval($start), intval($count)
2196 $ret = api_format_items($r,$user_info, false, $type);
2200 $data = array('status' => $ret);
2204 $data = api_rss_extra($a, $data, $user_info);
2207 return api_format_data("statuses", $type, $data);
2210 /// @TODO move to top of file or somwhere better
2211 api_register_func('api/favorites','api_favorites', true);
2213 function api_format_messages($item, $recipient, $sender) {
2214 // standard meta information
2216 'id' => $item['id'],
2217 'sender_id' => $sender['id'] ,
2219 'recipient_id' => $recipient['id'],
2220 'created_at' => api_date($item['created']),
2221 'sender_screen_name' => $sender['screen_name'],
2222 'recipient_screen_name' => $recipient['screen_name'],
2223 'sender' => $sender,
2224 'recipient' => $recipient,
2226 'friendica_seen' => $item['seen'],
2227 'friendica_parent_uri' => $item['parent-uri'],
2230 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2231 unset($ret["sender"]["uid"]);
2232 unset($ret["sender"]["self"]);
2233 unset($ret["recipient"]["uid"]);
2234 unset($ret["recipient"]["self"]);
2236 //don't send title to regular StatusNET requests to avoid confusing these apps
2237 if (x($_GET, 'getText')) {
2238 $ret['title'] = $item['title'];
2239 if ($_GET['getText'] == 'html') {
2240 $ret['text'] = bbcode($item['body'], false, false);
2241 } elseif ($_GET['getText'] == 'plain') {
2242 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2243 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2246 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2248 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2249 unset($ret['sender']);
2250 unset($ret['recipient']);
2256 function api_convert_item($item) {
2257 $body = $item['body'];
2258 $attachments = api_get_attachments($body);
2260 // Workaround for ostatus messages where the title is identically to the body
2261 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2262 $statusbody = trim(html2plain($html, 0));
2264 // handle data: images
2265 $statusbody = api_format_items_embeded_images($item,$statusbody);
2267 $statustitle = trim($item['title']);
2269 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2270 $statustext = trim($statusbody);
2272 $statustext = trim($statustitle."\n\n".$statusbody);
2275 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2276 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2279 $statushtml = trim(bbcode($body, false, false));
2281 // Workaround for clients with limited HTML parser functionality
2282 $search = array("<br>", "<blockquote>", "</blockquote>",
2283 "<h1>", "</h1>", "<h2>", "</h2>",
2284 "<h3>", "</h3>", "<h4>", "</h4>",
2285 "<h5>", "</h5>", "<h6>", "</h6>");
2286 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2287 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2288 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2289 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2290 $statushtml = str_replace($search, $replace, $statushtml);
2292 if ($item['title'] != "") {
2293 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2297 $oldtext = $statushtml;
2298 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2299 } while ($oldtext != $statushtml);
2301 if (substr($statushtml, 0, 4) == '<br>') {
2302 $statushtml = substr($statushtml, 4);
2305 if (substr($statushtml, 0, -4) == '<br>') {
2306 $statushtml = substr($statushtml, -4);
2309 // feeds without body should contain the link
2310 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2311 $statushtml .= bbcode($item['plink']);
2314 $entities = api_get_entitities($statustext, $body);
2317 "text" => $statustext,
2318 "html" => $statushtml,
2319 "attachments" => $attachments,
2320 "entities" => $entities
2324 function api_get_attachments(&$body) {
2327 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2329 $URLSearchString = "^\[\]";
2330 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2336 $attachments = array();
2338 foreach ($images[1] AS $image) {
2339 $imagedata = get_photo_info($image);
2342 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2346 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2347 foreach ($images[0] AS $orig) {
2348 $body = str_replace($orig, "", $body);
2352 return $attachments;
2355 function api_get_entitities(&$text, $bbcode) {
2358 * Links at the first character of the post
2363 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2365 if ($include_entities != "true") {
2367 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2369 foreach ($images[1] AS $image) {
2370 $replace = proxy_url($image);
2371 $text = str_replace($image, $replace, $text);
2376 $bbcode = bb_CleanPictureLinks($bbcode);
2378 // Change pure links in text to bbcode uris
2379 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2381 $entities = array();
2382 $entities["hashtags"] = array();
2383 $entities["symbols"] = array();
2384 $entities["urls"] = array();
2385 $entities["user_mentions"] = array();
2387 $URLSearchString = "^\[\]";
2389 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2391 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2392 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2393 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2395 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2396 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2397 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2399 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2400 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2401 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2403 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2405 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2406 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2408 $ordered_urls = array();
2409 foreach ($urls[1] AS $id => $url) {
2410 //$start = strpos($text, $url, $offset);
2411 $start = iconv_strpos($text, $url, 0, "UTF-8");
2412 if (!($start === false)) {
2413 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2417 ksort($ordered_urls);
2420 //foreach ($urls[1] AS $id=>$url) {
2421 foreach ($ordered_urls AS $url) {
2422 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
2423 !strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
2424 $display_url = $url["title"];
2426 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2427 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2429 if (strlen($display_url) > 26)
2430 $display_url = substr($display_url, 0, 25)."…";
2433 //$start = strpos($text, $url, $offset);
2434 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2435 if (!($start === false)) {
2436 $entities["urls"][] = array("url" => $url["url"],
2437 "expanded_url" => $url["url"],
2438 "display_url" => $display_url,
2439 "indices" => array($start, $start+strlen($url["url"])));
2440 $offset = $start + 1;
2444 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2445 $ordered_images = array();
2446 foreach ($images[1] AS $image) {
2447 //$start = strpos($text, $url, $offset);
2448 $start = iconv_strpos($text, $image, 0, "UTF-8");
2449 if (!($start === false))
2450 $ordered_images[$start] = $image;
2452 //$entities["media"] = array();
2455 foreach ($ordered_images AS $url) {
2456 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2457 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2459 if (strlen($display_url) > 26)
2460 $display_url = substr($display_url, 0, 25)."…";
2462 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2463 if (!($start === false)) {
2464 $image = get_photo_info($url);
2466 // If image cache is activated, then use the following sizes:
2467 // thumb (150), small (340), medium (600) and large (1024)
2468 if (!Config::get("system", "proxy_disabled")) {
2469 $media_url = proxy_url($url);
2472 $scale = scale_image($image[0], $image[1], 150);
2473 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2475 if (($image[0] > 150) || ($image[1] > 150)) {
2476 $scale = scale_image($image[0], $image[1], 340);
2477 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2480 $scale = scale_image($image[0], $image[1], 600);
2481 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2483 if (($image[0] > 600) || ($image[1] > 600)) {
2484 $scale = scale_image($image[0], $image[1], 1024);
2485 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2489 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2492 $entities["media"][] = array(
2494 "id_str" => (string)$start+1,
2495 "indices" => array($start, $start+strlen($url)),
2496 "media_url" => normalise_link($media_url),
2497 "media_url_https" => $media_url,
2499 "display_url" => $display_url,
2500 "expanded_url" => $url,
2504 $offset = $start + 1;
2510 function api_format_items_embeded_images(&$item, $text) {
2511 $text = preg_replace_callback(
2512 "|data:image/([^;]+)[^=]+=*|m",
2513 function($match) use ($item) {
2514 return System::baseUrl()."/display/".$item['guid'];
2522 * @brief return <a href='url'>name</a> as array
2524 * @param string $txt
2529 function api_contactlink_to_array($txt) {
2531 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2532 if ($r && count($match)==3) {
2534 'name' => $match[2],
2548 * @brief return likes, dislikes and attend status for item
2550 * @param array $item
2552 * likes => int count
2553 * dislikes => int count
2555 function api_format_items_activities(&$item, $type = "json") {
2559 $activities = array(
2561 'dislike' => array(),
2562 'attendyes' => array(),
2563 'attendno' => array(),
2564 'attendmaybe' => array(),
2567 $items = q('SELECT * FROM item
2568 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2569 intval($item['uid']),
2570 dbesc($item['uri']));
2572 foreach ($items as $i) {
2573 // not used as result should be structured like other user data
2574 //builtin_activity_puller($i, $activities);
2576 // get user data and add it to the array of the activity
2577 $user = api_get_user($a, $i['author-link']);
2578 switch ($i['verb']) {
2580 $activities['like'][] = $user;
2582 case ACTIVITY_DISLIKE:
2583 $activities['dislike'][] = $user;
2585 case ACTIVITY_ATTEND:
2586 $activities['attendyes'][] = $user;
2588 case ACTIVITY_ATTENDNO:
2589 $activities['attendno'][] = $user;
2591 case ACTIVITY_ATTENDMAYBE:
2592 $activities['attendmaybe'][] = $user;
2599 if ($type == "xml") {
2600 $xml_activities = array();
2601 foreach ($activities as $k => $v) {
2602 // change xml element from "like" to "friendica:like"
2603 $xml_activities["friendica:".$k] = $v;
2604 // add user data into xml output
2606 foreach ($v as $user)
2607 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2609 $activities = $xml_activities;
2618 * @brief return data from profiles
2620 * @param array $profile array containing data from db table 'profile'
2621 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2624 function api_format_items_profiles(&$profile = null, $type = "json") {
2625 if ($profile != null) {
2626 $profile = array('profile_id' => $profile['id'],
2627 'profile_name' => $profile['profile-name'],
2628 'is_default' => $profile['is-default'] ? true : false,
2629 'hide_friends'=> $profile['hide-friends'] ? true : false,
2630 'profile_photo' => $profile['photo'],
2631 'profile_thumb' => $profile['thumb'],
2632 'publish' => $profile['publish'] ? true : false,
2633 'net_publish' => $profile['net-publish'] ? true : false,
2634 'description' => $profile['pdesc'],
2635 'date_of_birth' => $profile['dob'],
2636 'address' => $profile['address'],
2637 'city' => $profile['locality'],
2638 'region' => $profile['region'],
2639 'postal_code' => $profile['postal-code'],
2640 'country' => $profile['country-name'],
2641 'hometown' => $profile['hometown'],
2642 'gender' => $profile['gender'],
2643 'marital' => $profile['marital'],
2644 'marital_with' => $profile['with'],
2645 'marital_since' => $profile['howlong'],
2646 'sexual' => $profile['sexual'],
2647 'politic' => $profile['politic'],
2648 'religion' => $profile['religion'],
2649 'public_keywords' => $profile['pub_keywords'],
2650 'private_keywords' => $profile['prv_keywords'],
2651 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2652 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2653 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2654 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2655 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2656 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2657 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2658 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2659 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2660 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2661 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2662 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2663 'homepage' => $profile['homepage'],
2670 * @brief format items to be returned by api
2672 * @param array $r array of items
2673 * @param array $user_info
2674 * @param bool $filter_user filter items by $user_info
2676 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2682 foreach ($r as $item) {
2684 localize_item($item);
2685 list($status_user, $owner_user) = api_item_get_user($a, $item);
2687 // Look if the posts are matching if they should be filtered by user id
2688 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2692 $in_reply_to = api_in_reply_to($item);
2694 $converted = api_convert_item($item);
2696 if ($type == "xml") {
2697 $geo = "georss:point";
2703 'text' => $converted["text"],
2704 'truncated' => False,
2705 'created_at'=> api_date($item['created']),
2706 'in_reply_to_status_id' => $in_reply_to['status_id'],
2707 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2708 'source' => (($item['app']) ? $item['app'] : 'web'),
2709 'id' => intval($item['id']),
2710 'id_str' => (string) intval($item['id']),
2711 'in_reply_to_user_id' => $in_reply_to['user_id'],
2712 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2713 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2715 'favorited' => $item['starred'] ? true : false,
2716 'user' => $status_user ,
2717 'friendica_owner' => $owner_user,
2718 //'entities' => NULL,
2719 'statusnet_html' => $converted["html"],
2720 'statusnet_conversation_id' => $item['parent'],
2721 'friendica_activities' => api_format_items_activities($item, $type),
2724 if (count($converted["attachments"]) > 0) {
2725 $status["attachments"] = $converted["attachments"];
2728 if (count($converted["entities"]) > 0) {
2729 $status["entities"] = $converted["entities"];
2732 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2733 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2734 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2735 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2739 // Retweets are only valid for top postings
2740 // It doesn't work reliable with the link if its a feed
2741 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2743 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2746 if ($item["id"] == $item["parent"]) {
2747 $retweeted_item = api_share_as_retweet($item);
2748 if ($retweeted_item !== false) {
2749 $retweeted_status = $status;
2751 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2752 } catch( BadRequestException $e ) {
2753 // user not found. should be found?
2754 /// @todo check if the user should be always found
2755 $retweeted_status["user"] = array();
2758 $rt_converted = api_convert_item($retweeted_item);
2760 $retweeted_status['text'] = $rt_converted["text"];
2761 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2762 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2763 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2764 $status['retweeted_status'] = $retweeted_status;
2768 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2769 unset($status["user"]["uid"]);
2770 unset($status["user"]["self"]);
2772 if ($item["coord"] != "") {
2773 $coords = explode(' ',$item["coord"]);
2774 if (count($coords) == 2) {
2775 if ($type == "json")
2776 $status["geo"] = array('type' => 'Point',
2777 'coordinates' => array((float) $coords[0],
2778 (float) $coords[1]));
2779 else // Not sure if this is the official format - if someone founds a documentation we can check
2780 $status["georss:point"] = $item["coord"];
2788 function api_account_rate_limit_status($type) {
2790 if ($type == "xml") {
2792 'remaining-hits' => '150',
2793 '@attributes' => array("type" => "integer"),
2794 'hourly-limit' => '150',
2795 '@attributes2' => array("type" => "integer"),
2796 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2797 '@attributes3' => array("type" => "datetime"),
2798 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2799 '@attributes4' => array("type" => "integer"),
2803 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2804 'remaining_hits' => '150',
2805 'hourly_limit' => '150',
2806 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2810 return api_format_data('hash', $type, array('hash' => $hash));
2813 /// @TODO move to top of file or somwhere better
2814 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2816 function api_help_test($type) {
2817 if ($type == 'xml') {
2823 return api_format_data('ok', $type, array("ok" => $ok));
2826 /// @TODO move to top of file or somwhere better
2827 api_register_func('api/help/test','api_help_test', false);
2829 function api_lists($type) {
2831 /// @TODO $ret is not filled here?
2832 return api_format_data('lists', $type, array("lists_list" => $ret));
2835 /// @TODO move to top of file or somwhere better
2836 api_register_func('api/lists','api_lists',true);
2838 function api_lists_list($type) {
2840 /// @TODO $ret is not filled here?
2841 return api_format_data('lists', $type, array("lists_list" => $ret));
2844 /// @TODO move to top of file or somwhere better
2845 api_register_func('api/lists/list','api_lists_list',true);
2848 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2849 * This function is deprecated by Twitter
2850 * returns: json, xml
2852 function api_statuses_f($type, $qtype) {
2856 if (api_user() === false) {
2857 throw new ForbiddenException();
2860 $user_info = api_get_user($a);
2862 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2863 /* this is to stop Hotot to load friends multiple times
2864 * I'm not sure if I'm missing return something or
2865 * is a bug in hotot. Workaround, meantime
2869 return array('$users' => $ret);*/
2873 if ($qtype == 'friends') {
2874 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2876 if ($qtype == 'followers') {
2877 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2880 // friends and followers only for self
2881 if ($user_info['self'] == 0) {
2882 $sql_extra = " AND false ";
2885 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2890 foreach ($r as $cid) {
2891 $user = api_get_user($a, $cid['nurl']);
2892 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2893 unset($user["uid"]);
2894 unset($user["self"]);
2901 return array('user' => $ret);
2905 function api_statuses_friends($type) {
2906 $data = api_statuses_f($type, "friends");
2907 if ($data === false) {
2910 return api_format_data("users", $type, $data);
2913 function api_statuses_followers($type) {
2914 $data = api_statuses_f($type, "followers");
2915 if ($data === false) {
2918 return api_format_data("users", $type, $data);
2921 /// @TODO move to top of file or somewhere better
2922 api_register_func('api/statuses/friends','api_statuses_friends',true);
2923 api_register_func('api/statuses/followers','api_statuses_followers',true);
2925 function api_statusnet_config($type) {
2929 $name = $a->config['sitename'];
2930 $server = $a->get_hostname();
2931 $logo = System::baseUrl() . '/images/friendica-64.png';
2932 $email = $a->config['admin_email'];
2933 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2934 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2935 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2936 if ($a->config['api_import_size']) {
2937 $texlimit = string($a->config['api_import_size']);
2939 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2940 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',System::baseUrl()) : '');
2943 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2944 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2945 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2946 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2947 'shorturllength' => '30',
2948 'friendica' => array(
2949 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2950 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2951 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2952 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2957 return api_format_data('config', $type, array('config' => $config));
2961 /// @TODO move to top of file or somewhere better
2962 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2963 api_register_func('api/statusnet/config','api_statusnet_config', false);
2965 function api_statusnet_version($type) {
2967 $fake_statusnet_version = "0.9.7";
2969 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2972 /// @TODO move to top of file or somewhere better
2973 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2974 api_register_func('api/statusnet/version','api_statusnet_version', false);
2977 * @todo use api_format_data() to return data
2979 function api_ff_ids($type,$qtype) {
2984 throw new ForbiddenException();
2987 $user_info = api_get_user($a);
2989 if ($qtype == 'friends') {
2990 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2992 if ($qtype == 'followers') {
2993 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2996 if (!$user_info["self"]) {
2997 $sql_extra = " AND false ";
3000 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3002 $r = q("SELECT `pcontact`.`id` FROM `contact`
3003 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3004 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3008 if (!DBM::is_result($r)) {
3013 foreach ($r as $rr) {
3014 if ($stringify_ids) {
3017 $ids[] = intval($rr['id']);
3021 return api_format_data("ids", $type, array('id' => $ids));
3024 function api_friends_ids($type) {
3025 return api_ff_ids($type,'friends');
3028 function api_followers_ids($type) {
3029 return api_ff_ids($type,'followers');
3032 /// @TODO move to top of file or somewhere better
3033 api_register_func('api/friends/ids','api_friends_ids',true);
3034 api_register_func('api/followers/ids','api_followers_ids',true);
3036 function api_direct_messages_new($type) {
3040 if (api_user() === false) throw new ForbiddenException();
3042 if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
3044 $sender = api_get_user($a);
3046 if ($_POST['screen_name']) {
3047 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3049 dbesc($_POST['screen_name']));
3051 // Selecting the id by priority, friendica first
3052 api_best_nickname($r);
3054 $recipient = api_get_user($a, $r[0]['nurl']);
3056 $recipient = api_get_user($a, $_POST['user_id']);
3061 if (x($_REQUEST, 'replyto')) {
3062 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3064 intval($_REQUEST['replyto']));
3065 $replyto = $r[0]['parent-uri'];
3066 $sub = $r[0]['title'];
3068 if (x($_REQUEST, 'title')) {
3069 $sub = $_REQUEST['title'];
3071 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3075 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3078 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3079 $ret = api_format_messages($r[0], $recipient, $sender);
3081 $ret = array("error"=>$id);
3084 $data = array('direct_message'=>$ret);
3089 $data = api_rss_extra($a, $data, $user_info);
3092 return api_format_data("direct-messages", $type, $data);
3096 /// @TODO move to top of file or somewhere better
3097 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3100 * @brief delete a direct_message from mail table through api
3102 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3105 function api_direct_messages_destroy($type) {
3108 if (api_user() === false) {
3109 throw new ForbiddenException();
3113 $user_info = api_get_user($a);
3115 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3117 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3118 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3119 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3121 $uid = $user_info['uid'];
3122 // error if no id or parenturi specified (for clients posting parent-uri as well)
3123 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3124 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3125 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3128 // BadRequestException if no id specified (for clients using Twitter API)
3130 throw new BadRequestException('Message id not specified');
3133 // add parent-uri to sql command if specified by calling app
3134 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3136 // get data of the specified message id
3137 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3141 // error message if specified id is not in database
3142 if (!DBM::is_result($r)) {
3143 if ($verbose == "true") {
3144 $answer = array('result' => 'error', 'message' => 'message id not in database');
3145 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3147 /// @todo BadRequestException ok for Twitter API clients?
3148 throw new BadRequestException('message id not in database');
3152 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3156 if ($verbose == "true") {
3159 $answer = array('result' => 'ok', 'message' => 'message deleted');
3160 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3162 $answer = array('result' => 'error', 'message' => 'unknown error');
3163 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3166 /// @todo return JSON data like Twitter API not yet implemented
3170 /// @TODO move to top of file or somewhere better
3171 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3173 function api_direct_messages_box($type, $box, $verbose) {
3177 if (api_user() === false) {
3178 throw new ForbiddenException();
3182 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3183 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3188 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3189 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3191 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3192 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3195 unset($_REQUEST["user_id"]);
3196 unset($_GET["user_id"]);
3198 unset($_REQUEST["screen_name"]);
3199 unset($_GET["screen_name"]);
3201 $user_info = api_get_user($a);
3202 $profile_url = $user_info["url"];
3205 $start = $page * $count;
3208 if ($box=="sentbox") {
3209 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3210 } elseif ($box == "conversation") {
3211 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3212 } elseif ($box == "all") {
3213 $sql_extra = "true";
3214 } elseif ($box == "inbox") {
3215 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3219 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3222 if ($user_id != "") {
3223 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3224 } elseif ($screen_name !="") {
3225 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3228 $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",
3231 intval($start), intval($count)
3233 if ($verbose == "true" && !DBM::is_result($r)) {
3234 $answer = array('result' => 'error', 'message' => 'no mails available');
3235 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3239 foreach ($r as $item) {
3240 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3241 $recipient = $user_info;
3242 $sender = api_get_user($a,normalise_link($item['contact-url']));
3243 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3244 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3245 $sender = $user_info;
3248 $ret[] = api_format_messages($item, $recipient, $sender);
3252 $data = array('direct_message' => $ret);
3256 $data = api_rss_extra($a, $data, $user_info);
3259 return api_format_data("direct-messages", $type, $data);
3263 function api_direct_messages_sentbox($type) {
3264 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3265 return api_direct_messages_box($type, "sentbox", $verbose);
3268 function api_direct_messages_inbox($type) {
3269 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3270 return api_direct_messages_box($type, "inbox", $verbose);
3273 function api_direct_messages_all($type) {
3274 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3275 return api_direct_messages_box($type, "all", $verbose);
3278 function api_direct_messages_conversation($type) {
3279 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3280 return api_direct_messages_box($type, "conversation", $verbose);
3283 /// @TODO move to top of file or somewhere better
3284 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3285 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3286 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3287 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3289 function api_oauth_request_token($type) {
3291 $oauth = new FKOAuth1();
3292 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3293 } catch (Exception $e) {
3294 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3301 function api_oauth_access_token($type) {
3303 $oauth = new FKOAuth1();
3304 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3305 } catch (Exception $e) {
3306 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3312 /// @TODO move to top of file or somewhere better
3313 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3314 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3318 * @brief delete a complete photoalbum with all containing photos from database through api
3320 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3323 function api_fr_photoalbum_delete($type) {
3324 if (api_user() === false) {
3325 throw new ForbiddenException();
3328 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3330 // we do not allow calls without album string
3332 throw new BadRequestException("no albumname specified");
3334 // check if album is existing
3335 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3338 if (!DBM::is_result($r))
3339 throw new BadRequestException("album not available");
3341 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3342 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3343 foreach ($r as $rr) {
3344 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3345 intval(local_user()),
3346 dbesc($rr['resource-id'])
3349 if (!DBM::is_result($photo_item)) {
3350 throw new InternalServerErrorException("problem with deleting items occured");
3352 drop_item($photo_item[0]['id'],false);
3355 // now let's delete all photos from the album
3356 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3360 // return success of deletion or error message
3362 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3363 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3365 throw new InternalServerErrorException("unknown error - deleting from database failed");
3371 * @brief update the name of the album for all photos of an album
3373 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3376 function api_fr_photoalbum_update($type) {
3377 if (api_user() === false) {
3378 throw new ForbiddenException();
3381 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3382 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3384 // we do not allow calls without album string
3386 throw new BadRequestException("no albumname specified");
3388 if ($album_new == "") {
3389 throw new BadRequestException("no new albumname specified");
3391 // check if album is existing
3392 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3395 if (!DBM::is_result($r)) {
3396 throw new BadRequestException("album not available");
3398 // now let's update all photos to the albumname
3399 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3404 // return success of updating or error message
3406 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3407 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3409 throw new InternalServerErrorException("unknown error - updating in database failed");
3415 * @brief list all photos of the authenticated user
3417 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3420 function api_fr_photos_list($type) {
3421 if (api_user() === false) {
3422 throw new ForbiddenException();
3424 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3425 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3426 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3427 intval(local_user())
3430 'image/jpeg' => 'jpg',
3431 'image/png' => 'png',
3432 'image/gif' => 'gif'
3434 $data = array('photo'=>array());
3435 if (DBM::is_result($r)) {
3436 foreach ($r as $rr) {
3438 $photo['id'] = $rr['resource-id'];
3439 $photo['album'] = $rr['album'];
3440 $photo['filename'] = $rr['filename'];
3441 $photo['type'] = $rr['type'];
3442 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3443 $photo['created'] = $rr['created'];
3444 $photo['edited'] = $rr['edited'];
3445 $photo['desc'] = $rr['desc'];
3447 if ($type == "xml") {
3448 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3450 $photo['thumb'] = $thumb;
3451 $data['photo'][] = $photo;
3455 return api_format_data("photos", $type, $data);
3459 * @brief upload a new photo or change an existing photo
3461 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3464 function api_fr_photo_create_update($type) {
3465 if (api_user() === false) {
3466 throw new ForbiddenException();
3469 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3470 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3471 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3472 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3473 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3474 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3475 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3476 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3477 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3479 // do several checks on input parameters
3480 // we do not allow calls without album string
3481 if ($album == null) {
3482 throw new BadRequestException("no albumname specified");
3484 // if photo_id == null --> we are uploading a new photo
3485 if ($photo_id == null) {
3488 // error if no media posted in create-mode
3489 if (!x($_FILES,'media')) {
3491 throw new BadRequestException("no media data submitted");
3494 // album_new will be ignored in create-mode
3499 // check if photo is existing in database
3500 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3504 if (!DBM::is_result($r)) {
3505 throw new BadRequestException("photo not available");
3509 // checks on acl strings provided by clients
3510 $acl_input_error = false;
3511 $acl_input_error |= check_acl_input($allow_cid);
3512 $acl_input_error |= check_acl_input($deny_cid);
3513 $acl_input_error |= check_acl_input($allow_gid);
3514 $acl_input_error |= check_acl_input($deny_gid);
3515 if ($acl_input_error) {
3516 throw new BadRequestException("acl data invalid");
3518 // now let's upload the new media in create-mode
3519 if ($mode == "create") {
3520 $media = $_FILES['media'];
3521 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3523 // return success of updating or error message
3524 if (!is_null($data)) {
3525 return api_format_data("photo_create", $type, $data);
3527 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3531 // now let's do the changes in update-mode
3532 if ($mode == "update") {
3535 if (!is_null($desc)) {
3536 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3539 if (!is_null($album_new)) {
3540 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3543 if (!is_null($allow_cid)) {
3544 $allow_cid = trim($allow_cid);
3545 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3548 if (!is_null($deny_cid)) {
3549 $deny_cid = trim($deny_cid);
3550 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3553 if (!is_null($allow_gid)) {
3554 $allow_gid = trim($allow_gid);
3555 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3558 if (!is_null($deny_gid)) {
3559 $deny_gid = trim($deny_gid);
3560 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3564 if ($sql_extra != "") {
3565 $nothingtodo = false;
3566 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3568 datetime_convert(), // update edited timestamp
3573 $nothingtodo = true;
3576 if (x($_FILES,'media')) {
3577 $nothingtodo = false;
3578 $media = $_FILES['media'];
3579 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3580 if (!is_null($data)) {
3581 return api_format_data("photo_update", $type, $data);
3585 // return success of updating or error message
3587 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3588 return api_format_data("photo_update", $type, array('$result' => $answer));
3591 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3592 return api_format_data("photo_update", $type, array('$result' => $answer));
3594 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3597 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3602 * @brief delete a single photo from the database through api
3604 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3607 function api_fr_photo_delete($type) {
3608 if (api_user() === false) {
3609 throw new ForbiddenException();
3612 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3614 // do several checks on input parameters
3615 // we do not allow calls without photo id
3616 if ($photo_id == null) {
3617 throw new BadRequestException("no photo_id specified");
3619 // check if photo is existing in database
3620 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3624 if (!DBM::is_result($r)) {
3625 throw new BadRequestException("photo not available");
3627 // now we can perform on the deletion of the photo
3628 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3632 // return success of deletion or error message
3634 // retrieve the id of the parent element (the photo element)
3635 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3636 intval(local_user()),
3640 if (!DBM::is_result($photo_item)) {
3641 throw new InternalServerErrorException("problem with deleting items occured");
3643 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3644 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3645 drop_item($photo_item[0]['id'], false);
3647 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3648 return api_format_data("photo_delete", $type, array('$result' => $answer));
3650 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3656 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3658 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3661 function api_fr_photo_detail($type) {
3662 if (api_user() === false) {
3663 throw new ForbiddenException();
3665 if (!x($_REQUEST, 'photo_id')) {
3666 throw new BadRequestException("No photo id.");
3669 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3670 $photo_id = $_REQUEST['photo_id'];
3672 // prepare json/xml output with data from database for the requested photo
3673 $data = prepare_photo_data($type, $scale, $photo_id);
3675 return api_format_data("photo_detail", $type, $data);
3680 * @brief updates the profile image for the user (either a specified profile or the default profile)
3682 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3685 function api_account_update_profile_image($type) {
3686 if (api_user() === false) {
3687 throw new ForbiddenException();
3690 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3692 // error if image data is missing
3693 if (!x($_FILES, 'image')) {
3694 throw new BadRequestException("no media data submitted");
3697 // check if specified profile id is valid
3698 if ($profileid != 0) {
3699 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3701 intval($profileid));
3702 // error message if specified profile id is not in database
3703 if (!DBM::is_result($r)) {
3704 throw new BadRequestException("profile_id not available");
3706 $is_default_profile = $r['profile'];
3708 $is_default_profile = 1;
3711 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3713 if (x($_FILES, 'image')) {
3714 $media = $_FILES['image'];
3715 } elseif (x($_FILES, 'media')) {
3716 $media = $_FILES['media'];
3718 // save new profile image
3719 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3722 if (is_array($media['type'])) {
3723 $filetype = $media['type'][0];
3725 $filetype = $media['type'];
3727 if ($filetype == "image/jpeg") {
3729 } elseif ($filetype == "image/png") {
3732 // change specified profile or all profiles to the new resource-id
3733 if ($is_default_profile) {
3734 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3735 dbesc($data['photo']['id']),
3736 intval(local_user())
3739 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3740 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3741 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3742 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3743 intval(local_user())
3746 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3747 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3748 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3749 intval($_REQUEST['profile']),
3750 intval(local_user())
3754 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3755 // so that browsers will do a cache update unconditionally
3757 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3758 dbesc(datetime_convert()),
3759 intval(local_user())
3762 // Update global directory in background
3763 //$user = api_get_user(get_app());
3764 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3765 if ($url && strlen(Config::get('system', 'directory'))) {
3766 Worker::add(PRIORITY_LOW, "directory", $url);
3769 Worker::add(PRIORITY_LOW, 'profile_update', api_user());
3771 // output for client
3773 return api_account_verify_credentials($type);
3775 // SaveMediaToDatabase failed for some reason
3776 throw new InternalServerErrorException("image upload failed");
3780 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3781 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3782 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3783 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3784 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3785 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3786 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3787 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3788 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3791 function check_acl_input($acl_string) {
3792 if ($acl_string == null || $acl_string == " ") {
3795 $contact_not_found = false;
3797 // split <x><y><z> into array of cid's
3798 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3800 // check for each cid if it is available on server
3801 $cid_array = $array[0];
3802 foreach ($cid_array as $cid) {
3803 $cid = str_replace("<", "", $cid);
3804 $cid = str_replace(">", "", $cid);
3805 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3807 intval(api_user()));
3808 $contact_not_found |= !DBM::is_result($contact);
3810 return $contact_not_found;
3813 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) {
3820 if (is_array($media)) {
3821 if (is_array($media['tmp_name'])) {
3822 $src = $media['tmp_name'][0];
3824 $src = $media['tmp_name'];
3826 if (is_array($media['name'])) {
3827 $filename = basename($media['name'][0]);
3829 $filename = basename($media['name']);
3831 if (is_array($media['size'])) {
3832 $filesize = intval($media['size'][0]);
3834 $filesize = intval($media['size']);
3836 if (is_array($media['type'])) {
3837 $filetype = $media['type'][0];
3839 $filetype = $media['type'];
3843 if ($filetype == "") {
3844 $filetype=guess_image_type($filename);
3846 $imagedata = getimagesize($src);
3848 $filetype = $imagedata['mime'];
3850 logger("File upload src: " . $src . " - filename: " . $filename .
3851 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3853 // check if there was a php upload error
3854 if ($filesize == 0 && $media['error'] == 1) {
3855 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3857 // check against max upload size within Friendica instance
3858 $maximagesize = Config::get('system', 'maximagesize');
3859 if (($maximagesize) && ($filesize > $maximagesize)) {
3860 $formattedBytes = formatBytes($maximagesize);
3861 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3864 // create Photo instance with the data of the image
3865 $imagedata = @file_get_contents($src);
3866 $ph = new Photo($imagedata, $filetype);
3867 if (! $ph->is_valid()) {
3868 throw new InternalServerErrorException("unable to process image data");
3871 // check orientation of image
3875 // check max length of images on server
3876 $max_length = Config::get('system', 'max_image_length');
3877 if (! $max_length) {
3878 $max_length = MAX_IMAGE_LENGTH;
3880 if ($max_length > 0) {
3881 $ph->scaleImage($max_length);
3882 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3884 $width = $ph->getWidth();
3885 $height = $ph->getHeight();
3887 // create a new resource-id if not already provided
3888 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3890 if ($mediatype == "photo") {
3891 // upload normal image (scales 0, 1, 2)
3892 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3894 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3896 logger("photo upload: image upload with scale 0 (original size) failed");
3898 if($width > 640 || $height > 640) {
3899 $ph->scaleImage(640);
3900 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3902 logger("photo upload: image upload with scale 1 (640x640) failed");
3906 if ($width > 320 || $height > 320) {
3907 $ph->scaleImage(320);
3908 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3910 logger("photo upload: image upload with scale 2 (320x320) failed");
3913 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3914 } elseif ($mediatype == "profileimage") {
3915 // upload profile image (scales 4, 5, 6)
3916 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3918 if ($width > 175 || $height > 175) {
3919 $ph->scaleImage(175);
3920 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3922 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3926 if ($width > 80 || $height > 80) {
3927 $ph->scaleImage(80);
3928 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3930 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3934 if ($width > 48 || $height > 48) {
3935 $ph->scaleImage(48);
3936 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3938 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3942 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3946 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3947 if ($photo_id == null && $mediatype == "photo") {
3948 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3950 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3951 return prepare_photo_data($type, false, $hash);
3953 throw new InternalServerErrorException("image upload failed");
3957 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3958 // get data about the api authenticated user
3959 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3960 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3963 $arr['guid'] = get_guid(32);
3964 $arr['uid'] = intval(api_user());
3966 $arr['parent-uri'] = $uri;
3967 $arr['type'] = 'photo';
3969 $arr['resource-id'] = $hash;
3970 $arr['contact-id'] = $owner_record[0]['id'];
3971 $arr['owner-name'] = $owner_record[0]['name'];
3972 $arr['owner-link'] = $owner_record[0]['url'];
3973 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3974 $arr['author-name'] = $owner_record[0]['name'];
3975 $arr['author-link'] = $owner_record[0]['url'];
3976 $arr['author-avatar'] = $owner_record[0]['thumb'];
3978 $arr['allow_cid'] = $allow_cid;
3979 $arr['allow_gid'] = $allow_gid;
3980 $arr['deny_cid'] = $deny_cid;
3981 $arr['deny_gid'] = $deny_gid;
3982 $arr['last-child'] = 1;
3983 $arr['visible'] = $visibility;
3987 'image/jpeg' => 'jpg',
3988 'image/png' => 'png',
3989 'image/gif' => 'gif'
3992 // adds link to the thumbnail scale photo
3993 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
3994 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3997 // do the magic for storing the item in the database and trigger the federation to other contacts
4001 function prepare_photo_data($type, $scale, $photo_id) {
4002 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4003 $data_sql = ($scale === false ? "" : "data, ");
4005 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4006 // clients needs to convert this in their way for further processing
4007 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4008 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4009 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4010 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4012 intval(local_user()),
4018 'image/jpeg' => 'jpg',
4019 'image/png' => 'png',
4020 'image/gif' => 'gif'
4023 // prepare output data for photo
4024 if (DBM::is_result($r)) {
4025 $data = array('photo' => $r[0]);
4026 $data['photo']['id'] = $data['photo']['resource-id'];
4027 if ($scale !== false) {
4028 $data['photo']['data'] = base64_encode($data['photo']['data']);
4030 unset($data['photo']['datasize']); //needed only with scale param
4032 if ($type == "xml") {
4033 $data['photo']['links'] = array();
4034 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4035 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4037 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4040 $data['photo']['link'] = array();
4041 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4043 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4044 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4048 unset($data['photo']['resource-id']);
4049 unset($data['photo']['minscale']);
4050 unset($data['photo']['maxscale']);
4053 throw new NotFoundException();
4056 // retrieve item element for getting activities (like, dislike etc.) related to photo
4057 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4058 intval(local_user()),
4061 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4063 // retrieve comments on photo
4064 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4065 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4066 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4067 `contact`.`id` AS `cid`
4069 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4070 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4071 WHERE `item`.`parent` = %d AND `item`.`visible`
4072 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4073 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4074 intval($item[0]['parent']),
4076 dbesc(ACTIVITY_POST)
4079 // prepare output of comments
4080 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4081 $comments = array();
4082 if ($type == "xml") {
4084 foreach ($commentData as $comment) {
4085 $comments[$k++ . ":comment"] = $comment;
4088 foreach ($commentData as $comment) {
4089 $comments[] = $comment;
4092 $data['photo']['friendica_comments'] = $comments;
4094 // include info if rights on photo and rights on item are mismatching
4095 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4096 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4097 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4098 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4099 $data['photo']['rights_mismatch'] = $rights_mismatch;
4106 * similar as /mod/redir.php
4107 * redirect to 'url' after dfrn auth
4109 * why this when there is mod/redir.php already?
4110 * This use api_user() and api_login()
4113 * c_url: url of remote contact to auth to
4114 * url: string, url to redirect after auth
4116 function api_friendica_remoteauth() {
4117 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4118 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4120 if ($url === '' || $c_url === '') {
4121 throw new BadRequestException("Wrong parameters.");
4124 $c_url = normalise_link($c_url);
4128 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4133 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4134 throw new BadRequestException("Unknown contact");
4139 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4141 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4142 $orig_id = $r[0]['issued-id'];
4143 $dfrn_id = '1:' . $orig_id;
4145 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4146 $orig_id = $r[0]['dfrn-id'];
4147 $dfrn_id = '0:' . $orig_id;
4150 $sec = random_string();
4152 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4153 VALUES( %d, %s, '%s', '%s', %d )",
4161 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4162 $dest = (($url) ? '&destination_url=' . $url : '');
4163 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4164 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4165 . '&type=profile&sec=' . $sec . $dest . $quiet );
4167 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4170 * @brief Return the item shared, if the item contains only the [share] tag
4172 * @param array $item Sharer item
4173 * @return array Shared item or false if not a reshare
4175 function api_share_as_retweet(&$item) {
4176 $body = trim($item["body"]);
4178 if (Diaspora::is_reshare($body, false)===false) {
4182 /// @TODO "$1" should maybe mean '$1' ?
4183 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4185 * Skip if there is no shared message in there
4186 * we already checked this in diaspora::is_reshare()
4187 * but better one more than one less...
4189 if ($body == $attributes) {
4194 // build the fake reshared item
4195 $reshared_item = $item;
4198 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4199 if ($matches[1] != "") {
4200 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4203 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4204 if ($matches[1] != "") {
4205 $author = $matches[1];
4209 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4210 if ($matches[1] != "") {
4211 $profile = $matches[1];
4214 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4215 if ($matches[1] != "") {
4216 $profile = $matches[1];
4220 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4221 if ($matches[1] != "") {
4222 $avatar = $matches[1];
4225 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4226 if ($matches[1] != "") {
4227 $avatar = $matches[1];
4231 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4232 if ($matches[1] != "") {
4233 $link = $matches[1];
4236 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4237 if ($matches[1] != "") {
4238 $link = $matches[1];
4242 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4243 if ($matches[1] != "")
4244 $posted = $matches[1];
4246 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4247 if ($matches[1] != "") {
4248 $posted = $matches[1];
4251 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4253 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4257 $reshared_item["body"] = $shared_body;
4258 $reshared_item["author-name"] = $author;
4259 $reshared_item["author-link"] = $profile;
4260 $reshared_item["author-avatar"] = $avatar;
4261 $reshared_item["plink"] = $link;
4262 $reshared_item["created"] = $posted;
4263 $reshared_item["edited"] = $posted;
4265 return $reshared_item;
4269 function api_get_nick($profile) {
4271 - remove trailing junk from profile url
4272 - pump.io check has to check the website
4277 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4278 dbesc(normalise_link($profile)));
4280 if (DBM::is_result($r)) {
4281 $nick = $r[0]["nick"];
4285 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4286 dbesc(normalise_link($profile)));
4288 if (DBM::is_result($r)) {
4289 $nick = $r[0]["nick"];
4294 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4295 if ($friendica != $profile) {
4301 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4302 if ($diaspora != $profile) {
4308 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4309 if ($twitter != $profile) {
4316 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4317 if ($StatusnetHost != $profile) {
4318 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4319 if ($StatusnetUser != $profile) {
4320 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4321 $user = json_decode($UserData);
4323 $nick = $user->screen_name;
4329 // To-Do: look at the page if its really a pumpio site
4330 //if (!$nick == "") {
4331 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4332 // if ($pumpio != $profile)
4334 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4345 function api_in_reply_to($item) {
4346 $in_reply_to = array();
4348 $in_reply_to['status_id'] = NULL;
4349 $in_reply_to['user_id'] = NULL;
4350 $in_reply_to['status_id_str'] = NULL;
4351 $in_reply_to['user_id_str'] = NULL;
4352 $in_reply_to['screen_name'] = NULL;
4354 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4355 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4356 intval($item['uid']),
4357 dbesc($item['thr-parent']));
4359 if (DBM::is_result($r)) {
4360 $in_reply_to['status_id'] = intval($r[0]['id']);
4362 $in_reply_to['status_id'] = intval($item['parent']);
4365 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4367 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4368 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4369 WHERE `item`.`id` = %d LIMIT 1",
4370 intval($in_reply_to['status_id'])
4373 if (DBM::is_result($r)) {
4374 if ($r[0]['nick'] == "") {
4375 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4378 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4379 $in_reply_to['user_id'] = intval($r[0]['id']);
4380 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4383 // There seems to be situation, where both fields are identical:
4384 // https://github.com/friendica/friendica/issues/1010
4385 // This is a bugfix for that.
4386 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4387 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4388 $in_reply_to['status_id'] = NULL;
4389 $in_reply_to['user_id'] = NULL;
4390 $in_reply_to['status_id_str'] = NULL;
4391 $in_reply_to['user_id_str'] = NULL;
4392 $in_reply_to['screen_name'] = NULL;
4396 return $in_reply_to;
4399 function api_clean_plain_items($Text) {
4400 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4402 $Text = bb_CleanPictureLinks($Text);
4403 $URLSearchString = "^\[\]";
4405 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4407 if ($include_entities == "true") {
4408 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4411 // Simplify "attachment" element
4412 $Text = api_clean_attachments($Text);
4418 * @brief Removes most sharing information for API text export
4420 * @param string $body The original body
4422 * @return string Cleaned body
4424 function api_clean_attachments($body) {
4425 $data = get_attachment_data($body);
4432 if (isset($data["text"]))
4433 $body = $data["text"];
4435 if (($body == "") && (isset($data["title"])))
4436 $body = $data["title"];
4438 if (isset($data["url"]))
4439 $body .= "\n".$data["url"];
4441 $body .= $data["after"];
4446 function api_best_nickname(&$contacts) {
4447 $best_contact = array();
4449 if (count($contact) == 0)
4452 foreach ($contacts AS $contact)
4453 if ($contact["network"] == "") {
4454 $contact["network"] = "dfrn";
4455 $best_contact = array($contact);
4458 if (sizeof($best_contact) == 0)
4459 foreach ($contacts AS $contact)
4460 if ($contact["network"] == "dfrn")
4461 $best_contact = array($contact);
4463 if (sizeof($best_contact) == 0)
4464 foreach ($contacts AS $contact)
4465 if ($contact["network"] == "dspr")
4466 $best_contact = array($contact);
4468 if (sizeof($best_contact) == 0)
4469 foreach ($contacts AS $contact)
4470 if ($contact["network"] == "stat")
4471 $best_contact = array($contact);
4473 if (sizeof($best_contact) == 0)
4474 foreach ($contacts AS $contact)
4475 if ($contact["network"] == "pump")
4476 $best_contact = array($contact);
4478 if (sizeof($best_contact) == 0)
4479 foreach ($contacts AS $contact)
4480 if ($contact["network"] == "twit")
4481 $best_contact = array($contact);
4483 if (sizeof($best_contact) == 1)
4484 $contacts = $best_contact;
4486 $contacts = array($contacts[0]);
4489 // return all or a specified group of the user with the containing contacts
4490 function api_friendica_group_show($type) {
4494 if (api_user() === false) throw new ForbiddenException();
4497 $user_info = api_get_user($a);
4498 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4499 $uid = $user_info['uid'];
4501 // get data of the specified group id or all groups if not specified
4503 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4506 // error message if specified gid is not in database
4507 if (!DBM::is_result($r))
4508 throw new BadRequestException("gid not available");
4511 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4514 // loop through all groups and retrieve all members for adding data in the user array
4515 foreach ($r as $rr) {
4516 $members = group_get_members($rr['id']);
4519 if ($type == "xml") {
4520 $user_element = "users";
4522 foreach ($members as $member) {
4523 $user = api_get_user($a, $member['nurl']);
4524 $users[$k++.":user"] = $user;
4527 $user_element = "user";
4528 foreach ($members as $member) {
4529 $user = api_get_user($a, $member['nurl']);
4533 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4535 return api_format_data("groups", $type, array('group' => $grps));
4537 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4540 // delete the specified group of the user
4541 function api_friendica_group_delete($type) {
4545 if (api_user() === false) throw new ForbiddenException();
4548 $user_info = api_get_user($a);
4549 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4550 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4551 $uid = $user_info['uid'];
4553 // error if no gid specified
4554 if ($gid == 0 || $name == "")
4555 throw new BadRequestException('gid or name not specified');
4557 // get data of the specified group id
4558 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4561 // error message if specified gid is not in database
4562 if (!DBM::is_result($r))
4563 throw new BadRequestException('gid not available');
4565 // get data of the specified group id and group name
4566 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4570 // error message if specified gid is not in database
4571 if (!DBM::is_result($rname))
4572 throw new BadRequestException('wrong group name');
4575 $ret = group_rmv($uid, $name);
4578 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4579 return api_format_data("group_delete", $type, array('result' => $success));
4582 throw new BadRequestException('other API error');
4584 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4587 // create the specified group with the posted array of contacts
4588 function api_friendica_group_create($type) {
4592 if (api_user() === false) throw new ForbiddenException();
4595 $user_info = api_get_user($a);
4596 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4597 $uid = $user_info['uid'];
4598 $json = json_decode($_POST['json'], true);
4599 $users = $json['user'];
4601 // error if no name specified
4603 throw new BadRequestException('group name not specified');
4605 // get data of the specified group name
4606 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4609 // error message if specified group name already exists
4610 if (DBM::is_result($rname))
4611 throw new BadRequestException('group name already exists');
4613 // check if specified group name is a deleted group
4614 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4617 // error message if specified group name already exists
4618 if (DBM::is_result($rname))
4619 $reactivate_group = true;
4622 $ret = group_add($uid, $name);
4624 $gid = group_byname($uid, $name);
4626 throw new BadRequestException('other API error');
4629 $erroraddinguser = false;
4630 $errorusers = array();
4631 foreach ($users as $user) {
4632 $cid = $user['cid'];
4633 // check if user really exists as contact
4634 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4637 if (count($contact))
4638 $result = group_add_member($uid, $name, $cid, $gid);
4640 $erroraddinguser = true;
4641 $errorusers[] = $cid;
4645 // return success message incl. missing users in array
4646 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4647 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4648 return api_format_data("group_create", $type, array('result' => $success));
4650 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4653 // update the specified group with the posted array of contacts
4654 function api_friendica_group_update($type) {
4658 if (api_user() === false) throw new ForbiddenException();
4661 $user_info = api_get_user($a);
4662 $uid = $user_info['uid'];
4663 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4664 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4665 $json = json_decode($_POST['json'], true);
4666 $users = $json['user'];
4668 // error if no name specified
4670 throw new BadRequestException('group name not specified');
4672 // error if no gid specified
4674 throw new BadRequestException('gid not specified');
4677 $members = group_get_members($gid);
4678 foreach ($members as $member) {
4679 $cid = $member['id'];
4680 foreach ($users as $user) {
4681 $found = ($user['cid'] == $cid ? true : false);
4684 $ret = group_rmv_member($uid, $name, $cid);
4689 $erroraddinguser = false;
4690 $errorusers = array();
4691 foreach ($users as $user) {
4692 $cid = $user['cid'];
4693 // check if user really exists as contact
4694 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4697 if (count($contact))
4698 $result = group_add_member($uid, $name, $cid, $gid);
4700 $erroraddinguser = true;
4701 $errorusers[] = $cid;
4705 // return success message incl. missing users in array
4706 $status = ($erroraddinguser ? "missing user" : "ok");
4707 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4708 return api_format_data("group_update", $type, array('result' => $success));
4711 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4713 function api_friendica_activity($type) {
4717 if (api_user() === false) throw new ForbiddenException();
4718 $verb = strtolower($a->argv[3]);
4719 $verb = preg_replace("|\..*$|", "", $verb);
4721 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4723 $res = do_like($id, $verb);
4730 return api_format_data('ok', $type, array('ok' => $ok));
4732 throw new BadRequestException('Error adding activity');
4737 /// @TODO move to top of file or somwhere better
4738 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4739 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4740 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4741 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4742 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4743 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4744 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4745 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4746 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4747 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4750 * @brief Returns notifications
4752 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4755 function api_friendica_notification($type) {
4759 if (api_user() === false) throw new ForbiddenException();
4760 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4761 $nm = new NotificationsManager();
4763 $notes = $nm->getAll(array(), "+seen -date", 50);
4765 if ($type == "xml") {
4766 $xmlnotes = array();
4767 foreach ($notes AS $note)
4768 $xmlnotes[] = array("@attributes" => $note);
4773 return api_format_data("notes", $type, array('note' => $notes));
4777 * @brief Set notification as seen and returns associated item (if possible)
4779 * POST request with 'id' param as notification id
4781 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4784 function api_friendica_notification_seen($type) {
4788 if (api_user() === false) throw new ForbiddenException();
4789 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4791 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4793 $nm = new NotificationsManager();
4794 $note = $nm->getByID($id);
4795 if (is_null($note)) throw new BadRequestException("Invalid argument");
4797 $nm->setSeen($note);
4798 if ($note['otype']=='item') {
4799 // would be really better with an ItemsManager and $im->getByID() :-P
4800 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4801 intval($note['iid']),
4802 intval(local_user())
4805 // we found the item, return it to the user
4806 $user_info = api_get_user($a);
4807 $ret = api_format_items($r,$user_info, false, $type);
4808 $data = array('status' => $ret);
4809 return api_format_data("status", $type, $data);
4811 // the item can't be found, but we set the note as seen, so we count this as a success
4813 return api_format_data('result', $type, array('result' => "success"));
4816 /// @TODO move to top of file or somwhere better
4817 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4818 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4821 * @brief update a direct_message to seen state
4823 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4824 * @return string (success result=ok, error result=error with error message)
4826 function api_friendica_direct_messages_setseen($type) {
4828 if (api_user() === false) {
4829 throw new ForbiddenException();
4833 $user_info = api_get_user($a);
4834 $uid = $user_info['uid'];
4835 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4837 // return error if id is zero
4839 $answer = array('result' => 'error', 'message' => 'message id not specified');
4840 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4843 // get data of the specified message id
4844 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4848 // error message if specified id is not in database
4849 if (!DBM::is_result($r)) {
4850 $answer = array('result' => 'error', 'message' => 'message id not in database');
4851 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4854 // update seen indicator
4855 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4861 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4862 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4864 $answer = array('result' => 'error', 'message' => 'unknown error');
4865 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4869 /// @TODO move to top of file or somwhere better
4870 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4873 * @brief search for direct_messages containing a searchstring through api
4875 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4876 * @return string (success: success=true if found and search_result contains found messages
4877 * success=false if nothing was found, search_result='nothing found',
4878 * error: result=error with error message)
4880 function api_friendica_direct_messages_search($type) {
4883 if (api_user() === false) {
4884 throw new ForbiddenException();
4888 $user_info = api_get_user($a);
4889 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4890 $uid = $user_info['uid'];
4892 // error if no searchstring specified
4893 if ($searchstring == "") {
4894 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4895 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4898 // get data for the specified searchstring
4899 $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",
4901 dbesc('%'.$searchstring.'%')
4904 $profile_url = $user_info["url"];
4906 // message if nothing was found
4907 if (!DBM::is_result($r)) {
4908 $success = array('success' => false, 'search_results' => 'problem with query');
4909 } elseif (count($r) == 0) {
4910 $success = array('success' => false, 'search_results' => 'nothing found');
4913 foreach ($r as $item) {
4914 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4915 $recipient = $user_info;
4916 $sender = api_get_user($a,normalise_link($item['contact-url']));
4917 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4918 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4919 $sender = $user_info;
4922 $ret[] = api_format_messages($item, $recipient, $sender);
4924 $success = array('success' => true, 'search_results' => $ret);
4927 return api_format_data("direct_message_search", $type, array('$result' => $success));
4930 /// @TODO move to top of file or somwhere better
4931 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4934 * @brief return data of all the profiles a user has to the client
4936 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4939 function api_friendica_profile_show($type) {
4942 if (api_user() === false) {
4943 throw new ForbiddenException();
4947 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4949 // retrieve general information about profiles for user
4950 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4951 $directory = Config::get('system', 'directory');
4953 // get data of the specified profile id or all profiles of the user if not specified
4954 if ($profileid != 0) {
4955 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4957 intval($profileid));
4959 // error message if specified gid is not in database
4960 if (!DBM::is_result($r)) {
4961 throw new BadRequestException("profile_id not available");
4964 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4965 intval(api_user()));
4967 // loop through all returned profiles and retrieve data and users
4969 foreach ($r as $rr) {
4970 $profile = api_format_items_profiles($rr, $type);
4972 // select all users from contact table, loop and prepare standard return for user data
4974 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4976 intval($rr['profile_id']));
4978 foreach ($r as $rr) {
4979 $user = api_get_user($a, $rr['nurl']);
4980 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4982 $profile['users'] = $users;
4984 // add prepared profile data to array for final return
4985 if ($type == "xml") {
4986 $profiles[$k++ . ":profile"] = $profile;
4988 $profiles[] = $profile;
4992 // return settings, authenticated user and profiles data
4993 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4995 $result = array('multi_profiles' => $multi_profiles ? true : false,
4996 'global_dir' => $directory,
4997 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4998 'profiles' => $profiles);
4999 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5001 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5004 @TODO Maybe open to implement?
5006 [pagename] => api/1.1/statuses/lookup.json
5007 [id] => 605138389168451584
5008 [include_cards] => true
5009 [cards_platform] => Android-12
5010 [include_entities] => true
5011 [include_my_retweet] => 1
5013 [include_reply_count] => true
5014 [include_descendent_reply_count] => true
5018 Not implemented by now:
5019 statuses/retweets_of_me
5024 account/update_location
5025 account/update_profile_background_image
5028 friendica/profile/update
5029 friendica/profile/create
5030 friendica/profile/delete
5032 Not implemented in status.net:
5033 statuses/retweeted_to_me
5034 statuses/retweeted_by_me
5035 direct_messages/destroy
5037 account/update_delivery_device
5038 notifications/follow