3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Core\Config;
12 require_once 'include/HTTPExceptions.php';
13 require_once 'include/bbcode.php';
14 require_once 'include/datetime.php';
15 require_once 'include/conversation.php';
16 require_once 'include/oauth.php';
17 require_once 'include/html2plain.php';
18 require_once 'mod/share.php';
19 require_once 'include/Photo.php';
20 require_once 'mod/item.php';
21 require_once 'include/security.php';
22 require_once 'include/contact_selectors.php';
23 require_once 'include/html2bbcode.php';
24 require_once 'mod/wall_upload.php';
25 require_once 'mod/proxy.php';
26 require_once 'include/message.php';
27 require_once 'include/group.php';
28 require_once 'include/like.php';
29 require_once 'include/NotificationsManager.php';
30 require_once 'include/plaintext.php';
31 require_once 'include/xml.php';
33 define('API_METHOD_ANY', '*');
34 define('API_METHOD_GET', 'GET');
35 define('API_METHOD_POST', 'POST,PUT');
36 define('API_METHOD_DELETE', 'POST,DELETE');
41 /// @TODO Fix intending
43 * @brief Auth API user
45 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
46 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
47 * into a page, and visitors will post something without noticing it).
50 if (x($_SESSION, 'allow_api')) {
58 * @brief Get source name from API client
60 * Clients can send 'source' parameter to be show in post metadata
61 * as "sent via <source>".
62 * Some clients doesn't send a source param, we support ones we know
66 * Client source name, default to "api" if unset/unknown
68 function api_source() {
69 if (requestdata('source')) {
70 return requestdata('source');
73 // Support for known clients that doesn't send a source name
74 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
78 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
84 * @brief Format date for API
86 * @param string $str Source date, as UTC
87 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
89 function api_date($str) {
90 // Wed May 23 06:01:13 +0000 2007
91 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
95 * @brief Register API endpoint
97 * Register a function to be the endpont for defined API path.
99 * @param string $path API URL path, relative to App::get_baseurl()
100 * @param string $func Function name to call on path request
101 * @param bool $auth API need logged user
102 * @param string $method HTTP method reqiured to call this endpoint.
104 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
105 * Default to API_METHOD_ANY
107 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
116 // Workaround for hotot
117 $path = str_replace("api/", "api/1.1/", $path);
127 * @brief Login API user
129 * Log in user via OAuth1 or Simple HTTP Auth.
130 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
133 * @hook 'authenticate'
135 * 'username' => username from login form
136 * 'password' => password from login form
137 * 'authenticated' => return status,
138 * 'user_record' => return authenticated user record
140 * array $user logged user record
142 function api_login(App $a) {
145 $oauth = new FKOAuth1();
146 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
147 if (!is_null($token)) {
148 $oauth->loginUser($token->uid);
149 call_hooks('logged_in', $a->user);
152 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
153 var_dump($consumer, $token);
155 } catch (Exception $e) {
159 // workaround for HTTP-auth in CGI mode
160 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
161 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
162 if (strlen($userpass)) {
163 list($name, $password) = explode(':', $userpass);
164 $_SERVER['PHP_AUTH_USER'] = $name;
165 $_SERVER['PHP_AUTH_PW'] = $password;
169 if (!x($_SERVER, 'PHP_AUTH_USER')) {
170 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
171 header('WWW-Authenticate: Basic realm="Friendica"');
172 throw new UnauthorizedException("This API requires login");
175 $user = $_SERVER['PHP_AUTH_USER'];
176 $password = $_SERVER['PHP_AUTH_PW'];
177 $encrypted = hash('whirlpool', trim($password));
179 // allow "user@server" login (but ignore 'server' part)
180 $at = strstr($user, "@", true);
185 // next code from mod/auth.php. needs better solution
189 'username' => trim($user),
190 'password' => trim($password),
191 'authenticated' => 0,
192 'user_record' => null,
196 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
197 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
198 * and later plugins should not interfere with an earlier one that succeeded.
200 call_hooks('authenticate', $addon_auth);
202 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
203 $record = $addon_auth['user_record'];
205 // process normal login request
206 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
207 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
212 if (dbm::is_result($r)) {
217 if ((! $record) || (! count($record))) {
218 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
219 header('WWW-Authenticate: Basic realm="Friendica"');
220 //header('HTTP/1.0 401 Unauthorized');
221 //die('This api requires login');
222 throw new UnauthorizedException("This API requires login");
225 authenticate_success($record);
227 $_SESSION["allow_api"] = true;
229 call_hooks('logged_in', $a->user);
234 * @brief Check HTTP method of called API
236 * API endpoints can define which HTTP method to accept when called.
237 * This function check the current HTTP method agains endpoint
240 * @param string $method Required methods, uppercase, separated by comma
243 function api_check_method($method) {
244 if ($method == "*") {
247 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
251 * @brief Main API entry point
253 * Authenticate user, call registered API function, set HTTP headers
256 * @return string API call result
258 function api_call(App $a) {
259 global $API, $called_api;
262 if (strpos($a->query_string, ".xml") > 0) {
265 if (strpos($a->query_string, ".json") > 0) {
268 if (strpos($a->query_string, ".rss") > 0) {
271 if (strpos($a->query_string, ".atom") > 0) {
276 foreach ($API as $p => $info) {
277 if (strpos($a->query_string, $p) === 0) {
278 if (!api_check_method($info['method'])) {
279 throw new MethodNotAllowedException();
282 $called_api = explode("/", $p);
283 //unset($_SERVER['PHP_AUTH_USER']);
285 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
286 if ($info['auth'] === true && api_user() === false) {
290 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
291 logger('API parameters: ' . print_r($_REQUEST, true));
293 $stamp = microtime(true);
294 $r = call_user_func($info['func'], $type);
295 $duration = (float) (microtime(true) - $stamp);
296 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
298 if (get_config("system", "profiler")) {
299 $duration = microtime(true)-$a->performance["start"];
301 /// @TODO round() really everywhere?
302 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
303 round($a->performance["database"] - $a->performance["database_write"], 3),
304 round($a->performance["database_write"], 3),
305 round($a->performance["network"], 2),
306 round($a->performance["file"], 2),
307 round($duration - ($a->performance["database"] + $a->performance["network"]
308 + $a->performance["file"]), 2),
309 round($duration, 2)),
313 if (get_config("rendertime", "callstack")) {
314 $o = "Database Read:\n";
315 foreach ($a->callstack["database"] AS $func => $time) {
316 $time = round($time, 3);
318 $o .= $func . ": " . $time . "\n";
321 $o .= "\nDatabase Write:\n";
322 foreach ($a->callstack["database_write"] AS $func => $time) {
323 $time = round($time, 3);
325 $o .= $func . ": " . $time . "\n";
329 $o .= "\nNetwork:\n";
330 foreach ($a->callstack["network"] AS $func => $time) {
331 $time = round($time, 3);
333 $o .= $func . ": " . $time . "\n";
336 logger($o, LOGGER_DEBUG);
342 * api function returned false withour throw an
343 * exception. This should not happend, throw a 500
345 throw new InternalServerErrorException();
350 header ("Content-Type: text/xml");
354 header ("Content-Type: application/json");
356 $json = json_encode($rr);
357 if (x($_GET, 'callback')) {
358 $json = $_GET['callback'] . "(" . $json . ")";
363 header ("Content-Type: application/rss+xml");
364 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
367 header ("Content-Type: application/atom+xml");
368 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
374 logger('API call not implemented: ' . $a->query_string);
375 throw new NotImplementedException();
376 } catch (HTTPException $e) {
377 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
378 return api_error($type, $e);
383 * @brief Format API error string
385 * @param string $type Return type (xml, json, rss, as)
386 * @param HTTPException $error Error object
387 * @return strin error message formatted as $type
389 function api_error($type, $e) {
393 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
394 /// @TODO: https://dev.twitter.com/overview/api/response-codes
396 $error = array("error" => $error,
397 "code" => $e->httpcode . " " . $e->httpdesc,
398 "request" => $a->query_string);
400 $ret = api_format_data('status', $type, array('status' => $error));
404 header ("Content-Type: text/xml");
408 header ("Content-Type: application/json");
409 return json_encode($ret);
412 header ("Content-Type: application/rss+xml");
416 header ("Content-Type: application/atom+xml");
423 * @brief Set values for RSS template
426 * @param array $arr Array to be passed to template
427 * @param array $user_info
429 * @todo find proper type-hints
431 function api_rss_extra(App $a, $arr, $user_info) {
432 if (is_null($user_info)) {
433 $user_info = api_get_user($a);
436 $arr['$user'] = $user_info;
437 $arr['$rss'] = array(
438 'alternate' => $user_info['url'],
439 'self' => App::get_baseurl() . "/" . $a->query_string,
440 'base' => App::get_baseurl(),
441 'updated' => api_date(null),
442 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
443 'language' => $user_info['language'],
444 'logo' => App::get_baseurl() . "/images/friendica-32.png",
452 * @brief Unique contact to contact url.
454 * @param int $id Contact id
455 * @return bool|string
456 * Contact url or False if contact id is unknown
458 function api_unique_id_to_url($id) {
459 $r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
462 return (dbm::is_result($r) && $r[0]["url"]);
466 * @brief Get user info array.
469 * @param int|string $contact_id Contact ID or URL
470 * @param string $type Return type (for errors)
472 function api_get_user(App $a, $contact_id = null, $type = "json") {
480 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
482 // Searching for contact URL
483 if (!is_null($contact_id) AND (intval($contact_id) == 0)) {
484 $user = dbesc(normalise_link($contact_id));
486 $extra_query = "AND `contact`.`nurl` = '%s' ";
487 if (api_user() !== false) {
488 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
492 // Searching for contact id with uid = 0
493 if (!is_null($contact_id) AND (intval($contact_id) != 0)) {
494 $user = dbesc(api_unique_id_to_url($contact_id));
497 throw new BadRequestException("User not found.");
501 $extra_query = "AND `contact`.`nurl` = '%s' ";
502 if (api_user() !== false) {
503 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
507 if (is_null($user) && x($_GET, 'user_id')) {
508 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
511 throw new BadRequestException("User not found.");
515 $extra_query = "AND `contact`.`nurl` = '%s' ";
516 if (api_user() !== false) {
517 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
520 if (is_null($user) && x($_GET, 'screen_name')) {
521 $user = dbesc($_GET['screen_name']);
523 $extra_query = "AND `contact`.`nick` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
529 if (is_null($user) && x($_GET, 'profileurl')) {
530 $user = dbesc(normalise_link($_GET['profileurl']));
532 $extra_query = "AND `contact`.`nurl` = '%s' ";
533 if (api_user() !== false) {
534 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
538 if (is_null($user) AND ($a->argc > (count($called_api) - 1)) AND (count($called_api) > 0)) {
539 $argid = count($called_api);
540 list($user, $null) = explode(".", $a->argv[$argid]);
541 if (is_numeric($user)) {
542 $user = dbesc(api_unique_id_to_url($user));
549 $extra_query = "AND `contact`.`nurl` = '%s' ";
550 if (api_user() !== false) {
551 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
554 $user = dbesc($user);
556 $extra_query = "AND `contact`.`nick` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
563 logger("api_get_user: user ".$user, LOGGER_DEBUG);
566 if (api_user() === false) {
570 $user = $_SESSION['uid'];
571 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
576 logger('api_user: ' . $extra_query . ', user: ' . $user);
579 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
585 // Selecting the id by priority, friendica first
586 api_best_nickname($uinfo);
588 // if the contact wasn't found, fetch it from the contacts with uid = 0
589 if (!dbm::is_result($uinfo)) {
593 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
596 if (dbm::is_result($r)) {
597 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
599 // If no nick where given, extract it from the address
600 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick'])) {
601 $r[0]['nick'] = api_get_nick($r[0]["url"]);
606 'id_str' => (string) $r[0]["id"],
607 'name' => $r[0]["name"],
608 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
609 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
610 'description' => $r[0]["about"],
611 'profile_image_url' => $r[0]["micro"],
612 'profile_image_url_https' => $r[0]["micro"],
613 'url' => $r[0]["url"],
614 'protected' => false,
615 'followers_count' => 0,
616 'friends_count' => 0,
618 'created_at' => api_date($r[0]["created"]),
619 'favourites_count' => 0,
621 'time_zone' => 'UTC',
622 'geo_enabled' => false,
624 'statuses_count' => 0,
626 'contributors_enabled' => false,
627 'is_translator' => false,
628 'is_translation_enabled' => false,
629 'following' => false,
630 'follow_request_sent' => false,
631 'statusnet_blocking' => false,
632 'notifications' => false,
633 'statusnet_profile_url' => $r[0]["url"],
635 'cid' => get_contact($r[0]["url"], api_user(), true),
637 'network' => $r[0]["network"],
642 throw new BadRequestException("User not found.");
646 if ($uinfo[0]['self']) {
648 if ($uinfo[0]['network'] == "") {
649 $uinfo[0]['network'] = NETWORK_DFRN;
652 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
655 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
659 /// @TODO old-lost code? (twice)
660 // Counting is deactivated by now, due to performance issues
661 // count public wall messages
662 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
663 // intval($uinfo[0]['uid'])
665 //$countitms = $r[0]['count'];
668 // Counting is deactivated by now, due to performance issues
669 //$r = q("SELECT count(*) as `count` FROM `item`
670 // WHERE `contact-id` = %d",
671 // intval($uinfo[0]['id'])
673 //$countitms = $r[0]['count'];
677 /// @TODO old-lost code? (twice)
679 // Counting is deactivated by now, due to performance issues
681 $r = q("SELECT count(*) as `count` FROM `contact`
682 WHERE `uid` = %d AND `rel` IN ( %d, %d )
683 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
684 intval($uinfo[0]['uid']),
685 intval(CONTACT_IS_SHARING),
686 intval(CONTACT_IS_FRIEND)
688 $countfriends = $r[0]['count'];
690 $r = q("SELECT count(*) as `count` FROM `contact`
691 WHERE `uid` = %d AND `rel` IN ( %d, %d )
692 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
693 intval($uinfo[0]['uid']),
694 intval(CONTACT_IS_FOLLOWER),
695 intval(CONTACT_IS_FRIEND)
697 $countfollowers = $r[0]['count'];
699 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
700 intval($uinfo[0]['uid'])
702 $starred = $r[0]['count'];
705 if (! $uinfo[0]['self']) {
715 // Add a nick if it isn't present there
716 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
717 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
720 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
722 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
725 'id' => intval($pcontact_id),
726 'id_str' => (string) intval($pcontact_id),
727 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
728 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
729 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
730 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
731 'profile_image_url' => $uinfo[0]['micro'],
732 'profile_image_url_https' => $uinfo[0]['micro'],
733 'url' => $uinfo[0]['url'],
734 'protected' => false,
735 'followers_count' => intval($countfollowers),
736 'friends_count' => intval($countfriends),
738 'created_at' => api_date($uinfo[0]['created']),
739 'favourites_count' => intval($starred),
741 'time_zone' => 'UTC',
742 'geo_enabled' => false,
744 'statuses_count' => intval($countitms),
746 'contributors_enabled' => false,
747 'is_translator' => false,
748 'is_translation_enabled' => false,
749 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
750 'follow_request_sent' => false,
751 'statusnet_blocking' => false,
752 'notifications' => false,
754 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
755 'statusnet_profile_url' => $uinfo[0]['url'],
756 'uid' => intval($uinfo[0]['uid']),
757 'cid' => intval($uinfo[0]['cid']),
758 'self' => $uinfo[0]['self'],
759 'network' => $uinfo[0]['network'],
767 * @brief return api-formatted array for item's author and owner
770 * @param array $item : item from db
771 * @return array(array:author, array:owner)
773 function api_item_get_user(App $a, $item) {
775 $status_user = api_get_user($a, $item["author-link"]);
777 $status_user["protected"] = (($item["allow_cid"] != "") OR
778 ($item["allow_gid"] != "") OR
779 ($item["deny_cid"] != "") OR
780 ($item["deny_gid"] != "") OR
783 if ($item['thr-parent'] == $item['uri']) {
784 $owner_user = api_get_user($a, $item["owner-link"]);
786 $owner_user = $status_user;
789 return (array($status_user, $owner_user));
793 * @brief walks recursively through an array with the possibility to change value and key
795 * @param array $array The array to walk through
796 * @param string $callback The callback function
798 * @return array the transformed array
800 function api_walk_recursive(array &$array, callable $callback) {
802 $new_array = array();
804 foreach ($array as $k => $v) {
806 if ($callback($v, $k)) {
807 $new_array[$k] = api_walk_recursive($v, $callback);
810 if ($callback($v, $k)) {
821 * @brief Callback function to transform the array in an array that can be transformed in a XML file
823 * @param variant $item Array item value
824 * @param string $key Array key
826 * @return boolean Should the array item be deleted?
828 function api_reformat_xml(&$item, &$key) {
829 if (is_bool($item)) {
830 $item = ($item ? "true" : "false");
833 if (substr($key, 0, 10) == "statusnet_") {
834 $key = "statusnet:".substr($key, 10);
835 } elseif (substr($key, 0, 10) == "friendica_") {
836 $key = "friendica:".substr($key, 10);
838 /// @TODO old-lost code?
840 // $key = "default:".$key;
846 * @brief Creates the XML from a JSON style array
848 * @param array $data JSON style array
849 * @param string $root_element Name of the root element
851 * @return string The XML data
853 function api_create_xml($data, $root_element) {
854 $childname = key($data);
855 $data2 = array_pop($data);
858 $namespaces = array("" => "http://api.twitter.com",
859 "statusnet" => "http://status.net/schema/api/1/",
860 "friendica" => "http://friendi.ca/schema/api/1/",
861 "georss" => "http://www.georss.org/georss");
863 /// @todo Auto detection of needed namespaces
864 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
865 $namespaces = array();
868 if (is_array($data2)) {
869 api_walk_recursive($data2, "api_reformat_xml");
876 foreach ($data2 AS $item) {
877 $data4[$i++.":".$childname] = $item;
883 $data3 = array($root_element => $data2);
885 $ret = xml::from_array($data3, $xml, false, $namespaces);
890 * @brief Formats the data according to the data type
892 * @param string $root_element Name of the root element
893 * @param string $type Return type (atom, rss, xml, json)
894 * @param array $data JSON style array
896 * @return (string|object) XML data or JSON data
898 function api_format_data($root_element, $type, $data) {
906 $ret = api_create_xml($data, $root_element);
921 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
922 * returns a 401 status code and an error message if not.
923 * http://developer.twitter.com/doc/get/account/verify_credentials
925 function api_account_verify_credentials($type) {
929 if (api_user() === false) {
930 throw new ForbiddenException();
933 unset($_REQUEST["user_id"]);
934 unset($_GET["user_id"]);
936 unset($_REQUEST["screen_name"]);
937 unset($_GET["screen_name"]);
939 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
941 $user_info = api_get_user($a);
943 // "verified" isn't used here in the standard
944 unset($user_info["verified"]);
946 // - Adding last status
948 $user_info["status"] = api_status_show("raw");
949 if (!count($user_info["status"])) {
950 unset($user_info["status"]);
952 unset($user_info["status"]["user"]);
956 // "uid" and "self" are only needed for some internal stuff, so remove it from here
957 unset($user_info["uid"]);
958 unset($user_info["self"]);
960 return api_format_data("user", $type, array('user' => $user_info));
964 /// @TODO move to top of file or somwhere better
965 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
968 * get data from $_POST or $_GET
970 function requestdata($k) {
980 /*Waitman Gobble Mod*/
981 function api_statuses_mediap($type) {
985 if (api_user() === false) {
986 logger('api_statuses_update: no user');
987 throw new ForbiddenException();
989 $user_info = api_get_user($a);
991 $_REQUEST['type'] = 'wall';
992 $_REQUEST['profile_uid'] = api_user();
993 $_REQUEST['api_source'] = true;
994 $txt = requestdata('status');
995 /// @TODO old-lost code?
996 //$txt = urldecode(requestdata('status'));
998 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1000 $txt = html2bb_video($txt);
1001 $config = HTMLPurifier_Config::createDefault();
1002 $config->set('Cache.DefinitionImpl', null);
1003 $purifier = new HTMLPurifier($config);
1004 $txt = $purifier->purify($txt);
1006 $txt = html2bbcode($txt);
1008 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1010 // tell wall_upload function to return img info instead of echo
1011 $_REQUEST['hush'] = 'yeah';
1012 $bebop = wall_upload_post($a);
1014 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1015 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1018 // this should output the last post (the one we just posted).
1019 return api_status_show($type);
1022 /// @TODO move this to top of file or somewhere better!
1023 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1025 function api_statuses_update($type) {
1029 if (api_user() === false) {
1030 logger('api_statuses_update: no user');
1031 throw new ForbiddenException();
1034 $user_info = api_get_user($a);
1036 // convert $_POST array items to the form we use for web posts.
1038 // logger('api_post: ' . print_r($_POST,true));
1040 if (requestdata('htmlstatus')) {
1041 $txt = requestdata('htmlstatus');
1042 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1043 $txt = html2bb_video($txt);
1045 $config = HTMLPurifier_Config::createDefault();
1046 $config->set('Cache.DefinitionImpl', null);
1048 $purifier = new HTMLPurifier($config);
1049 $txt = $purifier->purify($txt);
1051 $_REQUEST['body'] = html2bbcode($txt);
1055 $_REQUEST['body'] = requestdata('status');
1058 $_REQUEST['title'] = requestdata('title');
1060 $parent = requestdata('in_reply_to_status_id');
1062 // Twidere sends "-1" if it is no reply ...
1063 if ($parent == -1) {
1067 if (ctype_digit($parent)) {
1068 $_REQUEST['parent'] = $parent;
1070 $_REQUEST['parent_uri'] = $parent;
1073 if (requestdata('lat') && requestdata('long')) {
1074 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1076 $_REQUEST['profile_uid'] = api_user();
1079 $_REQUEST['type'] = 'net-comment';
1081 // Check for throttling (maximum posts per day, week and month)
1082 $throttle_day = get_config('system','throttle_limit_day');
1083 if ($throttle_day > 0) {
1084 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1086 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1087 AND `created` > '%s' AND `id` = `parent`",
1088 intval(api_user()), dbesc($datefrom));
1090 if (dbm::is_result($r)) {
1091 $posts_day = $r[0]["posts_day"];
1096 if ($posts_day > $throttle_day) {
1097 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1098 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1099 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1103 $throttle_week = get_config('system','throttle_limit_week');
1104 if ($throttle_week > 0) {
1105 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1107 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1108 AND `created` > '%s' AND `id` = `parent`",
1109 intval(api_user()), dbesc($datefrom));
1111 if (dbm::is_result($r)) {
1112 $posts_week = $r[0]["posts_week"];
1117 if ($posts_week > $throttle_week) {
1118 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1119 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1120 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1124 $throttle_month = get_config('system','throttle_limit_month');
1125 if ($throttle_month > 0) {
1126 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1128 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1129 AND `created` > '%s' AND `id` = `parent`",
1130 intval(api_user()), dbesc($datefrom));
1132 if (dbm::is_result($r)) {
1133 $posts_month = $r[0]["posts_month"];
1138 if ($posts_month > $throttle_month) {
1139 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1140 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1141 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1145 $_REQUEST['type'] = 'wall';
1148 if (x($_FILES, 'media')) {
1149 // upload the image if we have one
1150 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1151 $media = wall_upload_post($a);
1152 if (strlen($media) > 0) {
1153 $_REQUEST['body'] .= "\n\n" . $media;
1157 // To-Do: Multiple IDs
1158 if (requestdata('media_ids')) {
1159 $r = q("SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1160 intval(requestdata('media_ids')), api_user());
1161 if (dbm::is_result($r)) {
1162 $phototypes = Photo::supportedTypes();
1163 $ext = $phototypes[$r[0]['type']];
1164 $_REQUEST['body'] .= "\n\n" . '[url=' . App::get_baseurl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1165 $_REQUEST['body'] .= '[img]' . App::get_baseurl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1169 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1171 $_REQUEST['api_source'] = true;
1173 if (!x($_REQUEST, "source")) {
1174 $_REQUEST["source"] = api_source();
1177 // call out normal post function
1180 // this should output the last post (the one we just posted).
1181 return api_status_show($type);
1184 /// @TODO move to top of file or somwhere better
1185 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1186 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1188 function api_media_upload($type) {
1192 if (api_user() === false) {
1194 throw new ForbiddenException();
1197 $user_info = api_get_user($a);
1199 if (!x($_FILES, 'media')) {
1201 throw new BadRequestException("No media.");
1204 $media = wall_upload_post($a, false);
1207 throw new InternalServerErrorException();
1210 $returndata = array();
1211 $returndata["media_id"] = $media["id"];
1212 $returndata["media_id_string"] = (string)$media["id"];
1213 $returndata["size"] = $media["size"];
1214 $returndata["image"] = array("w" => $media["width"],
1215 "h" => $media["height"],
1216 "image_type" => $media["type"]);
1218 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1220 return array("media" => $returndata);
1223 /// @TODO move to top of file or somwhere better
1224 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1226 function api_status_show($type) {
1230 $user_info = api_get_user($a);
1232 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1234 if ($type == "raw") {
1235 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1240 // get last public wall message
1241 $lastwall = q("SELECT `item`.*
1243 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1244 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1245 AND `item`.`type` != 'activity' $privacy_sql
1246 ORDER BY `item`.`id` DESC
1248 intval($user_info['cid']),
1250 dbesc($user_info['url']),
1251 dbesc(normalise_link($user_info['url'])),
1252 dbesc($user_info['url']),
1253 dbesc(normalise_link($user_info['url']))
1256 if (dbm::is_result($lastwall)) {
1257 $lastwall = $lastwall[0];
1259 $in_reply_to = api_in_reply_to($lastwall);
1261 $converted = api_convert_item($lastwall);
1263 if ($type == "xml") {
1264 $geo = "georss:point";
1269 $status_info = array(
1270 'created_at' => api_date($lastwall['created']),
1271 'id' => intval($lastwall['id']),
1272 'id_str' => (string) $lastwall['id'],
1273 'text' => $converted["text"],
1274 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1275 'truncated' => false,
1276 'in_reply_to_status_id' => $in_reply_to['status_id'],
1277 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1278 'in_reply_to_user_id' => $in_reply_to['user_id'],
1279 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1280 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1281 'user' => $user_info,
1283 'coordinates' => "",
1285 'contributors' => "",
1286 'is_quote_status' => false,
1287 'retweet_count' => 0,
1288 'favorite_count' => 0,
1289 'favorited' => $lastwall['starred'] ? true : false,
1290 'retweeted' => false,
1291 'possibly_sensitive' => false,
1293 'statusnet_html' => $converted["html"],
1294 'statusnet_conversation_id' => $lastwall['parent'],
1297 if (count($converted["attachments"]) > 0) {
1298 $status_info["attachments"] = $converted["attachments"];
1301 if (count($converted["entities"]) > 0) {
1302 $status_info["entities"] = $converted["entities"];
1305 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web')) {
1306 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1307 } elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1308 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1311 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1312 unset($status_info["user"]["uid"]);
1313 unset($status_info["user"]["self"]);
1316 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1318 if ($type == "raw") {
1319 return $status_info;
1322 return api_format_data("statuses", $type, array('status' => $status_info));
1327 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1328 * The author's most recent status will be returned inline.
1329 * http://developer.twitter.com/doc/get/users/show
1331 function api_users_show($type) {
1335 $user_info = api_get_user($a);
1336 $lastwall = q("SELECT `item`.*
1338 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1339 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1340 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1341 AND `type`!='activity'
1342 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1346 dbesc(ACTIVITY_POST),
1347 intval($user_info['cid']),
1348 dbesc($user_info['url']),
1349 dbesc(normalise_link($user_info['url'])),
1350 dbesc($user_info['url']),
1351 dbesc(normalise_link($user_info['url']))
1354 if (dbm::is_result($lastwall)) {
1355 $lastwall = $lastwall[0];
1357 $in_reply_to = api_in_reply_to($lastwall);
1359 $converted = api_convert_item($lastwall);
1361 if ($type == "xml") {
1362 $geo = "georss:point";
1367 $user_info['status'] = array(
1368 'text' => $converted["text"],
1369 'truncated' => false,
1370 'created_at' => api_date($lastwall['created']),
1371 'in_reply_to_status_id' => $in_reply_to['status_id'],
1372 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1373 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1374 'id' => intval($lastwall['contact-id']),
1375 'id_str' => (string) $lastwall['contact-id'],
1376 'in_reply_to_user_id' => $in_reply_to['user_id'],
1377 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1378 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1380 'favorited' => $lastwall['starred'] ? true : false,
1381 'statusnet_html' => $converted["html"],
1382 'statusnet_conversation_id' => $lastwall['parent'],
1385 if (count($converted["attachments"]) > 0) {
1386 $user_info["status"]["attachments"] = $converted["attachments"];
1389 if (count($converted["entities"]) > 0) {
1390 $user_info["status"]["entities"] = $converted["entities"];
1393 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web')) {
1394 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1397 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1398 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1403 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1404 unset($user_info["uid"]);
1405 unset($user_info["self"]);
1407 return api_format_data("user", $type, array('user' => $user_info));
1411 /// @TODO move to top of file or somewhere better
1412 api_register_func('api/users/show','api_users_show');
1413 api_register_func('api/externalprofile/show','api_users_show');
1415 function api_users_search($type) {
1419 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1421 $userlist = array();
1423 if (x($_GET, 'q')) {
1424 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1426 if (!dbm::is_result($r)) {
1427 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1430 if (dbm::is_result($r)) {
1432 foreach ($r AS $user) {
1433 $user_info = api_get_user($a, $user["id"], "json");
1435 if ($type == "xml") {
1436 $userlist[$k++.":user"] = $user_info;
1438 $userlist[] = $user_info;
1441 $userlist = array("users" => $userlist);
1443 throw new BadRequestException("User not found.");
1446 throw new BadRequestException("User not found.");
1448 return api_format_data("users", $type, $userlist);
1451 /// @TODO move to top of file or somewhere better
1452 api_register_func('api/users/search','api_users_search');
1456 * http://developer.twitter.com/doc/get/statuses/home_timeline
1458 * TODO: Optional parameters
1459 * TODO: Add reply info
1461 function api_statuses_home_timeline($type) {
1465 if (api_user() === false) {
1466 throw new ForbiddenException();
1469 unset($_REQUEST["user_id"]);
1470 unset($_GET["user_id"]);
1472 unset($_REQUEST["screen_name"]);
1473 unset($_GET["screen_name"]);
1475 $user_info = api_get_user($a);
1476 // get last newtork messages
1479 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1480 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1484 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1485 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1486 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1487 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1488 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1490 $start = $page * $count;
1494 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1496 if ($exclude_replies > 0) {
1497 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1499 if ($conversation_id > 0) {
1500 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1503 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1504 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1505 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1506 `contact`.`id` AS `cid`
1508 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1509 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1510 WHERE `item`.`uid` = %d AND `verb` = '%s'
1511 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1514 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1516 dbesc(ACTIVITY_POST),
1518 intval($start), intval($count)
1521 $ret = api_format_items($r, $user_info, false, $type);
1523 // Set all posts from the query above to seen
1525 foreach ($r AS $item) {
1526 $idarray[] = intval($item["id"]);
1529 $idlist = implode(",", $idarray);
1531 if ($idlist != "") {
1532 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1535 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1539 $data = array('status' => $ret);
1543 $data = api_rss_extra($a, $data, $user_info);
1547 return api_format_data("statuses", $type, $data);
1550 /// @TODO move to top of file or somewhere better
1551 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1552 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1554 function api_statuses_public_timeline($type) {
1558 if (api_user() === false) {
1559 throw new ForbiddenException();
1562 $user_info = api_get_user($a);
1563 // get last newtork messages
1566 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1567 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1571 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1572 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1573 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1574 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1575 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1577 $start = $page * $count;
1580 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1582 if ($exclude_replies > 0) {
1583 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1585 if ($conversation_id > 0) {
1586 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1589 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1590 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1591 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1592 `contact`.`id` AS `cid`,
1593 `user`.`nickname`, `user`.`hidewall`
1595 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1596 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1597 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1598 AND NOT `user`.`hidewall`
1599 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1600 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1601 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1602 AND NOT `item`.`private` AND `item`.`wall`
1605 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1606 dbesc(ACTIVITY_POST),
1611 $ret = api_format_items($r, $user_info, false, $type);
1613 $data = array('status' => $ret);
1617 $data = api_rss_extra($a, $data, $user_info);
1621 return api_format_data("statuses", $type, $data);
1624 /// @TODO move to top of file or somewhere better
1625 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1628 * @TODO nothing to say?
1630 function api_statuses_show($type) {
1634 if (api_user() === false) {
1635 throw new ForbiddenException();
1638 $user_info = api_get_user($a);
1641 $id = intval($a->argv[3]);
1644 $id = intval($_REQUEST["id"]);
1649 $id = intval($a->argv[4]);
1652 logger('API: api_statuses_show: ' . $id);
1654 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1657 if ($conversation) {
1658 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1660 $sql_extra .= " AND `item`.`id` = %d";
1663 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1664 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1665 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1666 `contact`.`id` AS `cid`
1668 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1669 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1670 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1671 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1674 dbesc(ACTIVITY_POST),
1678 /// @TODO How about copying this to above methods which don't check $r ?
1679 if (!dbm::is_result($r)) {
1680 throw new BadRequestException("There is no status with this id.");
1683 $ret = api_format_items($r,$user_info, false, $type);
1685 if ($conversation) {
1686 $data = array('status' => $ret);
1687 return api_format_data("statuses", $type, $data);
1689 $data = array('status' => $ret[0]);
1690 return api_format_data("status", $type, $data);
1694 /// @TODO move to top of file or somewhere better
1695 api_register_func('api/statuses/show','api_statuses_show', true);
1698 * @TODO nothing to say?
1700 function api_conversation_show($type) {
1704 if (api_user() === false) {
1705 throw new ForbiddenException();
1708 $user_info = api_get_user($a);
1711 $id = intval($a->argv[3]);
1712 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1713 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1717 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1718 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1720 $start = $page*$count;
1723 $id = intval($_REQUEST["id"]);
1728 $id = intval($a->argv[4]);
1731 logger('API: api_conversation_show: '.$id);
1733 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1734 if (dbm::is_result($r)) {
1735 $id = $r[0]["parent"];
1741 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1744 // Not sure why this query was so complicated. We should keep it here for a while,
1745 // just to make sure that we really don't need it.
1746 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1747 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1749 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1750 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1751 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1752 `contact`.`id` AS `cid`
1754 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1755 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1756 WHERE `item`.`parent` = %d AND `item`.`visible`
1757 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1758 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1759 AND `item`.`id`>%d $sql_extra
1760 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1761 intval($id), intval(api_user()),
1762 dbesc(ACTIVITY_POST),
1764 intval($start), intval($count)
1767 if (!dbm::is_result($r)) {
1768 throw new BadRequestException("There is no status with this id.");
1771 $ret = api_format_items($r, $user_info, false, $type);
1773 $data = array('status' => $ret);
1774 return api_format_data("statuses", $type, $data);
1777 /// @TODO move to top of file or somewhere better
1778 api_register_func('api/conversation/show','api_conversation_show', true);
1779 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1782 * @TODO nothing to say?
1784 function api_statuses_repeat($type) {
1789 if (api_user() === false) {
1790 throw new ForbiddenException();
1793 $user_info = api_get_user($a);
1796 $id = intval($a->argv[3]);
1799 $id = intval($_REQUEST["id"]);
1804 $id = intval($a->argv[4]);
1807 logger('API: api_statuses_repeat: '.$id);
1809 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1810 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1811 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1812 `contact`.`id` AS `cid`
1814 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1815 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1816 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1817 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1818 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1820 AND `item`.`id`=%d",
1824 /// @TODO other style than above functions!
1825 if (dbm::is_result($r) && $r[0]['body'] != "") {
1826 if (strpos($r[0]['body'], "[/share]") !== false) {
1827 $pos = strpos($r[0]['body'], "[share");
1828 $post = substr($r[0]['body'], $pos);
1830 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1832 $post .= $r[0]['body'];
1833 $post .= "[/share]";
1835 $_REQUEST['body'] = $post;
1836 $_REQUEST['profile_uid'] = api_user();
1837 $_REQUEST['type'] = 'wall';
1838 $_REQUEST['api_source'] = true;
1840 if (!x($_REQUEST, "source")) {
1841 $_REQUEST["source"] = api_source();
1846 throw new ForbiddenException();
1849 // this should output the last post (the one we just posted).
1851 return api_status_show($type);
1854 /// @TODO move to top of file or somewhere better
1855 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1858 * @TODO nothing to say?
1860 function api_statuses_destroy($type) {
1864 if (api_user() === false) {
1865 throw new ForbiddenException();
1868 $user_info = api_get_user($a);
1871 $id = intval($a->argv[3]);
1874 $id = intval($_REQUEST["id"]);
1879 $id = intval($a->argv[4]);
1882 logger('API: api_statuses_destroy: '.$id);
1884 $ret = api_statuses_show($type);
1886 drop_item($id, false);
1891 /// @TODO move to top of file or somewhere better
1892 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1895 * @TODO Nothing more than an URL to say?
1896 * http://developer.twitter.com/doc/get/statuses/mentions
1898 function api_statuses_mentions($type) {
1902 if (api_user() === false) {
1903 throw new ForbiddenException();
1906 unset($_REQUEST["user_id"]);
1907 unset($_GET["user_id"]);
1909 unset($_REQUEST["screen_name"]);
1910 unset($_GET["screen_name"]);
1912 $user_info = api_get_user($a);
1913 // get last newtork messages
1917 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1918 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1922 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1923 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1924 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1926 $start = $page * $count;
1928 // Ugly code - should be changed
1929 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1930 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1931 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1932 $myurl = str_replace('www.', '', $myurl);
1933 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1936 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1939 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1940 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1941 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1942 `contact`.`id` AS `cid`
1943 FROM `item` FORCE INDEX (`uid_id`)
1944 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1945 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1946 WHERE `item`.`uid` = %d AND `verb` = '%s'
1947 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1948 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1949 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1952 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1954 dbesc(ACTIVITY_POST),
1955 dbesc(protect_sprintf($myurl)),
1956 dbesc(protect_sprintf($myurl)),
1959 intval($start), intval($count)
1962 $ret = api_format_items($r, $user_info, false, $type);
1964 $data = array('status' => $ret);
1968 $data = api_rss_extra($a, $data, $user_info);
1972 return api_format_data("statuses", $type, $data);
1975 /// @TODO move to top of file or somewhere better
1976 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1977 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1979 function api_statuses_user_timeline($type) {
1983 if (api_user() === false) {
1984 throw new ForbiddenException();
1987 $user_info = api_get_user($a);
1988 // get last network messages
1990 logger("api_statuses_user_timeline: api_user: ". api_user() .
1991 "\nuser_info: ".print_r($user_info, true) .
1992 "\n_REQUEST: ".print_r($_REQUEST, true),
1996 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1997 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2001 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2002 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2003 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2004 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2006 $start = $page * $count;
2009 if ($user_info['self'] == 1) {
2010 $sql_extra .= " AND `item`.`wall` = 1 ";
2013 if ($exclude_replies > 0) {
2014 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2016 if ($conversation_id > 0) {
2017 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2020 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2021 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2022 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2023 `contact`.`id` AS `cid`
2024 FROM `item` FORCE INDEX (`uid_contactid_id`)
2025 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2026 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2027 WHERE `item`.`uid` = %d AND `verb` = '%s'
2028 AND `item`.`contact-id` = %d
2029 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2032 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2034 dbesc(ACTIVITY_POST),
2035 intval($user_info['cid']),
2037 intval($start), intval($count)
2040 $ret = api_format_items($r, $user_info, true, $type);
2042 $data = array('status' => $ret);
2046 $data = api_rss_extra($a, $data, $user_info);
2050 return api_format_data("statuses", $type, $data);
2053 /// @TODO move to top of file or somwhere better
2054 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2057 * Star/unstar an item
2058 * param: id : id of the item
2060 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2062 function api_favorites_create_destroy($type) {
2066 if (api_user() === false) {
2067 throw new ForbiddenException();
2070 // for versioned api.
2071 /// @TODO We need a better global soluton
2072 $action_argv_id = 2;
2073 if ($a->argv[1] == "1.1") {
2074 $action_argv_id = 3;
2077 if ($a->argc <= $action_argv_id) {
2078 throw new BadRequestException("Invalid request.");
2080 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2081 if ($a->argc == $action_argv_id + 2) {
2082 $itemid = intval($a->argv[$action_argv_id + 1]);
2084 /// @TODO use x() to check if _REQUEST contains 'id'
2085 $itemid = intval($_REQUEST['id']);
2088 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2089 $itemid, api_user());
2091 if (!dbm::is_result($item) || count($item) == 0) {
2092 throw new BadRequestException("Invalid item.");
2097 $item[0]['starred'] = 1;
2100 $item[0]['starred'] = 0;
2103 throw new BadRequestException("Invalid action ".$action);
2106 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2107 $item[0]['starred'], $itemid, api_user());
2109 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2110 $item[0]['starred'], $itemid, api_user());
2113 throw new InternalServerErrorException("DB error");
2117 $user_info = api_get_user($a);
2118 $rets = api_format_items($item, $user_info, false, $type);
2121 $data = array('status' => $ret);
2125 $data = api_rss_extra($a, $data, $user_info);
2128 return api_format_data("status", $type, $data);
2131 /// @TODO move to top of file or somwhere better
2132 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2133 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2135 function api_favorites($type) {
2140 if (api_user() === false) {
2141 throw new ForbiddenException();
2144 $called_api = array();
2146 $user_info = api_get_user($a);
2148 // in friendica starred item are private
2149 // return favorites only for self
2150 logger('api_favorites: self:' . $user_info['self']);
2152 if ($user_info['self'] == 0) {
2158 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2159 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2160 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2161 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2166 $start = $page*$count;
2169 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2172 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2173 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2174 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2175 `contact`.`id` AS `cid`
2176 FROM `item`, `contact`
2177 WHERE `item`.`uid` = %d
2178 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
2179 AND `item`.`starred` = 1
2180 AND `contact`.`id` = `item`.`contact-id`
2181 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2184 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2187 intval($start), intval($count)
2190 $ret = api_format_items($r,$user_info, false, $type);
2194 $data = array('status' => $ret);
2198 $data = api_rss_extra($a, $data, $user_info);
2201 return api_format_data("statuses", $type, $data);
2204 /// @TODO move to top of file or somwhere better
2205 api_register_func('api/favorites','api_favorites', true);
2207 function api_format_messages($item, $recipient, $sender) {
2208 // standard meta information
2210 'id' => $item['id'],
2211 'sender_id' => $sender['id'] ,
2213 'recipient_id' => $recipient['id'],
2214 'created_at' => api_date($item['created']),
2215 'sender_screen_name' => $sender['screen_name'],
2216 'recipient_screen_name' => $recipient['screen_name'],
2217 'sender' => $sender,
2218 'recipient' => $recipient,
2220 'friendica_seen' => $item['seen'],
2221 'friendica_parent_uri' => $item['parent-uri'],
2224 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2225 unset($ret["sender"]["uid"]);
2226 unset($ret["sender"]["self"]);
2227 unset($ret["recipient"]["uid"]);
2228 unset($ret["recipient"]["self"]);
2230 //don't send title to regular StatusNET requests to avoid confusing these apps
2231 if (x($_GET, 'getText')) {
2232 $ret['title'] = $item['title'] ;
2233 if ($_GET['getText'] == 'html') {
2234 $ret['text'] = bbcode($item['body'], false, false);
2235 } elseif ($_GET['getText'] == 'plain') {
2236 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2237 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2240 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2242 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2243 unset($ret['sender']);
2244 unset($ret['recipient']);
2250 function api_convert_item($item) {
2251 $body = $item['body'];
2252 $attachments = api_get_attachments($body);
2254 // Workaround for ostatus messages where the title is identically to the body
2255 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2256 $statusbody = trim(html2plain($html, 0));
2258 // handle data: images
2259 $statusbody = api_format_items_embeded_images($item,$statusbody);
2261 $statustitle = trim($item['title']);
2263 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false)) {
2264 $statustext = trim($statusbody);
2266 $statustext = trim($statustitle."\n\n".$statusbody);
2269 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000)) {
2270 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2273 $statushtml = trim(bbcode($body, false, false));
2275 $search = array("<br>", "<blockquote>", "</blockquote>",
2276 "<h1>", "</h1>", "<h2>", "</h2>",
2277 "<h3>", "</h3>", "<h4>", "</h4>",
2278 "<h5>", "</h5>", "<h6>", "</h6>");
2279 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2280 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2281 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2282 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2283 $statushtml = str_replace($search, $replace, $statushtml);
2285 if ($item['title'] != "") {
2286 $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
2289 $entities = api_get_entitities($statustext, $body);
2292 "text" => $statustext,
2293 "html" => $statushtml,
2294 "attachments" => $attachments,
2295 "entities" => $entities
2299 function api_get_attachments(&$body) {
2302 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2304 $URLSearchString = "^\[\]";
2305 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2311 $attachments = array();
2313 foreach ($images[1] AS $image) {
2314 $imagedata = get_photo_info($image);
2317 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2321 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2322 foreach ($images[0] AS $orig) {
2323 $body = str_replace($orig, "", $body);
2327 return $attachments;
2330 function api_get_entitities(&$text, $bbcode) {
2333 * Links at the first character of the post
2338 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2340 if ($include_entities != "true") {
2342 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2344 foreach ($images[1] AS $image) {
2345 $replace = proxy_url($image);
2346 $text = str_replace($image, $replace, $text);
2351 $bbcode = bb_CleanPictureLinks($bbcode);
2353 // Change pure links in text to bbcode uris
2354 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2356 $entities = array();
2357 $entities["hashtags"] = array();
2358 $entities["symbols"] = array();
2359 $entities["urls"] = array();
2360 $entities["user_mentions"] = array();
2362 $URLSearchString = "^\[\]";
2364 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2366 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2367 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2368 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2370 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2371 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2372 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2374 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2375 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2376 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2378 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2380 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2381 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2383 $ordered_urls = array();
2384 foreach ($urls[1] AS $id => $url) {
2385 //$start = strpos($text, $url, $offset);
2386 $start = iconv_strpos($text, $url, 0, "UTF-8");
2387 if (!($start === false)) {
2388 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2392 ksort($ordered_urls);
2395 //foreach ($urls[1] AS $id=>$url) {
2396 foreach ($ordered_urls AS $url) {
2397 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2398 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2399 $display_url = $url["title"];
2401 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2402 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2404 if (strlen($display_url) > 26)
2405 $display_url = substr($display_url, 0, 25)."…";
2408 //$start = strpos($text, $url, $offset);
2409 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2410 if (!($start === false)) {
2411 $entities["urls"][] = array("url" => $url["url"],
2412 "expanded_url" => $url["url"],
2413 "display_url" => $display_url,
2414 "indices" => array($start, $start+strlen($url["url"])));
2415 $offset = $start + 1;
2419 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2420 $ordered_images = array();
2421 foreach ($images[1] AS $image) {
2422 //$start = strpos($text, $url, $offset);
2423 $start = iconv_strpos($text, $image, 0, "UTF-8");
2424 if (!($start === false))
2425 $ordered_images[$start] = $image;
2427 //$entities["media"] = array();
2430 foreach ($ordered_images AS $url) {
2431 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2432 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2434 if (strlen($display_url) > 26)
2435 $display_url = substr($display_url, 0, 25)."…";
2437 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2438 if (!($start === false)) {
2439 $image = get_photo_info($url);
2441 // If image cache is activated, then use the following sizes:
2442 // thumb (150), small (340), medium (600) and large (1024)
2443 if (!get_config("system", "proxy_disabled")) {
2444 $media_url = proxy_url($url);
2447 $scale = scale_image($image[0], $image[1], 150);
2448 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2450 if (($image[0] > 150) OR ($image[1] > 150)) {
2451 $scale = scale_image($image[0], $image[1], 340);
2452 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2455 $scale = scale_image($image[0], $image[1], 600);
2456 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2458 if (($image[0] > 600) OR ($image[1] > 600)) {
2459 $scale = scale_image($image[0], $image[1], 1024);
2460 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2464 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2467 $entities["media"][] = array(
2469 "id_str" => (string)$start+1,
2470 "indices" => array($start, $start+strlen($url)),
2471 "media_url" => normalise_link($media_url),
2472 "media_url_https" => $media_url,
2474 "display_url" => $display_url,
2475 "expanded_url" => $url,
2479 $offset = $start + 1;
2485 function api_format_items_embeded_images(&$item, $text) {
2486 $text = preg_replace_callback(
2487 "|data:image/([^;]+)[^=]+=*|m",
2488 function($match) use ($item) {
2489 return App::get_baseurl()."/display/".$item['guid'];
2497 * @brief return <a href='url'>name</a> as array
2499 * @param string $txt
2504 function api_contactlink_to_array($txt) {
2506 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2507 if ($r && count($match)==3) {
2509 'name' => $match[2],
2523 * @brief return likes, dislikes and attend status for item
2525 * @param array $item
2527 * likes => int count
2528 * dislikes => int count
2530 function api_format_items_activities(&$item, $type = "json") {
2534 $activities = array(
2536 'dislike' => array(),
2537 'attendyes' => array(),
2538 'attendno' => array(),
2539 'attendmaybe' => array(),
2542 $items = q('SELECT * FROM item
2543 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2544 intval($item['uid']),
2545 dbesc($item['uri']));
2547 foreach ($items as $i) {
2548 // not used as result should be structured like other user data
2549 //builtin_activity_puller($i, $activities);
2551 // get user data and add it to the array of the activity
2552 $user = api_get_user($a, $i['author-link']);
2553 switch ($i['verb']) {
2555 $activities['like'][] = $user;
2557 case ACTIVITY_DISLIKE:
2558 $activities['dislike'][] = $user;
2560 case ACTIVITY_ATTEND:
2561 $activities['attendyes'][] = $user;
2563 case ACTIVITY_ATTENDNO:
2564 $activities['attendno'][] = $user;
2566 case ACTIVITY_ATTENDMAYBE:
2567 $activities['attendmaybe'][] = $user;
2574 if ($type == "xml") {
2575 $xml_activities = array();
2576 foreach ($activities as $k => $v) {
2577 // change xml element from "like" to "friendica:like"
2578 $xml_activities["friendica:".$k] = $v;
2579 // add user data into xml output
2581 foreach ($v as $user)
2582 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2584 $activities = $xml_activities;
2593 * @brief return data from profiles
2595 * @param array $profile array containing data from db table 'profile'
2596 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2599 function api_format_items_profiles(&$profile = null, $type = "json") {
2600 if ($profile != null) {
2601 $profile = array('profile_id' => $profile['id'],
2602 'profile_name' => $profile['profile-name'],
2603 'is_default' => $profile['is-default'] ? true : false,
2604 'hide_friends'=> $profile['hide-friends'] ? true : false,
2605 'profile_photo' => $profile['photo'],
2606 'profile_thumb' => $profile['thumb'],
2607 'publish' => $profile['publish'] ? true : false,
2608 'net_publish' => $profile['net-publish'] ? true : false,
2609 'description' => $profile['pdesc'],
2610 'date_of_birth' => $profile['dob'],
2611 'address' => $profile['address'],
2612 'city' => $profile['locality'],
2613 'region' => $profile['region'],
2614 'postal_code' => $profile['postal-code'],
2615 'country' => $profile['country-name'],
2616 'hometown' => $profile['hometown'],
2617 'gender' => $profile['gender'],
2618 'marital' => $profile['marital'],
2619 'marital_with' => $profile['with'],
2620 'marital_since' => $profile['howlong'],
2621 'sexual' => $profile['sexual'],
2622 'politic' => $profile['politic'],
2623 'religion' => $profile['religion'],
2624 'public_keywords' => $profile['pub_keywords'],
2625 'private_keywords' => $profile['prv_keywords'],
2626 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2627 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2628 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2629 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2630 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2631 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2632 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2633 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2634 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2635 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2636 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2637 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2638 'homepage' => $profile['homepage'],
2645 * @brief format items to be returned by api
2647 * @param array $r array of items
2648 * @param array $user_info
2649 * @param bool $filter_user filter items by $user_info
2651 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2657 foreach ($r as $item) {
2659 localize_item($item);
2660 list($status_user, $owner_user) = api_item_get_user($a, $item);
2662 // Look if the posts are matching if they should be filtered by user id
2663 if ($filter_user AND ($status_user["id"] != $user_info["id"])) {
2667 $in_reply_to = api_in_reply_to($item);
2669 $converted = api_convert_item($item);
2671 if ($type == "xml") {
2672 $geo = "georss:point";
2678 'text' => $converted["text"],
2679 'truncated' => False,
2680 'created_at'=> api_date($item['created']),
2681 'in_reply_to_status_id' => $in_reply_to['status_id'],
2682 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2683 'source' => (($item['app']) ? $item['app'] : 'web'),
2684 'id' => intval($item['id']),
2685 'id_str' => (string) intval($item['id']),
2686 'in_reply_to_user_id' => $in_reply_to['user_id'],
2687 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2688 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2690 'favorited' => $item['starred'] ? true : false,
2691 'user' => $status_user ,
2692 'friendica_owner' => $owner_user,
2693 //'entities' => NULL,
2694 'statusnet_html' => $converted["html"],
2695 'statusnet_conversation_id' => $item['parent'],
2696 'friendica_activities' => api_format_items_activities($item, $type),
2699 if (count($converted["attachments"]) > 0) {
2700 $status["attachments"] = $converted["attachments"];
2703 if (count($converted["entities"]) > 0) {
2704 $status["entities"] = $converted["entities"];
2707 if (($item['item_network'] != "") AND ($status["source"] == 'web')) {
2708 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2709 } elseif (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2710 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2714 // Retweets are only valid for top postings
2715 // It doesn't work reliable with the link if its a feed
2716 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2718 // $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2721 if ($item["id"] == $item["parent"]) {
2722 $retweeted_item = api_share_as_retweet($item);
2723 if ($retweeted_item !== false) {
2724 $retweeted_status = $status;
2726 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2727 } catch( BadRequestException $e ) {
2728 // user not found. should be found?
2729 /// @todo check if the user should be always found
2730 $retweeted_status["user"] = array();
2733 $rt_converted = api_convert_item($retweeted_item);
2735 $retweeted_status['text'] = $rt_converted["text"];
2736 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2737 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2738 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2739 $status['retweeted_status'] = $retweeted_status;
2743 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2744 unset($status["user"]["uid"]);
2745 unset($status["user"]["self"]);
2747 if ($item["coord"] != "") {
2748 $coords = explode(' ',$item["coord"]);
2749 if (count($coords) == 2) {
2750 if ($type == "json")
2751 $status["geo"] = array('type' => 'Point',
2752 'coordinates' => array((float) $coords[0],
2753 (float) $coords[1]));
2754 else // Not sure if this is the official format - if someone founds a documentation we can check
2755 $status["georss:point"] = $item["coord"];
2763 function api_account_rate_limit_status($type) {
2765 if ($type == "xml") {
2767 'remaining-hits' => '150',
2768 '@attributes' => array("type" => "integer"),
2769 'hourly-limit' => '150',
2770 '@attributes2' => array("type" => "integer"),
2771 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2772 '@attributes3' => array("type" => "datetime"),
2773 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2774 '@attributes4' => array("type" => "integer"),
2778 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2779 'remaining_hits' => '150',
2780 'hourly_limit' => '150',
2781 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2785 return api_format_data('hash', $type, array('hash' => $hash));
2788 /// @TODO move to top of file or somwhere better
2789 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2791 function api_help_test($type) {
2792 if ($type == 'xml') {
2798 return api_format_data('ok', $type, array("ok" => $ok));
2801 /// @TODO move to top of file or somwhere better
2802 api_register_func('api/help/test','api_help_test', false);
2804 function api_lists($type) {
2806 /// @TODO $ret is not filled here?
2807 return api_format_data('lists', $type, array("lists_list" => $ret));
2810 /// @TODO move to top of file or somwhere better
2811 api_register_func('api/lists','api_lists',true);
2813 function api_lists_list($type) {
2815 /// @TODO $ret is not filled here?
2816 return api_format_data('lists', $type, array("lists_list" => $ret));
2819 /// @TODO move to top of file or somwhere better
2820 api_register_func('api/lists/list','api_lists_list',true);
2823 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2824 * This function is deprecated by Twitter
2825 * returns: json, xml
2827 function api_statuses_f($type, $qtype) {
2831 if (api_user() === false) {
2832 throw new ForbiddenException();
2835 $user_info = api_get_user($a);
2837 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2838 /* this is to stop Hotot to load friends multiple times
2839 * I'm not sure if I'm missing return something or
2840 * is a bug in hotot. Workaround, meantime
2844 return array('$users' => $ret);*/
2848 if ($qtype == 'friends') {
2849 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2851 if ($qtype == 'followers') {
2852 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2855 // friends and followers only for self
2856 if ($user_info['self'] == 0) {
2857 $sql_extra = " AND false ";
2860 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2865 foreach ($r as $cid) {
2866 $user = api_get_user($a, $cid['nurl']);
2867 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2868 unset($user["uid"]);
2869 unset($user["self"]);
2876 return array('user' => $ret);
2880 function api_statuses_friends($type) {
2881 $data = api_statuses_f($type, "friends");
2882 if ($data === false) {
2885 return api_format_data("users", $type, $data);
2888 function api_statuses_followers($type) {
2889 $data = api_statuses_f($type, "followers");
2890 if ($data === false) {
2893 return api_format_data("users", $type, $data);
2896 /// @TODO move to top of file or somewhere better
2897 api_register_func('api/statuses/friends','api_statuses_friends',true);
2898 api_register_func('api/statuses/followers','api_statuses_followers',true);
2900 function api_statusnet_config($type) {
2904 $name = $a->config['sitename'];
2905 $server = $a->get_hostname();
2906 $logo = App::get_baseurl() . '/images/friendica-64.png';
2907 $email = $a->config['admin_email'];
2908 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2909 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2910 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2911 if ($a->config['api_import_size']) {
2912 $texlimit = string($a->config['api_import_size']);
2914 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2915 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2918 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2919 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2920 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2921 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2922 'shorturllength' => '30',
2923 'friendica' => array(
2924 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2925 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2926 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2927 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2932 return api_format_data('config', $type, array('config' => $config));
2936 /// @TODO move to top of file or somewhere better
2937 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2938 api_register_func('api/statusnet/config','api_statusnet_config', false);
2940 function api_statusnet_version($type) {
2942 $fake_statusnet_version = "0.9.7";
2944 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2947 /// @TODO move to top of file or somewhere better
2948 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2949 api_register_func('api/statusnet/version','api_statusnet_version', false);
2952 * @todo use api_format_data() to return data
2954 function api_ff_ids($type,$qtype) {
2959 throw new ForbiddenException();
2962 $user_info = api_get_user($a);
2964 if ($qtype == 'friends') {
2965 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2967 if ($qtype == 'followers') {
2968 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2971 if (!$user_info["self"]) {
2972 $sql_extra = " AND false ";
2975 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
2977 $r = q("SELECT `pcontact`.`id` FROM `contact`
2978 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2979 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2983 if (!dbm::is_result($r)) {
2988 foreach ($r as $rr) {
2989 if ($stringify_ids) {
2992 $ids[] = intval($rr['id']);
2996 return api_format_data("ids", $type, array('id' => $ids));
2999 function api_friends_ids($type) {
3000 return api_ff_ids($type,'friends');
3003 function api_followers_ids($type) {
3004 return api_ff_ids($type,'followers');
3007 /// @TODO move to top of file or somewhere better
3008 api_register_func('api/friends/ids','api_friends_ids',true);
3009 api_register_func('api/followers/ids','api_followers_ids',true);
3011 function api_direct_messages_new($type) {
3015 if (api_user() === false) throw new ForbiddenException();
3017 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
3019 $sender = api_get_user($a);
3021 if ($_POST['screen_name']) {
3022 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3024 dbesc($_POST['screen_name']));
3026 // Selecting the id by priority, friendica first
3027 api_best_nickname($r);
3029 $recipient = api_get_user($a, $r[0]['nurl']);
3031 $recipient = api_get_user($a, $_POST['user_id']);
3035 if (x($_REQUEST, 'replyto')) {
3036 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3038 intval($_REQUEST['replyto']));
3039 $replyto = $r[0]['parent-uri'];
3040 $sub = $r[0]['title'];
3042 if (x($_REQUEST, 'title')) {
3043 $sub = $_REQUEST['title'];
3045 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3049 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3052 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3053 $ret = api_format_messages($r[0], $recipient, $sender);
3055 $ret = array("error"=>$id);
3058 $data = array('direct_message'=>$ret);
3063 $data = api_rss_extra($a, $data, $user_info);
3066 return api_format_data("direct-messages", $type, $data);
3070 /// @TODO move to top of file or somewhere better
3071 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3074 * @brief delete a direct_message from mail table through api
3076 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3079 function api_direct_messages_destroy($type) {
3082 if (api_user() === false) {
3083 throw new ForbiddenException();
3087 $user_info = api_get_user($a);
3089 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3091 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3092 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3093 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3095 $uid = $user_info['uid'];
3096 // error if no id or parenturi specified (for clients posting parent-uri as well)
3097 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3098 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3099 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3102 // BadRequestException if no id specified (for clients using Twitter API)
3104 throw new BadRequestException('Message id not specified');
3107 // add parent-uri to sql command if specified by calling app
3108 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3110 // get data of the specified message id
3111 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3115 // error message if specified id is not in database
3116 if (!dbm::is_result($r)) {
3117 if ($verbose == "true") {
3118 $answer = array('result' => 'error', 'message' => 'message id not in database');
3119 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3121 /// @todo BadRequestException ok for Twitter API clients?
3122 throw new BadRequestException('message id not in database');
3126 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3130 if ($verbose == "true") {
3133 $answer = array('result' => 'ok', 'message' => 'message deleted');
3134 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3136 $answer = array('result' => 'error', 'message' => 'unknown error');
3137 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3140 /// @todo return JSON data like Twitter API not yet implemented
3144 /// @TODO move to top of file or somewhere better
3145 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3147 function api_direct_messages_box($type, $box, $verbose) {
3151 if (api_user() === false) {
3152 throw new ForbiddenException();
3156 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3157 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3162 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3163 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3165 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3166 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3169 unset($_REQUEST["user_id"]);
3170 unset($_GET["user_id"]);
3172 unset($_REQUEST["screen_name"]);
3173 unset($_GET["screen_name"]);
3175 $user_info = api_get_user($a);
3176 $profile_url = $user_info["url"];
3179 $start = $page * $count;
3182 if ($box=="sentbox") {
3183 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3184 } elseif ($box == "conversation") {
3185 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3186 } elseif ($box == "all") {
3187 $sql_extra = "true";
3188 } elseif ($box == "inbox") {
3189 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3193 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3196 if ($user_id != "") {
3197 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3198 } elseif ($screen_name !="") {
3199 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3202 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
3205 intval($start), intval($count)
3207 if ($verbose == "true" && !dbm::is_result($r)) {
3208 $answer = array('result' => 'error', 'message' => 'no mails available');
3209 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3213 foreach ($r as $item) {
3214 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3215 $recipient = $user_info;
3216 $sender = api_get_user($a,normalise_link($item['contact-url']));
3217 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3218 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3219 $sender = $user_info;
3222 $ret[] = api_format_messages($item, $recipient, $sender);
3226 $data = array('direct_message' => $ret);
3230 $data = api_rss_extra($a, $data, $user_info);
3233 return api_format_data("direct-messages", $type, $data);
3237 function api_direct_messages_sentbox($type) {
3238 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3239 return api_direct_messages_box($type, "sentbox", $verbose);
3242 function api_direct_messages_inbox($type) {
3243 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3244 return api_direct_messages_box($type, "inbox", $verbose);
3247 function api_direct_messages_all($type) {
3248 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3249 return api_direct_messages_box($type, "all", $verbose);
3252 function api_direct_messages_conversation($type) {
3253 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3254 return api_direct_messages_box($type, "conversation", $verbose);
3257 /// @TODO move to top of file or somewhere better
3258 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3259 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3260 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3261 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3263 function api_oauth_request_token($type) {
3265 $oauth = new FKOAuth1();
3266 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3267 } catch (Exception $e) {
3268 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3275 function api_oauth_access_token($type) {
3277 $oauth = new FKOAuth1();
3278 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3279 } catch (Exception $e) {
3280 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3286 /// @TODO move to top of file or somewhere better
3287 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3288 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3292 * @brief delete a complete photoalbum with all containing photos from database through api
3294 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3297 function api_fr_photoalbum_delete($type) {
3298 if (api_user() === false) {
3299 throw new ForbiddenException();
3302 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3304 // we do not allow calls without album string
3306 throw new BadRequestException("no albumname specified");
3308 // check if album is existing
3309 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3312 if (!dbm::is_result($r))
3313 throw new BadRequestException("album not available");
3315 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3316 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3317 foreach ($r as $rr) {
3318 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3319 intval(local_user()),
3320 dbesc($rr['resource-id'])
3323 if (!dbm::is_result($photo_item)) {
3324 throw new InternalServerErrorException("problem with deleting items occured");
3326 drop_item($photo_item[0]['id'],false);
3329 // now let's delete all photos from the album
3330 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3334 // return success of deletion or error message
3336 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3337 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3339 throw new InternalServerErrorException("unknown error - deleting from database failed");
3345 * @brief update the name of the album for all photos of an album
3347 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3350 function api_fr_photoalbum_update($type) {
3351 if (api_user() === false) {
3352 throw new ForbiddenException();
3355 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3356 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3358 // we do not allow calls without album string
3360 throw new BadRequestException("no albumname specified");
3362 if ($album_new == "") {
3363 throw new BadRequestException("no new albumname specified");
3365 // check if album is existing
3366 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3369 if (!dbm::is_result($r)) {
3370 throw new BadRequestException("album not available");
3372 // now let's update all photos to the albumname
3373 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3378 // return success of updating or error message
3380 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3381 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3383 throw new InternalServerErrorException("unknown error - updating in database failed");
3389 * @brief list all photos of the authenticated user
3391 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3394 function api_fr_photos_list($type) {
3395 if (api_user() === false) {
3396 throw new ForbiddenException();
3398 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3399 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3400 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3401 intval(local_user())
3404 'image/jpeg' => 'jpg',
3405 'image/png' => 'png',
3406 'image/gif' => 'gif'
3408 $data = array('photo'=>array());
3409 if (dbm::is_result($r)) {
3410 foreach ($r as $rr) {
3412 $photo['id'] = $rr['resource-id'];
3413 $photo['album'] = $rr['album'];
3414 $photo['filename'] = $rr['filename'];
3415 $photo['type'] = $rr['type'];
3416 $thumb = App::get_baseurl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3417 $photo['created'] = $rr['created'];
3418 $photo['edited'] = $rr['edited'];
3419 $photo['desc'] = $rr['desc'];
3421 if ($type == "xml") {
3422 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3424 $photo['thumb'] = $thumb;
3425 $data['photo'][] = $photo;
3429 return api_format_data("photos", $type, $data);
3433 * @brief upload a new photo or change an existing photo
3435 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3438 function api_fr_photo_create_update($type) {
3439 if (api_user() === false) {
3440 throw new ForbiddenException();
3443 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3444 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3445 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3446 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3447 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3448 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3449 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3450 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3451 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3453 // do several checks on input parameters
3454 // we do not allow calls without album string
3455 if ($album == null) {
3456 throw new BadRequestException("no albumname specified");
3458 // if photo_id == null --> we are uploading a new photo
3459 if ($photo_id == null) {
3462 // error if no media posted in create-mode
3463 if (!x($_FILES,'media')) {
3465 throw new BadRequestException("no media data submitted");
3468 // album_new will be ignored in create-mode
3473 // check if photo is existing in database
3474 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3478 if (!dbm::is_result($r)) {
3479 throw new BadRequestException("photo not available");
3483 // checks on acl strings provided by clients
3484 $acl_input_error = false;
3485 $acl_input_error |= check_acl_input($allow_cid);
3486 $acl_input_error |= check_acl_input($deny_cid);
3487 $acl_input_error |= check_acl_input($allow_gid);
3488 $acl_input_error |= check_acl_input($deny_gid);
3489 if ($acl_input_error) {
3490 throw new BadRequestException("acl data invalid");
3492 // now let's upload the new media in create-mode
3493 if ($mode == "create") {
3494 $media = $_FILES['media'];
3495 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3497 // return success of updating or error message
3498 if (!is_null($data)) {
3499 return api_format_data("photo_create", $type, $data);
3501 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3505 // now let's do the changes in update-mode
3506 if ($mode == "update") {
3509 if (!is_null($desc)) {
3510 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3513 if (!is_null($album_new)) {
3514 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3517 if (!is_null($allow_cid)) {
3518 $allow_cid = trim($allow_cid);
3519 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3522 if (!is_null($deny_cid)) {
3523 $deny_cid = trim($deny_cid);
3524 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3527 if (!is_null($allow_gid)) {
3528 $allow_gid = trim($allow_gid);
3529 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3532 if (!is_null($deny_gid)) {
3533 $deny_gid = trim($deny_gid);
3534 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3538 if ($sql_extra != "") {
3539 $nothingtodo = false;
3540 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3542 datetime_convert(), // update edited timestamp
3547 $nothingtodo = true;
3550 if (x($_FILES,'media')) {
3551 $nothingtodo = false;
3552 $media = $_FILES['media'];
3553 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3554 if (!is_null($data)) {
3555 return api_format_data("photo_update", $type, $data);
3559 // return success of updating or error message
3561 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3562 return api_format_data("photo_update", $type, array('$result' => $answer));
3565 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3566 return api_format_data("photo_update", $type, array('$result' => $answer));
3568 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3571 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3576 * @brief delete a single photo from the database through api
3578 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3581 function api_fr_photo_delete($type) {
3582 if (api_user() === false) {
3583 throw new ForbiddenException();
3586 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3588 // do several checks on input parameters
3589 // we do not allow calls without photo id
3590 if ($photo_id == null) {
3591 throw new BadRequestException("no photo_id specified");
3593 // check if photo is existing in database
3594 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3598 if (!dbm::is_result($r)) {
3599 throw new BadRequestException("photo not available");
3601 // now we can perform on the deletion of the photo
3602 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3606 // return success of deletion or error message
3608 // retrieve the id of the parent element (the photo element)
3609 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3610 intval(local_user()),
3614 if (!dbm::is_result($photo_item)) {
3615 throw new InternalServerErrorException("problem with deleting items occured");
3617 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3618 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3619 drop_item($photo_item[0]['id'], false);
3621 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3622 return api_format_data("photo_delete", $type, array('$result' => $answer));
3624 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3630 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3632 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3635 function api_fr_photo_detail($type) {
3636 if (api_user() === false) {
3637 throw new ForbiddenException();
3639 if (!x($_REQUEST, 'photo_id')) {
3640 throw new BadRequestException("No photo id.");
3643 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3644 $photo_id = $_REQUEST['photo_id'];
3646 // prepare json/xml output with data from database for the requested photo
3647 $data = prepare_photo_data($type, $scale, $photo_id);
3649 return api_format_data("photo_detail", $type, $data);
3654 * @brief updates the profile image for the user (either a specified profile or the default profile)
3656 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3659 function api_account_update_profile_image($type) {
3660 if (api_user() === false) {
3661 throw new ForbiddenException();
3664 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3666 // error if image data is missing
3667 if (!x($_FILES, 'image')) {
3668 throw new BadRequestException("no media data submitted");
3671 // check if specified profile id is valid
3672 if ($profileid != 0) {
3673 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3675 intval($profileid));
3676 // error message if specified profile id is not in database
3677 if (!dbm::is_result($r)) {
3678 throw new BadRequestException("profile_id not available");
3680 $is_default_profile = $r['profile'];
3682 $is_default_profile = 1;
3685 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3687 if (x($_FILES, 'image')) {
3688 $media = $_FILES['image'];
3689 } elseif (x($_FILES, 'media')) {
3690 $media = $_FILES['media'];
3692 // save new profile image
3693 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3696 if (is_array($media['type'])) {
3697 $filetype = $media['type'][0];
3699 $filetype = $media['type'];
3701 if ($filetype == "image/jpeg") {
3703 } elseif ($filetype == "image/png") {
3706 // change specified profile or all profiles to the new resource-id
3707 if ($is_default_profile) {
3708 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3709 dbesc($data['photo']['id']),
3710 intval(local_user())
3713 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3714 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3715 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3716 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3717 intval(local_user())
3720 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3721 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3722 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3723 intval($_REQUEST['profile']),
3724 intval(local_user())
3728 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3729 // so that browsers will do a cache update unconditionally
3731 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3732 dbesc(datetime_convert()),
3733 intval(local_user())
3736 // Update global directory in background
3737 //$user = api_get_user(get_app());
3738 $url = App::get_baseurl() . '/profile/' . get_app()->user['nickname'];
3739 if ($url && strlen(get_config('system', 'directory'))) {
3740 proc_run(PRIORITY_LOW, "include/directory.php", $url);
3743 require_once 'include/profile_update.php';
3746 // output for client
3748 return api_account_verify_credentials($type);
3750 // SaveMediaToDatabase failed for some reason
3751 throw new InternalServerErrorException("image upload failed");
3755 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3756 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3757 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3758 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3759 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3760 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3761 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3762 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3763 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3766 function check_acl_input($acl_string) {
3767 if ($acl_string == null || $acl_string == " ") {
3770 $contact_not_found = false;
3772 // split <x><y><z> into array of cid's
3773 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3775 // check for each cid if it is available on server
3776 $cid_array = $array[0];
3777 foreach ($cid_array as $cid) {
3778 $cid = str_replace("<", "", $cid);
3779 $cid = str_replace(">", "", $cid);
3780 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3782 intval(api_user()));
3783 $contact_not_found |= !dbm::is_result($contact);
3785 return $contact_not_found;
3788 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) {
3795 if (is_array($media)) {
3796 if (is_array($media['tmp_name'])) {
3797 $src = $media['tmp_name'][0];
3799 $src = $media['tmp_name'];
3801 if (is_array($media['name'])) {
3802 $filename = basename($media['name'][0]);
3804 $filename = basename($media['name']);
3806 if (is_array($media['size'])) {
3807 $filesize = intval($media['size'][0]);
3809 $filesize = intval($media['size']);
3811 if (is_array($media['type'])) {
3812 $filetype = $media['type'][0];
3814 $filetype = $media['type'];
3818 if ($filetype == "") {
3819 $filetype=guess_image_type($filename);
3821 $imagedata = getimagesize($src);
3823 $filetype = $imagedata['mime'];
3825 logger("File upload src: " . $src . " - filename: " . $filename .
3826 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3828 // check if there was a php upload error
3829 if ($filesize == 0 && $media['error'] == 1) {
3830 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3832 // check against max upload size within Friendica instance
3833 $maximagesize = get_config('system', 'maximagesize');
3834 if (($maximagesize) && ($filesize > $maximagesize)) {
3835 $formattedBytes = formatBytes($maximagesize);
3836 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3839 // create Photo instance with the data of the image
3840 $imagedata = @file_get_contents($src);
3841 $ph = new Photo($imagedata, $filetype);
3842 if (! $ph->is_valid()) {
3843 throw new InternalServerErrorException("unable to process image data");
3846 // check orientation of image
3850 // check max length of images on server
3851 $max_length = get_config('system', 'max_image_length');
3852 if (! $max_length) {
3853 $max_length = MAX_IMAGE_LENGTH;
3855 if ($max_length > 0) {
3856 $ph->scaleImage($max_length);
3857 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3859 $width = $ph->getWidth();
3860 $height = $ph->getHeight();
3862 // create a new resource-id if not already provided
3863 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3865 if ($mediatype == "photo") {
3866 // upload normal image (scales 0, 1, 2)
3867 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3869 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3871 logger("photo upload: image upload with scale 0 (original size) failed");
3873 if($width > 640 || $height > 640) {
3874 $ph->scaleImage(640);
3875 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3877 logger("photo upload: image upload with scale 1 (640x640) failed");
3881 if ($width > 320 || $height > 320) {
3882 $ph->scaleImage(320);
3883 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3885 logger("photo upload: image upload with scale 2 (320x320) failed");
3888 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3889 } elseif ($mediatype == "profileimage") {
3890 // upload profile image (scales 4, 5, 6)
3891 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3893 if ($width > 175 || $height > 175) {
3894 $ph->scaleImage(175);
3895 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3897 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3901 if ($width > 80 || $height > 80) {
3902 $ph->scaleImage(80);
3903 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3905 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3909 if ($width > 48 || $height > 48) {
3910 $ph->scaleImage(48);
3911 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3913 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3917 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3921 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3922 if ($photo_id == null && $mediatype == "photo") {
3923 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3925 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3926 return prepare_photo_data($type, false, $hash);
3928 throw new InternalServerErrorException("image upload failed");
3932 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3933 // get data about the api authenticated user
3934 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3935 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3938 $arr['guid'] = get_guid(32);
3939 $arr['uid'] = intval(api_user());
3941 $arr['parent-uri'] = $uri;
3942 $arr['type'] = 'photo';
3944 $arr['resource-id'] = $hash;
3945 $arr['contact-id'] = $owner_record[0]['id'];
3946 $arr['owner-name'] = $owner_record[0]['name'];
3947 $arr['owner-link'] = $owner_record[0]['url'];
3948 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3949 $arr['author-name'] = $owner_record[0]['name'];
3950 $arr['author-link'] = $owner_record[0]['url'];
3951 $arr['author-avatar'] = $owner_record[0]['thumb'];
3953 $arr['allow_cid'] = $allow_cid;
3954 $arr['allow_gid'] = $allow_gid;
3955 $arr['deny_cid'] = $deny_cid;
3956 $arr['deny_gid'] = $deny_gid;
3957 $arr['last-child'] = 1;
3958 $arr['visible'] = $visibility;
3962 'image/jpeg' => 'jpg',
3963 'image/png' => 'png',
3964 'image/gif' => 'gif'
3967 // adds link to the thumbnail scale photo
3968 $arr['body'] = '[url=' . App::get_baseurl() . '/photos/' . $owner_record[0]['name'] . '/image/' . $hash . ']'
3969 . '[img]' . App::get_baseurl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3972 // do the magic for storing the item in the database and trigger the federation to other contacts
3976 function prepare_photo_data($type, $scale, $photo_id) {
3977 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d", intval($scale)));
3978 $data_sql = ($scale === false ? "" : "data, ");
3980 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3981 // clients needs to convert this in their way for further processing
3982 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3983 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3984 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3985 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
3987 intval(local_user()),
3993 'image/jpeg' => 'jpg',
3994 'image/png' => 'png',
3995 'image/gif' => 'gif'
3998 // prepare output data for photo
3999 if (dbm::is_result($r)) {
4000 $data = array('photo' => $r[0]);
4001 $data['photo']['id'] = $data['photo']['resource-id'];
4002 if ($scale !== false) {
4003 $data['photo']['data'] = base64_encode($data['photo']['data']);
4005 unset($data['photo']['datasize']); //needed only with scale param
4007 if ($type == "xml") {
4008 $data['photo']['links'] = array();
4009 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4010 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4012 "href" => App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4015 $data['photo']['link'] = array();
4016 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4018 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4019 $data['photo']['link'][$i] = App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4023 unset($data['photo']['resource-id']);
4024 unset($data['photo']['minscale']);
4025 unset($data['photo']['maxscale']);
4028 throw new NotFoundException();
4031 // retrieve item element for getting activities (like, dislike etc.) related to photo
4032 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4033 intval(local_user()),
4036 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4038 // retrieve comments on photo
4039 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4040 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4041 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4042 `contact`.`id` AS `cid`
4044 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4045 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4046 WHERE `item`.`parent` = %d AND `item`.`visible`
4047 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4048 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4049 intval($item[0]['parent']),
4051 dbesc(ACTIVITY_POST)
4054 // prepare output of comments
4055 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4056 $comments = array();
4057 if ($type == "xml") {
4059 foreach ($commentData as $comment) {
4060 $comments[$k++ . ":comment"] = $comment;
4063 foreach ($commentData as $comment) {
4064 $comments[] = $comment;
4067 $data['photo']['friendica_comments'] = $comments;
4069 // include info if rights on photo and rights on item are mismatching
4070 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4071 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4072 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4073 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4074 $data['photo']['rights_mismatch'] = $rights_mismatch;
4081 * similar as /mod/redir.php
4082 * redirect to 'url' after dfrn auth
4084 * why this when there is mod/redir.php already?
4085 * This use api_user() and api_login()
4088 * c_url: url of remote contact to auth to
4089 * url: string, url to redirect after auth
4091 function api_friendica_remoteauth() {
4092 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4093 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4095 if ($url === '' || $c_url === '') {
4096 throw new BadRequestException("Wrong parameters.");
4099 $c_url = normalise_link($c_url);
4103 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4108 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4109 throw new BadRequestException("Unknown contact");
4114 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4116 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4117 $orig_id = $r[0]['issued-id'];
4118 $dfrn_id = '1:' . $orig_id;
4120 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4121 $orig_id = $r[0]['dfrn-id'];
4122 $dfrn_id = '0:' . $orig_id;
4125 $sec = random_string();
4127 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4128 VALUES( %d, %s, '%s', '%s', %d )",
4136 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4137 $dest = (($url) ? '&destination_url=' . $url : '');
4138 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4139 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4140 . '&type=profile&sec=' . $sec . $dest . $quiet );
4142 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4145 * @brief Return the item shared, if the item contains only the [share] tag
4147 * @param array $item Sharer item
4148 * @return array Shared item or false if not a reshare
4150 function api_share_as_retweet(&$item) {
4151 $body = trim($item["body"]);
4153 if (Diaspora::is_reshare($body, false)===false) {
4157 /// @TODO "$1" should maybe mean '$1' ?
4158 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4160 * Skip if there is no shared message in there
4161 * we already checked this in diaspora::is_reshare()
4162 * but better one more than one less...
4164 if ($body == $attributes) {
4169 // build the fake reshared item
4170 $reshared_item = $item;
4173 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4174 if ($matches[1] != "") {
4175 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4178 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4179 if ($matches[1] != "") {
4180 $author = $matches[1];
4184 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4185 if ($matches[1] != "") {
4186 $profile = $matches[1];
4189 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4190 if ($matches[1] != "") {
4191 $profile = $matches[1];
4195 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4196 if ($matches[1] != "") {
4197 $avatar = $matches[1];
4200 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4201 if ($matches[1] != "") {
4202 $avatar = $matches[1];
4206 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4207 if ($matches[1] != "") {
4208 $link = $matches[1];
4211 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4212 if ($matches[1] != "") {
4213 $link = $matches[1];
4217 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4218 if ($matches[1] != "")
4219 $posted = $matches[1];
4221 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4222 if ($matches[1] != "") {
4223 $posted = $matches[1];
4226 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4228 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4232 $reshared_item["body"] = $shared_body;
4233 $reshared_item["author-name"] = $author;
4234 $reshared_item["author-link"] = $profile;
4235 $reshared_item["author-avatar"] = $avatar;
4236 $reshared_item["plink"] = $link;
4237 $reshared_item["created"] = $posted;
4238 $reshared_item["edited"] = $posted;
4240 return $reshared_item;
4244 function api_get_nick($profile) {
4246 - remove trailing junk from profile url
4247 - pump.io check has to check the website
4252 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4253 dbesc(normalise_link($profile)));
4255 if (dbm::is_result($r)) {
4256 $nick = $r[0]["nick"];
4260 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4261 dbesc(normalise_link($profile)));
4263 if (dbm::is_result($r)) {
4264 $nick = $r[0]["nick"];
4269 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4270 if ($friendica != $profile) {
4276 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4277 if ($diaspora != $profile) {
4283 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4284 if ($twitter != $profile) {
4291 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4292 if ($StatusnetHost != $profile) {
4293 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4294 if ($StatusnetUser != $profile) {
4295 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4296 $user = json_decode($UserData);
4298 $nick = $user->screen_name;
4304 // To-Do: look at the page if its really a pumpio site
4305 //if (!$nick == "") {
4306 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4307 // if ($pumpio != $profile)
4309 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4320 function api_in_reply_to($item) {
4321 $in_reply_to = array();
4323 $in_reply_to['status_id'] = NULL;
4324 $in_reply_to['user_id'] = NULL;
4325 $in_reply_to['status_id_str'] = NULL;
4326 $in_reply_to['user_id_str'] = NULL;
4327 $in_reply_to['screen_name'] = NULL;
4329 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
4330 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4331 intval($item['uid']),
4332 dbesc($item['thr-parent']));
4334 if (dbm::is_result($r)) {
4335 $in_reply_to['status_id'] = intval($r[0]['id']);
4337 $in_reply_to['status_id'] = intval($item['parent']);
4340 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4342 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4343 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4344 WHERE `item`.`id` = %d LIMIT 1",
4345 intval($in_reply_to['status_id'])
4348 if (dbm::is_result($r)) {
4349 if ($r[0]['nick'] == "") {
4350 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4353 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4354 $in_reply_to['user_id'] = intval($r[0]['id']);
4355 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4358 // There seems to be situation, where both fields are identical:
4359 // https://github.com/friendica/friendica/issues/1010
4360 // This is a bugfix for that.
4361 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4362 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4363 $in_reply_to['status_id'] = NULL;
4364 $in_reply_to['user_id'] = NULL;
4365 $in_reply_to['status_id_str'] = NULL;
4366 $in_reply_to['user_id_str'] = NULL;
4367 $in_reply_to['screen_name'] = NULL;
4371 return $in_reply_to;
4374 function api_clean_plain_items($Text) {
4375 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4377 $Text = bb_CleanPictureLinks($Text);
4378 $URLSearchString = "^\[\]";
4380 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4382 if ($include_entities == "true") {
4383 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4386 // Simplify "attachment" element
4387 $Text = api_clean_attachments($Text);
4393 * @brief Removes most sharing information for API text export
4395 * @param string $body The original body
4397 * @return string Cleaned body
4399 function api_clean_attachments($body) {
4400 $data = get_attachment_data($body);
4407 if (isset($data["text"]))
4408 $body = $data["text"];
4410 if (($body == "") AND (isset($data["title"])))
4411 $body = $data["title"];
4413 if (isset($data["url"]))
4414 $body .= "\n".$data["url"];
4416 $body .= $data["after"];
4421 function api_best_nickname(&$contacts) {
4422 $best_contact = array();
4424 if (count($contact) == 0)
4427 foreach ($contacts AS $contact)
4428 if ($contact["network"] == "") {
4429 $contact["network"] = "dfrn";
4430 $best_contact = array($contact);
4433 if (sizeof($best_contact) == 0)
4434 foreach ($contacts AS $contact)
4435 if ($contact["network"] == "dfrn")
4436 $best_contact = array($contact);
4438 if (sizeof($best_contact) == 0)
4439 foreach ($contacts AS $contact)
4440 if ($contact["network"] == "dspr")
4441 $best_contact = array($contact);
4443 if (sizeof($best_contact) == 0)
4444 foreach ($contacts AS $contact)
4445 if ($contact["network"] == "stat")
4446 $best_contact = array($contact);
4448 if (sizeof($best_contact) == 0)
4449 foreach ($contacts AS $contact)
4450 if ($contact["network"] == "pump")
4451 $best_contact = array($contact);
4453 if (sizeof($best_contact) == 0)
4454 foreach ($contacts AS $contact)
4455 if ($contact["network"] == "twit")
4456 $best_contact = array($contact);
4458 if (sizeof($best_contact) == 1)
4459 $contacts = $best_contact;
4461 $contacts = array($contacts[0]);
4464 // return all or a specified group of the user with the containing contacts
4465 function api_friendica_group_show($type) {
4469 if (api_user() === false) throw new ForbiddenException();
4472 $user_info = api_get_user($a);
4473 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4474 $uid = $user_info['uid'];
4476 // get data of the specified group id or all groups if not specified
4478 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4481 // error message if specified gid is not in database
4482 if (!dbm::is_result($r))
4483 throw new BadRequestException("gid not available");
4486 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4489 // loop through all groups and retrieve all members for adding data in the user array
4490 foreach ($r as $rr) {
4491 $members = group_get_members($rr['id']);
4494 if ($type == "xml") {
4495 $user_element = "users";
4497 foreach ($members as $member) {
4498 $user = api_get_user($a, $member['nurl']);
4499 $users[$k++.":user"] = $user;
4502 $user_element = "user";
4503 foreach ($members as $member) {
4504 $user = api_get_user($a, $member['nurl']);
4508 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4510 return api_format_data("groups", $type, array('group' => $grps));
4512 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4515 // delete the specified group of the user
4516 function api_friendica_group_delete($type) {
4520 if (api_user() === false) throw new ForbiddenException();
4523 $user_info = api_get_user($a);
4524 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4525 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4526 $uid = $user_info['uid'];
4528 // error if no gid specified
4529 if ($gid == 0 || $name == "")
4530 throw new BadRequestException('gid or name not specified');
4532 // get data of the specified group id
4533 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4536 // error message if specified gid is not in database
4537 if (!dbm::is_result($r))
4538 throw new BadRequestException('gid not available');
4540 // get data of the specified group id and group name
4541 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4545 // error message if specified gid is not in database
4546 if (!dbm::is_result($rname))
4547 throw new BadRequestException('wrong group name');
4550 $ret = group_rmv($uid, $name);
4553 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4554 return api_format_data("group_delete", $type, array('result' => $success));
4557 throw new BadRequestException('other API error');
4559 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4562 // create the specified group with the posted array of contacts
4563 function api_friendica_group_create($type) {
4567 if (api_user() === false) throw new ForbiddenException();
4570 $user_info = api_get_user($a);
4571 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4572 $uid = $user_info['uid'];
4573 $json = json_decode($_POST['json'], true);
4574 $users = $json['user'];
4576 // error if no name specified
4578 throw new BadRequestException('group name not specified');
4580 // get data of the specified group name
4581 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4584 // error message if specified group name already exists
4585 if (dbm::is_result($rname))
4586 throw new BadRequestException('group name already exists');
4588 // check if specified group name is a deleted group
4589 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4592 // error message if specified group name already exists
4593 if (dbm::is_result($rname))
4594 $reactivate_group = true;
4597 $ret = group_add($uid, $name);
4599 $gid = group_byname($uid, $name);
4601 throw new BadRequestException('other API error');
4604 $erroraddinguser = false;
4605 $errorusers = array();
4606 foreach ($users as $user) {
4607 $cid = $user['cid'];
4608 // check if user really exists as contact
4609 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4612 if (count($contact))
4613 $result = group_add_member($uid, $name, $cid, $gid);
4615 $erroraddinguser = true;
4616 $errorusers[] = $cid;
4620 // return success message incl. missing users in array
4621 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4622 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4623 return api_format_data("group_create", $type, array('result' => $success));
4625 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4628 // update the specified group with the posted array of contacts
4629 function api_friendica_group_update($type) {
4633 if (api_user() === false) throw new ForbiddenException();
4636 $user_info = api_get_user($a);
4637 $uid = $user_info['uid'];
4638 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4639 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4640 $json = json_decode($_POST['json'], true);
4641 $users = $json['user'];
4643 // error if no name specified
4645 throw new BadRequestException('group name not specified');
4647 // error if no gid specified
4649 throw new BadRequestException('gid not specified');
4652 $members = group_get_members($gid);
4653 foreach ($members as $member) {
4654 $cid = $member['id'];
4655 foreach ($users as $user) {
4656 $found = ($user['cid'] == $cid ? true : false);
4659 $ret = group_rmv_member($uid, $name, $cid);
4664 $erroraddinguser = false;
4665 $errorusers = array();
4666 foreach ($users as $user) {
4667 $cid = $user['cid'];
4668 // check if user really exists as contact
4669 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4672 if (count($contact))
4673 $result = group_add_member($uid, $name, $cid, $gid);
4675 $erroraddinguser = true;
4676 $errorusers[] = $cid;
4680 // return success message incl. missing users in array
4681 $status = ($erroraddinguser ? "missing user" : "ok");
4682 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4683 return api_format_data("group_update", $type, array('result' => $success));
4686 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4688 function api_friendica_activity($type) {
4692 if (api_user() === false) throw new ForbiddenException();
4693 $verb = strtolower($a->argv[3]);
4694 $verb = preg_replace("|\..*$|", "", $verb);
4696 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4698 $res = do_like($id, $verb);
4705 return api_format_data('ok', $type, array('ok' => $ok));
4707 throw new BadRequestException('Error adding activity');
4712 /// @TODO move to top of file or somwhere better
4713 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4714 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4715 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4716 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4717 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4718 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4719 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4720 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4721 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4722 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4725 * @brief Returns notifications
4727 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4730 function api_friendica_notification($type) {
4734 if (api_user() === false) throw new ForbiddenException();
4735 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4736 $nm = new NotificationsManager();
4738 $notes = $nm->getAll(array(), "+seen -date", 50);
4740 if ($type == "xml") {
4741 $xmlnotes = array();
4742 foreach ($notes AS $note)
4743 $xmlnotes[] = array("@attributes" => $note);
4748 return api_format_data("notes", $type, array('note' => $notes));
4752 * @brief Set notification as seen and returns associated item (if possible)
4754 * POST request with 'id' param as notification id
4756 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4759 function api_friendica_notification_seen($type) {
4763 if (api_user() === false) throw new ForbiddenException();
4764 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4766 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4768 $nm = new NotificationsManager();
4769 $note = $nm->getByID($id);
4770 if (is_null($note)) throw new BadRequestException("Invalid argument");
4772 $nm->setSeen($note);
4773 if ($note['otype']=='item') {
4774 // would be really better with an ItemsManager and $im->getByID() :-P
4775 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4776 intval($note['iid']),
4777 intval(local_user())
4780 // we found the item, return it to the user
4781 $user_info = api_get_user($a);
4782 $ret = api_format_items($r,$user_info, false, $type);
4783 $data = array('status' => $ret);
4784 return api_format_data("status", $type, $data);
4786 // the item can't be found, but we set the note as seen, so we count this as a success
4788 return api_format_data('result', $type, array('result' => "success"));
4791 /// @TODO move to top of file or somwhere better
4792 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4793 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4796 * @brief update a direct_message to seen state
4798 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4799 * @return string (success result=ok, error result=error with error message)
4801 function api_friendica_direct_messages_setseen($type) {
4803 if (api_user() === false) {
4804 throw new ForbiddenException();
4808 $user_info = api_get_user($a);
4809 $uid = $user_info['uid'];
4810 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4812 // return error if id is zero
4814 $answer = array('result' => 'error', 'message' => 'message id not specified');
4815 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4818 // get data of the specified message id
4819 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4823 // error message if specified id is not in database
4824 if (!dbm::is_result($r)) {
4825 $answer = array('result' => 'error', 'message' => 'message id not in database');
4826 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4829 // update seen indicator
4830 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4836 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4837 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4839 $answer = array('result' => 'error', 'message' => 'unknown error');
4840 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4844 /// @TODO move to top of file or somwhere better
4845 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4848 * @brief search for direct_messages containing a searchstring through api
4850 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4851 * @return string (success: success=true if found and search_result contains found messages
4852 * success=false if nothing was found, search_result='nothing found',
4853 * error: result=error with error message)
4855 function api_friendica_direct_messages_search($type) {
4858 if (api_user() === false) {
4859 throw new ForbiddenException();
4863 $user_info = api_get_user($a);
4864 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4865 $uid = $user_info['uid'];
4867 // error if no searchstring specified
4868 if ($searchstring == "") {
4869 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4870 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4873 // get data for the specified searchstring
4874 $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",
4876 dbesc('%'.$searchstring.'%')
4879 $profile_url = $user_info["url"];
4881 // message if nothing was found
4882 if (!dbm::is_result($r)) {
4883 $success = array('success' => false, 'search_results' => 'problem with query');
4884 } elseif (count($r) == 0) {
4885 $success = array('success' => false, 'search_results' => 'nothing found');
4888 foreach ($r as $item) {
4889 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4890 $recipient = $user_info;
4891 $sender = api_get_user($a,normalise_link($item['contact-url']));
4892 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4893 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4894 $sender = $user_info;
4897 $ret[] = api_format_messages($item, $recipient, $sender);
4899 $success = array('success' => true, 'search_results' => $ret);
4902 return api_format_data("direct_message_search", $type, array('$result' => $success));
4905 /// @TODO move to top of file or somwhere better
4906 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4909 * @brief return data of all the profiles a user has to the client
4911 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4914 function api_friendica_profile_show($type) {
4917 if (api_user() === false) {
4918 throw new ForbiddenException();
4922 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4924 // retrieve general information about profiles for user
4925 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4926 $directory = get_config('system', 'directory');
4928 // get data of the specified profile id or all profiles of the user if not specified
4929 if ($profileid != 0) {
4930 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4932 intval($profileid));
4934 // error message if specified gid is not in database
4935 if (!dbm::is_result($r)) {
4936 throw new BadRequestException("profile_id not available");
4939 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4940 intval(api_user()));
4942 // loop through all returned profiles and retrieve data and users
4944 foreach ($r as $rr) {
4945 $profile = api_format_items_profiles($rr, $type);
4947 // select all users from contact table, loop and prepare standard return for user data
4949 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4951 intval($rr['profile_id']));
4953 foreach ($r as $rr) {
4954 $user = api_get_user($a, $rr['nurl']);
4955 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4957 $profile['users'] = $users;
4959 // add prepared profile data to array for final return
4960 if ($type == "xml") {
4961 $profiles[$k++ . ":profile"] = $profile;
4963 $profiles[] = $profile;
4967 // return settings, authenticated user and profiles data
4968 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4970 $result = array('multi_profiles' => $multi_profiles ? true : false,
4971 'global_dir' => $directory,
4972 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4973 'profiles' => $profiles);
4974 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4976 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4979 @TODO Maybe open to implement?
4981 [pagename] => api/1.1/statuses/lookup.json
4982 [id] => 605138389168451584
4983 [include_cards] => true
4984 [cards_platform] => Android-12
4985 [include_entities] => true
4986 [include_my_retweet] => 1
4988 [include_reply_count] => true
4989 [include_descendent_reply_count] => true
4993 Not implemented by now:
4994 statuses/retweets_of_me
4999 account/update_location
5000 account/update_profile_background_image
5003 friendica/profile/update
5004 friendica/profile/create
5005 friendica/profile/delete
5007 Not implemented in status.net:
5008 statuses/retweeted_to_me
5009 statuses/retweeted_by_me
5010 direct_messages/destroy
5012 account/update_delivery_device
5013 notifications/follow