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 = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
461 if (dbm::is_result($r)) {
469 * @brief Get user info array.
472 * @param int|string $contact_id Contact ID or URL
473 * @param string $type Return type (for errors)
475 function api_get_user(App $a, $contact_id = null, $type = "json") {
483 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
485 // Searching for contact URL
486 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
487 $user = dbesc(normalise_link($contact_id));
489 $extra_query = "AND `contact`.`nurl` = '%s' ";
490 if (api_user() !== false) {
491 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
495 // Searching for contact id with uid = 0
496 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
497 $user = dbesc(api_unique_id_to_url($contact_id));
500 throw new BadRequestException("User not found.");
504 $extra_query = "AND `contact`.`nurl` = '%s' ";
505 if (api_user() !== false) {
506 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
510 if (is_null($user) && x($_GET, 'user_id')) {
511 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
514 throw new BadRequestException("User not found.");
518 $extra_query = "AND `contact`.`nurl` = '%s' ";
519 if (api_user() !== false) {
520 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
523 if (is_null($user) && x($_GET, 'screen_name')) {
524 $user = dbesc($_GET['screen_name']);
526 $extra_query = "AND `contact`.`nick` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
532 if (is_null($user) && x($_GET, 'profileurl')) {
533 $user = dbesc(normalise_link($_GET['profileurl']));
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
541 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
542 $argid = count($called_api);
543 list($user, $null) = explode(".", $a->argv[$argid]);
544 if (is_numeric($user)) {
545 $user = dbesc(api_unique_id_to_url($user));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
557 $user = dbesc($user);
559 $extra_query = "AND `contact`.`nick` = '%s' ";
560 if (api_user() !== false) {
561 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
566 logger("api_get_user: user ".$user, LOGGER_DEBUG);
569 if (api_user() === false) {
573 $user = $_SESSION['uid'];
574 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
579 logger('api_user: ' . $extra_query . ', user: ' . $user);
582 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
588 // Selecting the id by priority, friendica first
589 api_best_nickname($uinfo);
591 // if the contact wasn't found, fetch it from the contacts with uid = 0
592 if (!dbm::is_result($uinfo)) {
596 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
599 if (dbm::is_result($r)) {
600 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
602 // If no nick where given, extract it from the address
603 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
604 $r[0]['nick'] = api_get_nick($r[0]["url"]);
609 'id_str' => (string) $r[0]["id"],
610 'name' => $r[0]["name"],
611 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
612 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
613 'description' => $r[0]["about"],
614 'profile_image_url' => $r[0]["micro"],
615 'profile_image_url_https' => $r[0]["micro"],
616 'url' => $r[0]["url"],
617 'protected' => false,
618 'followers_count' => 0,
619 'friends_count' => 0,
621 'created_at' => api_date($r[0]["created"]),
622 'favourites_count' => 0,
624 'time_zone' => 'UTC',
625 'geo_enabled' => false,
627 'statuses_count' => 0,
629 'contributors_enabled' => false,
630 'is_translator' => false,
631 'is_translation_enabled' => false,
632 'following' => false,
633 'follow_request_sent' => false,
634 'statusnet_blocking' => false,
635 'notifications' => false,
636 'statusnet_profile_url' => $r[0]["url"],
638 'cid' => get_contact($r[0]["url"], api_user(), true),
640 'network' => $r[0]["network"],
645 throw new BadRequestException("User not found.");
649 if ($uinfo[0]['self']) {
651 if ($uinfo[0]['network'] == "") {
652 $uinfo[0]['network'] = NETWORK_DFRN;
655 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
658 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
662 /// @TODO old-lost code? (twice)
663 // Counting is deactivated by now, due to performance issues
664 // count public wall messages
665 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
666 // intval($uinfo[0]['uid'])
668 //$countitms = $r[0]['count'];
671 // Counting is deactivated by now, due to performance issues
672 //$r = q("SELECT count(*) as `count` FROM `item`
673 // WHERE `contact-id` = %d",
674 // intval($uinfo[0]['id'])
676 //$countitms = $r[0]['count'];
680 /// @TODO old-lost code? (twice)
682 // Counting is deactivated by now, due to performance issues
684 $r = q("SELECT count(*) as `count` FROM `contact`
685 WHERE `uid` = %d AND `rel` IN ( %d, %d )
686 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
687 intval($uinfo[0]['uid']),
688 intval(CONTACT_IS_SHARING),
689 intval(CONTACT_IS_FRIEND)
691 $countfriends = $r[0]['count'];
693 $r = q("SELECT count(*) as `count` FROM `contact`
694 WHERE `uid` = %d AND `rel` IN ( %d, %d )
695 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
696 intval($uinfo[0]['uid']),
697 intval(CONTACT_IS_FOLLOWER),
698 intval(CONTACT_IS_FRIEND)
700 $countfollowers = $r[0]['count'];
702 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
703 intval($uinfo[0]['uid'])
705 $starred = $r[0]['count'];
708 if (! $uinfo[0]['self']) {
718 // Add a nick if it isn't present there
719 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
720 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
723 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
725 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
728 'id' => intval($pcontact_id),
729 'id_str' => (string) intval($pcontact_id),
730 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
731 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
732 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
733 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
734 'profile_image_url' => $uinfo[0]['micro'],
735 'profile_image_url_https' => $uinfo[0]['micro'],
736 'url' => $uinfo[0]['url'],
737 'protected' => false,
738 'followers_count' => intval($countfollowers),
739 'friends_count' => intval($countfriends),
741 'created_at' => api_date($uinfo[0]['created']),
742 'favourites_count' => intval($starred),
744 'time_zone' => 'UTC',
745 'geo_enabled' => false,
747 'statuses_count' => intval($countitms),
749 'contributors_enabled' => false,
750 'is_translator' => false,
751 'is_translation_enabled' => false,
752 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
753 'follow_request_sent' => false,
754 'statusnet_blocking' => false,
755 'notifications' => false,
757 //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
758 'statusnet_profile_url' => $uinfo[0]['url'],
759 'uid' => intval($uinfo[0]['uid']),
760 'cid' => intval($uinfo[0]['cid']),
761 'self' => $uinfo[0]['self'],
762 'network' => $uinfo[0]['network'],
770 * @brief return api-formatted array for item's author and owner
773 * @param array $item : item from db
774 * @return array(array:author, array:owner)
776 function api_item_get_user(App $a, $item) {
778 $status_user = api_get_user($a, $item["author-link"]);
780 $status_user["protected"] = (($item["allow_cid"] != "") ||
781 ($item["allow_gid"] != "") ||
782 ($item["deny_cid"] != "") ||
783 ($item["deny_gid"] != "") ||
786 if ($item['thr-parent'] == $item['uri']) {
787 $owner_user = api_get_user($a, $item["owner-link"]);
789 $owner_user = $status_user;
792 return (array($status_user, $owner_user));
796 * @brief walks recursively through an array with the possibility to change value and key
798 * @param array $array The array to walk through
799 * @param string $callback The callback function
801 * @return array the transformed array
803 function api_walk_recursive(array &$array, callable $callback) {
805 $new_array = array();
807 foreach ($array as $k => $v) {
809 if ($callback($v, $k)) {
810 $new_array[$k] = api_walk_recursive($v, $callback);
813 if ($callback($v, $k)) {
824 * @brief Callback function to transform the array in an array that can be transformed in a XML file
826 * @param variant $item Array item value
827 * @param string $key Array key
829 * @return boolean Should the array item be deleted?
831 function api_reformat_xml(&$item, &$key) {
832 if (is_bool($item)) {
833 $item = ($item ? "true" : "false");
836 if (substr($key, 0, 10) == "statusnet_") {
837 $key = "statusnet:".substr($key, 10);
838 } elseif (substr($key, 0, 10) == "friendica_") {
839 $key = "friendica:".substr($key, 10);
841 /// @TODO old-lost code?
843 // $key = "default:".$key;
849 * @brief Creates the XML from a JSON style array
851 * @param array $data JSON style array
852 * @param string $root_element Name of the root element
854 * @return string The XML data
856 function api_create_xml($data, $root_element) {
857 $childname = key($data);
858 $data2 = array_pop($data);
861 $namespaces = array("" => "http://api.twitter.com",
862 "statusnet" => "http://status.net/schema/api/1/",
863 "friendica" => "http://friendi.ca/schema/api/1/",
864 "georss" => "http://www.georss.org/georss");
866 /// @todo Auto detection of needed namespaces
867 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
868 $namespaces = array();
871 if (is_array($data2)) {
872 api_walk_recursive($data2, "api_reformat_xml");
879 foreach ($data2 AS $item) {
880 $data4[$i++.":".$childname] = $item;
886 $data3 = array($root_element => $data2);
888 $ret = xml::from_array($data3, $xml, false, $namespaces);
893 * @brief Formats the data according to the data type
895 * @param string $root_element Name of the root element
896 * @param string $type Return type (atom, rss, xml, json)
897 * @param array $data JSON style array
899 * @return (string|object) XML data or JSON data
901 function api_format_data($root_element, $type, $data) {
909 $ret = api_create_xml($data, $root_element);
924 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
925 * returns a 401 status code and an error message if not.
926 * http://developer.twitter.com/doc/get/account/verify_credentials
928 function api_account_verify_credentials($type) {
932 if (api_user() === false) {
933 throw new ForbiddenException();
936 unset($_REQUEST["user_id"]);
937 unset($_GET["user_id"]);
939 unset($_REQUEST["screen_name"]);
940 unset($_GET["screen_name"]);
942 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
944 $user_info = api_get_user($a);
946 // "verified" isn't used here in the standard
947 unset($user_info["verified"]);
949 // - Adding last status
951 $user_info["status"] = api_status_show("raw");
952 if (!count($user_info["status"])) {
953 unset($user_info["status"]);
955 unset($user_info["status"]["user"]);
959 // "uid" and "self" are only needed for some internal stuff, so remove it from here
960 unset($user_info["uid"]);
961 unset($user_info["self"]);
963 return api_format_data("user", $type, array('user' => $user_info));
967 /// @TODO move to top of file or somwhere better
968 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
971 * get data from $_POST or $_GET
973 function requestdata($k) {
983 /*Waitman Gobble Mod*/
984 function api_statuses_mediap($type) {
988 if (api_user() === false) {
989 logger('api_statuses_update: no user');
990 throw new ForbiddenException();
992 $user_info = api_get_user($a);
994 $_REQUEST['type'] = 'wall';
995 $_REQUEST['profile_uid'] = api_user();
996 $_REQUEST['api_source'] = true;
997 $txt = requestdata('status');
998 /// @TODO old-lost code?
999 //$txt = urldecode(requestdata('status'));
1001 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1003 $txt = html2bb_video($txt);
1004 $config = HTMLPurifier_Config::createDefault();
1005 $config->set('Cache.DefinitionImpl', null);
1006 $purifier = new HTMLPurifier($config);
1007 $txt = $purifier->purify($txt);
1009 $txt = html2bbcode($txt);
1011 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1013 // tell wall_upload function to return img info instead of echo
1014 $_REQUEST['hush'] = 'yeah';
1015 $bebop = wall_upload_post($a);
1017 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1018 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1021 // this should output the last post (the one we just posted).
1022 return api_status_show($type);
1025 /// @TODO move this to top of file or somewhere better!
1026 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1028 function api_statuses_update($type) {
1032 if (api_user() === false) {
1033 logger('api_statuses_update: no user');
1034 throw new ForbiddenException();
1037 $user_info = api_get_user($a);
1039 // convert $_POST array items to the form we use for web posts.
1041 // logger('api_post: ' . print_r($_POST,true));
1043 if (requestdata('htmlstatus')) {
1044 $txt = requestdata('htmlstatus');
1045 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1046 $txt = html2bb_video($txt);
1048 $config = HTMLPurifier_Config::createDefault();
1049 $config->set('Cache.DefinitionImpl', null);
1051 $purifier = new HTMLPurifier($config);
1052 $txt = $purifier->purify($txt);
1054 $_REQUEST['body'] = html2bbcode($txt);
1058 $_REQUEST['body'] = requestdata('status');
1061 $_REQUEST['title'] = requestdata('title');
1063 $parent = requestdata('in_reply_to_status_id');
1065 // Twidere sends "-1" if it is no reply ...
1066 if ($parent == -1) {
1070 if (ctype_digit($parent)) {
1071 $_REQUEST['parent'] = $parent;
1073 $_REQUEST['parent_uri'] = $parent;
1076 if (requestdata('lat') && requestdata('long')) {
1077 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1079 $_REQUEST['profile_uid'] = api_user();
1082 $_REQUEST['type'] = 'net-comment';
1084 // Check for throttling (maximum posts per day, week and month)
1085 $throttle_day = get_config('system','throttle_limit_day');
1086 if ($throttle_day > 0) {
1087 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1089 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1090 AND `created` > '%s' AND `id` = `parent`",
1091 intval(api_user()), dbesc($datefrom));
1093 if (dbm::is_result($r)) {
1094 $posts_day = $r[0]["posts_day"];
1099 if ($posts_day > $throttle_day) {
1100 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1101 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1102 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1106 $throttle_week = get_config('system','throttle_limit_week');
1107 if ($throttle_week > 0) {
1108 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1110 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1111 AND `created` > '%s' AND `id` = `parent`",
1112 intval(api_user()), dbesc($datefrom));
1114 if (dbm::is_result($r)) {
1115 $posts_week = $r[0]["posts_week"];
1120 if ($posts_week > $throttle_week) {
1121 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1122 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1123 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1127 $throttle_month = get_config('system','throttle_limit_month');
1128 if ($throttle_month > 0) {
1129 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1131 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1132 AND `created` > '%s' AND `id` = `parent`",
1133 intval(api_user()), dbesc($datefrom));
1135 if (dbm::is_result($r)) {
1136 $posts_month = $r[0]["posts_month"];
1141 if ($posts_month > $throttle_month) {
1142 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1143 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1144 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1148 $_REQUEST['type'] = 'wall';
1151 if (x($_FILES, 'media')) {
1152 // upload the image if we have one
1153 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1154 $media = wall_upload_post($a);
1155 if (strlen($media) > 0) {
1156 $_REQUEST['body'] .= "\n\n" . $media;
1160 // To-Do: Multiple IDs
1161 if (requestdata('media_ids')) {
1162 $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",
1163 intval(requestdata('media_ids')), api_user());
1164 if (dbm::is_result($r)) {
1165 $phototypes = Photo::supportedTypes();
1166 $ext = $phototypes[$r[0]['type']];
1167 $_REQUEST['body'] .= "\n\n" . '[url=' . App::get_baseurl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1168 $_REQUEST['body'] .= '[img]' . App::get_baseurl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1172 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1174 $_REQUEST['api_source'] = true;
1176 if (!x($_REQUEST, "source")) {
1177 $_REQUEST["source"] = api_source();
1180 // call out normal post function
1183 // this should output the last post (the one we just posted).
1184 return api_status_show($type);
1187 /// @TODO move to top of file or somwhere better
1188 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1189 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1191 function api_media_upload($type) {
1195 if (api_user() === false) {
1197 throw new ForbiddenException();
1200 $user_info = api_get_user($a);
1202 if (!x($_FILES, 'media')) {
1204 throw new BadRequestException("No media.");
1207 $media = wall_upload_post($a, false);
1210 throw new InternalServerErrorException();
1213 $returndata = array();
1214 $returndata["media_id"] = $media["id"];
1215 $returndata["media_id_string"] = (string)$media["id"];
1216 $returndata["size"] = $media["size"];
1217 $returndata["image"] = array("w" => $media["width"],
1218 "h" => $media["height"],
1219 "image_type" => $media["type"]);
1221 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1223 return array("media" => $returndata);
1226 /// @TODO move to top of file or somwhere better
1227 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1229 function api_status_show($type) {
1233 $user_info = api_get_user($a);
1235 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1237 if ($type == "raw") {
1238 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1243 // get last public wall message
1244 $lastwall = q("SELECT `item`.*
1246 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1247 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1248 AND `item`.`type` != 'activity' $privacy_sql
1249 ORDER BY `item`.`id` DESC
1251 intval($user_info['cid']),
1253 dbesc($user_info['url']),
1254 dbesc(normalise_link($user_info['url'])),
1255 dbesc($user_info['url']),
1256 dbesc(normalise_link($user_info['url']))
1259 if (dbm::is_result($lastwall)) {
1260 $lastwall = $lastwall[0];
1262 $in_reply_to = api_in_reply_to($lastwall);
1264 $converted = api_convert_item($lastwall);
1266 if ($type == "xml") {
1267 $geo = "georss:point";
1272 $status_info = array(
1273 'created_at' => api_date($lastwall['created']),
1274 'id' => intval($lastwall['id']),
1275 'id_str' => (string) $lastwall['id'],
1276 'text' => $converted["text"],
1277 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1278 'truncated' => false,
1279 'in_reply_to_status_id' => $in_reply_to['status_id'],
1280 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1281 'in_reply_to_user_id' => $in_reply_to['user_id'],
1282 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1283 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1284 'user' => $user_info,
1286 'coordinates' => "",
1288 'contributors' => "",
1289 'is_quote_status' => false,
1290 'retweet_count' => 0,
1291 'favorite_count' => 0,
1292 'favorited' => $lastwall['starred'] ? true : false,
1293 'retweeted' => false,
1294 'possibly_sensitive' => false,
1296 'statusnet_html' => $converted["html"],
1297 'statusnet_conversation_id' => $lastwall['parent'],
1300 if (count($converted["attachments"]) > 0) {
1301 $status_info["attachments"] = $converted["attachments"];
1304 if (count($converted["entities"]) > 0) {
1305 $status_info["entities"] = $converted["entities"];
1308 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1309 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1310 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1311 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1314 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1315 unset($status_info["user"]["uid"]);
1316 unset($status_info["user"]["self"]);
1319 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1321 if ($type == "raw") {
1322 return $status_info;
1325 return api_format_data("statuses", $type, array('status' => $status_info));
1330 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1331 * The author's most recent status will be returned inline.
1332 * http://developer.twitter.com/doc/get/users/show
1334 function api_users_show($type) {
1338 $user_info = api_get_user($a);
1339 $lastwall = q("SELECT `item`.*
1341 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1342 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1343 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1344 AND `type`!='activity'
1345 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1349 dbesc(ACTIVITY_POST),
1350 intval($user_info['cid']),
1351 dbesc($user_info['url']),
1352 dbesc(normalise_link($user_info['url'])),
1353 dbesc($user_info['url']),
1354 dbesc(normalise_link($user_info['url']))
1357 if (dbm::is_result($lastwall)) {
1358 $lastwall = $lastwall[0];
1360 $in_reply_to = api_in_reply_to($lastwall);
1362 $converted = api_convert_item($lastwall);
1364 if ($type == "xml") {
1365 $geo = "georss:point";
1370 $user_info['status'] = array(
1371 'text' => $converted["text"],
1372 'truncated' => false,
1373 'created_at' => api_date($lastwall['created']),
1374 'in_reply_to_status_id' => $in_reply_to['status_id'],
1375 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1376 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1377 'id' => intval($lastwall['contact-id']),
1378 'id_str' => (string) $lastwall['contact-id'],
1379 'in_reply_to_user_id' => $in_reply_to['user_id'],
1380 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1381 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1383 'favorited' => $lastwall['starred'] ? true : false,
1384 'statusnet_html' => $converted["html"],
1385 'statusnet_conversation_id' => $lastwall['parent'],
1388 if (count($converted["attachments"]) > 0) {
1389 $user_info["status"]["attachments"] = $converted["attachments"];
1392 if (count($converted["entities"]) > 0) {
1393 $user_info["status"]["entities"] = $converted["entities"];
1396 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1397 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1400 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1401 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1406 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1407 unset($user_info["uid"]);
1408 unset($user_info["self"]);
1410 return api_format_data("user", $type, array('user' => $user_info));
1414 /// @TODO move to top of file or somewhere better
1415 api_register_func('api/users/show','api_users_show');
1416 api_register_func('api/externalprofile/show','api_users_show');
1418 function api_users_search($type) {
1422 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1424 $userlist = array();
1426 if (x($_GET, 'q')) {
1427 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1429 if (!dbm::is_result($r)) {
1430 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1433 if (dbm::is_result($r)) {
1435 foreach ($r AS $user) {
1436 $user_info = api_get_user($a, $user["id"], "json");
1438 if ($type == "xml") {
1439 $userlist[$k++.":user"] = $user_info;
1441 $userlist[] = $user_info;
1444 $userlist = array("users" => $userlist);
1446 throw new BadRequestException("User not found.");
1449 throw new BadRequestException("User not found.");
1451 return api_format_data("users", $type, $userlist);
1454 /// @TODO move to top of file or somewhere better
1455 api_register_func('api/users/search','api_users_search');
1459 * http://developer.twitter.com/doc/get/statuses/home_timeline
1461 * TODO: Optional parameters
1462 * TODO: Add reply info
1464 function api_statuses_home_timeline($type) {
1468 if (api_user() === false) {
1469 throw new ForbiddenException();
1472 unset($_REQUEST["user_id"]);
1473 unset($_GET["user_id"]);
1475 unset($_REQUEST["screen_name"]);
1476 unset($_GET["screen_name"]);
1478 $user_info = api_get_user($a);
1479 // get last newtork messages
1482 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1483 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1487 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1488 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1489 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1490 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1491 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1493 $start = $page * $count;
1497 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1499 if ($exclude_replies > 0) {
1500 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1502 if ($conversation_id > 0) {
1503 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1506 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1507 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1508 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1509 `contact`.`id` AS `cid`
1511 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1512 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1513 WHERE `item`.`uid` = %d AND `verb` = '%s'
1514 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1517 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1519 dbesc(ACTIVITY_POST),
1521 intval($start), intval($count)
1524 $ret = api_format_items($r, $user_info, false, $type);
1526 // Set all posts from the query above to seen
1528 foreach ($r AS $item) {
1529 $idarray[] = intval($item["id"]);
1532 $idlist = implode(",", $idarray);
1534 if ($idlist != "") {
1535 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1538 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1542 $data = array('status' => $ret);
1546 $data = api_rss_extra($a, $data, $user_info);
1550 return api_format_data("statuses", $type, $data);
1553 /// @TODO move to top of file or somewhere better
1554 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1555 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1557 function api_statuses_public_timeline($type) {
1561 if (api_user() === false) {
1562 throw new ForbiddenException();
1565 $user_info = api_get_user($a);
1566 // get last newtork messages
1569 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1570 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1574 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1575 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1576 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1577 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1578 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1580 $start = $page * $count;
1583 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1585 if ($exclude_replies > 0) {
1586 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1588 if ($conversation_id > 0) {
1589 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1592 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1593 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1594 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1595 `contact`.`id` AS `cid`,
1596 `user`.`nickname`, `user`.`hidewall`
1598 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1599 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1600 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1601 AND NOT `user`.`hidewall`
1602 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1603 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1604 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1605 AND NOT `item`.`private` AND `item`.`wall`
1608 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1609 dbesc(ACTIVITY_POST),
1614 $ret = api_format_items($r, $user_info, false, $type);
1616 $data = array('status' => $ret);
1620 $data = api_rss_extra($a, $data, $user_info);
1624 return api_format_data("statuses", $type, $data);
1627 /// @TODO move to top of file or somewhere better
1628 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1631 * @TODO nothing to say?
1633 function api_statuses_show($type) {
1637 if (api_user() === false) {
1638 throw new ForbiddenException();
1641 $user_info = api_get_user($a);
1644 $id = intval($a->argv[3]);
1647 $id = intval($_REQUEST["id"]);
1652 $id = intval($a->argv[4]);
1655 logger('API: api_statuses_show: ' . $id);
1657 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1660 if ($conversation) {
1661 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1663 $sql_extra .= " AND `item`.`id` = %d";
1666 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1667 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1668 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1669 `contact`.`id` AS `cid`
1671 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1672 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1673 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1674 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1677 dbesc(ACTIVITY_POST),
1681 /// @TODO How about copying this to above methods which don't check $r ?
1682 if (!dbm::is_result($r)) {
1683 throw new BadRequestException("There is no status with this id.");
1686 $ret = api_format_items($r,$user_info, false, $type);
1688 if ($conversation) {
1689 $data = array('status' => $ret);
1690 return api_format_data("statuses", $type, $data);
1692 $data = array('status' => $ret[0]);
1693 return api_format_data("status", $type, $data);
1697 /// @TODO move to top of file or somewhere better
1698 api_register_func('api/statuses/show','api_statuses_show', true);
1701 * @TODO nothing to say?
1703 function api_conversation_show($type) {
1707 if (api_user() === false) {
1708 throw new ForbiddenException();
1711 $user_info = api_get_user($a);
1714 $id = intval($a->argv[3]);
1715 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1716 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1720 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1721 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1723 $start = $page*$count;
1726 $id = intval($_REQUEST["id"]);
1731 $id = intval($a->argv[4]);
1734 logger('API: api_conversation_show: '.$id);
1736 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1737 if (dbm::is_result($r)) {
1738 $id = $r[0]["parent"];
1744 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1747 // Not sure why this query was so complicated. We should keep it here for a while,
1748 // just to make sure that we really don't need it.
1749 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1750 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1752 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1753 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1754 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1755 `contact`.`id` AS `cid`
1757 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1758 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1759 WHERE `item`.`parent` = %d AND `item`.`visible`
1760 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1761 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1762 AND `item`.`id`>%d $sql_extra
1763 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1764 intval($id), intval(api_user()),
1765 dbesc(ACTIVITY_POST),
1767 intval($start), intval($count)
1770 if (!dbm::is_result($r)) {
1771 throw new BadRequestException("There is no status with this id.");
1774 $ret = api_format_items($r, $user_info, false, $type);
1776 $data = array('status' => $ret);
1777 return api_format_data("statuses", $type, $data);
1780 /// @TODO move to top of file or somewhere better
1781 api_register_func('api/conversation/show','api_conversation_show', true);
1782 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1785 * @TODO nothing to say?
1787 function api_statuses_repeat($type) {
1792 if (api_user() === false) {
1793 throw new ForbiddenException();
1796 $user_info = api_get_user($a);
1799 $id = intval($a->argv[3]);
1802 $id = intval($_REQUEST["id"]);
1807 $id = intval($a->argv[4]);
1810 logger('API: api_statuses_repeat: '.$id);
1812 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1813 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1814 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1815 `contact`.`id` AS `cid`
1817 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1818 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1819 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1820 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1821 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1823 AND `item`.`id`=%d",
1827 /// @TODO other style than above functions!
1828 if (dbm::is_result($r) && $r[0]['body'] != "") {
1829 if (strpos($r[0]['body'], "[/share]") !== false) {
1830 $pos = strpos($r[0]['body'], "[share");
1831 $post = substr($r[0]['body'], $pos);
1833 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1835 $post .= $r[0]['body'];
1836 $post .= "[/share]";
1838 $_REQUEST['body'] = $post;
1839 $_REQUEST['profile_uid'] = api_user();
1840 $_REQUEST['type'] = 'wall';
1841 $_REQUEST['api_source'] = true;
1843 if (!x($_REQUEST, "source")) {
1844 $_REQUEST["source"] = api_source();
1849 throw new ForbiddenException();
1852 // this should output the last post (the one we just posted).
1854 return api_status_show($type);
1857 /// @TODO move to top of file or somewhere better
1858 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1861 * @TODO nothing to say?
1863 function api_statuses_destroy($type) {
1867 if (api_user() === false) {
1868 throw new ForbiddenException();
1871 $user_info = api_get_user($a);
1874 $id = intval($a->argv[3]);
1877 $id = intval($_REQUEST["id"]);
1882 $id = intval($a->argv[4]);
1885 logger('API: api_statuses_destroy: '.$id);
1887 $ret = api_statuses_show($type);
1889 drop_item($id, false);
1894 /// @TODO move to top of file or somewhere better
1895 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1898 * @TODO Nothing more than an URL to say?
1899 * http://developer.twitter.com/doc/get/statuses/mentions
1901 function api_statuses_mentions($type) {
1905 if (api_user() === false) {
1906 throw new ForbiddenException();
1909 unset($_REQUEST["user_id"]);
1910 unset($_GET["user_id"]);
1912 unset($_REQUEST["screen_name"]);
1913 unset($_GET["screen_name"]);
1915 $user_info = api_get_user($a);
1916 // get last newtork messages
1920 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1921 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1925 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1926 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1927 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1929 $start = $page * $count;
1931 // Ugly code - should be changed
1932 $myurl = App::get_baseurl() . '/profile/'. $a->user['nickname'];
1933 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1934 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1935 $myurl = str_replace('www.', '', $myurl);
1936 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1939 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1942 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1943 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1944 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1945 `contact`.`id` AS `cid`
1946 FROM `item` FORCE INDEX (`uid_id`)
1947 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1948 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1949 WHERE `item`.`uid` = %d AND `verb` = '%s'
1950 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1951 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1952 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1955 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1957 dbesc(ACTIVITY_POST),
1958 dbesc(protect_sprintf($myurl)),
1959 dbesc(protect_sprintf($myurl)),
1962 intval($start), intval($count)
1965 $ret = api_format_items($r, $user_info, false, $type);
1967 $data = array('status' => $ret);
1971 $data = api_rss_extra($a, $data, $user_info);
1975 return api_format_data("statuses", $type, $data);
1978 /// @TODO move to top of file or somewhere better
1979 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1980 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1982 function api_statuses_user_timeline($type) {
1986 if (api_user() === false) {
1987 throw new ForbiddenException();
1990 $user_info = api_get_user($a);
1991 // get last network messages
1993 logger("api_statuses_user_timeline: api_user: ". api_user() .
1994 "\nuser_info: ".print_r($user_info, true) .
1995 "\n_REQUEST: ".print_r($_REQUEST, true),
1999 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2000 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2004 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2005 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2006 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2007 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2009 $start = $page * $count;
2012 if ($user_info['self'] == 1) {
2013 $sql_extra .= " AND `item`.`wall` = 1 ";
2016 if ($exclude_replies > 0) {
2017 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2019 if ($conversation_id > 0) {
2020 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2023 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2024 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2025 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2026 `contact`.`id` AS `cid`
2027 FROM `item` FORCE INDEX (`uid_contactid_id`)
2028 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2029 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2030 WHERE `item`.`uid` = %d AND `verb` = '%s'
2031 AND `item`.`contact-id` = %d
2032 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2035 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2037 dbesc(ACTIVITY_POST),
2038 intval($user_info['cid']),
2040 intval($start), intval($count)
2043 $ret = api_format_items($r, $user_info, true, $type);
2045 $data = array('status' => $ret);
2049 $data = api_rss_extra($a, $data, $user_info);
2053 return api_format_data("statuses", $type, $data);
2056 /// @TODO move to top of file or somwhere better
2057 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2060 * Star/unstar an item
2061 * param: id : id of the item
2063 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2065 function api_favorites_create_destroy($type) {
2069 if (api_user() === false) {
2070 throw new ForbiddenException();
2073 // for versioned api.
2074 /// @TODO We need a better global soluton
2075 $action_argv_id = 2;
2076 if ($a->argv[1] == "1.1") {
2077 $action_argv_id = 3;
2080 if ($a->argc <= $action_argv_id) {
2081 throw new BadRequestException("Invalid request.");
2083 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2084 if ($a->argc == $action_argv_id + 2) {
2085 $itemid = intval($a->argv[$action_argv_id + 1]);
2087 /// @TODO use x() to check if _REQUEST contains 'id'
2088 $itemid = intval($_REQUEST['id']);
2091 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2092 $itemid, api_user());
2094 if (!dbm::is_result($item) || count($item) == 0) {
2095 throw new BadRequestException("Invalid item.");
2100 $item[0]['starred'] = 1;
2103 $item[0]['starred'] = 0;
2106 throw new BadRequestException("Invalid action ".$action);
2109 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2110 $item[0]['starred'], $itemid, api_user());
2112 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2113 $item[0]['starred'], $itemid, api_user());
2116 throw new InternalServerErrorException("DB error");
2120 $user_info = api_get_user($a);
2121 $rets = api_format_items($item, $user_info, false, $type);
2124 $data = array('status' => $ret);
2128 $data = api_rss_extra($a, $data, $user_info);
2131 return api_format_data("status", $type, $data);
2134 /// @TODO move to top of file or somwhere better
2135 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2136 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2138 function api_favorites($type) {
2143 if (api_user() === false) {
2144 throw new ForbiddenException();
2147 $called_api = array();
2149 $user_info = api_get_user($a);
2151 // in friendica starred item are private
2152 // return favorites only for self
2153 logger('api_favorites: self:' . $user_info['self']);
2155 if ($user_info['self'] == 0) {
2161 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2162 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2163 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2164 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2169 $start = $page*$count;
2172 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2175 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2176 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2177 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2178 `contact`.`id` AS `cid`
2179 FROM `item`, `contact`
2180 WHERE `item`.`uid` = %d
2181 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2182 AND `item`.`starred` = 1
2183 AND `contact`.`id` = `item`.`contact-id`
2184 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2187 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2190 intval($start), intval($count)
2193 $ret = api_format_items($r,$user_info, false, $type);
2197 $data = array('status' => $ret);
2201 $data = api_rss_extra($a, $data, $user_info);
2204 return api_format_data("statuses", $type, $data);
2207 /// @TODO move to top of file or somwhere better
2208 api_register_func('api/favorites','api_favorites', true);
2210 function api_format_messages($item, $recipient, $sender) {
2211 // standard meta information
2213 'id' => $item['id'],
2214 'sender_id' => $sender['id'] ,
2216 'recipient_id' => $recipient['id'],
2217 'created_at' => api_date($item['created']),
2218 'sender_screen_name' => $sender['screen_name'],
2219 'recipient_screen_name' => $recipient['screen_name'],
2220 'sender' => $sender,
2221 'recipient' => $recipient,
2223 'friendica_seen' => $item['seen'],
2224 'friendica_parent_uri' => $item['parent-uri'],
2227 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2228 unset($ret["sender"]["uid"]);
2229 unset($ret["sender"]["self"]);
2230 unset($ret["recipient"]["uid"]);
2231 unset($ret["recipient"]["self"]);
2233 //don't send title to regular StatusNET requests to avoid confusing these apps
2234 if (x($_GET, 'getText')) {
2235 $ret['title'] = $item['title'] ;
2236 if ($_GET['getText'] == 'html') {
2237 $ret['text'] = bbcode($item['body'], false, false);
2238 } elseif ($_GET['getText'] == 'plain') {
2239 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2240 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2243 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2245 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2246 unset($ret['sender']);
2247 unset($ret['recipient']);
2253 function api_convert_item($item) {
2254 $body = $item['body'];
2255 $attachments = api_get_attachments($body);
2257 // Workaround for ostatus messages where the title is identically to the body
2258 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2259 $statusbody = trim(html2plain($html, 0));
2261 // handle data: images
2262 $statusbody = api_format_items_embeded_images($item,$statusbody);
2264 $statustitle = trim($item['title']);
2266 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2267 $statustext = trim($statusbody);
2269 $statustext = trim($statustitle."\n\n".$statusbody);
2272 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2273 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2276 $statushtml = trim(bbcode($body, false, false));
2278 $search = array("<br>", "<blockquote>", "</blockquote>",
2279 "<h1>", "</h1>", "<h2>", "</h2>",
2280 "<h3>", "</h3>", "<h4>", "</h4>",
2281 "<h5>", "</h5>", "<h6>", "</h6>");
2282 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2283 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2284 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2285 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2286 $statushtml = str_replace($search, $replace, $statushtml);
2288 if ($item['title'] != "") {
2289 $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml;
2292 // feeds without body should contain the link
2293 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2294 $statushtml .= bbcode($item['plink']);
2297 $entities = api_get_entitities($statustext, $body);
2300 "text" => $statustext,
2301 "html" => $statushtml,
2302 "attachments" => $attachments,
2303 "entities" => $entities
2307 function api_get_attachments(&$body) {
2310 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2312 $URLSearchString = "^\[\]";
2313 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2319 $attachments = array();
2321 foreach ($images[1] AS $image) {
2322 $imagedata = get_photo_info($image);
2325 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2329 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2330 foreach ($images[0] AS $orig) {
2331 $body = str_replace($orig, "", $body);
2335 return $attachments;
2338 function api_get_entitities(&$text, $bbcode) {
2341 * Links at the first character of the post
2346 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2348 if ($include_entities != "true") {
2350 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2352 foreach ($images[1] AS $image) {
2353 $replace = proxy_url($image);
2354 $text = str_replace($image, $replace, $text);
2359 $bbcode = bb_CleanPictureLinks($bbcode);
2361 // Change pure links in text to bbcode uris
2362 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2364 $entities = array();
2365 $entities["hashtags"] = array();
2366 $entities["symbols"] = array();
2367 $entities["urls"] = array();
2368 $entities["user_mentions"] = array();
2370 $URLSearchString = "^\[\]";
2372 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2374 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2375 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2376 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2378 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2379 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2380 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2382 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2383 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2384 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2386 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2388 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2389 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2391 $ordered_urls = array();
2392 foreach ($urls[1] AS $id => $url) {
2393 //$start = strpos($text, $url, $offset);
2394 $start = iconv_strpos($text, $url, 0, "UTF-8");
2395 if (!($start === false)) {
2396 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2400 ksort($ordered_urls);
2403 //foreach ($urls[1] AS $id=>$url) {
2404 foreach ($ordered_urls AS $url) {
2405 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
2406 !strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
2407 $display_url = $url["title"];
2409 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2410 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2412 if (strlen($display_url) > 26)
2413 $display_url = substr($display_url, 0, 25)."…";
2416 //$start = strpos($text, $url, $offset);
2417 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2418 if (!($start === false)) {
2419 $entities["urls"][] = array("url" => $url["url"],
2420 "expanded_url" => $url["url"],
2421 "display_url" => $display_url,
2422 "indices" => array($start, $start+strlen($url["url"])));
2423 $offset = $start + 1;
2427 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2428 $ordered_images = array();
2429 foreach ($images[1] AS $image) {
2430 //$start = strpos($text, $url, $offset);
2431 $start = iconv_strpos($text, $image, 0, "UTF-8");
2432 if (!($start === false))
2433 $ordered_images[$start] = $image;
2435 //$entities["media"] = array();
2438 foreach ($ordered_images AS $url) {
2439 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2440 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2442 if (strlen($display_url) > 26)
2443 $display_url = substr($display_url, 0, 25)."…";
2445 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2446 if (!($start === false)) {
2447 $image = get_photo_info($url);
2449 // If image cache is activated, then use the following sizes:
2450 // thumb (150), small (340), medium (600) and large (1024)
2451 if (!get_config("system", "proxy_disabled")) {
2452 $media_url = proxy_url($url);
2455 $scale = scale_image($image[0], $image[1], 150);
2456 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2458 if (($image[0] > 150) || ($image[1] > 150)) {
2459 $scale = scale_image($image[0], $image[1], 340);
2460 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2463 $scale = scale_image($image[0], $image[1], 600);
2464 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2466 if (($image[0] > 600) || ($image[1] > 600)) {
2467 $scale = scale_image($image[0], $image[1], 1024);
2468 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2472 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2475 $entities["media"][] = array(
2477 "id_str" => (string)$start+1,
2478 "indices" => array($start, $start+strlen($url)),
2479 "media_url" => normalise_link($media_url),
2480 "media_url_https" => $media_url,
2482 "display_url" => $display_url,
2483 "expanded_url" => $url,
2487 $offset = $start + 1;
2493 function api_format_items_embeded_images(&$item, $text) {
2494 $text = preg_replace_callback(
2495 "|data:image/([^;]+)[^=]+=*|m",
2496 function($match) use ($item) {
2497 return App::get_baseurl()."/display/".$item['guid'];
2505 * @brief return <a href='url'>name</a> as array
2507 * @param string $txt
2512 function api_contactlink_to_array($txt) {
2514 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2515 if ($r && count($match)==3) {
2517 'name' => $match[2],
2531 * @brief return likes, dislikes and attend status for item
2533 * @param array $item
2535 * likes => int count
2536 * dislikes => int count
2538 function api_format_items_activities(&$item, $type = "json") {
2542 $activities = array(
2544 'dislike' => array(),
2545 'attendyes' => array(),
2546 'attendno' => array(),
2547 'attendmaybe' => array(),
2550 $items = q('SELECT * FROM item
2551 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2552 intval($item['uid']),
2553 dbesc($item['uri']));
2555 foreach ($items as $i) {
2556 // not used as result should be structured like other user data
2557 //builtin_activity_puller($i, $activities);
2559 // get user data and add it to the array of the activity
2560 $user = api_get_user($a, $i['author-link']);
2561 switch ($i['verb']) {
2563 $activities['like'][] = $user;
2565 case ACTIVITY_DISLIKE:
2566 $activities['dislike'][] = $user;
2568 case ACTIVITY_ATTEND:
2569 $activities['attendyes'][] = $user;
2571 case ACTIVITY_ATTENDNO:
2572 $activities['attendno'][] = $user;
2574 case ACTIVITY_ATTENDMAYBE:
2575 $activities['attendmaybe'][] = $user;
2582 if ($type == "xml") {
2583 $xml_activities = array();
2584 foreach ($activities as $k => $v) {
2585 // change xml element from "like" to "friendica:like"
2586 $xml_activities["friendica:".$k] = $v;
2587 // add user data into xml output
2589 foreach ($v as $user)
2590 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2592 $activities = $xml_activities;
2601 * @brief return data from profiles
2603 * @param array $profile array containing data from db table 'profile'
2604 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2607 function api_format_items_profiles(&$profile = null, $type = "json") {
2608 if ($profile != null) {
2609 $profile = array('profile_id' => $profile['id'],
2610 'profile_name' => $profile['profile-name'],
2611 'is_default' => $profile['is-default'] ? true : false,
2612 'hide_friends'=> $profile['hide-friends'] ? true : false,
2613 'profile_photo' => $profile['photo'],
2614 'profile_thumb' => $profile['thumb'],
2615 'publish' => $profile['publish'] ? true : false,
2616 'net_publish' => $profile['net-publish'] ? true : false,
2617 'description' => $profile['pdesc'],
2618 'date_of_birth' => $profile['dob'],
2619 'address' => $profile['address'],
2620 'city' => $profile['locality'],
2621 'region' => $profile['region'],
2622 'postal_code' => $profile['postal-code'],
2623 'country' => $profile['country-name'],
2624 'hometown' => $profile['hometown'],
2625 'gender' => $profile['gender'],
2626 'marital' => $profile['marital'],
2627 'marital_with' => $profile['with'],
2628 'marital_since' => $profile['howlong'],
2629 'sexual' => $profile['sexual'],
2630 'politic' => $profile['politic'],
2631 'religion' => $profile['religion'],
2632 'public_keywords' => $profile['pub_keywords'],
2633 'private_keywords' => $profile['prv_keywords'],
2634 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2635 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2636 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2637 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2638 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2639 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2640 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2641 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2642 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2643 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2644 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2645 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2646 'homepage' => $profile['homepage'],
2653 * @brief format items to be returned by api
2655 * @param array $r array of items
2656 * @param array $user_info
2657 * @param bool $filter_user filter items by $user_info
2659 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2665 foreach ($r as $item) {
2667 localize_item($item);
2668 list($status_user, $owner_user) = api_item_get_user($a, $item);
2670 // Look if the posts are matching if they should be filtered by user id
2671 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2675 $in_reply_to = api_in_reply_to($item);
2677 $converted = api_convert_item($item);
2679 if ($type == "xml") {
2680 $geo = "georss:point";
2686 'text' => $converted["text"],
2687 'truncated' => False,
2688 'created_at'=> api_date($item['created']),
2689 'in_reply_to_status_id' => $in_reply_to['status_id'],
2690 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2691 'source' => (($item['app']) ? $item['app'] : 'web'),
2692 'id' => intval($item['id']),
2693 'id_str' => (string) intval($item['id']),
2694 'in_reply_to_user_id' => $in_reply_to['user_id'],
2695 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2696 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2698 'favorited' => $item['starred'] ? true : false,
2699 'user' => $status_user ,
2700 'friendica_owner' => $owner_user,
2701 //'entities' => NULL,
2702 'statusnet_html' => $converted["html"],
2703 'statusnet_conversation_id' => $item['parent'],
2704 'friendica_activities' => api_format_items_activities($item, $type),
2707 if (count($converted["attachments"]) > 0) {
2708 $status["attachments"] = $converted["attachments"];
2711 if (count($converted["entities"]) > 0) {
2712 $status["entities"] = $converted["entities"];
2715 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2716 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2717 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2718 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2722 // Retweets are only valid for top postings
2723 // It doesn't work reliable with the link if its a feed
2724 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2726 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2729 if ($item["id"] == $item["parent"]) {
2730 $retweeted_item = api_share_as_retweet($item);
2731 if ($retweeted_item !== false) {
2732 $retweeted_status = $status;
2734 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2735 } catch( BadRequestException $e ) {
2736 // user not found. should be found?
2737 /// @todo check if the user should be always found
2738 $retweeted_status["user"] = array();
2741 $rt_converted = api_convert_item($retweeted_item);
2743 $retweeted_status['text'] = $rt_converted["text"];
2744 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2745 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2746 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2747 $status['retweeted_status'] = $retweeted_status;
2751 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2752 unset($status["user"]["uid"]);
2753 unset($status["user"]["self"]);
2755 if ($item["coord"] != "") {
2756 $coords = explode(' ',$item["coord"]);
2757 if (count($coords) == 2) {
2758 if ($type == "json")
2759 $status["geo"] = array('type' => 'Point',
2760 'coordinates' => array((float) $coords[0],
2761 (float) $coords[1]));
2762 else // Not sure if this is the official format - if someone founds a documentation we can check
2763 $status["georss:point"] = $item["coord"];
2771 function api_account_rate_limit_status($type) {
2773 if ($type == "xml") {
2775 'remaining-hits' => '150',
2776 '@attributes' => array("type" => "integer"),
2777 'hourly-limit' => '150',
2778 '@attributes2' => array("type" => "integer"),
2779 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2780 '@attributes3' => array("type" => "datetime"),
2781 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2782 '@attributes4' => array("type" => "integer"),
2786 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2787 'remaining_hits' => '150',
2788 'hourly_limit' => '150',
2789 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2793 return api_format_data('hash', $type, array('hash' => $hash));
2796 /// @TODO move to top of file or somwhere better
2797 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2799 function api_help_test($type) {
2800 if ($type == 'xml') {
2806 return api_format_data('ok', $type, array("ok" => $ok));
2809 /// @TODO move to top of file or somwhere better
2810 api_register_func('api/help/test','api_help_test', false);
2812 function api_lists($type) {
2814 /// @TODO $ret is not filled here?
2815 return api_format_data('lists', $type, array("lists_list" => $ret));
2818 /// @TODO move to top of file or somwhere better
2819 api_register_func('api/lists','api_lists',true);
2821 function api_lists_list($type) {
2823 /// @TODO $ret is not filled here?
2824 return api_format_data('lists', $type, array("lists_list" => $ret));
2827 /// @TODO move to top of file or somwhere better
2828 api_register_func('api/lists/list','api_lists_list',true);
2831 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2832 * This function is deprecated by Twitter
2833 * returns: json, xml
2835 function api_statuses_f($type, $qtype) {
2839 if (api_user() === false) {
2840 throw new ForbiddenException();
2843 $user_info = api_get_user($a);
2845 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2846 /* this is to stop Hotot to load friends multiple times
2847 * I'm not sure if I'm missing return something or
2848 * is a bug in hotot. Workaround, meantime
2852 return array('$users' => $ret);*/
2856 if ($qtype == 'friends') {
2857 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2859 if ($qtype == 'followers') {
2860 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2863 // friends and followers only for self
2864 if ($user_info['self'] == 0) {
2865 $sql_extra = " AND false ";
2868 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra",
2873 foreach ($r as $cid) {
2874 $user = api_get_user($a, $cid['nurl']);
2875 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2876 unset($user["uid"]);
2877 unset($user["self"]);
2884 return array('user' => $ret);
2888 function api_statuses_friends($type) {
2889 $data = api_statuses_f($type, "friends");
2890 if ($data === false) {
2893 return api_format_data("users", $type, $data);
2896 function api_statuses_followers($type) {
2897 $data = api_statuses_f($type, "followers");
2898 if ($data === false) {
2901 return api_format_data("users", $type, $data);
2904 /// @TODO move to top of file or somewhere better
2905 api_register_func('api/statuses/friends','api_statuses_friends',true);
2906 api_register_func('api/statuses/followers','api_statuses_followers',true);
2908 function api_statusnet_config($type) {
2912 $name = $a->config['sitename'];
2913 $server = $a->get_hostname();
2914 $logo = App::get_baseurl() . '/images/friendica-64.png';
2915 $email = $a->config['admin_email'];
2916 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2917 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2918 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2919 if ($a->config['api_import_size']) {
2920 $texlimit = string($a->config['api_import_size']);
2922 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2923 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',App::get_baseurl()) : '');
2926 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2927 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2928 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2929 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2930 'shorturllength' => '30',
2931 'friendica' => array(
2932 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2933 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2934 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2935 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2940 return api_format_data('config', $type, array('config' => $config));
2944 /// @TODO move to top of file or somewhere better
2945 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2946 api_register_func('api/statusnet/config','api_statusnet_config', false);
2948 function api_statusnet_version($type) {
2950 $fake_statusnet_version = "0.9.7";
2952 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2955 /// @TODO move to top of file or somewhere better
2956 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2957 api_register_func('api/statusnet/version','api_statusnet_version', false);
2960 * @todo use api_format_data() to return data
2962 function api_ff_ids($type,$qtype) {
2967 throw new ForbiddenException();
2970 $user_info = api_get_user($a);
2972 if ($qtype == 'friends') {
2973 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2975 if ($qtype == 'followers') {
2976 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2979 if (!$user_info["self"]) {
2980 $sql_extra = " AND false ";
2983 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
2985 $r = q("SELECT `pcontact`.`id` FROM `contact`
2986 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2987 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2991 if (!dbm::is_result($r)) {
2996 foreach ($r as $rr) {
2997 if ($stringify_ids) {
3000 $ids[] = intval($rr['id']);
3004 return api_format_data("ids", $type, array('id' => $ids));
3007 function api_friends_ids($type) {
3008 return api_ff_ids($type,'friends');
3011 function api_followers_ids($type) {
3012 return api_ff_ids($type,'followers');
3015 /// @TODO move to top of file or somewhere better
3016 api_register_func('api/friends/ids','api_friends_ids',true);
3017 api_register_func('api/followers/ids','api_followers_ids',true);
3019 function api_direct_messages_new($type) {
3023 if (api_user() === false) throw new ForbiddenException();
3025 if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
3027 $sender = api_get_user($a);
3029 if ($_POST['screen_name']) {
3030 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3032 dbesc($_POST['screen_name']));
3034 // Selecting the id by priority, friendica first
3035 api_best_nickname($r);
3037 $recipient = api_get_user($a, $r[0]['nurl']);
3039 $recipient = api_get_user($a, $_POST['user_id']);
3044 if (x($_REQUEST, 'replyto')) {
3045 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3047 intval($_REQUEST['replyto']));
3048 $replyto = $r[0]['parent-uri'];
3049 $sub = $r[0]['title'];
3051 if (x($_REQUEST, 'title')) {
3052 $sub = $_REQUEST['title'];
3054 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3058 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3061 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3062 $ret = api_format_messages($r[0], $recipient, $sender);
3064 $ret = array("error"=>$id);
3067 $data = array('direct_message'=>$ret);
3072 $data = api_rss_extra($a, $data, $user_info);
3075 return api_format_data("direct-messages", $type, $data);
3079 /// @TODO move to top of file or somewhere better
3080 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3083 * @brief delete a direct_message from mail table through api
3085 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3088 function api_direct_messages_destroy($type) {
3091 if (api_user() === false) {
3092 throw new ForbiddenException();
3096 $user_info = api_get_user($a);
3098 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3100 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3101 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3102 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3104 $uid = $user_info['uid'];
3105 // error if no id or parenturi specified (for clients posting parent-uri as well)
3106 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3107 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3108 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3111 // BadRequestException if no id specified (for clients using Twitter API)
3113 throw new BadRequestException('Message id not specified');
3116 // add parent-uri to sql command if specified by calling app
3117 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3119 // get data of the specified message id
3120 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3124 // error message if specified id is not in database
3125 if (!dbm::is_result($r)) {
3126 if ($verbose == "true") {
3127 $answer = array('result' => 'error', 'message' => 'message id not in database');
3128 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3130 /// @todo BadRequestException ok for Twitter API clients?
3131 throw new BadRequestException('message id not in database');
3135 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3139 if ($verbose == "true") {
3142 $answer = array('result' => 'ok', 'message' => 'message deleted');
3143 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3145 $answer = array('result' => 'error', 'message' => 'unknown error');
3146 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3149 /// @todo return JSON data like Twitter API not yet implemented
3153 /// @TODO move to top of file or somewhere better
3154 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3156 function api_direct_messages_box($type, $box, $verbose) {
3160 if (api_user() === false) {
3161 throw new ForbiddenException();
3165 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3166 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3171 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3172 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3174 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3175 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3178 unset($_REQUEST["user_id"]);
3179 unset($_GET["user_id"]);
3181 unset($_REQUEST["screen_name"]);
3182 unset($_GET["screen_name"]);
3184 $user_info = api_get_user($a);
3185 $profile_url = $user_info["url"];
3188 $start = $page * $count;
3191 if ($box=="sentbox") {
3192 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3193 } elseif ($box == "conversation") {
3194 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3195 } elseif ($box == "all") {
3196 $sql_extra = "true";
3197 } elseif ($box == "inbox") {
3198 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3202 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3205 if ($user_id != "") {
3206 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3207 } elseif ($screen_name !="") {
3208 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3211 $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",
3214 intval($start), intval($count)
3216 if ($verbose == "true" && !dbm::is_result($r)) {
3217 $answer = array('result' => 'error', 'message' => 'no mails available');
3218 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3222 foreach ($r as $item) {
3223 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3224 $recipient = $user_info;
3225 $sender = api_get_user($a,normalise_link($item['contact-url']));
3226 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3227 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3228 $sender = $user_info;
3231 $ret[] = api_format_messages($item, $recipient, $sender);
3235 $data = array('direct_message' => $ret);
3239 $data = api_rss_extra($a, $data, $user_info);
3242 return api_format_data("direct-messages", $type, $data);
3246 function api_direct_messages_sentbox($type) {
3247 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3248 return api_direct_messages_box($type, "sentbox", $verbose);
3251 function api_direct_messages_inbox($type) {
3252 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3253 return api_direct_messages_box($type, "inbox", $verbose);
3256 function api_direct_messages_all($type) {
3257 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3258 return api_direct_messages_box($type, "all", $verbose);
3261 function api_direct_messages_conversation($type) {
3262 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3263 return api_direct_messages_box($type, "conversation", $verbose);
3266 /// @TODO move to top of file or somewhere better
3267 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3268 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3269 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3270 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3272 function api_oauth_request_token($type) {
3274 $oauth = new FKOAuth1();
3275 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3276 } catch (Exception $e) {
3277 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3284 function api_oauth_access_token($type) {
3286 $oauth = new FKOAuth1();
3287 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3288 } catch (Exception $e) {
3289 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3295 /// @TODO move to top of file or somewhere better
3296 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3297 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3301 * @brief delete a complete photoalbum with all containing photos from database through api
3303 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3306 function api_fr_photoalbum_delete($type) {
3307 if (api_user() === false) {
3308 throw new ForbiddenException();
3311 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3313 // we do not allow calls without album string
3315 throw new BadRequestException("no albumname specified");
3317 // check if album is existing
3318 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3321 if (!dbm::is_result($r))
3322 throw new BadRequestException("album not available");
3324 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3325 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3326 foreach ($r as $rr) {
3327 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3328 intval(local_user()),
3329 dbesc($rr['resource-id'])
3332 if (!dbm::is_result($photo_item)) {
3333 throw new InternalServerErrorException("problem with deleting items occured");
3335 drop_item($photo_item[0]['id'],false);
3338 // now let's delete all photos from the album
3339 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3343 // return success of deletion or error message
3345 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3346 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3348 throw new InternalServerErrorException("unknown error - deleting from database failed");
3354 * @brief update the name of the album for all photos of an album
3356 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3359 function api_fr_photoalbum_update($type) {
3360 if (api_user() === false) {
3361 throw new ForbiddenException();
3364 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3365 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3367 // we do not allow calls without album string
3369 throw new BadRequestException("no albumname specified");
3371 if ($album_new == "") {
3372 throw new BadRequestException("no new albumname specified");
3374 // check if album is existing
3375 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3378 if (!dbm::is_result($r)) {
3379 throw new BadRequestException("album not available");
3381 // now let's update all photos to the albumname
3382 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3387 // return success of updating or error message
3389 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3390 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3392 throw new InternalServerErrorException("unknown error - updating in database failed");
3398 * @brief list all photos of the authenticated user
3400 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3403 function api_fr_photos_list($type) {
3404 if (api_user() === false) {
3405 throw new ForbiddenException();
3407 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3408 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3409 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3410 intval(local_user())
3413 'image/jpeg' => 'jpg',
3414 'image/png' => 'png',
3415 'image/gif' => 'gif'
3417 $data = array('photo'=>array());
3418 if (dbm::is_result($r)) {
3419 foreach ($r as $rr) {
3421 $photo['id'] = $rr['resource-id'];
3422 $photo['album'] = $rr['album'];
3423 $photo['filename'] = $rr['filename'];
3424 $photo['type'] = $rr['type'];
3425 $thumb = App::get_baseurl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3426 $photo['created'] = $rr['created'];
3427 $photo['edited'] = $rr['edited'];
3428 $photo['desc'] = $rr['desc'];
3430 if ($type == "xml") {
3431 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3433 $photo['thumb'] = $thumb;
3434 $data['photo'][] = $photo;
3438 return api_format_data("photos", $type, $data);
3442 * @brief upload a new photo or change an existing photo
3444 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3447 function api_fr_photo_create_update($type) {
3448 if (api_user() === false) {
3449 throw new ForbiddenException();
3452 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3453 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3454 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3455 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3456 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3457 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3458 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3459 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3460 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3462 // do several checks on input parameters
3463 // we do not allow calls without album string
3464 if ($album == null) {
3465 throw new BadRequestException("no albumname specified");
3467 // if photo_id == null --> we are uploading a new photo
3468 if ($photo_id == null) {
3471 // error if no media posted in create-mode
3472 if (!x($_FILES,'media')) {
3474 throw new BadRequestException("no media data submitted");
3477 // album_new will be ignored in create-mode
3482 // check if photo is existing in database
3483 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3487 if (!dbm::is_result($r)) {
3488 throw new BadRequestException("photo not available");
3492 // checks on acl strings provided by clients
3493 $acl_input_error = false;
3494 $acl_input_error |= check_acl_input($allow_cid);
3495 $acl_input_error |= check_acl_input($deny_cid);
3496 $acl_input_error |= check_acl_input($allow_gid);
3497 $acl_input_error |= check_acl_input($deny_gid);
3498 if ($acl_input_error) {
3499 throw new BadRequestException("acl data invalid");
3501 // now let's upload the new media in create-mode
3502 if ($mode == "create") {
3503 $media = $_FILES['media'];
3504 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3506 // return success of updating or error message
3507 if (!is_null($data)) {
3508 return api_format_data("photo_create", $type, $data);
3510 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3514 // now let's do the changes in update-mode
3515 if ($mode == "update") {
3518 if (!is_null($desc)) {
3519 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3522 if (!is_null($album_new)) {
3523 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3526 if (!is_null($allow_cid)) {
3527 $allow_cid = trim($allow_cid);
3528 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3531 if (!is_null($deny_cid)) {
3532 $deny_cid = trim($deny_cid);
3533 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3536 if (!is_null($allow_gid)) {
3537 $allow_gid = trim($allow_gid);
3538 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3541 if (!is_null($deny_gid)) {
3542 $deny_gid = trim($deny_gid);
3543 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3547 if ($sql_extra != "") {
3548 $nothingtodo = false;
3549 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3551 datetime_convert(), // update edited timestamp
3556 $nothingtodo = true;
3559 if (x($_FILES,'media')) {
3560 $nothingtodo = false;
3561 $media = $_FILES['media'];
3562 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3563 if (!is_null($data)) {
3564 return api_format_data("photo_update", $type, $data);
3568 // return success of updating or error message
3570 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3571 return api_format_data("photo_update", $type, array('$result' => $answer));
3574 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3575 return api_format_data("photo_update", $type, array('$result' => $answer));
3577 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3580 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3585 * @brief delete a single photo from the database through api
3587 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3590 function api_fr_photo_delete($type) {
3591 if (api_user() === false) {
3592 throw new ForbiddenException();
3595 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3597 // do several checks on input parameters
3598 // we do not allow calls without photo id
3599 if ($photo_id == null) {
3600 throw new BadRequestException("no photo_id specified");
3602 // check if photo is existing in database
3603 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3607 if (!dbm::is_result($r)) {
3608 throw new BadRequestException("photo not available");
3610 // now we can perform on the deletion of the photo
3611 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3615 // return success of deletion or error message
3617 // retrieve the id of the parent element (the photo element)
3618 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3619 intval(local_user()),
3623 if (!dbm::is_result($photo_item)) {
3624 throw new InternalServerErrorException("problem with deleting items occured");
3626 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3627 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3628 drop_item($photo_item[0]['id'], false);
3630 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3631 return api_format_data("photo_delete", $type, array('$result' => $answer));
3633 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3639 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3641 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3644 function api_fr_photo_detail($type) {
3645 if (api_user() === false) {
3646 throw new ForbiddenException();
3648 if (!x($_REQUEST, 'photo_id')) {
3649 throw new BadRequestException("No photo id.");
3652 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3653 $photo_id = $_REQUEST['photo_id'];
3655 // prepare json/xml output with data from database for the requested photo
3656 $data = prepare_photo_data($type, $scale, $photo_id);
3658 return api_format_data("photo_detail", $type, $data);
3663 * @brief updates the profile image for the user (either a specified profile or the default profile)
3665 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3668 function api_account_update_profile_image($type) {
3669 if (api_user() === false) {
3670 throw new ForbiddenException();
3673 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3675 // error if image data is missing
3676 if (!x($_FILES, 'image')) {
3677 throw new BadRequestException("no media data submitted");
3680 // check if specified profile id is valid
3681 if ($profileid != 0) {
3682 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3684 intval($profileid));
3685 // error message if specified profile id is not in database
3686 if (!dbm::is_result($r)) {
3687 throw new BadRequestException("profile_id not available");
3689 $is_default_profile = $r['profile'];
3691 $is_default_profile = 1;
3694 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3696 if (x($_FILES, 'image')) {
3697 $media = $_FILES['image'];
3698 } elseif (x($_FILES, 'media')) {
3699 $media = $_FILES['media'];
3701 // save new profile image
3702 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3705 if (is_array($media['type'])) {
3706 $filetype = $media['type'][0];
3708 $filetype = $media['type'];
3710 if ($filetype == "image/jpeg") {
3712 } elseif ($filetype == "image/png") {
3715 // change specified profile or all profiles to the new resource-id
3716 if ($is_default_profile) {
3717 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3718 dbesc($data['photo']['id']),
3719 intval(local_user())
3722 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3723 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3724 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3725 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3726 intval(local_user())
3729 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3730 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3731 dbesc(App::get_baseurl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3732 intval($_REQUEST['profile']),
3733 intval(local_user())
3737 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3738 // so that browsers will do a cache update unconditionally
3740 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3741 dbesc(datetime_convert()),
3742 intval(local_user())
3745 // Update global directory in background
3746 //$user = api_get_user(get_app());
3747 $url = App::get_baseurl() . '/profile/' . get_app()->user['nickname'];
3748 if ($url && strlen(get_config('system', 'directory'))) {
3749 proc_run(PRIORITY_LOW, "include/directory.php", $url);
3752 proc_run(PRIORITY_LOW, 'include/profile_update.php', api_user());
3754 // output for client
3756 return api_account_verify_credentials($type);
3758 // SaveMediaToDatabase failed for some reason
3759 throw new InternalServerErrorException("image upload failed");
3763 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3764 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3765 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3766 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3767 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3768 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3769 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3770 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3771 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3774 function check_acl_input($acl_string) {
3775 if ($acl_string == null || $acl_string == " ") {
3778 $contact_not_found = false;
3780 // split <x><y><z> into array of cid's
3781 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3783 // check for each cid if it is available on server
3784 $cid_array = $array[0];
3785 foreach ($cid_array as $cid) {
3786 $cid = str_replace("<", "", $cid);
3787 $cid = str_replace(">", "", $cid);
3788 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3790 intval(api_user()));
3791 $contact_not_found |= !dbm::is_result($contact);
3793 return $contact_not_found;
3796 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) {
3803 if (is_array($media)) {
3804 if (is_array($media['tmp_name'])) {
3805 $src = $media['tmp_name'][0];
3807 $src = $media['tmp_name'];
3809 if (is_array($media['name'])) {
3810 $filename = basename($media['name'][0]);
3812 $filename = basename($media['name']);
3814 if (is_array($media['size'])) {
3815 $filesize = intval($media['size'][0]);
3817 $filesize = intval($media['size']);
3819 if (is_array($media['type'])) {
3820 $filetype = $media['type'][0];
3822 $filetype = $media['type'];
3826 if ($filetype == "") {
3827 $filetype=guess_image_type($filename);
3829 $imagedata = getimagesize($src);
3831 $filetype = $imagedata['mime'];
3833 logger("File upload src: " . $src . " - filename: " . $filename .
3834 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3836 // check if there was a php upload error
3837 if ($filesize == 0 && $media['error'] == 1) {
3838 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3840 // check against max upload size within Friendica instance
3841 $maximagesize = get_config('system', 'maximagesize');
3842 if (($maximagesize) && ($filesize > $maximagesize)) {
3843 $formattedBytes = formatBytes($maximagesize);
3844 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3847 // create Photo instance with the data of the image
3848 $imagedata = @file_get_contents($src);
3849 $ph = new Photo($imagedata, $filetype);
3850 if (! $ph->is_valid()) {
3851 throw new InternalServerErrorException("unable to process image data");
3854 // check orientation of image
3858 // check max length of images on server
3859 $max_length = get_config('system', 'max_image_length');
3860 if (! $max_length) {
3861 $max_length = MAX_IMAGE_LENGTH;
3863 if ($max_length > 0) {
3864 $ph->scaleImage($max_length);
3865 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3867 $width = $ph->getWidth();
3868 $height = $ph->getHeight();
3870 // create a new resource-id if not already provided
3871 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3873 if ($mediatype == "photo") {
3874 // upload normal image (scales 0, 1, 2)
3875 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3877 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3879 logger("photo upload: image upload with scale 0 (original size) failed");
3881 if($width > 640 || $height > 640) {
3882 $ph->scaleImage(640);
3883 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3885 logger("photo upload: image upload with scale 1 (640x640) failed");
3889 if ($width > 320 || $height > 320) {
3890 $ph->scaleImage(320);
3891 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3893 logger("photo upload: image upload with scale 2 (320x320) failed");
3896 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3897 } elseif ($mediatype == "profileimage") {
3898 // upload profile image (scales 4, 5, 6)
3899 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3901 if ($width > 175 || $height > 175) {
3902 $ph->scaleImage(175);
3903 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3905 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3909 if ($width > 80 || $height > 80) {
3910 $ph->scaleImage(80);
3911 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3913 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3917 if ($width > 48 || $height > 48) {
3918 $ph->scaleImage(48);
3919 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3921 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3925 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3929 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3930 if ($photo_id == null && $mediatype == "photo") {
3931 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3933 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3934 return prepare_photo_data($type, false, $hash);
3936 throw new InternalServerErrorException("image upload failed");
3940 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3941 // get data about the api authenticated user
3942 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3943 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3946 $arr['guid'] = get_guid(32);
3947 $arr['uid'] = intval(api_user());
3949 $arr['parent-uri'] = $uri;
3950 $arr['type'] = 'photo';
3952 $arr['resource-id'] = $hash;
3953 $arr['contact-id'] = $owner_record[0]['id'];
3954 $arr['owner-name'] = $owner_record[0]['name'];
3955 $arr['owner-link'] = $owner_record[0]['url'];
3956 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3957 $arr['author-name'] = $owner_record[0]['name'];
3958 $arr['author-link'] = $owner_record[0]['url'];
3959 $arr['author-avatar'] = $owner_record[0]['thumb'];
3961 $arr['allow_cid'] = $allow_cid;
3962 $arr['allow_gid'] = $allow_gid;
3963 $arr['deny_cid'] = $deny_cid;
3964 $arr['deny_gid'] = $deny_gid;
3965 $arr['last-child'] = 1;
3966 $arr['visible'] = $visibility;
3970 'image/jpeg' => 'jpg',
3971 'image/png' => 'png',
3972 'image/gif' => 'gif'
3975 // adds link to the thumbnail scale photo
3976 $arr['body'] = '[url=' . App::get_baseurl() . '/photos/' . $owner_record[0]['name'] . '/image/' . $hash . ']'
3977 . '[img]' . App::get_baseurl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3980 // do the magic for storing the item in the database and trigger the federation to other contacts
3984 function prepare_photo_data($type, $scale, $photo_id) {
3985 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3986 $data_sql = ($scale === false ? "" : "data, ");
3988 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3989 // clients needs to convert this in their way for further processing
3990 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3991 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3992 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3993 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
3995 intval(local_user()),
4001 'image/jpeg' => 'jpg',
4002 'image/png' => 'png',
4003 'image/gif' => 'gif'
4006 // prepare output data for photo
4007 if (dbm::is_result($r)) {
4008 $data = array('photo' => $r[0]);
4009 $data['photo']['id'] = $data['photo']['resource-id'];
4010 if ($scale !== false) {
4011 $data['photo']['data'] = base64_encode($data['photo']['data']);
4013 unset($data['photo']['datasize']); //needed only with scale param
4015 if ($type == "xml") {
4016 $data['photo']['links'] = array();
4017 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4018 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4020 "href" => App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4023 $data['photo']['link'] = array();
4024 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4026 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4027 $data['photo']['link'][$i] = App::get_baseurl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4031 unset($data['photo']['resource-id']);
4032 unset($data['photo']['minscale']);
4033 unset($data['photo']['maxscale']);
4036 throw new NotFoundException();
4039 // retrieve item element for getting activities (like, dislike etc.) related to photo
4040 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4041 intval(local_user()),
4044 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4046 // retrieve comments on photo
4047 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4048 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4049 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4050 `contact`.`id` AS `cid`
4052 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4053 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4054 WHERE `item`.`parent` = %d AND `item`.`visible`
4055 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4056 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4057 intval($item[0]['parent']),
4059 dbesc(ACTIVITY_POST)
4062 // prepare output of comments
4063 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4064 $comments = array();
4065 if ($type == "xml") {
4067 foreach ($commentData as $comment) {
4068 $comments[$k++ . ":comment"] = $comment;
4071 foreach ($commentData as $comment) {
4072 $comments[] = $comment;
4075 $data['photo']['friendica_comments'] = $comments;
4077 // include info if rights on photo and rights on item are mismatching
4078 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4079 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4080 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4081 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4082 $data['photo']['rights_mismatch'] = $rights_mismatch;
4089 * similar as /mod/redir.php
4090 * redirect to 'url' after dfrn auth
4092 * why this when there is mod/redir.php already?
4093 * This use api_user() and api_login()
4096 * c_url: url of remote contact to auth to
4097 * url: string, url to redirect after auth
4099 function api_friendica_remoteauth() {
4100 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4101 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4103 if ($url === '' || $c_url === '') {
4104 throw new BadRequestException("Wrong parameters.");
4107 $c_url = normalise_link($c_url);
4111 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4116 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4117 throw new BadRequestException("Unknown contact");
4122 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4124 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4125 $orig_id = $r[0]['issued-id'];
4126 $dfrn_id = '1:' . $orig_id;
4128 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4129 $orig_id = $r[0]['dfrn-id'];
4130 $dfrn_id = '0:' . $orig_id;
4133 $sec = random_string();
4135 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4136 VALUES( %d, %s, '%s', '%s', %d )",
4144 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4145 $dest = (($url) ? '&destination_url=' . $url : '');
4146 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4147 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4148 . '&type=profile&sec=' . $sec . $dest . $quiet );
4150 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4153 * @brief Return the item shared, if the item contains only the [share] tag
4155 * @param array $item Sharer item
4156 * @return array Shared item or false if not a reshare
4158 function api_share_as_retweet(&$item) {
4159 $body = trim($item["body"]);
4161 if (Diaspora::is_reshare($body, false)===false) {
4165 /// @TODO "$1" should maybe mean '$1' ?
4166 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4168 * Skip if there is no shared message in there
4169 * we already checked this in diaspora::is_reshare()
4170 * but better one more than one less...
4172 if ($body == $attributes) {
4177 // build the fake reshared item
4178 $reshared_item = $item;
4181 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4182 if ($matches[1] != "") {
4183 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4186 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4187 if ($matches[1] != "") {
4188 $author = $matches[1];
4192 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4193 if ($matches[1] != "") {
4194 $profile = $matches[1];
4197 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4198 if ($matches[1] != "") {
4199 $profile = $matches[1];
4203 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4204 if ($matches[1] != "") {
4205 $avatar = $matches[1];
4208 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4209 if ($matches[1] != "") {
4210 $avatar = $matches[1];
4214 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4215 if ($matches[1] != "") {
4216 $link = $matches[1];
4219 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4220 if ($matches[1] != "") {
4221 $link = $matches[1];
4225 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4226 if ($matches[1] != "")
4227 $posted = $matches[1];
4229 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4230 if ($matches[1] != "") {
4231 $posted = $matches[1];
4234 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4236 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4240 $reshared_item["body"] = $shared_body;
4241 $reshared_item["author-name"] = $author;
4242 $reshared_item["author-link"] = $profile;
4243 $reshared_item["author-avatar"] = $avatar;
4244 $reshared_item["plink"] = $link;
4245 $reshared_item["created"] = $posted;
4246 $reshared_item["edited"] = $posted;
4248 return $reshared_item;
4252 function api_get_nick($profile) {
4254 - remove trailing junk from profile url
4255 - pump.io check has to check the website
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"];
4268 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4269 dbesc(normalise_link($profile)));
4271 if (dbm::is_result($r)) {
4272 $nick = $r[0]["nick"];
4277 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4278 if ($friendica != $profile) {
4284 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4285 if ($diaspora != $profile) {
4291 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4292 if ($twitter != $profile) {
4299 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4300 if ($StatusnetHost != $profile) {
4301 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4302 if ($StatusnetUser != $profile) {
4303 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4304 $user = json_decode($UserData);
4306 $nick = $user->screen_name;
4312 // To-Do: look at the page if its really a pumpio site
4313 //if (!$nick == "") {
4314 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4315 // if ($pumpio != $profile)
4317 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4328 function api_in_reply_to($item) {
4329 $in_reply_to = array();
4331 $in_reply_to['status_id'] = NULL;
4332 $in_reply_to['user_id'] = NULL;
4333 $in_reply_to['status_id_str'] = NULL;
4334 $in_reply_to['user_id_str'] = NULL;
4335 $in_reply_to['screen_name'] = NULL;
4337 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4338 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4339 intval($item['uid']),
4340 dbesc($item['thr-parent']));
4342 if (dbm::is_result($r)) {
4343 $in_reply_to['status_id'] = intval($r[0]['id']);
4345 $in_reply_to['status_id'] = intval($item['parent']);
4348 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4350 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4351 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4352 WHERE `item`.`id` = %d LIMIT 1",
4353 intval($in_reply_to['status_id'])
4356 if (dbm::is_result($r)) {
4357 if ($r[0]['nick'] == "") {
4358 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4361 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4362 $in_reply_to['user_id'] = intval($r[0]['id']);
4363 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4366 // There seems to be situation, where both fields are identical:
4367 // https://github.com/friendica/friendica/issues/1010
4368 // This is a bugfix for that.
4369 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4370 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4371 $in_reply_to['status_id'] = NULL;
4372 $in_reply_to['user_id'] = NULL;
4373 $in_reply_to['status_id_str'] = NULL;
4374 $in_reply_to['user_id_str'] = NULL;
4375 $in_reply_to['screen_name'] = NULL;
4379 return $in_reply_to;
4382 function api_clean_plain_items($Text) {
4383 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4385 $Text = bb_CleanPictureLinks($Text);
4386 $URLSearchString = "^\[\]";
4388 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4390 if ($include_entities == "true") {
4391 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4394 // Simplify "attachment" element
4395 $Text = api_clean_attachments($Text);
4401 * @brief Removes most sharing information for API text export
4403 * @param string $body The original body
4405 * @return string Cleaned body
4407 function api_clean_attachments($body) {
4408 $data = get_attachment_data($body);
4415 if (isset($data["text"]))
4416 $body = $data["text"];
4418 if (($body == "") && (isset($data["title"])))
4419 $body = $data["title"];
4421 if (isset($data["url"]))
4422 $body .= "\n".$data["url"];
4424 $body .= $data["after"];
4429 function api_best_nickname(&$contacts) {
4430 $best_contact = array();
4432 if (count($contact) == 0)
4435 foreach ($contacts AS $contact)
4436 if ($contact["network"] == "") {
4437 $contact["network"] = "dfrn";
4438 $best_contact = array($contact);
4441 if (sizeof($best_contact) == 0)
4442 foreach ($contacts AS $contact)
4443 if ($contact["network"] == "dfrn")
4444 $best_contact = array($contact);
4446 if (sizeof($best_contact) == 0)
4447 foreach ($contacts AS $contact)
4448 if ($contact["network"] == "dspr")
4449 $best_contact = array($contact);
4451 if (sizeof($best_contact) == 0)
4452 foreach ($contacts AS $contact)
4453 if ($contact["network"] == "stat")
4454 $best_contact = array($contact);
4456 if (sizeof($best_contact) == 0)
4457 foreach ($contacts AS $contact)
4458 if ($contact["network"] == "pump")
4459 $best_contact = array($contact);
4461 if (sizeof($best_contact) == 0)
4462 foreach ($contacts AS $contact)
4463 if ($contact["network"] == "twit")
4464 $best_contact = array($contact);
4466 if (sizeof($best_contact) == 1)
4467 $contacts = $best_contact;
4469 $contacts = array($contacts[0]);
4472 // return all or a specified group of the user with the containing contacts
4473 function api_friendica_group_show($type) {
4477 if (api_user() === false) throw new ForbiddenException();
4480 $user_info = api_get_user($a);
4481 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4482 $uid = $user_info['uid'];
4484 // get data of the specified group id or all groups if not specified
4486 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4489 // error message if specified gid is not in database
4490 if (!dbm::is_result($r))
4491 throw new BadRequestException("gid not available");
4494 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4497 // loop through all groups and retrieve all members for adding data in the user array
4498 foreach ($r as $rr) {
4499 $members = group_get_members($rr['id']);
4502 if ($type == "xml") {
4503 $user_element = "users";
4505 foreach ($members as $member) {
4506 $user = api_get_user($a, $member['nurl']);
4507 $users[$k++.":user"] = $user;
4510 $user_element = "user";
4511 foreach ($members as $member) {
4512 $user = api_get_user($a, $member['nurl']);
4516 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4518 return api_format_data("groups", $type, array('group' => $grps));
4520 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4523 // delete the specified group of the user
4524 function api_friendica_group_delete($type) {
4528 if (api_user() === false) throw new ForbiddenException();
4531 $user_info = api_get_user($a);
4532 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4533 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4534 $uid = $user_info['uid'];
4536 // error if no gid specified
4537 if ($gid == 0 || $name == "")
4538 throw new BadRequestException('gid or name not specified');
4540 // get data of the specified group id
4541 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4544 // error message if specified gid is not in database
4545 if (!dbm::is_result($r))
4546 throw new BadRequestException('gid not available');
4548 // get data of the specified group id and group name
4549 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4553 // error message if specified gid is not in database
4554 if (!dbm::is_result($rname))
4555 throw new BadRequestException('wrong group name');
4558 $ret = group_rmv($uid, $name);
4561 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4562 return api_format_data("group_delete", $type, array('result' => $success));
4565 throw new BadRequestException('other API error');
4567 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4570 // create the specified group with the posted array of contacts
4571 function api_friendica_group_create($type) {
4575 if (api_user() === false) throw new ForbiddenException();
4578 $user_info = api_get_user($a);
4579 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4580 $uid = $user_info['uid'];
4581 $json = json_decode($_POST['json'], true);
4582 $users = $json['user'];
4584 // error if no name specified
4586 throw new BadRequestException('group name not specified');
4588 // get data of the specified group name
4589 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4592 // error message if specified group name already exists
4593 if (dbm::is_result($rname))
4594 throw new BadRequestException('group name already exists');
4596 // check if specified group name is a deleted group
4597 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4600 // error message if specified group name already exists
4601 if (dbm::is_result($rname))
4602 $reactivate_group = true;
4605 $ret = group_add($uid, $name);
4607 $gid = group_byname($uid, $name);
4609 throw new BadRequestException('other API error');
4612 $erroraddinguser = false;
4613 $errorusers = array();
4614 foreach ($users as $user) {
4615 $cid = $user['cid'];
4616 // check if user really exists as contact
4617 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4620 if (count($contact))
4621 $result = group_add_member($uid, $name, $cid, $gid);
4623 $erroraddinguser = true;
4624 $errorusers[] = $cid;
4628 // return success message incl. missing users in array
4629 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4630 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4631 return api_format_data("group_create", $type, array('result' => $success));
4633 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4636 // update the specified group with the posted array of contacts
4637 function api_friendica_group_update($type) {
4641 if (api_user() === false) throw new ForbiddenException();
4644 $user_info = api_get_user($a);
4645 $uid = $user_info['uid'];
4646 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4647 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4648 $json = json_decode($_POST['json'], true);
4649 $users = $json['user'];
4651 // error if no name specified
4653 throw new BadRequestException('group name not specified');
4655 // error if no gid specified
4657 throw new BadRequestException('gid not specified');
4660 $members = group_get_members($gid);
4661 foreach ($members as $member) {
4662 $cid = $member['id'];
4663 foreach ($users as $user) {
4664 $found = ($user['cid'] == $cid ? true : false);
4667 $ret = group_rmv_member($uid, $name, $cid);
4672 $erroraddinguser = false;
4673 $errorusers = array();
4674 foreach ($users as $user) {
4675 $cid = $user['cid'];
4676 // check if user really exists as contact
4677 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4680 if (count($contact))
4681 $result = group_add_member($uid, $name, $cid, $gid);
4683 $erroraddinguser = true;
4684 $errorusers[] = $cid;
4688 // return success message incl. missing users in array
4689 $status = ($erroraddinguser ? "missing user" : "ok");
4690 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4691 return api_format_data("group_update", $type, array('result' => $success));
4694 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4696 function api_friendica_activity($type) {
4700 if (api_user() === false) throw new ForbiddenException();
4701 $verb = strtolower($a->argv[3]);
4702 $verb = preg_replace("|\..*$|", "", $verb);
4704 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4706 $res = do_like($id, $verb);
4713 return api_format_data('ok', $type, array('ok' => $ok));
4715 throw new BadRequestException('Error adding activity');
4720 /// @TODO move to top of file or somwhere better
4721 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4722 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4723 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4724 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4725 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4726 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4727 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4728 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4729 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4730 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4733 * @brief Returns notifications
4735 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4738 function api_friendica_notification($type) {
4742 if (api_user() === false) throw new ForbiddenException();
4743 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4744 $nm = new NotificationsManager();
4746 $notes = $nm->getAll(array(), "+seen -date", 50);
4748 if ($type == "xml") {
4749 $xmlnotes = array();
4750 foreach ($notes AS $note)
4751 $xmlnotes[] = array("@attributes" => $note);
4756 return api_format_data("notes", $type, array('note' => $notes));
4760 * @brief Set notification as seen and returns associated item (if possible)
4762 * POST request with 'id' param as notification id
4764 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4767 function api_friendica_notification_seen($type) {
4771 if (api_user() === false) throw new ForbiddenException();
4772 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4774 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4776 $nm = new NotificationsManager();
4777 $note = $nm->getByID($id);
4778 if (is_null($note)) throw new BadRequestException("Invalid argument");
4780 $nm->setSeen($note);
4781 if ($note['otype']=='item') {
4782 // would be really better with an ItemsManager and $im->getByID() :-P
4783 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4784 intval($note['iid']),
4785 intval(local_user())
4788 // we found the item, return it to the user
4789 $user_info = api_get_user($a);
4790 $ret = api_format_items($r,$user_info, false, $type);
4791 $data = array('status' => $ret);
4792 return api_format_data("status", $type, $data);
4794 // the item can't be found, but we set the note as seen, so we count this as a success
4796 return api_format_data('result', $type, array('result' => "success"));
4799 /// @TODO move to top of file or somwhere better
4800 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4801 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4804 * @brief update a direct_message to seen state
4806 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4807 * @return string (success result=ok, error result=error with error message)
4809 function api_friendica_direct_messages_setseen($type) {
4811 if (api_user() === false) {
4812 throw new ForbiddenException();
4816 $user_info = api_get_user($a);
4817 $uid = $user_info['uid'];
4818 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4820 // return error if id is zero
4822 $answer = array('result' => 'error', 'message' => 'message id not specified');
4823 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4826 // get data of the specified message id
4827 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4831 // error message if specified id is not in database
4832 if (!dbm::is_result($r)) {
4833 $answer = array('result' => 'error', 'message' => 'message id not in database');
4834 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4837 // update seen indicator
4838 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4844 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4845 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4847 $answer = array('result' => 'error', 'message' => 'unknown error');
4848 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4852 /// @TODO move to top of file or somwhere better
4853 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4856 * @brief search for direct_messages containing a searchstring through api
4858 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4859 * @return string (success: success=true if found and search_result contains found messages
4860 * success=false if nothing was found, search_result='nothing found',
4861 * error: result=error with error message)
4863 function api_friendica_direct_messages_search($type) {
4866 if (api_user() === false) {
4867 throw new ForbiddenException();
4871 $user_info = api_get_user($a);
4872 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4873 $uid = $user_info['uid'];
4875 // error if no searchstring specified
4876 if ($searchstring == "") {
4877 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4878 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4881 // get data for the specified searchstring
4882 $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",
4884 dbesc('%'.$searchstring.'%')
4887 $profile_url = $user_info["url"];
4889 // message if nothing was found
4890 if (!dbm::is_result($r)) {
4891 $success = array('success' => false, 'search_results' => 'problem with query');
4892 } elseif (count($r) == 0) {
4893 $success = array('success' => false, 'search_results' => 'nothing found');
4896 foreach ($r as $item) {
4897 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4898 $recipient = $user_info;
4899 $sender = api_get_user($a,normalise_link($item['contact-url']));
4900 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4901 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4902 $sender = $user_info;
4905 $ret[] = api_format_messages($item, $recipient, $sender);
4907 $success = array('success' => true, 'search_results' => $ret);
4910 return api_format_data("direct_message_search", $type, array('$result' => $success));
4913 /// @TODO move to top of file or somwhere better
4914 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4917 * @brief return data of all the profiles a user has to the client
4919 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4922 function api_friendica_profile_show($type) {
4925 if (api_user() === false) {
4926 throw new ForbiddenException();
4930 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4932 // retrieve general information about profiles for user
4933 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4934 $directory = get_config('system', 'directory');
4936 // get data of the specified profile id or all profiles of the user if not specified
4937 if ($profileid != 0) {
4938 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4940 intval($profileid));
4942 // error message if specified gid is not in database
4943 if (!dbm::is_result($r)) {
4944 throw new BadRequestException("profile_id not available");
4947 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4948 intval(api_user()));
4950 // loop through all returned profiles and retrieve data and users
4952 foreach ($r as $rr) {
4953 $profile = api_format_items_profiles($rr, $type);
4955 // select all users from contact table, loop and prepare standard return for user data
4957 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4959 intval($rr['profile_id']));
4961 foreach ($r as $rr) {
4962 $user = api_get_user($a, $rr['nurl']);
4963 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4965 $profile['users'] = $users;
4967 // add prepared profile data to array for final return
4968 if ($type == "xml") {
4969 $profiles[$k++ . ":profile"] = $profile;
4971 $profiles[] = $profile;
4975 // return settings, authenticated user and profiles data
4976 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4978 $result = array('multi_profiles' => $multi_profiles ? true : false,
4979 'global_dir' => $directory,
4980 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4981 'profiles' => $profiles);
4982 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4984 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4987 @TODO Maybe open to implement?
4989 [pagename] => api/1.1/statuses/lookup.json
4990 [id] => 605138389168451584
4991 [include_cards] => true
4992 [cards_platform] => Android-12
4993 [include_entities] => true
4994 [include_my_retweet] => 1
4996 [include_reply_count] => true
4997 [include_descendent_reply_count] => true
5001 Not implemented by now:
5002 statuses/retweets_of_me
5007 account/update_location
5008 account/update_profile_background_image
5011 friendica/profile/update
5012 friendica/profile/create
5013 friendica/profile/delete
5015 Not implemented in status.net:
5016 statuses/retweeted_to_me
5017 statuses/retweeted_by_me
5018 direct_messages/destroy
5020 account/update_delivery_device
5021 notifications/follow