3 * @file include/api.php
4 * Friendica implementation of statusnet/twitter API
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Core\NotificationsManager;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Protocol\Diaspora;
17 require_once 'include/HTTPExceptions.php';
18 require_once 'include/bbcode.php';
19 require_once 'include/datetime.php';
20 require_once 'include/conversation.php';
21 require_once 'include/oauth.php';
22 require_once 'include/html2plain.php';
23 require_once 'mod/share.php';
24 require_once 'include/Photo.php';
25 require_once 'mod/item.php';
26 require_once 'include/security.php';
27 require_once 'include/contact_selectors.php';
28 require_once 'include/html2bbcode.php';
29 require_once 'mod/wall_upload.php';
30 require_once 'mod/proxy.php';
31 require_once 'include/message.php';
32 require_once 'include/group.php';
33 require_once 'include/like.php';
34 require_once 'include/plaintext.php';
35 require_once 'include/xml.php';
37 define('API_METHOD_ANY', '*');
38 define('API_METHOD_GET', 'GET');
39 define('API_METHOD_POST', 'POST,PUT');
40 define('API_METHOD_DELETE', 'POST,DELETE');
45 /// @TODO Fix intending
47 * @brief Auth API user
49 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
50 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
51 * into a page, and visitors will post something without noticing it).
54 if (x($_SESSION, 'allow_api')) {
62 * @brief Get source name from API client
64 * Clients can send 'source' parameter to be show in post metadata
65 * as "sent via <source>".
66 * Some clients doesn't send a source param, we support ones we know
70 * Client source name, default to "api" if unset/unknown
72 function api_source() {
73 if (requestdata('source')) {
74 return requestdata('source');
77 // Support for known clients that doesn't send a source name
78 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
82 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
88 * @brief Format date for API
90 * @param string $str Source date, as UTC
91 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
93 function api_date($str) {
94 // Wed May 23 06:01:13 +0000 2007
95 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
99 * @brief Register API endpoint
101 * Register a function to be the endpont for defined API path.
103 * @param string $path API URL path, relative to System::baseUrl()
104 * @param string $func Function name to call on path request
105 * @param bool $auth API need logged user
106 * @param string $method HTTP method reqiured to call this endpoint.
108 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
109 * Default to API_METHOD_ANY
111 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY) {
120 // Workaround for hotot
121 $path = str_replace("api/", "api/1.1/", $path);
131 * @brief Login API user
133 * Log in user via OAuth1 or Simple HTTP Auth.
134 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
137 * @hook 'authenticate'
139 * 'username' => username from login form
140 * 'password' => password from login form
141 * 'authenticated' => return status,
142 * 'user_record' => return authenticated user record
144 * array $user logged user record
146 function api_login(App $a) {
149 $oauth = new FKOAuth1();
150 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
151 if (!is_null($token)) {
152 $oauth->loginUser($token->uid);
153 call_hooks('logged_in', $a->user);
156 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
157 var_dump($consumer, $token);
159 } catch (Exception $e) {
163 // workaround for HTTP-auth in CGI mode
164 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
165 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
166 if (strlen($userpass)) {
167 list($name, $password) = explode(':', $userpass);
168 $_SERVER['PHP_AUTH_USER'] = $name;
169 $_SERVER['PHP_AUTH_PW'] = $password;
173 if (!x($_SERVER, 'PHP_AUTH_USER')) {
174 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
175 header('WWW-Authenticate: Basic realm="Friendica"');
176 throw new UnauthorizedException("This API requires login");
179 $user = $_SERVER['PHP_AUTH_USER'];
180 $password = $_SERVER['PHP_AUTH_PW'];
181 $encrypted = hash('whirlpool', trim($password));
183 // allow "user@server" login (but ignore 'server' part)
184 $at = strstr($user, "@", true);
189 // next code from mod/auth.php. needs better solution
193 'username' => trim($user),
194 'password' => trim($password),
195 'authenticated' => 0,
196 'user_record' => null,
200 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
201 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
202 * and later plugins should not interfere with an earlier one that succeeded.
204 call_hooks('authenticate', $addon_auth);
206 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
207 $record = $addon_auth['user_record'];
209 // process normal login request
210 $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
211 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
216 if (DBM::is_result($r)) {
221 if ((! $record) || (! count($record))) {
222 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
223 header('WWW-Authenticate: Basic realm="Friendica"');
224 //header('HTTP/1.0 401 Unauthorized');
225 //die('This api requires login');
226 throw new UnauthorizedException("This API requires login");
229 authenticate_success($record);
231 $_SESSION["allow_api"] = true;
233 call_hooks('logged_in', $a->user);
238 * @brief Check HTTP method of called API
240 * API endpoints can define which HTTP method to accept when called.
241 * This function check the current HTTP method agains endpoint
244 * @param string $method Required methods, uppercase, separated by comma
247 function api_check_method($method) {
248 if ($method == "*") {
251 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
255 * @brief Main API entry point
257 * Authenticate user, call registered API function, set HTTP headers
260 * @return string API call result
262 function api_call(App $a) {
263 global $API, $called_api;
266 if (strpos($a->query_string, ".xml") > 0) {
269 if (strpos($a->query_string, ".json") > 0) {
272 if (strpos($a->query_string, ".rss") > 0) {
275 if (strpos($a->query_string, ".atom") > 0) {
280 foreach ($API as $p => $info) {
281 if (strpos($a->query_string, $p) === 0) {
282 if (!api_check_method($info['method'])) {
283 throw new MethodNotAllowedException();
286 $called_api = explode("/", $p);
287 //unset($_SERVER['PHP_AUTH_USER']);
289 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
290 if ($info['auth'] === true && api_user() === false) {
294 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
295 logger('API parameters: ' . print_r($_REQUEST, true));
297 $stamp = microtime(true);
298 $r = call_user_func($info['func'], $type);
299 $duration = (float) (microtime(true) - $stamp);
300 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
302 if (Config::get("system", "profiler")) {
303 $duration = microtime(true)-$a->performance["start"];
305 /// @TODO round() really everywhere?
306 logger(parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
307 round($a->performance["database"] - $a->performance["database_write"], 3),
308 round($a->performance["database_write"], 3),
309 round($a->performance["network"], 2),
310 round($a->performance["file"], 2),
311 round($duration - ($a->performance["database"] + $a->performance["network"]
312 + $a->performance["file"]), 2),
313 round($duration, 2)),
317 if (Config::get("rendertime", "callstack")) {
318 $o = "Database Read:\n";
319 foreach ($a->callstack["database"] AS $func => $time) {
320 $time = round($time, 3);
322 $o .= $func . ": " . $time . "\n";
325 $o .= "\nDatabase Write:\n";
326 foreach ($a->callstack["database_write"] AS $func => $time) {
327 $time = round($time, 3);
329 $o .= $func . ": " . $time . "\n";
333 $o .= "\nNetwork:\n";
334 foreach ($a->callstack["network"] AS $func => $time) {
335 $time = round($time, 3);
337 $o .= $func . ": " . $time . "\n";
340 logger($o, LOGGER_DEBUG);
346 * api function returned false withour throw an
347 * exception. This should not happend, throw a 500
349 throw new InternalServerErrorException();
354 header ("Content-Type: text/xml");
358 header ("Content-Type: application/json");
360 $json = json_encode($rr);
361 if (x($_GET, 'callback')) {
362 $json = $_GET['callback'] . "(" . $json . ")";
367 header ("Content-Type: application/rss+xml");
368 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
371 header ("Content-Type: application/atom+xml");
372 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
378 logger('API call not implemented: ' . $a->query_string);
379 throw new NotImplementedException();
380 } catch (HTTPException $e) {
381 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
382 return api_error($type, $e);
387 * @brief Format API error string
389 * @param string $type Return type (xml, json, rss, as)
390 * @param HTTPException $error Error object
391 * @return strin error message formatted as $type
393 function api_error($type, $e) {
397 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
398 /// @TODO: https://dev.twitter.com/overview/api/response-codes
400 $error = array("error" => $error,
401 "code" => $e->httpcode . " " . $e->httpdesc,
402 "request" => $a->query_string);
404 $ret = api_format_data('status', $type, array('status' => $error));
408 header ("Content-Type: text/xml");
412 header ("Content-Type: application/json");
413 return json_encode($ret);
416 header ("Content-Type: application/rss+xml");
420 header ("Content-Type: application/atom+xml");
427 * @brief Set values for RSS template
430 * @param array $arr Array to be passed to template
431 * @param array $user_info
433 * @todo find proper type-hints
435 function api_rss_extra(App $a, $arr, $user_info) {
436 if (is_null($user_info)) {
437 $user_info = api_get_user($a);
440 $arr['$user'] = $user_info;
441 $arr['$rss'] = array(
442 'alternate' => $user_info['url'],
443 'self' => System::baseUrl() . "/" . $a->query_string,
444 'base' => System::baseUrl(),
445 'updated' => api_date(null),
446 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
447 'language' => $user_info['language'],
448 'logo' => System::baseUrl() . "/images/friendica-32.png",
456 * @brief Unique contact to contact url.
458 * @param int $id Contact id
459 * @return bool|string
460 * Contact url or False if contact id is unknown
462 function api_unique_id_to_url($id) {
463 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
465 if (DBM::is_result($r)) {
473 * @brief Get user info array.
476 * @param int|string $contact_id Contact ID or URL
477 * @param string $type Return type (for errors)
479 function api_get_user(App $a, $contact_id = null, $type = "json") {
487 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
489 // Searching for contact URL
490 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
491 $user = dbesc(normalise_link($contact_id));
493 $extra_query = "AND `contact`.`nurl` = '%s' ";
494 if (api_user() !== false) {
495 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
499 // Searching for contact id with uid = 0
500 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
501 $user = dbesc(api_unique_id_to_url($contact_id));
504 throw new BadRequestException("User not found.");
508 $extra_query = "AND `contact`.`nurl` = '%s' ";
509 if (api_user() !== false) {
510 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
514 if (is_null($user) && x($_GET, 'user_id')) {
515 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
518 throw new BadRequestException("User not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && x($_GET, 'screen_name')) {
528 $user = dbesc($_GET['screen_name']);
530 $extra_query = "AND `contact`.`nick` = '%s' ";
531 if (api_user() !== false) {
532 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
536 if (is_null($user) && x($_GET, 'profileurl')) {
537 $user = dbesc(normalise_link($_GET['profileurl']));
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
545 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
546 $argid = count($called_api);
547 list($user, $null) = explode(".", $a->argv[$argid]);
548 if (is_numeric($user)) {
549 $user = dbesc(api_unique_id_to_url($user));
556 $extra_query = "AND `contact`.`nurl` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
561 $user = dbesc($user);
563 $extra_query = "AND `contact`.`nick` = '%s' ";
564 if (api_user() !== false) {
565 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
570 logger("api_get_user: user ".$user, LOGGER_DEBUG);
573 if (api_user() === false) {
577 $user = $_SESSION['uid'];
578 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
583 logger('api_user: ' . $extra_query . ', user: ' . $user);
586 $uinfo = q("SELECT *, `contact`.`id` AS `cid` FROM `contact`
592 // Selecting the id by priority, friendica first
593 api_best_nickname($uinfo);
595 // if the contact wasn't found, fetch it from the contacts with uid = 0
596 if (!DBM::is_result($uinfo)) {
600 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
603 if (DBM::is_result($r)) {
604 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
606 // If no nick where given, extract it from the address
607 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
608 $r[0]['nick'] = api_get_nick($r[0]["url"]);
613 'id_str' => (string) $r[0]["id"],
614 'name' => $r[0]["name"],
615 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
616 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
617 'description' => $r[0]["about"],
618 'profile_image_url' => $r[0]["micro"],
619 'profile_image_url_https' => $r[0]["micro"],
620 'url' => $r[0]["url"],
621 'protected' => false,
622 'followers_count' => 0,
623 'friends_count' => 0,
625 'created_at' => api_date($r[0]["created"]),
626 'favourites_count' => 0,
628 'time_zone' => 'UTC',
629 'geo_enabled' => false,
631 'statuses_count' => 0,
633 'contributors_enabled' => false,
634 'is_translator' => false,
635 'is_translation_enabled' => false,
636 'following' => false,
637 'follow_request_sent' => false,
638 'statusnet_blocking' => false,
639 'notifications' => false,
640 'statusnet_profile_url' => $r[0]["url"],
642 'cid' => get_contact($r[0]["url"], api_user(), true),
644 'network' => $r[0]["network"],
649 throw new BadRequestException("User not found.");
653 if ($uinfo[0]['self']) {
655 if ($uinfo[0]['network'] == "") {
656 $uinfo[0]['network'] = NETWORK_DFRN;
659 $usr = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
662 $profile = q("SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
666 /// @TODO old-lost code? (twice)
667 // Counting is deactivated by now, due to performance issues
668 // count public wall messages
669 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
670 // intval($uinfo[0]['uid'])
672 //$countitms = $r[0]['count'];
675 // Counting is deactivated by now, due to performance issues
676 //$r = q("SELECT count(*) as `count` FROM `item`
677 // WHERE `contact-id` = %d",
678 // intval($uinfo[0]['id'])
680 //$countitms = $r[0]['count'];
684 /// @TODO old-lost code? (twice)
686 // Counting is deactivated by now, due to performance issues
688 $r = q("SELECT count(*) as `count` FROM `contact`
689 WHERE `uid` = %d AND `rel` IN ( %d, %d )
690 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
691 intval($uinfo[0]['uid']),
692 intval(CONTACT_IS_SHARING),
693 intval(CONTACT_IS_FRIEND)
695 $countfriends = $r[0]['count'];
697 $r = q("SELECT count(*) as `count` FROM `contact`
698 WHERE `uid` = %d AND `rel` IN ( %d, %d )
699 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
700 intval($uinfo[0]['uid']),
701 intval(CONTACT_IS_FOLLOWER),
702 intval(CONTACT_IS_FRIEND)
704 $countfollowers = $r[0]['count'];
706 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
707 intval($uinfo[0]['uid'])
709 $starred = $r[0]['count'];
712 if (! $uinfo[0]['self']) {
722 // Add a nick if it isn't present there
723 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
724 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
727 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
729 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
732 'id' => intval($pcontact_id),
733 'id_str' => (string) intval($pcontact_id),
734 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
735 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
736 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
737 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
738 'profile_image_url' => $uinfo[0]['micro'],
739 'profile_image_url_https' => $uinfo[0]['micro'],
740 'url' => $uinfo[0]['url'],
741 'protected' => false,
742 'followers_count' => intval($countfollowers),
743 'friends_count' => intval($countfriends),
745 'created_at' => api_date($uinfo[0]['created']),
746 'favourites_count' => intval($starred),
748 'time_zone' => 'UTC',
749 'geo_enabled' => false,
751 'statuses_count' => intval($countitms),
753 'contributors_enabled' => false,
754 'is_translator' => false,
755 'is_translation_enabled' => false,
756 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
757 'follow_request_sent' => false,
758 'statusnet_blocking' => false,
759 'notifications' => false,
761 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
762 'statusnet_profile_url' => $uinfo[0]['url'],
763 'uid' => intval($uinfo[0]['uid']),
764 'cid' => intval($uinfo[0]['cid']),
765 'self' => $uinfo[0]['self'],
766 'network' => $uinfo[0]['network'],
774 * @brief return api-formatted array for item's author and owner
777 * @param array $item : item from db
778 * @return array(array:author, array:owner)
780 function api_item_get_user(App $a, $item) {
782 $status_user = api_get_user($a, $item["author-link"]);
784 $status_user["protected"] = (($item["allow_cid"] != "") ||
785 ($item["allow_gid"] != "") ||
786 ($item["deny_cid"] != "") ||
787 ($item["deny_gid"] != "") ||
790 if ($item['thr-parent'] == $item['uri']) {
791 $owner_user = api_get_user($a, $item["owner-link"]);
793 $owner_user = $status_user;
796 return (array($status_user, $owner_user));
800 * @brief walks recursively through an array with the possibility to change value and key
802 * @param array $array The array to walk through
803 * @param string $callback The callback function
805 * @return array the transformed array
807 function api_walk_recursive(array &$array, callable $callback) {
809 $new_array = array();
811 foreach ($array as $k => $v) {
813 if ($callback($v, $k)) {
814 $new_array[$k] = api_walk_recursive($v, $callback);
817 if ($callback($v, $k)) {
828 * @brief Callback function to transform the array in an array that can be transformed in a XML file
830 * @param variant $item Array item value
831 * @param string $key Array key
833 * @return boolean Should the array item be deleted?
835 function api_reformat_xml(&$item, &$key) {
836 if (is_bool($item)) {
837 $item = ($item ? "true" : "false");
840 if (substr($key, 0, 10) == "statusnet_") {
841 $key = "statusnet:".substr($key, 10);
842 } elseif (substr($key, 0, 10) == "friendica_") {
843 $key = "friendica:".substr($key, 10);
845 /// @TODO old-lost code?
847 // $key = "default:".$key;
853 * @brief Creates the XML from a JSON style array
855 * @param array $data JSON style array
856 * @param string $root_element Name of the root element
858 * @return string The XML data
860 function api_create_xml($data, $root_element) {
861 $childname = key($data);
862 $data2 = array_pop($data);
865 $namespaces = array("" => "http://api.twitter.com",
866 "statusnet" => "http://status.net/schema/api/1/",
867 "friendica" => "http://friendi.ca/schema/api/1/",
868 "georss" => "http://www.georss.org/georss");
870 /// @todo Auto detection of needed namespaces
871 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
872 $namespaces = array();
875 if (is_array($data2)) {
876 api_walk_recursive($data2, "api_reformat_xml");
883 foreach ($data2 AS $item) {
884 $data4[$i++.":".$childname] = $item;
890 $data3 = array($root_element => $data2);
892 $ret = xml::from_array($data3, $xml, false, $namespaces);
897 * @brief Formats the data according to the data type
899 * @param string $root_element Name of the root element
900 * @param string $type Return type (atom, rss, xml, json)
901 * @param array $data JSON style array
903 * @return (string|object) XML data or JSON data
905 function api_format_data($root_element, $type, $data) {
913 $ret = api_create_xml($data, $root_element);
928 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
929 * returns a 401 status code and an error message if not.
930 * http://developer.twitter.com/doc/get/account/verify_credentials
932 function api_account_verify_credentials($type) {
936 if (api_user() === false) {
937 throw new ForbiddenException();
940 unset($_REQUEST["user_id"]);
941 unset($_GET["user_id"]);
943 unset($_REQUEST["screen_name"]);
944 unset($_GET["screen_name"]);
946 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
948 $user_info = api_get_user($a);
950 // "verified" isn't used here in the standard
951 unset($user_info["verified"]);
953 // - Adding last status
955 $user_info["status"] = api_status_show("raw");
956 if (!count($user_info["status"])) {
957 unset($user_info["status"]);
959 unset($user_info["status"]["user"]);
963 // "uid" and "self" are only needed for some internal stuff, so remove it from here
964 unset($user_info["uid"]);
965 unset($user_info["self"]);
967 return api_format_data("user", $type, array('user' => $user_info));
971 /// @TODO move to top of file or somwhere better
972 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
975 * get data from $_POST or $_GET
977 function requestdata($k) {
987 /*Waitman Gobble Mod*/
988 function api_statuses_mediap($type) {
992 if (api_user() === false) {
993 logger('api_statuses_update: no user');
994 throw new ForbiddenException();
996 $user_info = api_get_user($a);
998 $_REQUEST['type'] = 'wall';
999 $_REQUEST['profile_uid'] = api_user();
1000 $_REQUEST['api_source'] = true;
1001 $txt = requestdata('status');
1002 /// @TODO old-lost code?
1003 //$txt = urldecode(requestdata('status'));
1005 if ((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
1007 $txt = html2bb_video($txt);
1008 $config = HTMLPurifier_Config::createDefault();
1009 $config->set('Cache.DefinitionImpl', null);
1010 $purifier = new HTMLPurifier($config);
1011 $txt = $purifier->purify($txt);
1013 $txt = html2bbcode($txt);
1015 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1017 // tell wall_upload function to return img info instead of echo
1018 $_REQUEST['hush'] = 'yeah';
1019 $bebop = wall_upload_post($a);
1021 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1022 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1025 // this should output the last post (the one we just posted).
1026 return api_status_show($type);
1029 /// @TODO move this to top of file or somewhere better!
1030 api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
1032 function api_statuses_update($type) {
1036 if (api_user() === false) {
1037 logger('api_statuses_update: no user');
1038 throw new ForbiddenException();
1041 $user_info = api_get_user($a);
1043 // convert $_POST array items to the form we use for web posts.
1045 // logger('api_post: ' . print_r($_POST,true));
1047 if (requestdata('htmlstatus')) {
1048 $txt = requestdata('htmlstatus');
1049 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1050 $txt = html2bb_video($txt);
1052 $config = HTMLPurifier_Config::createDefault();
1053 $config->set('Cache.DefinitionImpl', null);
1055 $purifier = new HTMLPurifier($config);
1056 $txt = $purifier->purify($txt);
1058 $_REQUEST['body'] = html2bbcode($txt);
1062 $_REQUEST['body'] = requestdata('status');
1065 $_REQUEST['title'] = requestdata('title');
1067 $parent = requestdata('in_reply_to_status_id');
1069 // Twidere sends "-1" if it is no reply ...
1070 if ($parent == -1) {
1074 if (ctype_digit($parent)) {
1075 $_REQUEST['parent'] = $parent;
1077 $_REQUEST['parent_uri'] = $parent;
1080 if (requestdata('lat') && requestdata('long')) {
1081 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1083 $_REQUEST['profile_uid'] = api_user();
1086 $_REQUEST['type'] = 'net-comment';
1088 // Check for throttling (maximum posts per day, week and month)
1089 $throttle_day = Config::get('system','throttle_limit_day');
1090 if ($throttle_day > 0) {
1091 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1093 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1094 AND `created` > '%s' AND `id` = `parent`",
1095 intval(api_user()), dbesc($datefrom));
1097 if (DBM::is_result($r)) {
1098 $posts_day = $r[0]["posts_day"];
1103 if ($posts_day > $throttle_day) {
1104 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1105 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1106 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1110 $throttle_week = Config::get('system','throttle_limit_week');
1111 if ($throttle_week > 0) {
1112 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1114 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1115 AND `created` > '%s' AND `id` = `parent`",
1116 intval(api_user()), dbesc($datefrom));
1118 if (DBM::is_result($r)) {
1119 $posts_week = $r[0]["posts_week"];
1124 if ($posts_week > $throttle_week) {
1125 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1126 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1127 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1131 $throttle_month = Config::get('system','throttle_limit_month');
1132 if ($throttle_month > 0) {
1133 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1135 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1136 AND `created` > '%s' AND `id` = `parent`",
1137 intval(api_user()), dbesc($datefrom));
1139 if (DBM::is_result($r)) {
1140 $posts_month = $r[0]["posts_month"];
1145 if ($posts_month > $throttle_month) {
1146 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1147 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1148 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1152 $_REQUEST['type'] = 'wall';
1155 if (x($_FILES, 'media')) {
1156 // upload the image if we have one
1157 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1158 $media = wall_upload_post($a);
1159 if (strlen($media) > 0) {
1160 $_REQUEST['body'] .= "\n\n" . $media;
1164 // To-Do: Multiple IDs
1165 if (requestdata('media_ids')) {
1166 $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",
1167 intval(requestdata('media_ids')), api_user());
1168 if (DBM::is_result($r)) {
1169 $phototypes = Photo::supportedTypes();
1170 $ext = $phototypes[$r[0]['type']];
1171 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1172 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1176 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1178 $_REQUEST['api_source'] = true;
1180 if (!x($_REQUEST, "source")) {
1181 $_REQUEST["source"] = api_source();
1184 // call out normal post function
1187 // this should output the last post (the one we just posted).
1188 return api_status_show($type);
1191 /// @TODO move to top of file or somwhere better
1192 api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1193 api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1195 function api_media_upload($type) {
1199 if (api_user() === false) {
1201 throw new ForbiddenException();
1204 $user_info = api_get_user($a);
1206 if (!x($_FILES, 'media')) {
1208 throw new BadRequestException("No media.");
1211 $media = wall_upload_post($a, false);
1214 throw new InternalServerErrorException();
1217 $returndata = array();
1218 $returndata["media_id"] = $media["id"];
1219 $returndata["media_id_string"] = (string)$media["id"];
1220 $returndata["size"] = $media["size"];
1221 $returndata["image"] = array("w" => $media["width"],
1222 "h" => $media["height"],
1223 "image_type" => $media["type"]);
1225 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1227 return array("media" => $returndata);
1230 /// @TODO move to top of file or somwhere better
1231 api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1233 function api_status_show($type) {
1237 $user_info = api_get_user($a);
1239 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1241 if ($type == "raw") {
1242 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1247 // get last public wall message
1248 $lastwall = q("SELECT `item`.*
1250 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1251 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1252 AND `item`.`type` != 'activity' $privacy_sql
1253 ORDER BY `item`.`id` DESC
1255 intval($user_info['cid']),
1257 dbesc($user_info['url']),
1258 dbesc(normalise_link($user_info['url'])),
1259 dbesc($user_info['url']),
1260 dbesc(normalise_link($user_info['url']))
1263 if (DBM::is_result($lastwall)) {
1264 $lastwall = $lastwall[0];
1266 $in_reply_to = api_in_reply_to($lastwall);
1268 $converted = api_convert_item($lastwall);
1270 if ($type == "xml") {
1271 $geo = "georss:point";
1276 $status_info = array(
1277 'created_at' => api_date($lastwall['created']),
1278 'id' => intval($lastwall['id']),
1279 'id_str' => (string) $lastwall['id'],
1280 'text' => $converted["text"],
1281 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1282 'truncated' => false,
1283 'in_reply_to_status_id' => $in_reply_to['status_id'],
1284 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1285 'in_reply_to_user_id' => $in_reply_to['user_id'],
1286 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1287 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1288 'user' => $user_info,
1290 'coordinates' => "",
1292 'contributors' => "",
1293 'is_quote_status' => false,
1294 'retweet_count' => 0,
1295 'favorite_count' => 0,
1296 'favorited' => $lastwall['starred'] ? true : false,
1297 'retweeted' => false,
1298 'possibly_sensitive' => false,
1300 'statusnet_html' => $converted["html"],
1301 'statusnet_conversation_id' => $lastwall['parent'],
1304 if (count($converted["attachments"]) > 0) {
1305 $status_info["attachments"] = $converted["attachments"];
1308 if (count($converted["entities"]) > 0) {
1309 $status_info["entities"] = $converted["entities"];
1312 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1313 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1314 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1315 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1318 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1319 unset($status_info["user"]["uid"]);
1320 unset($status_info["user"]["self"]);
1323 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1325 if ($type == "raw") {
1326 return $status_info;
1329 return api_format_data("statuses", $type, array('status' => $status_info));
1334 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1335 * The author's most recent status will be returned inline.
1336 * http://developer.twitter.com/doc/get/users/show
1338 function api_users_show($type) {
1342 $user_info = api_get_user($a);
1343 $lastwall = q("SELECT `item`.*
1345 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1346 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1347 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1348 AND `type`!='activity'
1349 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1353 dbesc(ACTIVITY_POST),
1354 intval($user_info['cid']),
1355 dbesc($user_info['url']),
1356 dbesc(normalise_link($user_info['url'])),
1357 dbesc($user_info['url']),
1358 dbesc(normalise_link($user_info['url']))
1361 if (DBM::is_result($lastwall)) {
1362 $lastwall = $lastwall[0];
1364 $in_reply_to = api_in_reply_to($lastwall);
1366 $converted = api_convert_item($lastwall);
1368 if ($type == "xml") {
1369 $geo = "georss:point";
1374 $user_info['status'] = array(
1375 'text' => $converted["text"],
1376 'truncated' => false,
1377 'created_at' => api_date($lastwall['created']),
1378 'in_reply_to_status_id' => $in_reply_to['status_id'],
1379 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1380 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1381 'id' => intval($lastwall['contact-id']),
1382 'id_str' => (string) $lastwall['contact-id'],
1383 'in_reply_to_user_id' => $in_reply_to['user_id'],
1384 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1385 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1387 'favorited' => $lastwall['starred'] ? true : false,
1388 'statusnet_html' => $converted["html"],
1389 'statusnet_conversation_id' => $lastwall['parent'],
1392 if (count($converted["attachments"]) > 0) {
1393 $user_info["status"]["attachments"] = $converted["attachments"];
1396 if (count($converted["entities"]) > 0) {
1397 $user_info["status"]["entities"] = $converted["entities"];
1400 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1401 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1404 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1405 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1410 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1411 unset($user_info["uid"]);
1412 unset($user_info["self"]);
1414 return api_format_data("user", $type, array('user' => $user_info));
1418 /// @TODO move to top of file or somewhere better
1419 api_register_func('api/users/show','api_users_show');
1420 api_register_func('api/externalprofile/show','api_users_show');
1422 function api_users_search($type) {
1426 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1428 $userlist = array();
1430 if (x($_GET, 'q')) {
1431 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1433 if (!DBM::is_result($r)) {
1434 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1437 if (DBM::is_result($r)) {
1439 foreach ($r AS $user) {
1440 $user_info = api_get_user($a, $user["id"], "json");
1442 if ($type == "xml") {
1443 $userlist[$k++.":user"] = $user_info;
1445 $userlist[] = $user_info;
1448 $userlist = array("users" => $userlist);
1450 throw new BadRequestException("User not found.");
1453 throw new BadRequestException("User not found.");
1455 return api_format_data("users", $type, $userlist);
1458 /// @TODO move to top of file or somewhere better
1459 api_register_func('api/users/search','api_users_search');
1463 * http://developer.twitter.com/doc/get/statuses/home_timeline
1465 * TODO: Optional parameters
1466 * TODO: Add reply info
1468 function api_statuses_home_timeline($type) {
1472 if (api_user() === false) {
1473 throw new ForbiddenException();
1476 unset($_REQUEST["user_id"]);
1477 unset($_GET["user_id"]);
1479 unset($_REQUEST["screen_name"]);
1480 unset($_GET["screen_name"]);
1482 $user_info = api_get_user($a);
1483 // get last newtork messages
1486 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1487 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1491 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1492 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1493 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1494 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1495 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1497 $start = $page * $count;
1501 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1503 if ($exclude_replies > 0) {
1504 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1506 if ($conversation_id > 0) {
1507 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1510 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1511 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1512 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1513 `contact`.`id` AS `cid`
1515 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1516 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1517 WHERE `item`.`uid` = %d AND `verb` = '%s'
1518 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1521 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1523 dbesc(ACTIVITY_POST),
1525 intval($start), intval($count)
1528 $ret = api_format_items($r, $user_info, false, $type);
1530 // Set all posts from the query above to seen
1532 foreach ($r AS $item) {
1533 $idarray[] = intval($item["id"]);
1536 $idlist = implode(",", $idarray);
1538 if ($idlist != "") {
1539 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1542 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1546 $data = array('status' => $ret);
1550 $data = api_rss_extra($a, $data, $user_info);
1554 return api_format_data("statuses", $type, $data);
1557 /// @TODO move to top of file or somewhere better
1558 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1559 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1561 function api_statuses_public_timeline($type) {
1565 if (api_user() === false) {
1566 throw new ForbiddenException();
1569 $user_info = api_get_user($a);
1570 // get last newtork messages
1573 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1574 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1578 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1579 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1580 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1581 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1582 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1584 $start = $page * $count;
1587 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1589 if ($exclude_replies > 0) {
1590 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1592 if ($conversation_id > 0) {
1593 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1596 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1597 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1598 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1599 `contact`.`id` AS `cid`,
1600 `user`.`nickname`, `user`.`hidewall`
1602 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1603 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1604 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1605 AND NOT `user`.`hidewall`
1606 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1607 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1608 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1609 AND NOT `item`.`private` AND `item`.`wall`
1612 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1613 dbesc(ACTIVITY_POST),
1618 $ret = api_format_items($r, $user_info, false, $type);
1620 $data = array('status' => $ret);
1624 $data = api_rss_extra($a, $data, $user_info);
1628 return api_format_data("statuses", $type, $data);
1631 /// @TODO move to top of file or somewhere better
1632 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1635 * @TODO nothing to say?
1637 function api_statuses_show($type) {
1641 if (api_user() === false) {
1642 throw new ForbiddenException();
1645 $user_info = api_get_user($a);
1648 $id = intval($a->argv[3]);
1651 $id = intval($_REQUEST["id"]);
1656 $id = intval($a->argv[4]);
1659 logger('API: api_statuses_show: ' . $id);
1661 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1664 if ($conversation) {
1665 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1667 $sql_extra .= " AND `item`.`id` = %d";
1670 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1671 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1672 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1673 `contact`.`id` AS `cid`
1675 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1676 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1677 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1678 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1681 dbesc(ACTIVITY_POST),
1685 /// @TODO How about copying this to above methods which don't check $r ?
1686 if (!DBM::is_result($r)) {
1687 throw new BadRequestException("There is no status with this id.");
1690 $ret = api_format_items($r,$user_info, false, $type);
1692 if ($conversation) {
1693 $data = array('status' => $ret);
1694 return api_format_data("statuses", $type, $data);
1696 $data = array('status' => $ret[0]);
1697 return api_format_data("status", $type, $data);
1701 /// @TODO move to top of file or somewhere better
1702 api_register_func('api/statuses/show','api_statuses_show', true);
1705 * @TODO nothing to say?
1707 function api_conversation_show($type) {
1711 if (api_user() === false) {
1712 throw new ForbiddenException();
1715 $user_info = api_get_user($a);
1718 $id = intval($a->argv[3]);
1719 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1720 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1724 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1725 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1727 $start = $page*$count;
1730 $id = intval($_REQUEST["id"]);
1735 $id = intval($a->argv[4]);
1738 logger('API: api_conversation_show: '.$id);
1740 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1741 if (DBM::is_result($r)) {
1742 $id = $r[0]["parent"];
1748 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1751 // Not sure why this query was so complicated. We should keep it here for a while,
1752 // just to make sure that we really don't need it.
1753 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1754 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1756 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1757 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1758 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1759 `contact`.`id` AS `cid`
1761 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1762 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1763 WHERE `item`.`parent` = %d AND `item`.`visible`
1764 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1765 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1766 AND `item`.`id`>%d $sql_extra
1767 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1768 intval($id), intval(api_user()),
1769 dbesc(ACTIVITY_POST),
1771 intval($start), intval($count)
1774 if (!DBM::is_result($r)) {
1775 throw new BadRequestException("There is no status with this id.");
1778 $ret = api_format_items($r, $user_info, false, $type);
1780 $data = array('status' => $ret);
1781 return api_format_data("statuses", $type, $data);
1784 /// @TODO move to top of file or somewhere better
1785 api_register_func('api/conversation/show','api_conversation_show', true);
1786 api_register_func('api/statusnet/conversation','api_conversation_show', true);
1789 * @TODO nothing to say?
1791 function api_statuses_repeat($type) {
1796 if (api_user() === false) {
1797 throw new ForbiddenException();
1800 $user_info = api_get_user($a);
1803 $id = intval($a->argv[3]);
1806 $id = intval($_REQUEST["id"]);
1811 $id = intval($a->argv[4]);
1814 logger('API: api_statuses_repeat: '.$id);
1816 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1817 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1818 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1819 `contact`.`id` AS `cid`
1821 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1822 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1823 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1824 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1825 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1827 AND `item`.`id`=%d",
1831 /// @TODO other style than above functions!
1832 if (DBM::is_result($r) && $r[0]['body'] != "") {
1833 if (strpos($r[0]['body'], "[/share]") !== false) {
1834 $pos = strpos($r[0]['body'], "[share");
1835 $post = substr($r[0]['body'], $pos);
1837 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1839 $post .= $r[0]['body'];
1840 $post .= "[/share]";
1842 $_REQUEST['body'] = $post;
1843 $_REQUEST['profile_uid'] = api_user();
1844 $_REQUEST['type'] = 'wall';
1845 $_REQUEST['api_source'] = true;
1847 if (!x($_REQUEST, "source")) {
1848 $_REQUEST["source"] = api_source();
1853 throw new ForbiddenException();
1856 // this should output the last post (the one we just posted).
1858 return api_status_show($type);
1861 /// @TODO move to top of file or somewhere better
1862 api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1865 * @TODO nothing to say?
1867 function api_statuses_destroy($type) {
1871 if (api_user() === false) {
1872 throw new ForbiddenException();
1875 $user_info = api_get_user($a);
1878 $id = intval($a->argv[3]);
1881 $id = intval($_REQUEST["id"]);
1886 $id = intval($a->argv[4]);
1889 logger('API: api_statuses_destroy: '.$id);
1891 $ret = api_statuses_show($type);
1893 drop_item($id, false);
1898 /// @TODO move to top of file or somewhere better
1899 api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1902 * @TODO Nothing more than an URL to say?
1903 * http://developer.twitter.com/doc/get/statuses/mentions
1905 function api_statuses_mentions($type) {
1909 if (api_user() === false) {
1910 throw new ForbiddenException();
1913 unset($_REQUEST["user_id"]);
1914 unset($_GET["user_id"]);
1916 unset($_REQUEST["screen_name"]);
1917 unset($_GET["screen_name"]);
1919 $user_info = api_get_user($a);
1920 // get last newtork messages
1924 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1925 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1929 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1930 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1931 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1933 $start = $page * $count;
1935 // Ugly code - should be changed
1936 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1937 $myurl = substr($myurl,strpos($myurl, '://') + 3);
1938 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1939 $myurl = str_replace('www.', '', $myurl);
1940 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1943 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1946 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1947 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1948 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1949 `contact`.`id` AS `cid`
1950 FROM `item` FORCE INDEX (`uid_id`)
1951 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1952 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1953 WHERE `item`.`uid` = %d AND `verb` = '%s'
1954 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1955 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1956 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1959 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1961 dbesc(ACTIVITY_POST),
1962 dbesc(protect_sprintf($myurl)),
1963 dbesc(protect_sprintf($myurl)),
1966 intval($start), intval($count)
1969 $ret = api_format_items($r, $user_info, false, $type);
1971 $data = array('status' => $ret);
1975 $data = api_rss_extra($a, $data, $user_info);
1979 return api_format_data("statuses", $type, $data);
1982 /// @TODO move to top of file or somewhere better
1983 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1984 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1986 function api_statuses_user_timeline($type) {
1990 if (api_user() === false) {
1991 throw new ForbiddenException();
1994 $user_info = api_get_user($a);
1995 // get last network messages
1997 logger("api_statuses_user_timeline: api_user: ". api_user() .
1998 "\nuser_info: ".print_r($user_info, true) .
1999 "\n_REQUEST: ".print_r($_REQUEST, true),
2003 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2004 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2008 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2009 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2010 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2011 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2013 $start = $page * $count;
2016 if ($user_info['self'] == 1) {
2017 $sql_extra .= " AND `item`.`wall` = 1 ";
2020 if ($exclude_replies > 0) {
2021 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2023 if ($conversation_id > 0) {
2024 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2027 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2028 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2029 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2030 `contact`.`id` AS `cid`
2031 FROM `item` FORCE INDEX (`uid_contactid_id`)
2032 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2033 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2034 WHERE `item`.`uid` = %d AND `verb` = '%s'
2035 AND `item`.`contact-id` = %d
2036 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2039 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2041 dbesc(ACTIVITY_POST),
2042 intval($user_info['cid']),
2044 intval($start), intval($count)
2047 $ret = api_format_items($r, $user_info, true, $type);
2049 $data = array('status' => $ret);
2053 $data = api_rss_extra($a, $data, $user_info);
2057 return api_format_data("statuses", $type, $data);
2060 /// @TODO move to top of file or somwhere better
2061 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2064 * Star/unstar an item
2065 * param: id : id of the item
2067 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2069 function api_favorites_create_destroy($type) {
2073 if (api_user() === false) {
2074 throw new ForbiddenException();
2077 // for versioned api.
2078 /// @TODO We need a better global soluton
2079 $action_argv_id = 2;
2080 if ($a->argv[1] == "1.1") {
2081 $action_argv_id = 3;
2084 if ($a->argc <= $action_argv_id) {
2085 throw new BadRequestException("Invalid request.");
2087 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2088 if ($a->argc == $action_argv_id + 2) {
2089 $itemid = intval($a->argv[$action_argv_id + 1]);
2091 /// @TODO use x() to check if _REQUEST contains 'id'
2092 $itemid = intval($_REQUEST['id']);
2095 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1",
2096 $itemid, api_user());
2098 if (!DBM::is_result($item) || count($item) == 0) {
2099 throw new BadRequestException("Invalid item.");
2104 $item[0]['starred'] = 1;
2107 $item[0]['starred'] = 0;
2110 throw new BadRequestException("Invalid action ".$action);
2113 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
2114 $item[0]['starred'], $itemid, api_user());
2116 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
2117 $item[0]['starred'], $itemid, api_user());
2120 throw new InternalServerErrorException("DB error");
2124 $user_info = api_get_user($a);
2125 $rets = api_format_items($item, $user_info, false, $type);
2128 $data = array('status' => $ret);
2132 $data = api_rss_extra($a, $data, $user_info);
2135 return api_format_data("status", $type, $data);
2138 /// @TODO move to top of file or somwhere better
2139 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2140 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2142 function api_favorites($type) {
2147 if (api_user() === false) {
2148 throw new ForbiddenException();
2151 $called_api = array();
2153 $user_info = api_get_user($a);
2155 // in friendica starred item are private
2156 // return favorites only for self
2157 logger('api_favorites: self:' . $user_info['self']);
2159 if ($user_info['self'] == 0) {
2165 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2166 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2167 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2168 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2173 $start = $page*$count;
2176 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2179 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2180 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2181 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2182 `contact`.`id` AS `cid`
2183 FROM `item`, `contact`
2184 WHERE `item`.`uid` = %d
2185 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2186 AND `item`.`starred` = 1
2187 AND `contact`.`id` = `item`.`contact-id`
2188 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2191 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2194 intval($start), intval($count)
2197 $ret = api_format_items($r,$user_info, false, $type);
2201 $data = array('status' => $ret);
2205 $data = api_rss_extra($a, $data, $user_info);
2208 return api_format_data("statuses", $type, $data);
2211 /// @TODO move to top of file or somwhere better
2212 api_register_func('api/favorites','api_favorites', true);
2214 function api_format_messages($item, $recipient, $sender) {
2215 // standard meta information
2217 'id' => $item['id'],
2218 'sender_id' => $sender['id'] ,
2220 'recipient_id' => $recipient['id'],
2221 'created_at' => api_date($item['created']),
2222 'sender_screen_name' => $sender['screen_name'],
2223 'recipient_screen_name' => $recipient['screen_name'],
2224 'sender' => $sender,
2225 'recipient' => $recipient,
2227 'friendica_seen' => $item['seen'],
2228 'friendica_parent_uri' => $item['parent-uri'],
2231 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2232 unset($ret["sender"]["uid"]);
2233 unset($ret["sender"]["self"]);
2234 unset($ret["recipient"]["uid"]);
2235 unset($ret["recipient"]["self"]);
2237 //don't send title to regular StatusNET requests to avoid confusing these apps
2238 if (x($_GET, 'getText')) {
2239 $ret['title'] = $item['title'];
2240 if ($_GET['getText'] == 'html') {
2241 $ret['text'] = bbcode($item['body'], false, false);
2242 } elseif ($_GET['getText'] == 'plain') {
2243 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2244 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2247 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2249 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2250 unset($ret['sender']);
2251 unset($ret['recipient']);
2257 function api_convert_item($item) {
2258 $body = $item['body'];
2259 $attachments = api_get_attachments($body);
2261 // Workaround for ostatus messages where the title is identically to the body
2262 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2263 $statusbody = trim(html2plain($html, 0));
2265 // handle data: images
2266 $statusbody = api_format_items_embeded_images($item,$statusbody);
2268 $statustitle = trim($item['title']);
2270 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2271 $statustext = trim($statusbody);
2273 $statustext = trim($statustitle."\n\n".$statusbody);
2276 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2277 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2280 $statushtml = trim(bbcode($body, false, false));
2282 // Workaround for clients with limited HTML parser functionality
2283 $search = array("<br>", "<blockquote>", "</blockquote>",
2284 "<h1>", "</h1>", "<h2>", "</h2>",
2285 "<h3>", "</h3>", "<h4>", "</h4>",
2286 "<h5>", "</h5>", "<h6>", "</h6>");
2287 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2288 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2289 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2290 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2291 $statushtml = str_replace($search, $replace, $statushtml);
2293 if ($item['title'] != "") {
2294 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2298 $oldtext = $statushtml;
2299 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2300 } while ($oldtext != $statushtml);
2302 if (substr($statushtml, 0, 4) == '<br>') {
2303 $statushtml = substr($statushtml, 4);
2306 if (substr($statushtml, 0, -4) == '<br>') {
2307 $statushtml = substr($statushtml, -4);
2310 // feeds without body should contain the link
2311 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2312 $statushtml .= bbcode($item['plink']);
2315 $entities = api_get_entitities($statustext, $body);
2318 "text" => $statustext,
2319 "html" => $statushtml,
2320 "attachments" => $attachments,
2321 "entities" => $entities
2325 function api_get_attachments(&$body) {
2328 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2330 $URLSearchString = "^\[\]";
2331 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2337 $attachments = array();
2339 foreach ($images[1] AS $image) {
2340 $imagedata = get_photo_info($image);
2343 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2347 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2348 foreach ($images[0] AS $orig) {
2349 $body = str_replace($orig, "", $body);
2353 return $attachments;
2356 function api_get_entitities(&$text, $bbcode) {
2359 * Links at the first character of the post
2364 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2366 if ($include_entities != "true") {
2368 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2370 foreach ($images[1] AS $image) {
2371 $replace = proxy_url($image);
2372 $text = str_replace($image, $replace, $text);
2377 $bbcode = bb_CleanPictureLinks($bbcode);
2379 // Change pure links in text to bbcode uris
2380 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2382 $entities = array();
2383 $entities["hashtags"] = array();
2384 $entities["symbols"] = array();
2385 $entities["urls"] = array();
2386 $entities["user_mentions"] = array();
2388 $URLSearchString = "^\[\]";
2390 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2392 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2393 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2394 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2396 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2397 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2398 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2400 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2401 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2402 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2404 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2406 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2407 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2409 $ordered_urls = array();
2410 foreach ($urls[1] AS $id => $url) {
2411 //$start = strpos($text, $url, $offset);
2412 $start = iconv_strpos($text, $url, 0, "UTF-8");
2413 if (!($start === false)) {
2414 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2418 ksort($ordered_urls);
2421 //foreach ($urls[1] AS $id=>$url) {
2422 foreach ($ordered_urls AS $url) {
2423 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://") &&
2424 !strpos($url["title"], "http://") && !strpos($url["title"], "https://"))
2425 $display_url = $url["title"];
2427 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2428 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2430 if (strlen($display_url) > 26)
2431 $display_url = substr($display_url, 0, 25)."…";
2434 //$start = strpos($text, $url, $offset);
2435 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2436 if (!($start === false)) {
2437 $entities["urls"][] = array("url" => $url["url"],
2438 "expanded_url" => $url["url"],
2439 "display_url" => $display_url,
2440 "indices" => array($start, $start+strlen($url["url"])));
2441 $offset = $start + 1;
2445 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2446 $ordered_images = array();
2447 foreach ($images[1] AS $image) {
2448 //$start = strpos($text, $url, $offset);
2449 $start = iconv_strpos($text, $image, 0, "UTF-8");
2450 if (!($start === false))
2451 $ordered_images[$start] = $image;
2453 //$entities["media"] = array();
2456 foreach ($ordered_images AS $url) {
2457 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2458 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2460 if (strlen($display_url) > 26)
2461 $display_url = substr($display_url, 0, 25)."…";
2463 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2464 if (!($start === false)) {
2465 $image = get_photo_info($url);
2467 // If image cache is activated, then use the following sizes:
2468 // thumb (150), small (340), medium (600) and large (1024)
2469 if (!Config::get("system", "proxy_disabled")) {
2470 $media_url = proxy_url($url);
2473 $scale = scale_image($image[0], $image[1], 150);
2474 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2476 if (($image[0] > 150) || ($image[1] > 150)) {
2477 $scale = scale_image($image[0], $image[1], 340);
2478 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2481 $scale = scale_image($image[0], $image[1], 600);
2482 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2484 if (($image[0] > 600) || ($image[1] > 600)) {
2485 $scale = scale_image($image[0], $image[1], 1024);
2486 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2490 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2493 $entities["media"][] = array(
2495 "id_str" => (string)$start+1,
2496 "indices" => array($start, $start+strlen($url)),
2497 "media_url" => normalise_link($media_url),
2498 "media_url_https" => $media_url,
2500 "display_url" => $display_url,
2501 "expanded_url" => $url,
2505 $offset = $start + 1;
2511 function api_format_items_embeded_images(&$item, $text) {
2512 $text = preg_replace_callback(
2513 "|data:image/([^;]+)[^=]+=*|m",
2514 function($match) use ($item) {
2515 return System::baseUrl()."/display/".$item['guid'];
2523 * @brief return <a href='url'>name</a> as array
2525 * @param string $txt
2530 function api_contactlink_to_array($txt) {
2532 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2533 if ($r && count($match)==3) {
2535 'name' => $match[2],
2549 * @brief return likes, dislikes and attend status for item
2551 * @param array $item
2553 * likes => int count
2554 * dislikes => int count
2556 function api_format_items_activities(&$item, $type = "json") {
2560 $activities = array(
2562 'dislike' => array(),
2563 'attendyes' => array(),
2564 'attendno' => array(),
2565 'attendmaybe' => array(),
2568 $items = q('SELECT * FROM item
2569 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2570 intval($item['uid']),
2571 dbesc($item['uri']));
2573 foreach ($items as $i) {
2574 // not used as result should be structured like other user data
2575 //builtin_activity_puller($i, $activities);
2577 // get user data and add it to the array of the activity
2578 $user = api_get_user($a, $i['author-link']);
2579 switch ($i['verb']) {
2581 $activities['like'][] = $user;
2583 case ACTIVITY_DISLIKE:
2584 $activities['dislike'][] = $user;
2586 case ACTIVITY_ATTEND:
2587 $activities['attendyes'][] = $user;
2589 case ACTIVITY_ATTENDNO:
2590 $activities['attendno'][] = $user;
2592 case ACTIVITY_ATTENDMAYBE:
2593 $activities['attendmaybe'][] = $user;
2600 if ($type == "xml") {
2601 $xml_activities = array();
2602 foreach ($activities as $k => $v) {
2603 // change xml element from "like" to "friendica:like"
2604 $xml_activities["friendica:".$k] = $v;
2605 // add user data into xml output
2607 foreach ($v as $user)
2608 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2610 $activities = $xml_activities;
2619 * @brief return data from profiles
2621 * @param array $profile array containing data from db table 'profile'
2622 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2625 function api_format_items_profiles(&$profile = null, $type = "json") {
2626 if ($profile != null) {
2627 $profile = array('profile_id' => $profile['id'],
2628 'profile_name' => $profile['profile-name'],
2629 'is_default' => $profile['is-default'] ? true : false,
2630 'hide_friends'=> $profile['hide-friends'] ? true : false,
2631 'profile_photo' => $profile['photo'],
2632 'profile_thumb' => $profile['thumb'],
2633 'publish' => $profile['publish'] ? true : false,
2634 'net_publish' => $profile['net-publish'] ? true : false,
2635 'description' => $profile['pdesc'],
2636 'date_of_birth' => $profile['dob'],
2637 'address' => $profile['address'],
2638 'city' => $profile['locality'],
2639 'region' => $profile['region'],
2640 'postal_code' => $profile['postal-code'],
2641 'country' => $profile['country-name'],
2642 'hometown' => $profile['hometown'],
2643 'gender' => $profile['gender'],
2644 'marital' => $profile['marital'],
2645 'marital_with' => $profile['with'],
2646 'marital_since' => $profile['howlong'],
2647 'sexual' => $profile['sexual'],
2648 'politic' => $profile['politic'],
2649 'religion' => $profile['religion'],
2650 'public_keywords' => $profile['pub_keywords'],
2651 'private_keywords' => $profile['prv_keywords'],
2652 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2653 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2654 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2655 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2656 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2657 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2658 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2659 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2660 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2661 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2662 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2663 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2664 'homepage' => $profile['homepage'],
2671 * @brief format items to be returned by api
2673 * @param array $r array of items
2674 * @param array $user_info
2675 * @param bool $filter_user filter items by $user_info
2677 function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2683 foreach ($r as $item) {
2685 localize_item($item);
2686 list($status_user, $owner_user) = api_item_get_user($a, $item);
2688 // Look if the posts are matching if they should be filtered by user id
2689 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2693 $in_reply_to = api_in_reply_to($item);
2695 $converted = api_convert_item($item);
2697 if ($type == "xml") {
2698 $geo = "georss:point";
2704 'text' => $converted["text"],
2705 'truncated' => False,
2706 'created_at'=> api_date($item['created']),
2707 'in_reply_to_status_id' => $in_reply_to['status_id'],
2708 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2709 'source' => (($item['app']) ? $item['app'] : 'web'),
2710 'id' => intval($item['id']),
2711 'id_str' => (string) intval($item['id']),
2712 'in_reply_to_user_id' => $in_reply_to['user_id'],
2713 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2714 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2716 'favorited' => $item['starred'] ? true : false,
2717 'user' => $status_user ,
2718 'friendica_owner' => $owner_user,
2719 //'entities' => NULL,
2720 'statusnet_html' => $converted["html"],
2721 'statusnet_conversation_id' => $item['parent'],
2722 'friendica_activities' => api_format_items_activities($item, $type),
2725 if (count($converted["attachments"]) > 0) {
2726 $status["attachments"] = $converted["attachments"];
2729 if (count($converted["entities"]) > 0) {
2730 $status["entities"] = $converted["entities"];
2733 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2734 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2735 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2736 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2740 // Retweets are only valid for top postings
2741 // It doesn't work reliable with the link if its a feed
2742 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2744 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2747 if ($item["id"] == $item["parent"]) {
2748 $retweeted_item = api_share_as_retweet($item);
2749 if ($retweeted_item !== false) {
2750 $retweeted_status = $status;
2752 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2753 } catch( BadRequestException $e ) {
2754 // user not found. should be found?
2755 /// @todo check if the user should be always found
2756 $retweeted_status["user"] = array();
2759 $rt_converted = api_convert_item($retweeted_item);
2761 $retweeted_status['text'] = $rt_converted["text"];
2762 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2763 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2764 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2765 $status['retweeted_status'] = $retweeted_status;
2769 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2770 unset($status["user"]["uid"]);
2771 unset($status["user"]["self"]);
2773 if ($item["coord"] != "") {
2774 $coords = explode(' ',$item["coord"]);
2775 if (count($coords) == 2) {
2776 if ($type == "json")
2777 $status["geo"] = array('type' => 'Point',
2778 'coordinates' => array((float) $coords[0],
2779 (float) $coords[1]));
2780 else // Not sure if this is the official format - if someone founds a documentation we can check
2781 $status["georss:point"] = $item["coord"];
2789 function api_account_rate_limit_status($type) {
2791 if ($type == "xml") {
2793 'remaining-hits' => '150',
2794 '@attributes' => array("type" => "integer"),
2795 'hourly-limit' => '150',
2796 '@attributes2' => array("type" => "integer"),
2797 'reset-time' => datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME),
2798 '@attributes3' => array("type" => "datetime"),
2799 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2800 '@attributes4' => array("type" => "integer"),
2804 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2805 'remaining_hits' => '150',
2806 'hourly_limit' => '150',
2807 'reset_time' => api_date(datetime_convert('UTC', 'UTC','now + 1 hour',ATOM_TIME)),
2811 return api_format_data('hash', $type, array('hash' => $hash));
2814 /// @TODO move to top of file or somwhere better
2815 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2817 function api_help_test($type) {
2818 if ($type == 'xml') {
2824 return api_format_data('ok', $type, array("ok" => $ok));
2827 /// @TODO move to top of file or somwhere better
2828 api_register_func('api/help/test','api_help_test', false);
2830 function api_lists($type) {
2832 /// @TODO $ret is not filled here?
2833 return api_format_data('lists', $type, array("lists_list" => $ret));
2836 /// @TODO move to top of file or somwhere better
2837 api_register_func('api/lists','api_lists',true);
2839 function api_lists_list($type) {
2841 /// @TODO $ret is not filled here?
2842 return api_format_data('lists', $type, array("lists_list" => $ret));
2845 /// @TODO move to top of file or somwhere better
2846 api_register_func('api/lists/list','api_lists_list',true);
2849 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2850 * This function is deprecated by Twitter
2851 * returns: json, xml
2853 function api_statuses_f($type, $qtype) {
2857 if (api_user() === false) {
2858 throw new ForbiddenException();
2861 $user_info = api_get_user($a);
2863 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2864 /* this is to stop Hotot to load friends multiple times
2865 * I'm not sure if I'm missing return something or
2866 * is a bug in hotot. Workaround, meantime
2870 return array('$users' => $ret);*/
2874 if ($qtype == 'friends') {
2875 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2877 if ($qtype == 'followers') {
2878 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2881 // friends and followers only for self
2882 if ($user_info['self'] == 0) {
2883 $sql_extra = " AND false ";
2886 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2891 foreach ($r as $cid) {
2892 $user = api_get_user($a, $cid['nurl']);
2893 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2894 unset($user["uid"]);
2895 unset($user["self"]);
2902 return array('user' => $ret);
2906 function api_statuses_friends($type) {
2907 $data = api_statuses_f($type, "friends");
2908 if ($data === false) {
2911 return api_format_data("users", $type, $data);
2914 function api_statuses_followers($type) {
2915 $data = api_statuses_f($type, "followers");
2916 if ($data === false) {
2919 return api_format_data("users", $type, $data);
2922 /// @TODO move to top of file or somewhere better
2923 api_register_func('api/statuses/friends','api_statuses_friends',true);
2924 api_register_func('api/statuses/followers','api_statuses_followers',true);
2926 function api_statusnet_config($type) {
2930 $name = $a->config['sitename'];
2931 $server = $a->get_hostname();
2932 $logo = System::baseUrl() . '/images/friendica-64.png';
2933 $email = $a->config['admin_email'];
2934 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2935 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2936 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2937 if ($a->config['api_import_size']) {
2938 $texlimit = string($a->config['api_import_size']);
2940 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2941 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',System::baseUrl()) : '');
2944 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2945 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2946 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2947 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2948 'shorturllength' => '30',
2949 'friendica' => array(
2950 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2951 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2952 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2953 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2958 return api_format_data('config', $type, array('config' => $config));
2962 /// @TODO move to top of file or somewhere better
2963 api_register_func('api/gnusocial/config','api_statusnet_config', false);
2964 api_register_func('api/statusnet/config','api_statusnet_config', false);
2966 function api_statusnet_version($type) {
2968 $fake_statusnet_version = "0.9.7";
2970 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2973 /// @TODO move to top of file or somewhere better
2974 api_register_func('api/gnusocial/version','api_statusnet_version', false);
2975 api_register_func('api/statusnet/version','api_statusnet_version', false);
2978 * @todo use api_format_data() to return data
2980 function api_ff_ids($type,$qtype) {
2985 throw new ForbiddenException();
2988 $user_info = api_get_user($a);
2990 if ($qtype == 'friends') {
2991 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2993 if ($qtype == 'followers') {
2994 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2997 if (!$user_info["self"]) {
2998 $sql_extra = " AND false ";
3001 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3003 $r = q("SELECT `pcontact`.`id` FROM `contact`
3004 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3005 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3009 if (!DBM::is_result($r)) {
3014 foreach ($r as $rr) {
3015 if ($stringify_ids) {
3018 $ids[] = intval($rr['id']);
3022 return api_format_data("ids", $type, array('id' => $ids));
3025 function api_friends_ids($type) {
3026 return api_ff_ids($type,'friends');
3029 function api_followers_ids($type) {
3030 return api_ff_ids($type,'followers');
3033 /// @TODO move to top of file or somewhere better
3034 api_register_func('api/friends/ids','api_friends_ids',true);
3035 api_register_func('api/followers/ids','api_followers_ids',true);
3037 function api_direct_messages_new($type) {
3041 if (api_user() === false) throw new ForbiddenException();
3043 if (!x($_POST, "text") || (!x($_POST,"screen_name") && !x($_POST,"user_id"))) return;
3045 $sender = api_get_user($a);
3047 if ($_POST['screen_name']) {
3048 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3050 dbesc($_POST['screen_name']));
3052 // Selecting the id by priority, friendica first
3053 api_best_nickname($r);
3055 $recipient = api_get_user($a, $r[0]['nurl']);
3057 $recipient = api_get_user($a, $_POST['user_id']);
3062 if (x($_REQUEST, 'replyto')) {
3063 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3065 intval($_REQUEST['replyto']));
3066 $replyto = $r[0]['parent-uri'];
3067 $sub = $r[0]['title'];
3069 if (x($_REQUEST, 'title')) {
3070 $sub = $_REQUEST['title'];
3072 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'],0,10)."...":$_POST['text']);
3076 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3079 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3080 $ret = api_format_messages($r[0], $recipient, $sender);
3082 $ret = array("error"=>$id);
3085 $data = array('direct_message'=>$ret);
3090 $data = api_rss_extra($a, $data, $user_info);
3093 return api_format_data("direct-messages", $type, $data);
3097 /// @TODO move to top of file or somewhere better
3098 api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
3101 * @brief delete a direct_message from mail table through api
3103 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3106 function api_direct_messages_destroy($type) {
3109 if (api_user() === false) {
3110 throw new ForbiddenException();
3114 $user_info = api_get_user($a);
3116 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3118 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3119 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3120 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3122 $uid = $user_info['uid'];
3123 // error if no id or parenturi specified (for clients posting parent-uri as well)
3124 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3125 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3126 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3129 // BadRequestException if no id specified (for clients using Twitter API)
3131 throw new BadRequestException('Message id not specified');
3134 // add parent-uri to sql command if specified by calling app
3135 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3137 // get data of the specified message id
3138 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3142 // error message if specified id is not in database
3143 if (!DBM::is_result($r)) {
3144 if ($verbose == "true") {
3145 $answer = array('result' => 'error', 'message' => 'message id not in database');
3146 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3148 /// @todo BadRequestException ok for Twitter API clients?
3149 throw new BadRequestException('message id not in database');
3153 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3157 if ($verbose == "true") {
3160 $answer = array('result' => 'ok', 'message' => 'message deleted');
3161 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3163 $answer = array('result' => 'error', 'message' => 'unknown error');
3164 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3167 /// @todo return JSON data like Twitter API not yet implemented
3171 /// @TODO move to top of file or somewhere better
3172 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3174 function api_direct_messages_box($type, $box, $verbose) {
3178 if (api_user() === false) {
3179 throw new ForbiddenException();
3183 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3184 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3189 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3190 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3192 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3193 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3196 unset($_REQUEST["user_id"]);
3197 unset($_GET["user_id"]);
3199 unset($_REQUEST["screen_name"]);
3200 unset($_GET["screen_name"]);
3202 $user_info = api_get_user($a);
3203 $profile_url = $user_info["url"];
3206 $start = $page * $count;
3209 if ($box=="sentbox") {
3210 $sql_extra = "`mail`.`from-url`='" . dbesc( $profile_url ) . "'";
3211 } elseif ($box == "conversation") {
3212 $sql_extra = "`mail`.`parent-uri`='" . dbesc( $_GET["uri"] ) . "'";
3213 } elseif ($box == "all") {
3214 $sql_extra = "true";
3215 } elseif ($box == "inbox") {
3216 $sql_extra = "`mail`.`from-url`!='" . dbesc( $profile_url ) . "'";
3220 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3223 if ($user_id != "") {
3224 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3225 } elseif ($screen_name !="") {
3226 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3229 $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",
3232 intval($start), intval($count)
3234 if ($verbose == "true" && !DBM::is_result($r)) {
3235 $answer = array('result' => 'error', 'message' => 'no mails available');
3236 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3240 foreach ($r as $item) {
3241 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3242 $recipient = $user_info;
3243 $sender = api_get_user($a,normalise_link($item['contact-url']));
3244 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3245 $recipient = api_get_user($a,normalise_link($item['contact-url']));
3246 $sender = $user_info;
3249 $ret[] = api_format_messages($item, $recipient, $sender);
3253 $data = array('direct_message' => $ret);
3257 $data = api_rss_extra($a, $data, $user_info);
3260 return api_format_data("direct-messages", $type, $data);
3264 function api_direct_messages_sentbox($type) {
3265 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3266 return api_direct_messages_box($type, "sentbox", $verbose);
3269 function api_direct_messages_inbox($type) {
3270 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3271 return api_direct_messages_box($type, "inbox", $verbose);
3274 function api_direct_messages_all($type) {
3275 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3276 return api_direct_messages_box($type, "all", $verbose);
3279 function api_direct_messages_conversation($type) {
3280 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3281 return api_direct_messages_box($type, "conversation", $verbose);
3284 /// @TODO move to top of file or somewhere better
3285 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3286 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3287 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3288 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3290 function api_oauth_request_token($type) {
3292 $oauth = new FKOAuth1();
3293 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3294 } catch (Exception $e) {
3295 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3302 function api_oauth_access_token($type) {
3304 $oauth = new FKOAuth1();
3305 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3306 } catch (Exception $e) {
3307 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3313 /// @TODO move to top of file or somewhere better
3314 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3315 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3319 * @brief delete a complete photoalbum with all containing photos from database through api
3321 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3324 function api_fr_photoalbum_delete($type) {
3325 if (api_user() === false) {
3326 throw new ForbiddenException();
3329 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3331 // we do not allow calls without album string
3333 throw new BadRequestException("no albumname specified");
3335 // check if album is existing
3336 $r = q("SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3339 if (!DBM::is_result($r))
3340 throw new BadRequestException("album not available");
3342 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3343 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3344 foreach ($r as $rr) {
3345 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3346 intval(local_user()),
3347 dbesc($rr['resource-id'])
3350 if (!DBM::is_result($photo_item)) {
3351 throw new InternalServerErrorException("problem with deleting items occured");
3353 drop_item($photo_item[0]['id'],false);
3356 // now let's delete all photos from the album
3357 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3361 // return success of deletion or error message
3363 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3364 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3366 throw new InternalServerErrorException("unknown error - deleting from database failed");
3372 * @brief update the name of the album for all photos of an album
3374 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3377 function api_fr_photoalbum_update($type) {
3378 if (api_user() === false) {
3379 throw new ForbiddenException();
3382 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : "");
3383 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : "");
3385 // we do not allow calls without album string
3387 throw new BadRequestException("no albumname specified");
3389 if ($album_new == "") {
3390 throw new BadRequestException("no new albumname specified");
3392 // check if album is existing
3393 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3396 if (!DBM::is_result($r)) {
3397 throw new BadRequestException("album not available");
3399 // now let's update all photos to the albumname
3400 $result = q("UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3405 // return success of updating or error message
3407 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3408 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3410 throw new InternalServerErrorException("unknown error - updating in database failed");
3416 * @brief list all photos of the authenticated user
3418 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3421 function api_fr_photos_list($type) {
3422 if (api_user() === false) {
3423 throw new ForbiddenException();
3425 $r = q("SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3426 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3427 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3428 intval(local_user())
3431 'image/jpeg' => 'jpg',
3432 'image/png' => 'png',
3433 'image/gif' => 'gif'
3435 $data = array('photo'=>array());
3436 if (DBM::is_result($r)) {
3437 foreach ($r as $rr) {
3439 $photo['id'] = $rr['resource-id'];
3440 $photo['album'] = $rr['album'];
3441 $photo['filename'] = $rr['filename'];
3442 $photo['type'] = $rr['type'];
3443 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3444 $photo['created'] = $rr['created'];
3445 $photo['edited'] = $rr['edited'];
3446 $photo['desc'] = $rr['desc'];
3448 if ($type == "xml") {
3449 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3451 $photo['thumb'] = $thumb;
3452 $data['photo'][] = $photo;
3456 return api_format_data("photos", $type, $data);
3460 * @brief upload a new photo or change an existing photo
3462 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3465 function api_fr_photo_create_update($type) {
3466 if (api_user() === false) {
3467 throw new ForbiddenException();
3470 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3471 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3472 $album = (x($_REQUEST,'album') ? $_REQUEST['album'] : null);
3473 $album_new = (x($_REQUEST,'album_new') ? $_REQUEST['album_new'] : null);
3474 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3475 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3476 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3477 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3478 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3480 // do several checks on input parameters
3481 // we do not allow calls without album string
3482 if ($album == null) {
3483 throw new BadRequestException("no albumname specified");
3485 // if photo_id == null --> we are uploading a new photo
3486 if ($photo_id == null) {
3489 // error if no media posted in create-mode
3490 if (!x($_FILES,'media')) {
3492 throw new BadRequestException("no media data submitted");
3495 // album_new will be ignored in create-mode
3500 // check if photo is existing in database
3501 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3505 if (!DBM::is_result($r)) {
3506 throw new BadRequestException("photo not available");
3510 // checks on acl strings provided by clients
3511 $acl_input_error = false;
3512 $acl_input_error |= check_acl_input($allow_cid);
3513 $acl_input_error |= check_acl_input($deny_cid);
3514 $acl_input_error |= check_acl_input($allow_gid);
3515 $acl_input_error |= check_acl_input($deny_gid);
3516 if ($acl_input_error) {
3517 throw new BadRequestException("acl data invalid");
3519 // now let's upload the new media in create-mode
3520 if ($mode == "create") {
3521 $media = $_FILES['media'];
3522 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3524 // return success of updating or error message
3525 if (!is_null($data)) {
3526 return api_format_data("photo_create", $type, $data);
3528 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3532 // now let's do the changes in update-mode
3533 if ($mode == "update") {
3536 if (!is_null($desc)) {
3537 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3540 if (!is_null($album_new)) {
3541 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3544 if (!is_null($allow_cid)) {
3545 $allow_cid = trim($allow_cid);
3546 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3549 if (!is_null($deny_cid)) {
3550 $deny_cid = trim($deny_cid);
3551 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3554 if (!is_null($allow_gid)) {
3555 $allow_gid = trim($allow_gid);
3556 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3559 if (!is_null($deny_gid)) {
3560 $deny_gid = trim($deny_gid);
3561 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3565 if ($sql_extra != "") {
3566 $nothingtodo = false;
3567 $result = q("UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3569 datetime_convert(), // update edited timestamp
3574 $nothingtodo = true;
3577 if (x($_FILES,'media')) {
3578 $nothingtodo = false;
3579 $media = $_FILES['media'];
3580 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3581 if (!is_null($data)) {
3582 return api_format_data("photo_update", $type, $data);
3586 // return success of updating or error message
3588 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3589 return api_format_data("photo_update", $type, array('$result' => $answer));
3592 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3593 return api_format_data("photo_update", $type, array('$result' => $answer));
3595 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3598 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3603 * @brief delete a single photo from the database through api
3605 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3608 function api_fr_photo_delete($type) {
3609 if (api_user() === false) {
3610 throw new ForbiddenException();
3613 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3615 // do several checks on input parameters
3616 // we do not allow calls without photo id
3617 if ($photo_id == null) {
3618 throw new BadRequestException("no photo_id specified");
3620 // check if photo is existing in database
3621 $r = q("SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3625 if (!DBM::is_result($r)) {
3626 throw new BadRequestException("photo not available");
3628 // now we can perform on the deletion of the photo
3629 $result = q("DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3633 // return success of deletion or error message
3635 // retrieve the id of the parent element (the photo element)
3636 $photo_item = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3637 intval(local_user()),
3641 if (!DBM::is_result($photo_item)) {
3642 throw new InternalServerErrorException("problem with deleting items occured");
3644 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3645 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3646 drop_item($photo_item[0]['id'], false);
3648 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3649 return api_format_data("photo_delete", $type, array('$result' => $answer));
3651 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3657 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3659 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3662 function api_fr_photo_detail($type) {
3663 if (api_user() === false) {
3664 throw new ForbiddenException();
3666 if (!x($_REQUEST, 'photo_id')) {
3667 throw new BadRequestException("No photo id.");
3670 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3671 $photo_id = $_REQUEST['photo_id'];
3673 // prepare json/xml output with data from database for the requested photo
3674 $data = prepare_photo_data($type, $scale, $photo_id);
3676 return api_format_data("photo_detail", $type, $data);
3681 * @brief updates the profile image for the user (either a specified profile or the default profile)
3683 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3686 function api_account_update_profile_image($type) {
3687 if (api_user() === false) {
3688 throw new ForbiddenException();
3691 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3693 // error if image data is missing
3694 if (!x($_FILES, 'image')) {
3695 throw new BadRequestException("no media data submitted");
3698 // check if specified profile id is valid
3699 if ($profileid != 0) {
3700 $r = q("SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3702 intval($profileid));
3703 // error message if specified profile id is not in database
3704 if (!DBM::is_result($r)) {
3705 throw new BadRequestException("profile_id not available");
3707 $is_default_profile = $r['profile'];
3709 $is_default_profile = 1;
3712 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3714 if (x($_FILES, 'image')) {
3715 $media = $_FILES['image'];
3716 } elseif (x($_FILES, 'media')) {
3717 $media = $_FILES['media'];
3719 // save new profile image
3720 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3723 if (is_array($media['type'])) {
3724 $filetype = $media['type'][0];
3726 $filetype = $media['type'];
3728 if ($filetype == "image/jpeg") {
3730 } elseif ($filetype == "image/png") {
3733 // change specified profile or all profiles to the new resource-id
3734 if ($is_default_profile) {
3735 $r = q("UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3736 dbesc($data['photo']['id']),
3737 intval(local_user())
3740 $r = q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3741 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3742 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3743 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3744 intval(local_user())
3747 $r = q("UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3748 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3749 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3750 intval($_REQUEST['profile']),
3751 intval(local_user())
3755 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3756 // so that browsers will do a cache update unconditionally
3758 $r = q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3759 dbesc(datetime_convert()),
3760 intval(local_user())
3763 // Update global directory in background
3764 //$user = api_get_user(get_app());
3765 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3766 if ($url && strlen(Config::get('system', 'directory'))) {
3767 Worker::add(PRIORITY_LOW, "directory", $url);
3770 Worker::add(PRIORITY_LOW, 'profile_update', api_user());
3772 // output for client
3774 return api_account_verify_credentials($type);
3776 // SaveMediaToDatabase failed for some reason
3777 throw new InternalServerErrorException("image upload failed");
3781 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3782 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3783 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3784 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3785 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3786 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3787 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3788 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3789 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3792 function check_acl_input($acl_string) {
3793 if ($acl_string == null || $acl_string == " ") {
3796 $contact_not_found = false;
3798 // split <x><y><z> into array of cid's
3799 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3801 // check for each cid if it is available on server
3802 $cid_array = $array[0];
3803 foreach ($cid_array as $cid) {
3804 $cid = str_replace("<", "", $cid);
3805 $cid = str_replace(">", "", $cid);
3806 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3808 intval(api_user()));
3809 $contact_not_found |= !DBM::is_result($contact);
3811 return $contact_not_found;
3814 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) {
3821 if (is_array($media)) {
3822 if (is_array($media['tmp_name'])) {
3823 $src = $media['tmp_name'][0];
3825 $src = $media['tmp_name'];
3827 if (is_array($media['name'])) {
3828 $filename = basename($media['name'][0]);
3830 $filename = basename($media['name']);
3832 if (is_array($media['size'])) {
3833 $filesize = intval($media['size'][0]);
3835 $filesize = intval($media['size']);
3837 if (is_array($media['type'])) {
3838 $filetype = $media['type'][0];
3840 $filetype = $media['type'];
3844 if ($filetype == "") {
3845 $filetype=guess_image_type($filename);
3847 $imagedata = getimagesize($src);
3849 $filetype = $imagedata['mime'];
3851 logger("File upload src: " . $src . " - filename: " . $filename .
3852 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG);
3854 // check if there was a php upload error
3855 if ($filesize == 0 && $media['error'] == 1) {
3856 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3858 // check against max upload size within Friendica instance
3859 $maximagesize = Config::get('system', 'maximagesize');
3860 if (($maximagesize) && ($filesize > $maximagesize)) {
3861 $formattedBytes = formatBytes($maximagesize);
3862 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3865 // create Photo instance with the data of the image
3866 $imagedata = @file_get_contents($src);
3867 $ph = new Photo($imagedata, $filetype);
3868 if (! $ph->is_valid()) {
3869 throw new InternalServerErrorException("unable to process image data");
3872 // check orientation of image
3876 // check max length of images on server
3877 $max_length = Config::get('system', 'max_image_length');
3878 if (! $max_length) {
3879 $max_length = MAX_IMAGE_LENGTH;
3881 if ($max_length > 0) {
3882 $ph->scaleImage($max_length);
3883 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3885 $width = $ph->getWidth();
3886 $height = $ph->getHeight();
3888 // create a new resource-id if not already provided
3889 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
3891 if ($mediatype == "photo") {
3892 // upload normal image (scales 0, 1, 2)
3893 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
3895 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3897 logger("photo upload: image upload with scale 0 (original size) failed");
3899 if($width > 640 || $height > 640) {
3900 $ph->scaleImage(640);
3901 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3903 logger("photo upload: image upload with scale 1 (640x640) failed");
3907 if ($width > 320 || $height > 320) {
3908 $ph->scaleImage(320);
3909 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3911 logger("photo upload: image upload with scale 2 (320x320) failed");
3914 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
3915 } elseif ($mediatype == "profileimage") {
3916 // upload profile image (scales 4, 5, 6)
3917 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
3919 if ($width > 175 || $height > 175) {
3920 $ph->scaleImage(175);
3921 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3923 logger("photo upload: profile image upload with scale 4 (175x175) failed");
3927 if ($width > 80 || $height > 80) {
3928 $ph->scaleImage(80);
3929 $r = $ph->store(local_user(),$visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3931 logger("photo upload: profile image upload with scale 5 (80x80) failed");
3935 if ($width > 48 || $height > 48) {
3936 $ph->scaleImage(48);
3937 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3939 logger("photo upload: profile image upload with scale 6 (48x48) failed");
3943 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
3947 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3948 if ($photo_id == null && $mediatype == "photo") {
3949 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3951 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3952 return prepare_photo_data($type, false, $hash);
3954 throw new InternalServerErrorException("image upload failed");
3958 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false) {
3959 // get data about the api authenticated user
3960 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
3961 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
3964 $arr['guid'] = get_guid(32);
3965 $arr['uid'] = intval(api_user());
3967 $arr['parent-uri'] = $uri;
3968 $arr['type'] = 'photo';
3970 $arr['resource-id'] = $hash;
3971 $arr['contact-id'] = $owner_record[0]['id'];
3972 $arr['owner-name'] = $owner_record[0]['name'];
3973 $arr['owner-link'] = $owner_record[0]['url'];
3974 $arr['owner-avatar'] = $owner_record[0]['thumb'];
3975 $arr['author-name'] = $owner_record[0]['name'];
3976 $arr['author-link'] = $owner_record[0]['url'];
3977 $arr['author-avatar'] = $owner_record[0]['thumb'];
3979 $arr['allow_cid'] = $allow_cid;
3980 $arr['allow_gid'] = $allow_gid;
3981 $arr['deny_cid'] = $deny_cid;
3982 $arr['deny_gid'] = $deny_gid;
3983 $arr['last-child'] = 1;
3984 $arr['visible'] = $visibility;
3988 'image/jpeg' => 'jpg',
3989 'image/png' => 'png',
3990 'image/gif' => 'gif'
3993 // adds link to the thumbnail scale photo
3994 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
3995 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3998 // do the magic for storing the item in the database and trigger the federation to other contacts
4002 function prepare_photo_data($type, $scale, $photo_id) {
4003 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4004 $data_sql = ($scale === false ? "" : "data, ");
4006 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4007 // clients needs to convert this in their way for further processing
4008 $r = q("SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4009 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4010 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4011 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4013 intval(local_user()),
4019 'image/jpeg' => 'jpg',
4020 'image/png' => 'png',
4021 'image/gif' => 'gif'
4024 // prepare output data for photo
4025 if (DBM::is_result($r)) {
4026 $data = array('photo' => $r[0]);
4027 $data['photo']['id'] = $data['photo']['resource-id'];
4028 if ($scale !== false) {
4029 $data['photo']['data'] = base64_encode($data['photo']['data']);
4031 unset($data['photo']['datasize']); //needed only with scale param
4033 if ($type == "xml") {
4034 $data['photo']['links'] = array();
4035 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4036 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4038 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4041 $data['photo']['link'] = array();
4042 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4044 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4045 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4049 unset($data['photo']['resource-id']);
4050 unset($data['photo']['minscale']);
4051 unset($data['photo']['maxscale']);
4054 throw new NotFoundException();
4057 // retrieve item element for getting activities (like, dislike etc.) related to photo
4058 $item = q("SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4059 intval(local_user()),
4062 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4064 // retrieve comments on photo
4065 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4066 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4067 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4068 `contact`.`id` AS `cid`
4070 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4071 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4072 WHERE `item`.`parent` = %d AND `item`.`visible`
4073 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4074 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4075 intval($item[0]['parent']),
4077 dbesc(ACTIVITY_POST)
4080 // prepare output of comments
4081 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4082 $comments = array();
4083 if ($type == "xml") {
4085 foreach ($commentData as $comment) {
4086 $comments[$k++ . ":comment"] = $comment;
4089 foreach ($commentData as $comment) {
4090 $comments[] = $comment;
4093 $data['photo']['friendica_comments'] = $comments;
4095 // include info if rights on photo and rights on item are mismatching
4096 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4097 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4098 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4099 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4100 $data['photo']['rights_mismatch'] = $rights_mismatch;
4107 * similar as /mod/redir.php
4108 * redirect to 'url' after dfrn auth
4110 * why this when there is mod/redir.php already?
4111 * This use api_user() and api_login()
4114 * c_url: url of remote contact to auth to
4115 * url: string, url to redirect after auth
4117 function api_friendica_remoteauth() {
4118 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4119 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4121 if ($url === '' || $c_url === '') {
4122 throw new BadRequestException("Wrong parameters.");
4125 $c_url = normalise_link($c_url);
4129 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4134 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4135 throw new BadRequestException("Unknown contact");
4140 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4142 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4143 $orig_id = $r[0]['issued-id'];
4144 $dfrn_id = '1:' . $orig_id;
4146 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4147 $orig_id = $r[0]['dfrn-id'];
4148 $dfrn_id = '0:' . $orig_id;
4151 $sec = random_string();
4153 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4154 VALUES( %d, %s, '%s', '%s', %d )",
4162 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4163 $dest = (($url) ? '&destination_url=' . $url : '');
4164 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4165 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4166 . '&type=profile&sec=' . $sec . $dest . $quiet );
4168 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4171 * @brief Return the item shared, if the item contains only the [share] tag
4173 * @param array $item Sharer item
4174 * @return array Shared item or false if not a reshare
4176 function api_share_as_retweet(&$item) {
4177 $body = trim($item["body"]);
4179 if (Diaspora::is_reshare($body, false)===false) {
4183 /// @TODO "$1" should maybe mean '$1' ?
4184 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4186 * Skip if there is no shared message in there
4187 * we already checked this in diaspora::is_reshare()
4188 * but better one more than one less...
4190 if ($body == $attributes) {
4195 // build the fake reshared item
4196 $reshared_item = $item;
4199 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4200 if ($matches[1] != "") {
4201 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4204 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4205 if ($matches[1] != "") {
4206 $author = $matches[1];
4210 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4211 if ($matches[1] != "") {
4212 $profile = $matches[1];
4215 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4216 if ($matches[1] != "") {
4217 $profile = $matches[1];
4221 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4222 if ($matches[1] != "") {
4223 $avatar = $matches[1];
4226 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4227 if ($matches[1] != "") {
4228 $avatar = $matches[1];
4232 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4233 if ($matches[1] != "") {
4234 $link = $matches[1];
4237 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4238 if ($matches[1] != "") {
4239 $link = $matches[1];
4243 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4244 if ($matches[1] != "")
4245 $posted = $matches[1];
4247 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4248 if ($matches[1] != "") {
4249 $posted = $matches[1];
4252 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
4254 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4258 $reshared_item["body"] = $shared_body;
4259 $reshared_item["author-name"] = $author;
4260 $reshared_item["author-link"] = $profile;
4261 $reshared_item["author-avatar"] = $avatar;
4262 $reshared_item["plink"] = $link;
4263 $reshared_item["created"] = $posted;
4264 $reshared_item["edited"] = $posted;
4266 return $reshared_item;
4270 function api_get_nick($profile) {
4272 - remove trailing junk from profile url
4273 - pump.io check has to check the website
4278 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4279 dbesc(normalise_link($profile)));
4281 if (DBM::is_result($r)) {
4282 $nick = $r[0]["nick"];
4286 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4287 dbesc(normalise_link($profile)));
4289 if (DBM::is_result($r)) {
4290 $nick = $r[0]["nick"];
4295 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4296 if ($friendica != $profile) {
4302 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4303 if ($diaspora != $profile) {
4309 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4310 if ($twitter != $profile) {
4317 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4318 if ($StatusnetHost != $profile) {
4319 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4320 if ($StatusnetUser != $profile) {
4321 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4322 $user = json_decode($UserData);
4324 $nick = $user->screen_name;
4330 // To-Do: look at the page if its really a pumpio site
4331 //if (!$nick == "") {
4332 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4333 // if ($pumpio != $profile)
4335 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4346 function api_in_reply_to($item) {
4347 $in_reply_to = array();
4349 $in_reply_to['status_id'] = NULL;
4350 $in_reply_to['user_id'] = NULL;
4351 $in_reply_to['status_id_str'] = NULL;
4352 $in_reply_to['user_id_str'] = NULL;
4353 $in_reply_to['screen_name'] = NULL;
4355 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4356 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4357 intval($item['uid']),
4358 dbesc($item['thr-parent']));
4360 if (DBM::is_result($r)) {
4361 $in_reply_to['status_id'] = intval($r[0]['id']);
4363 $in_reply_to['status_id'] = intval($item['parent']);
4366 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4368 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4369 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4370 WHERE `item`.`id` = %d LIMIT 1",
4371 intval($in_reply_to['status_id'])
4374 if (DBM::is_result($r)) {
4375 if ($r[0]['nick'] == "") {
4376 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4379 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4380 $in_reply_to['user_id'] = intval($r[0]['id']);
4381 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4384 // There seems to be situation, where both fields are identical:
4385 // https://github.com/friendica/friendica/issues/1010
4386 // This is a bugfix for that.
4387 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4388 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4389 $in_reply_to['status_id'] = NULL;
4390 $in_reply_to['user_id'] = NULL;
4391 $in_reply_to['status_id_str'] = NULL;
4392 $in_reply_to['user_id_str'] = NULL;
4393 $in_reply_to['screen_name'] = NULL;
4397 return $in_reply_to;
4400 function api_clean_plain_items($Text) {
4401 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4403 $Text = bb_CleanPictureLinks($Text);
4404 $URLSearchString = "^\[\]";
4406 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
4408 if ($include_entities == "true") {
4409 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
4412 // Simplify "attachment" element
4413 $Text = api_clean_attachments($Text);
4419 * @brief Removes most sharing information for API text export
4421 * @param string $body The original body
4423 * @return string Cleaned body
4425 function api_clean_attachments($body) {
4426 $data = get_attachment_data($body);
4433 if (isset($data["text"]))
4434 $body = $data["text"];
4436 if (($body == "") && (isset($data["title"])))
4437 $body = $data["title"];
4439 if (isset($data["url"]))
4440 $body .= "\n".$data["url"];
4442 $body .= $data["after"];
4447 function api_best_nickname(&$contacts) {
4448 $best_contact = array();
4450 if (count($contact) == 0)
4453 foreach ($contacts AS $contact)
4454 if ($contact["network"] == "") {
4455 $contact["network"] = "dfrn";
4456 $best_contact = array($contact);
4459 if (sizeof($best_contact) == 0)
4460 foreach ($contacts AS $contact)
4461 if ($contact["network"] == "dfrn")
4462 $best_contact = array($contact);
4464 if (sizeof($best_contact) == 0)
4465 foreach ($contacts AS $contact)
4466 if ($contact["network"] == "dspr")
4467 $best_contact = array($contact);
4469 if (sizeof($best_contact) == 0)
4470 foreach ($contacts AS $contact)
4471 if ($contact["network"] == "stat")
4472 $best_contact = array($contact);
4474 if (sizeof($best_contact) == 0)
4475 foreach ($contacts AS $contact)
4476 if ($contact["network"] == "pump")
4477 $best_contact = array($contact);
4479 if (sizeof($best_contact) == 0)
4480 foreach ($contacts AS $contact)
4481 if ($contact["network"] == "twit")
4482 $best_contact = array($contact);
4484 if (sizeof($best_contact) == 1)
4485 $contacts = $best_contact;
4487 $contacts = array($contacts[0]);
4490 // return all or a specified group of the user with the containing contacts
4491 function api_friendica_group_show($type) {
4495 if (api_user() === false) throw new ForbiddenException();
4498 $user_info = api_get_user($a);
4499 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4500 $uid = $user_info['uid'];
4502 // get data of the specified group id or all groups if not specified
4504 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4507 // error message if specified gid is not in database
4508 if (!DBM::is_result($r))
4509 throw new BadRequestException("gid not available");
4512 $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4515 // loop through all groups and retrieve all members for adding data in the user array
4516 foreach ($r as $rr) {
4517 $members = group_get_members($rr['id']);
4520 if ($type == "xml") {
4521 $user_element = "users";
4523 foreach ($members as $member) {
4524 $user = api_get_user($a, $member['nurl']);
4525 $users[$k++.":user"] = $user;
4528 $user_element = "user";
4529 foreach ($members as $member) {
4530 $user = api_get_user($a, $member['nurl']);
4534 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4536 return api_format_data("groups", $type, array('group' => $grps));
4538 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4541 // delete the specified group of the user
4542 function api_friendica_group_delete($type) {
4546 if (api_user() === false) throw new ForbiddenException();
4549 $user_info = api_get_user($a);
4550 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4551 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4552 $uid = $user_info['uid'];
4554 // error if no gid specified
4555 if ($gid == 0 || $name == "")
4556 throw new BadRequestException('gid or name not specified');
4558 // get data of the specified group id
4559 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4562 // error message if specified gid is not in database
4563 if (!DBM::is_result($r))
4564 throw new BadRequestException('gid not available');
4566 // get data of the specified group id and group name
4567 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4571 // error message if specified gid is not in database
4572 if (!DBM::is_result($rname))
4573 throw new BadRequestException('wrong group name');
4576 $ret = group_rmv($uid, $name);
4579 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4580 return api_format_data("group_delete", $type, array('result' => $success));
4583 throw new BadRequestException('other API error');
4585 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4588 // create the specified group with the posted array of contacts
4589 function api_friendica_group_create($type) {
4593 if (api_user() === false) throw new ForbiddenException();
4596 $user_info = api_get_user($a);
4597 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4598 $uid = $user_info['uid'];
4599 $json = json_decode($_POST['json'], true);
4600 $users = $json['user'];
4602 // error if no name specified
4604 throw new BadRequestException('group name not specified');
4606 // get data of the specified group name
4607 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4610 // error message if specified group name already exists
4611 if (DBM::is_result($rname))
4612 throw new BadRequestException('group name already exists');
4614 // check if specified group name is a deleted group
4615 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4618 // error message if specified group name already exists
4619 if (DBM::is_result($rname))
4620 $reactivate_group = true;
4623 $ret = group_add($uid, $name);
4625 $gid = group_byname($uid, $name);
4627 throw new BadRequestException('other API error');
4630 $erroraddinguser = false;
4631 $errorusers = array();
4632 foreach ($users as $user) {
4633 $cid = $user['cid'];
4634 // check if user really exists as contact
4635 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4638 if (count($contact))
4639 $result = group_add_member($uid, $name, $cid, $gid);
4641 $erroraddinguser = true;
4642 $errorusers[] = $cid;
4646 // return success message incl. missing users in array
4647 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4648 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4649 return api_format_data("group_create", $type, array('result' => $success));
4651 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4654 // update the specified group with the posted array of contacts
4655 function api_friendica_group_update($type) {
4659 if (api_user() === false) throw new ForbiddenException();
4662 $user_info = api_get_user($a);
4663 $uid = $user_info['uid'];
4664 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4665 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4666 $json = json_decode($_POST['json'], true);
4667 $users = $json['user'];
4669 // error if no name specified
4671 throw new BadRequestException('group name not specified');
4673 // error if no gid specified
4675 throw new BadRequestException('gid not specified');
4678 $members = group_get_members($gid);
4679 foreach ($members as $member) {
4680 $cid = $member['id'];
4681 foreach ($users as $user) {
4682 $found = ($user['cid'] == $cid ? true : false);
4685 $ret = group_rmv_member($uid, $name, $cid);
4690 $erroraddinguser = false;
4691 $errorusers = array();
4692 foreach ($users as $user) {
4693 $cid = $user['cid'];
4694 // check if user really exists as contact
4695 $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4698 if (count($contact))
4699 $result = group_add_member($uid, $name, $cid, $gid);
4701 $erroraddinguser = true;
4702 $errorusers[] = $cid;
4706 // return success message incl. missing users in array
4707 $status = ($erroraddinguser ? "missing user" : "ok");
4708 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4709 return api_format_data("group_update", $type, array('result' => $success));
4712 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4714 function api_friendica_activity($type) {
4718 if (api_user() === false) throw new ForbiddenException();
4719 $verb = strtolower($a->argv[3]);
4720 $verb = preg_replace("|\..*$|", "", $verb);
4722 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4724 $res = do_like($id, $verb);
4731 return api_format_data('ok', $type, array('ok' => $ok));
4733 throw new BadRequestException('Error adding activity');
4738 /// @TODO move to top of file or somwhere better
4739 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4740 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4741 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4742 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4743 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4744 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4745 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4746 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4747 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4748 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4751 * @brief Returns notifications
4753 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4756 function api_friendica_notification($type) {
4760 if (api_user() === false) throw new ForbiddenException();
4761 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4762 $nm = new NotificationsManager();
4764 $notes = $nm->getAll(array(), "+seen -date", 50);
4766 if ($type == "xml") {
4767 $xmlnotes = array();
4768 foreach ($notes AS $note)
4769 $xmlnotes[] = array("@attributes" => $note);
4774 return api_format_data("notes", $type, array('note' => $notes));
4778 * @brief Set notification as seen and returns associated item (if possible)
4780 * POST request with 'id' param as notification id
4782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4785 function api_friendica_notification_seen($type) {
4789 if (api_user() === false) throw new ForbiddenException();
4790 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4792 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4794 $nm = new NotificationsManager();
4795 $note = $nm->getByID($id);
4796 if (is_null($note)) throw new BadRequestException("Invalid argument");
4798 $nm->setSeen($note);
4799 if ($note['otype']=='item') {
4800 // would be really better with an ItemsManager and $im->getByID() :-P
4801 $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4802 intval($note['iid']),
4803 intval(local_user())
4806 // we found the item, return it to the user
4807 $user_info = api_get_user($a);
4808 $ret = api_format_items($r,$user_info, false, $type);
4809 $data = array('status' => $ret);
4810 return api_format_data("status", $type, $data);
4812 // the item can't be found, but we set the note as seen, so we count this as a success
4814 return api_format_data('result', $type, array('result' => "success"));
4817 /// @TODO move to top of file or somwhere better
4818 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4819 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4822 * @brief update a direct_message to seen state
4824 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4825 * @return string (success result=ok, error result=error with error message)
4827 function api_friendica_direct_messages_setseen($type) {
4829 if (api_user() === false) {
4830 throw new ForbiddenException();
4834 $user_info = api_get_user($a);
4835 $uid = $user_info['uid'];
4836 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4838 // return error if id is zero
4840 $answer = array('result' => 'error', 'message' => 'message id not specified');
4841 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4844 // get data of the specified message id
4845 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
4849 // error message if specified id is not in database
4850 if (!DBM::is_result($r)) {
4851 $answer = array('result' => 'error', 'message' => 'message id not in database');
4852 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4855 // update seen indicator
4856 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
4862 $answer = array('result' => 'ok', 'message' => 'message set to seen');
4863 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
4865 $answer = array('result' => 'error', 'message' => 'unknown error');
4866 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4870 /// @TODO move to top of file or somwhere better
4871 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
4874 * @brief search for direct_messages containing a searchstring through api
4876 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4877 * @return string (success: success=true if found and search_result contains found messages
4878 * success=false if nothing was found, search_result='nothing found',
4879 * error: result=error with error message)
4881 function api_friendica_direct_messages_search($type) {
4884 if (api_user() === false) {
4885 throw new ForbiddenException();
4889 $user_info = api_get_user($a);
4890 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
4891 $uid = $user_info['uid'];
4893 // error if no searchstring specified
4894 if ($searchstring == "") {
4895 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
4896 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
4899 // get data for the specified searchstring
4900 $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",
4902 dbesc('%'.$searchstring.'%')
4905 $profile_url = $user_info["url"];
4907 // message if nothing was found
4908 if (!DBM::is_result($r)) {
4909 $success = array('success' => false, 'search_results' => 'problem with query');
4910 } elseif (count($r) == 0) {
4911 $success = array('success' => false, 'search_results' => 'nothing found');
4914 foreach ($r as $item) {
4915 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4916 $recipient = $user_info;
4917 $sender = api_get_user($a,normalise_link($item['contact-url']));
4918 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4919 $recipient = api_get_user($a,normalise_link($item['contact-url']));
4920 $sender = $user_info;
4923 $ret[] = api_format_messages($item, $recipient, $sender);
4925 $success = array('success' => true, 'search_results' => $ret);
4928 return api_format_data("direct_message_search", $type, array('$result' => $success));
4931 /// @TODO move to top of file or somwhere better
4932 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4935 * @brief return data of all the profiles a user has to the client
4937 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4940 function api_friendica_profile_show($type) {
4943 if (api_user() === false) {
4944 throw new ForbiddenException();
4948 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
4950 // retrieve general information about profiles for user
4951 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
4952 $directory = Config::get('system', 'directory');
4954 // get data of the specified profile id or all profiles of the user if not specified
4955 if ($profileid != 0) {
4956 $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
4958 intval($profileid));
4960 // error message if specified gid is not in database
4961 if (!DBM::is_result($r)) {
4962 throw new BadRequestException("profile_id not available");
4965 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
4966 intval(api_user()));
4968 // loop through all returned profiles and retrieve data and users
4970 foreach ($r as $rr) {
4971 $profile = api_format_items_profiles($rr, $type);
4973 // select all users from contact table, loop and prepare standard return for user data
4975 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
4977 intval($rr['profile_id']));
4979 foreach ($r as $rr) {
4980 $user = api_get_user($a, $rr['nurl']);
4981 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
4983 $profile['users'] = $users;
4985 // add prepared profile data to array for final return
4986 if ($type == "xml") {
4987 $profiles[$k++ . ":profile"] = $profile;
4989 $profiles[] = $profile;
4993 // return settings, authenticated user and profiles data
4994 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4996 $result = array('multi_profiles' => $multi_profiles ? true : false,
4997 'global_dir' => $directory,
4998 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
4999 'profiles' => $profiles);
5000 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5002 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5005 @TODO Maybe open to implement?
5007 [pagename] => api/1.1/statuses/lookup.json
5008 [id] => 605138389168451584
5009 [include_cards] => true
5010 [cards_platform] => Android-12
5011 [include_entities] => true
5012 [include_my_retweet] => 1
5014 [include_reply_count] => true
5015 [include_descendent_reply_count] => true
5019 Not implemented by now:
5020 statuses/retweets_of_me
5025 account/update_location
5026 account/update_profile_background_image
5029 friendica/profile/update
5030 friendica/profile/create
5031 friendica/profile/delete
5033 Not implemented in status.net:
5034 statuses/retweeted_to_me
5035 statuses/retweeted_by_me
5036 direct_messages/destroy
5038 account/update_delivery_device
5039 notifications/follow