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;
16 use Friendica\Util\XML;
18 require_once 'include/HTTPExceptions.php';
19 require_once 'include/bbcode.php';
20 require_once 'include/datetime.php';
21 require_once 'include/conversation.php';
22 require_once 'include/oauth.php';
23 require_once 'include/html2plain.php';
24 require_once 'mod/share.php';
25 require_once 'include/Photo.php';
26 require_once 'mod/item.php';
27 require_once 'include/security.php';
28 require_once 'include/contact_selectors.php';
29 require_once 'include/html2bbcode.php';
30 require_once 'mod/wall_upload.php';
31 require_once 'mod/proxy.php';
32 require_once 'include/message.php';
33 require_once 'include/group.php';
34 require_once 'include/like.php';
35 require_once 'include/plaintext.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');
46 * @brief Auth API user
48 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
49 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
50 * into a page, and visitors will post something without noticing it).
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
74 if (requestdata('source')) {
75 return requestdata('source');
78 // Support for known clients that doesn't send a source name
79 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
83 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
89 * @brief Format date for API
91 * @param string $str Source date, as UTC
92 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
94 function api_date($str)
96 // Wed May 23 06:01:13 +0000 2007
97 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
101 * @brief Register API endpoint
103 * Register a function to be the endpont for defined API path.
105 * @param string $path API URL path, relative to System::baseUrl()
106 * @param string $func Function name to call on path request
107 * @param bool $auth API need logged user
108 * @param string $method HTTP method reqiured to call this endpoint.
109 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
110 * Default to API_METHOD_ANY
112 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
122 // Workaround for hotot
123 $path = str_replace("api/", "api/1.1/", $path);
133 * @brief Login API user
135 * Log in user via OAuth1 or Simple HTTP Auth.
136 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
138 * @param object $a App
139 * @hook 'authenticate'
141 * 'username' => username from login form
142 * 'password' => password from login form
143 * 'authenticated' => return status,
144 * 'user_record' => return authenticated user record
146 * array $user logged user record
148 function api_login(App $a)
152 $oauth = new FKOAuth1();
153 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
154 if (!is_null($token)) {
155 $oauth->loginUser($token->uid);
156 call_hooks('logged_in', $a->user);
159 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
160 var_dump($consumer, $token);
162 } catch (Exception $e) {
166 // workaround for HTTP-auth in CGI mode
167 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
168 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
169 if (strlen($userpass)) {
170 list($name, $password) = explode(':', $userpass);
171 $_SERVER['PHP_AUTH_USER'] = $name;
172 $_SERVER['PHP_AUTH_PW'] = $password;
176 if (!x($_SERVER, 'PHP_AUTH_USER')) {
177 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
178 header('WWW-Authenticate: Basic realm="Friendica"');
179 throw new UnauthorizedException("This API requires login");
182 $user = $_SERVER['PHP_AUTH_USER'];
183 $password = $_SERVER['PHP_AUTH_PW'];
184 $encrypted = hash('whirlpool', trim($password));
186 // allow "user@server" login (but ignore 'server' part)
187 $at = strstr($user, "@", true);
192 // next code from mod/auth.php. needs better solution
196 'username' => trim($user),
197 'password' => trim($password),
198 'authenticated' => 0,
199 'user_record' => null,
203 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
204 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
205 * and later plugins should not interfere with an earlier one that succeeded.
207 call_hooks('authenticate', $addon_auth);
209 if (($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
210 $record = $addon_auth['user_record'];
212 // process normal login request
214 "SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
215 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
220 if (DBM::is_result($r)) {
225 if ((! $record) || (! count($record))) {
226 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
227 header('WWW-Authenticate: Basic realm="Friendica"');
228 //header('HTTP/1.0 401 Unauthorized');
229 //die('This api requires login');
230 throw new UnauthorizedException("This API requires login");
233 authenticate_success($record);
235 $_SESSION["allow_api"] = true;
237 call_hooks('logged_in', $a->user);
241 * @brief Check HTTP method of called API
243 * API endpoints can define which HTTP method to accept when called.
244 * This function check the current HTTP method agains endpoint
247 * @param string $method Required methods, uppercase, separated by comma
250 function api_check_method($method)
252 if ($method == "*") {
255 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
259 * @brief Main API entry point
261 * Authenticate user, call registered API function, set HTTP headers
263 * @param object $a App
264 * @return string API call result
266 function api_call(App $a)
268 global $API, $called_api;
271 if (strpos($a->query_string, ".xml") > 0) {
274 if (strpos($a->query_string, ".json") > 0) {
277 if (strpos($a->query_string, ".rss") > 0) {
280 if (strpos($a->query_string, ".atom") > 0) {
285 foreach ($API as $p => $info) {
286 if (strpos($a->query_string, $p) === 0) {
287 if (!api_check_method($info['method'])) {
288 throw new MethodNotAllowedException();
291 $called_api = explode("/", $p);
292 //unset($_SERVER['PHP_AUTH_USER']);
294 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
295 if ($info['auth'] === true && api_user() === false) {
299 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
300 logger('API parameters: ' . print_r($_REQUEST, true));
302 $stamp = microtime(true);
303 $r = call_user_func($info['func'], $type);
304 $duration = (float) (microtime(true) - $stamp);
305 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
307 if (Config::get("system", "profiler")) {
308 $duration = microtime(true)-$a->performance["start"];
310 /// @TODO round() really everywhere?
312 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
313 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
314 round($a->performance["database"] - $a->performance["database_write"], 3),
315 round($a->performance["database_write"], 3),
316 round($a->performance["network"], 2),
317 round($a->performance["file"], 2),
318 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
324 if (Config::get("rendertime", "callstack")) {
325 $o = "Database Read:\n";
326 foreach ($a->callstack["database"] as $func => $time) {
327 $time = round($time, 3);
329 $o .= $func . ": " . $time . "\n";
332 $o .= "\nDatabase Write:\n";
333 foreach ($a->callstack["database_write"] as $func => $time) {
334 $time = round($time, 3);
336 $o .= $func . ": " . $time . "\n";
340 $o .= "\nNetwork:\n";
341 foreach ($a->callstack["network"] as $func => $time) {
342 $time = round($time, 3);
344 $o .= $func . ": " . $time . "\n";
347 logger($o, LOGGER_DEBUG);
353 * api function returned false withour throw an
354 * exception. This should not happend, throw a 500
356 throw new InternalServerErrorException();
361 header("Content-Type: text/xml");
365 header("Content-Type: application/json");
367 $json = json_encode($rr);
368 if (x($_GET, 'callback')) {
369 $json = $_GET['callback'] . "(" . $json . ")";
374 header("Content-Type: application/rss+xml");
375 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
378 header("Content-Type: application/atom+xml");
379 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $r;
385 logger('API call not implemented: ' . $a->query_string);
386 throw new NotImplementedException();
387 } catch (HTTPException $e) {
388 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
389 return api_error($type, $e);
394 * @brief Format API error string
396 * @param string $type Return type (xml, json, rss, as)
397 * @param object $e HTTPException Error object
398 * @return strin error message formatted as $type
400 function api_error($type, $e)
404 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
405 /// @TODO: https://dev.twitter.com/overview/api/response-codes
407 $error = array("error" => $error,
408 "code" => $e->httpcode . " " . $e->httpdesc,
409 "request" => $a->query_string);
411 $ret = api_format_data('status', $type, array('status' => $error));
415 header("Content-Type: text/xml");
419 header("Content-Type: application/json");
420 return json_encode($ret);
423 header("Content-Type: application/rss+xml");
427 header("Content-Type: application/atom+xml");
434 * @brief Set values for RSS template
437 * @param array $arr Array to be passed to template
438 * @param array $user_info User info
440 * @todo find proper type-hints
442 function api_rss_extra(App $a, $arr, $user_info)
444 if (is_null($user_info)) {
445 $user_info = api_get_user($a);
448 $arr['$user'] = $user_info;
449 $arr['$rss'] = array(
450 'alternate' => $user_info['url'],
451 'self' => System::baseUrl() . "/" . $a->query_string,
452 'base' => System::baseUrl(),
453 'updated' => api_date(null),
454 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
455 'language' => $user_info['language'],
456 'logo' => System::baseUrl() . "/images/friendica-32.png",
464 * @brief Unique contact to contact url.
466 * @param int $id Contact id
467 * @return bool|string
468 * Contact url or False if contact id is unknown
470 function api_unique_id_to_url($id)
472 $r = dba::select('contact', array('url'), array('uid' => 0, 'id' => $id), array('limit' => 1));
474 if (DBM::is_result($r)) {
482 * @brief Get user info array.
484 * @param object $a App
485 * @param int|string $contact_id Contact ID or URL
486 * @param string $type Return type (for errors)
488 function api_get_user(App $a, $contact_id = null, $type = "json")
497 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
499 // Searching for contact URL
500 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
501 $user = dbesc(normalise_link($contact_id));
503 $extra_query = "AND `contact`.`nurl` = '%s' ";
504 if (api_user() !== false) {
505 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
509 // Searching for contact id with uid = 0
510 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
511 $user = dbesc(api_unique_id_to_url($contact_id));
514 throw new BadRequestException("User not found.");
518 $extra_query = "AND `contact`.`nurl` = '%s' ";
519 if (api_user() !== false) {
520 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 if (is_null($user) && x($_GET, 'user_id')) {
525 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
528 throw new BadRequestException("User not found.");
532 $extra_query = "AND `contact`.`nurl` = '%s' ";
533 if (api_user() !== false) {
534 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
537 if (is_null($user) && x($_GET, 'screen_name')) {
538 $user = dbesc($_GET['screen_name']);
540 $extra_query = "AND `contact`.`nick` = '%s' ";
541 if (api_user() !== false) {
542 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
546 if (is_null($user) && x($_GET, 'profileurl')) {
547 $user = dbesc(normalise_link($_GET['profileurl']));
549 $extra_query = "AND `contact`.`nurl` = '%s' ";
550 if (api_user() !== false) {
551 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
555 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
556 $argid = count($called_api);
557 list($user, $null) = explode(".", $a->argv[$argid]);
558 if (is_numeric($user)) {
559 $user = dbesc(api_unique_id_to_url($user));
566 $extra_query = "AND `contact`.`nurl` = '%s' ";
567 if (api_user() !== false) {
568 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
571 $user = dbesc($user);
573 $extra_query = "AND `contact`.`nick` = '%s' ";
574 if (api_user() !== false) {
575 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
580 logger("api_get_user: user ".$user, LOGGER_DEBUG);
583 if (api_user() === false) {
587 $user = $_SESSION['uid'];
588 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
592 logger('api_user: ' . $extra_query . ', user: ' . $user);
596 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
602 // Selecting the id by priority, friendica first
603 api_best_nickname($uinfo);
605 // if the contact wasn't found, fetch it from the contacts with uid = 0
606 if (!DBM::is_result($uinfo)) {
610 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
613 if (DBM::is_result($r)) {
614 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
616 // If no nick where given, extract it from the address
617 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
618 $r[0]['nick'] = api_get_nick($r[0]["url"]);
623 'id_str' => (string) $r[0]["id"],
624 'name' => $r[0]["name"],
625 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
626 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
627 'description' => $r[0]["about"],
628 'profile_image_url' => $r[0]["micro"],
629 'profile_image_url_https' => $r[0]["micro"],
630 'url' => $r[0]["url"],
631 'protected' => false,
632 'followers_count' => 0,
633 'friends_count' => 0,
635 'created_at' => api_date($r[0]["created"]),
636 'favourites_count' => 0,
638 'time_zone' => 'UTC',
639 'geo_enabled' => false,
641 'statuses_count' => 0,
643 'contributors_enabled' => false,
644 'is_translator' => false,
645 'is_translation_enabled' => false,
646 'following' => false,
647 'follow_request_sent' => false,
648 'statusnet_blocking' => false,
649 'notifications' => false,
650 'statusnet_profile_url' => $r[0]["url"],
652 'cid' => get_contact($r[0]["url"], api_user(), true),
654 'network' => $r[0]["network"],
659 throw new BadRequestException("User not found.");
663 if ($uinfo[0]['self']) {
664 if ($uinfo[0]['network'] == "") {
665 $uinfo[0]['network'] = NETWORK_DFRN;
669 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
673 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
677 /// @TODO old-lost code? (twice)
678 // Counting is deactivated by now, due to performance issues
679 // count public wall messages
680 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
681 // intval($uinfo[0]['uid'])
683 //$countitms = $r[0]['count'];
686 // Counting is deactivated by now, due to performance issues
687 //$r = q("SELECT count(*) as `count` FROM `item`
688 // WHERE `contact-id` = %d",
689 // intval($uinfo[0]['id'])
691 //$countitms = $r[0]['count'];
695 /// @TODO old-lost code? (twice)
697 // Counting is deactivated by now, due to performance issues
699 $r = q("SELECT count(*) as `count` FROM `contact`
700 WHERE `uid` = %d AND `rel` IN ( %d, %d )
701 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
702 intval($uinfo[0]['uid']),
703 intval(CONTACT_IS_SHARING),
704 intval(CONTACT_IS_FRIEND)
706 $countfriends = $r[0]['count'];
708 $r = q("SELECT count(*) as `count` FROM `contact`
709 WHERE `uid` = %d AND `rel` IN ( %d, %d )
710 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
711 intval($uinfo[0]['uid']),
712 intval(CONTACT_IS_FOLLOWER),
713 intval(CONTACT_IS_FRIEND)
715 $countfollowers = $r[0]['count'];
717 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
718 intval($uinfo[0]['uid'])
720 $starred = $r[0]['count'];
723 if (! $uinfo[0]['self']) {
733 // Add a nick if it isn't present there
734 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
735 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
738 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
740 $pcontact_id = get_contact($uinfo[0]['url'], 0, true);
743 'id' => intval($pcontact_id),
744 'id_str' => (string) intval($pcontact_id),
745 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
746 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
747 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
748 'description' => (($profile) ? $profile[0]['pdesc'] : null),
749 'profile_image_url' => $uinfo[0]['micro'],
750 'profile_image_url_https' => $uinfo[0]['micro'],
751 'url' => $uinfo[0]['url'],
752 'protected' => false,
753 'followers_count' => intval($countfollowers),
754 'friends_count' => intval($countfriends),
756 'created_at' => api_date($uinfo[0]['created']),
757 'favourites_count' => intval($starred),
759 'time_zone' => 'UTC',
760 'geo_enabled' => false,
762 'statuses_count' => intval($countitms),
764 'contributors_enabled' => false,
765 'is_translator' => false,
766 'is_translation_enabled' => false,
767 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
768 'follow_request_sent' => false,
769 'statusnet_blocking' => false,
770 'notifications' => false,
772 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
773 'statusnet_profile_url' => $uinfo[0]['url'],
774 'uid' => intval($uinfo[0]['uid']),
775 'cid' => intval($uinfo[0]['cid']),
776 'self' => $uinfo[0]['self'],
777 'network' => $uinfo[0]['network'],
784 * @brief return api-formatted array for item's author and owner
786 * @param object $a App
787 * @param array $item item from db
788 * @return array(array:author, array:owner)
790 function api_item_get_user(App $a, $item)
792 $status_user = api_get_user($a, $item["author-link"]);
794 $status_user["protected"] = (($item["allow_cid"] != "") ||
795 ($item["allow_gid"] != "") ||
796 ($item["deny_cid"] != "") ||
797 ($item["deny_gid"] != "") ||
800 if ($item['thr-parent'] == $item['uri']) {
801 $owner_user = api_get_user($a, $item["owner-link"]);
803 $owner_user = $status_user;
806 return (array($status_user, $owner_user));
810 * @brief walks recursively through an array with the possibility to change value and key
812 * @param array $array The array to walk through
813 * @param string $callback The callback function
815 * @return array the transformed array
817 function api_walk_recursive(array &$array, callable $callback)
819 $new_array = array();
821 foreach ($array as $k => $v) {
823 if ($callback($v, $k)) {
824 $new_array[$k] = api_walk_recursive($v, $callback);
827 if ($callback($v, $k)) {
838 * @brief Callback function to transform the array in an array that can be transformed in a XML file
840 * @param mixed $item Array item value
841 * @param string $key Array key
843 * @return boolean Should the array item be deleted?
845 function api_reformat_xml(&$item, &$key)
847 if (is_bool($item)) {
848 $item = ($item ? "true" : "false");
851 if (substr($key, 0, 10) == "statusnet_") {
852 $key = "statusnet:".substr($key, 10);
853 } elseif (substr($key, 0, 10) == "friendica_") {
854 $key = "friendica:".substr($key, 10);
856 /// @TODO old-lost code?
858 // $key = "default:".$key;
864 * @brief Creates the XML from a JSON style array
866 * @param array $data JSON style array
867 * @param string $root_element Name of the root element
869 * @return string The XML data
871 function api_create_xml($data, $root_element)
873 $childname = key($data);
874 $data2 = array_pop($data);
877 $namespaces = array("" => "http://api.twitter.com",
878 "statusnet" => "http://status.net/schema/api/1/",
879 "friendica" => "http://friendi.ca/schema/api/1/",
880 "georss" => "http://www.georss.org/georss");
882 /// @todo Auto detection of needed namespaces
883 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos"))) {
884 $namespaces = array();
887 if (is_array($data2)) {
888 api_walk_recursive($data2, "api_reformat_xml");
895 foreach ($data2 as $item) {
896 $data4[$i++.":".$childname] = $item;
902 $data3 = array($root_element => $data2);
904 $ret = XML::from_array($data3, $xml, false, $namespaces);
909 * @brief Formats the data according to the data type
911 * @param string $root_element Name of the root element
912 * @param string $type Return type (atom, rss, xml, json)
913 * @param array $data JSON style array
915 * @return (string|object) XML data or JSON data
917 function api_format_data($root_element, $type, $data)
925 $ret = api_create_xml($data, $root_element);
940 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
941 * returns a 401 status code and an error message if not.
942 * http://developer.twitter.com/doc/get/account/verify_credentials
944 function api_account_verify_credentials($type)
949 if (api_user() === false) {
950 throw new ForbiddenException();
953 unset($_REQUEST["user_id"]);
954 unset($_GET["user_id"]);
956 unset($_REQUEST["screen_name"]);
957 unset($_GET["screen_name"]);
959 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
961 $user_info = api_get_user($a);
963 // "verified" isn't used here in the standard
964 unset($user_info["verified"]);
966 // - Adding last status
968 $user_info["status"] = api_status_show("raw");
969 if (!count($user_info["status"])) {
970 unset($user_info["status"]);
972 unset($user_info["status"]["user"]);
976 // "uid" and "self" are only needed for some internal stuff, so remove it from here
977 unset($user_info["uid"]);
978 unset($user_info["self"]);
980 return api_format_data("user", $type, array('user' => $user_info));
983 /// @TODO move to top of file or somwhere better
984 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
987 * Get data from $_POST or $_GET
989 function requestdata($k)
1000 /*Waitman Gobble Mod*/
1001 function api_statuses_mediap($type)
1005 if (api_user() === false) {
1006 logger('api_statuses_update: no user');
1007 throw new ForbiddenException();
1009 $user_info = api_get_user($a);
1011 $_REQUEST['type'] = 'wall';
1012 $_REQUEST['profile_uid'] = api_user();
1013 $_REQUEST['api_source'] = true;
1014 $txt = requestdata('status');
1015 /// @TODO old-lost code?
1016 //$txt = urldecode(requestdata('status'));
1018 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1019 $txt = html2bb_video($txt);
1020 $config = HTMLPurifier_Config::createDefault();
1021 $config->set('Cache.DefinitionImpl', null);
1022 $purifier = new HTMLPurifier($config);
1023 $txt = $purifier->purify($txt);
1025 $txt = html2bbcode($txt);
1027 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1029 // tell wall_upload function to return img info instead of echo
1030 $_REQUEST['hush'] = 'yeah';
1031 $bebop = wall_upload_post($a);
1033 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1034 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1037 // this should output the last post (the one we just posted).
1038 return api_status_show($type);
1041 /// @TODO move this to top of file or somewhere better!
1042 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1044 function api_statuses_update($type)
1049 if (api_user() === false) {
1050 logger('api_statuses_update: no user');
1051 throw new ForbiddenException();
1054 $user_info = api_get_user($a);
1056 // convert $_POST array items to the form we use for web posts.
1058 // logger('api_post: ' . print_r($_POST,true));
1060 if (requestdata('htmlstatus')) {
1061 $txt = requestdata('htmlstatus');
1062 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1063 $txt = html2bb_video($txt);
1065 $config = HTMLPurifier_Config::createDefault();
1066 $config->set('Cache.DefinitionImpl', null);
1068 $purifier = new HTMLPurifier($config);
1069 $txt = $purifier->purify($txt);
1071 $_REQUEST['body'] = html2bbcode($txt);
1074 $_REQUEST['body'] = requestdata('status');
1077 $_REQUEST['title'] = requestdata('title');
1079 $parent = requestdata('in_reply_to_status_id');
1081 // Twidere sends "-1" if it is no reply ...
1082 if ($parent == -1) {
1086 if (ctype_digit($parent)) {
1087 $_REQUEST['parent'] = $parent;
1089 $_REQUEST['parent_uri'] = $parent;
1092 if (requestdata('lat') && requestdata('long')) {
1093 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1095 $_REQUEST['profile_uid'] = api_user();
1098 $_REQUEST['type'] = 'net-comment';
1100 // Check for throttling (maximum posts per day, week and month)
1101 $throttle_day = Config::get('system', 'throttle_limit_day');
1102 if ($throttle_day > 0) {
1103 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1106 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1107 AND `created` > '%s' AND `id` = `parent`",
1112 if (DBM::is_result($r)) {
1113 $posts_day = $r[0]["posts_day"];
1118 if ($posts_day > $throttle_day) {
1119 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1120 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1121 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1125 $throttle_week = Config::get('system', 'throttle_limit_week');
1126 if ($throttle_week > 0) {
1127 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1130 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1131 AND `created` > '%s' AND `id` = `parent`",
1136 if (DBM::is_result($r)) {
1137 $posts_week = $r[0]["posts_week"];
1142 if ($posts_week > $throttle_week) {
1143 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1144 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1145 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1149 $throttle_month = Config::get('system', 'throttle_limit_month');
1150 if ($throttle_month > 0) {
1151 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1154 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1155 AND `created` > '%s' AND `id` = `parent`",
1160 if (DBM::is_result($r)) {
1161 $posts_month = $r[0]["posts_month"];
1166 if ($posts_month > $throttle_month) {
1167 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1168 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1169 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1173 $_REQUEST['type'] = 'wall';
1176 if (x($_FILES, 'media')) {
1177 // upload the image if we have one
1178 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1179 $media = wall_upload_post($a);
1180 if (strlen($media) > 0) {
1181 $_REQUEST['body'] .= "\n\n" . $media;
1185 // To-Do: Multiple IDs
1186 if (requestdata('media_ids')) {
1188 "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",
1189 intval(requestdata('media_ids')),
1192 if (DBM::is_result($r)) {
1193 $phototypes = Photo::supportedTypes();
1194 $ext = $phototypes[$r[0]['type']];
1195 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1196 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1200 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1202 $_REQUEST['api_source'] = true;
1204 if (!x($_REQUEST, "source")) {
1205 $_REQUEST["source"] = api_source();
1208 // call out normal post function
1211 // this should output the last post (the one we just posted).
1212 return api_status_show($type);
1215 /// @TODO move to top of file or somwhere better
1216 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1217 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1219 function api_media_upload($type)
1223 if (api_user() === false) {
1225 throw new ForbiddenException();
1228 $user_info = api_get_user($a);
1230 if (!x($_FILES, 'media')) {
1232 throw new BadRequestException("No media.");
1235 $media = wall_upload_post($a, false);
1238 throw new InternalServerErrorException();
1241 $returndata = array();
1242 $returndata["media_id"] = $media["id"];
1243 $returndata["media_id_string"] = (string)$media["id"];
1244 $returndata["size"] = $media["size"];
1245 $returndata["image"] = array("w" => $media["width"],
1246 "h" => $media["height"],
1247 "image_type" => $media["type"]);
1249 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1251 return array("media" => $returndata);
1254 /// @TODO move to top of file or somwhere better
1255 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1257 function api_status_show($type)
1261 $user_info = api_get_user($a);
1263 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1265 if ($type == "raw") {
1266 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1271 // get last public wall message
1275 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1276 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1277 AND `item`.`type` != 'activity' $privacy_sql
1278 ORDER BY `item`.`id` DESC
1280 intval($user_info['cid']),
1282 dbesc($user_info['url']),
1283 dbesc(normalise_link($user_info['url'])),
1284 dbesc($user_info['url']),
1285 dbesc(normalise_link($user_info['url']))
1288 if (DBM::is_result($lastwall)) {
1289 $lastwall = $lastwall[0];
1291 $in_reply_to = api_in_reply_to($lastwall);
1293 $converted = api_convert_item($lastwall);
1295 if ($type == "xml") {
1296 $geo = "georss:point";
1301 $status_info = array(
1302 'created_at' => api_date($lastwall['created']),
1303 'id' => intval($lastwall['id']),
1304 'id_str' => (string) $lastwall['id'],
1305 'text' => $converted["text"],
1306 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1307 'truncated' => false,
1308 'in_reply_to_status_id' => $in_reply_to['status_id'],
1309 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1310 'in_reply_to_user_id' => $in_reply_to['user_id'],
1311 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1312 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1313 'user' => $user_info,
1315 'coordinates' => "",
1317 'contributors' => "",
1318 'is_quote_status' => false,
1319 'retweet_count' => 0,
1320 'favorite_count' => 0,
1321 'favorited' => $lastwall['starred'] ? true : false,
1322 'retweeted' => false,
1323 'possibly_sensitive' => false,
1325 'statusnet_html' => $converted["html"],
1326 'statusnet_conversation_id' => $lastwall['parent'],
1329 if (count($converted["attachments"]) > 0) {
1330 $status_info["attachments"] = $converted["attachments"];
1333 if (count($converted["entities"]) > 0) {
1334 $status_info["entities"] = $converted["entities"];
1337 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1338 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1339 } elseif (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1340 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1343 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1344 unset($status_info["user"]["uid"]);
1345 unset($status_info["user"]["self"]);
1348 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1350 if ($type == "raw") {
1351 return $status_info;
1354 return api_format_data("statuses", $type, array('status' => $status_info));
1358 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1359 * The author's most recent status will be returned inline.
1360 * http://developer.twitter.com/doc/get/users/show
1362 function api_users_show($type)
1366 $user_info = api_get_user($a);
1370 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1371 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1372 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1373 AND `type`!='activity'
1374 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1378 dbesc(ACTIVITY_POST),
1379 intval($user_info['cid']),
1380 dbesc($user_info['url']),
1381 dbesc(normalise_link($user_info['url'])),
1382 dbesc($user_info['url']),
1383 dbesc(normalise_link($user_info['url']))
1386 if (DBM::is_result($lastwall)) {
1387 $lastwall = $lastwall[0];
1389 $in_reply_to = api_in_reply_to($lastwall);
1391 $converted = api_convert_item($lastwall);
1393 if ($type == "xml") {
1394 $geo = "georss:point";
1399 $user_info['status'] = array(
1400 'text' => $converted["text"],
1401 'truncated' => false,
1402 'created_at' => api_date($lastwall['created']),
1403 'in_reply_to_status_id' => $in_reply_to['status_id'],
1404 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1405 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1406 'id' => intval($lastwall['contact-id']),
1407 'id_str' => (string) $lastwall['contact-id'],
1408 'in_reply_to_user_id' => $in_reply_to['user_id'],
1409 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1410 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1412 'favorited' => $lastwall['starred'] ? true : false,
1413 'statusnet_html' => $converted["html"],
1414 'statusnet_conversation_id' => $lastwall['parent'],
1417 if (count($converted["attachments"]) > 0) {
1418 $user_info["status"]["attachments"] = $converted["attachments"];
1421 if (count($converted["entities"]) > 0) {
1422 $user_info["status"]["entities"] = $converted["entities"];
1425 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1426 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1429 if (($lastwall['item_network'] != "") && (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1430 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . network_to_name($lastwall['item_network'], $user_info['url']) . ')');
1434 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1435 unset($user_info["uid"]);
1436 unset($user_info["self"]);
1438 return api_format_data("user", $type, array('user' => $user_info));
1441 /// @TODO move to top of file or somewhere better
1442 api_register_func('api/users/show', 'api_users_show');
1443 api_register_func('api/externalprofile/show', 'api_users_show');
1445 function api_users_search($type)
1449 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1451 $userlist = array();
1453 if (x($_GET, 'q')) {
1454 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1456 if (!DBM::is_result($r)) {
1457 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1460 if (DBM::is_result($r)) {
1462 foreach ($r as $user) {
1463 $user_info = api_get_user($a, $user["id"], "json");
1465 if ($type == "xml") {
1466 $userlist[$k++.":user"] = $user_info;
1468 $userlist[] = $user_info;
1471 $userlist = array("users" => $userlist);
1473 throw new BadRequestException("User not found.");
1476 throw new BadRequestException("User not found.");
1478 return api_format_data("users", $type, $userlist);
1481 /// @TODO move to top of file or somewhere better
1482 api_register_func('api/users/search', 'api_users_search');
1486 * http://developer.twitter.com/doc/get/statuses/home_timeline
1488 * TODO: Optional parameters
1489 * TODO: Add reply info
1491 function api_statuses_home_timeline($type)
1495 if (api_user() === false) {
1496 throw new ForbiddenException();
1499 unset($_REQUEST["user_id"]);
1500 unset($_GET["user_id"]);
1502 unset($_REQUEST["screen_name"]);
1503 unset($_GET["screen_name"]);
1505 $user_info = api_get_user($a);
1506 // get last newtork messages
1509 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1510 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1514 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1515 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1516 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1517 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1518 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1520 $start = $page * $count;
1524 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1526 if ($exclude_replies > 0) {
1527 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1529 if ($conversation_id > 0) {
1530 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1534 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1535 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1536 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1537 `contact`.`id` AS `cid`
1539 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1540 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1541 WHERE `item`.`uid` = %d AND `verb` = '%s'
1542 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1545 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1547 dbesc(ACTIVITY_POST),
1553 $ret = api_format_items($r, $user_info, false, $type);
1555 // Set all posts from the query above to seen
1557 foreach ($r as $item) {
1558 $idarray[] = intval($item["id"]);
1561 $idlist = implode(",", $idarray);
1563 if ($idlist != "") {
1564 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1567 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1571 $data = array('status' => $ret);
1575 $data = api_rss_extra($a, $data, $user_info);
1579 return api_format_data("statuses", $type, $data);
1582 /// @TODO move to top of file or somewhere better
1583 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1584 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1586 function api_statuses_public_timeline($type)
1590 if (api_user() === false) {
1591 throw new ForbiddenException();
1594 $user_info = api_get_user($a);
1595 // get last newtork messages
1598 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1599 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1603 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1604 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1605 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1606 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1607 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1609 $start = $page * $count;
1612 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1614 if ($exclude_replies > 0) {
1615 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1617 if ($conversation_id > 0) {
1618 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1622 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1623 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1624 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1625 `contact`.`id` AS `cid`,
1626 `user`.`nickname`, `user`.`hidewall`
1628 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1629 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1630 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1631 AND NOT `user`.`hidewall`
1632 WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1633 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1634 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1635 AND NOT `item`.`private` AND `item`.`wall`
1638 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1639 dbesc(ACTIVITY_POST),
1645 $ret = api_format_items($r, $user_info, false, $type);
1647 $data = array('status' => $ret);
1651 $data = api_rss_extra($a, $data, $user_info);
1655 return api_format_data("statuses", $type, $data);
1658 /// @TODO move to top of file or somewhere better
1659 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1662 * @TODO nothing to say?
1664 function api_statuses_show($type)
1668 if (api_user() === false) {
1669 throw new ForbiddenException();
1672 $user_info = api_get_user($a);
1675 $id = intval($a->argv[3]);
1678 $id = intval($_REQUEST["id"]);
1683 $id = intval($a->argv[4]);
1686 logger('API: api_statuses_show: ' . $id);
1688 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1691 if ($conversation) {
1692 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1694 $sql_extra .= " AND `item`.`id` = %d";
1698 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1699 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1700 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1701 `contact`.`id` AS `cid`
1703 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1704 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1705 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1706 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1709 dbesc(ACTIVITY_POST),
1713 /// @TODO How about copying this to above methods which don't check $r ?
1714 if (!DBM::is_result($r)) {
1715 throw new BadRequestException("There is no status with this id.");
1718 $ret = api_format_items($r, $user_info, false, $type);
1720 if ($conversation) {
1721 $data = array('status' => $ret);
1722 return api_format_data("statuses", $type, $data);
1724 $data = array('status' => $ret[0]);
1725 return api_format_data("status", $type, $data);
1729 /// @TODO move to top of file or somewhere better
1730 api_register_func('api/statuses/show', 'api_statuses_show', true);
1733 * @TODO nothing to say?
1735 function api_conversation_show($type)
1739 if (api_user() === false) {
1740 throw new ForbiddenException();
1743 $user_info = api_get_user($a);
1746 $id = intval($a->argv[3]);
1747 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1748 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1752 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1753 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1755 $start = $page*$count;
1758 $id = intval($_REQUEST["id"]);
1763 $id = intval($a->argv[4]);
1766 logger('API: api_conversation_show: '.$id);
1768 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1769 if (DBM::is_result($r)) {
1770 $id = $r[0]["parent"];
1776 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1779 // Not sure why this query was so complicated. We should keep it here for a while,
1780 // just to make sure that we really don't need it.
1781 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1782 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1785 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1786 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1787 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1788 `contact`.`id` AS `cid`
1790 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1791 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1792 WHERE `item`.`parent` = %d AND `item`.`visible`
1793 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1794 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1795 AND `item`.`id`>%d $sql_extra
1796 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1797 intval($id), intval(api_user()),
1798 dbesc(ACTIVITY_POST),
1800 intval($start), intval($count)
1803 if (!DBM::is_result($r)) {
1804 throw new BadRequestException("There is no status with this id.");
1807 $ret = api_format_items($r, $user_info, false, $type);
1809 $data = array('status' => $ret);
1810 return api_format_data("statuses", $type, $data);
1813 /// @TODO move to top of file or somewhere better
1814 api_register_func('api/conversation/show', 'api_conversation_show', true);
1815 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1818 * @TODO nothing to say?
1820 function api_statuses_repeat($type)
1826 if (api_user() === false) {
1827 throw new ForbiddenException();
1830 $user_info = api_get_user($a);
1833 $id = intval($a->argv[3]);
1836 $id = intval($_REQUEST["id"]);
1841 $id = intval($a->argv[4]);
1844 logger('API: api_statuses_repeat: '.$id);
1847 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1848 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1849 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1850 `contact`.`id` AS `cid`
1852 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1853 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1854 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1855 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1856 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1858 AND `item`.`id`=%d",
1862 /// @TODO other style than above functions!
1863 if (DBM::is_result($r) && $r[0]['body'] != "") {
1864 if (strpos($r[0]['body'], "[/share]") !== false) {
1865 $pos = strpos($r[0]['body'], "[share");
1866 $post = substr($r[0]['body'], $pos);
1868 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1870 $post .= $r[0]['body'];
1871 $post .= "[/share]";
1873 $_REQUEST['body'] = $post;
1874 $_REQUEST['profile_uid'] = api_user();
1875 $_REQUEST['type'] = 'wall';
1876 $_REQUEST['api_source'] = true;
1878 if (!x($_REQUEST, "source")) {
1879 $_REQUEST["source"] = api_source();
1884 throw new ForbiddenException();
1887 // this should output the last post (the one we just posted).
1889 return api_status_show($type);
1892 /// @TODO move to top of file or somewhere better
1893 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1896 * @TODO nothing to say?
1898 function api_statuses_destroy($type)
1902 if (api_user() === false) {
1903 throw new ForbiddenException();
1906 $user_info = api_get_user($a);
1909 $id = intval($a->argv[3]);
1912 $id = intval($_REQUEST["id"]);
1917 $id = intval($a->argv[4]);
1920 logger('API: api_statuses_destroy: '.$id);
1922 $ret = api_statuses_show($type);
1924 drop_item($id, false);
1929 /// @TODO move to top of file or somewhere better
1930 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1933 * @TODO Nothing more than an URL to say?
1934 * http://developer.twitter.com/doc/get/statuses/mentions
1936 function api_statuses_mentions($type)
1940 if (api_user() === false) {
1941 throw new ForbiddenException();
1944 unset($_REQUEST["user_id"]);
1945 unset($_GET["user_id"]);
1947 unset($_REQUEST["screen_name"]);
1948 unset($_GET["screen_name"]);
1950 $user_info = api_get_user($a);
1951 // get last newtork messages
1955 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1956 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1960 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1961 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1962 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1964 $start = $page * $count;
1966 // Ugly code - should be changed
1967 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
1968 $myurl = substr($myurl, strpos($myurl, '://') + 3);
1969 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1970 $myurl = str_replace('www.', '', $myurl);
1971 $diasp_url = str_replace('/profile/', '/u/', $myurl);
1974 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
1978 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1979 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1980 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1981 `contact`.`id` AS `cid`
1982 FROM `item` FORCE INDEX (`uid_id`)
1983 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1984 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1985 WHERE `item`.`uid` = %d AND `verb` = '%s'
1986 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1987 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1988 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1991 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1993 dbesc(ACTIVITY_POST),
1994 dbesc(protect_sprintf($myurl)),
1995 dbesc(protect_sprintf($myurl)),
2002 $ret = api_format_items($r, $user_info, false, $type);
2004 $data = array('status' => $ret);
2008 $data = api_rss_extra($a, $data, $user_info);
2012 return api_format_data("statuses", $type, $data);
2015 /// @TODO move to top of file or somewhere better
2016 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2017 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2019 function api_statuses_user_timeline($type)
2023 if (api_user() === false) {
2024 throw new ForbiddenException();
2027 $user_info = api_get_user($a);
2028 // get last network messages
2031 "api_statuses_user_timeline: api_user: ". api_user() .
2032 "\nuser_info: ".print_r($user_info, true) .
2033 "\n_REQUEST: ".print_r($_REQUEST, true),
2038 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2039 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2043 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2044 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
2045 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
2046 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
2048 $start = $page * $count;
2051 if ($user_info['self'] == 1) {
2052 $sql_extra .= " AND `item`.`wall` = 1 ";
2055 if ($exclude_replies > 0) {
2056 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2058 if ($conversation_id > 0) {
2059 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2063 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2064 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2065 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2066 `contact`.`id` AS `cid`
2067 FROM `item` FORCE INDEX (`uid_contactid_id`)
2068 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2069 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2070 WHERE `item`.`uid` = %d AND `verb` = '%s'
2071 AND `item`.`contact-id` = %d
2072 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2075 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2077 dbesc(ACTIVITY_POST),
2078 intval($user_info['cid']),
2084 $ret = api_format_items($r, $user_info, true, $type);
2086 $data = array('status' => $ret);
2090 $data = api_rss_extra($a, $data, $user_info);
2094 return api_format_data("statuses", $type, $data);
2097 /// @TODO move to top of file or somwhere better
2098 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
2101 * Star/unstar an item
2102 * param: id : id of the item
2104 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2106 function api_favorites_create_destroy($type)
2110 if (api_user() === false) {
2111 throw new ForbiddenException();
2114 // for versioned api.
2115 /// @TODO We need a better global soluton
2116 $action_argv_id = 2;
2117 if ($a->argv[1] == "1.1") {
2118 $action_argv_id = 3;
2121 if ($a->argc <= $action_argv_id) {
2122 throw new BadRequestException("Invalid request.");
2124 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2125 if ($a->argc == $action_argv_id + 2) {
2126 $itemid = intval($a->argv[$action_argv_id + 1]);
2128 /// @TODO use x() to check if _REQUEST contains 'id'
2129 $itemid = intval($_REQUEST['id']);
2132 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2134 if (!DBM::is_result($item) || count($item) == 0) {
2135 throw new BadRequestException("Invalid item.");
2140 $item[0]['starred'] = 1;
2143 $item[0]['starred'] = 0;
2146 throw new BadRequestException("Invalid action ".$action);
2149 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2151 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2154 throw new InternalServerErrorException("DB error");
2158 $user_info = api_get_user($a);
2159 $rets = api_format_items($item, $user_info, false, $type);
2162 $data = array('status' => $ret);
2166 $data = api_rss_extra($a, $data, $user_info);
2169 return api_format_data("status", $type, $data);
2172 /// @TODO move to top of file or somwhere better
2173 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2174 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2176 function api_favorites($type)
2182 if (api_user() === false) {
2183 throw new ForbiddenException();
2186 $called_api = array();
2188 $user_info = api_get_user($a);
2190 // in friendica starred item are private
2191 // return favorites only for self
2192 logger('api_favorites: self:' . $user_info['self']);
2194 if ($user_info['self'] == 0) {
2200 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2201 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2202 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2203 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2208 $start = $page*$count;
2211 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2215 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2216 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2217 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2218 `contact`.`id` AS `cid`
2219 FROM `item`, `contact`
2220 WHERE `item`.`uid` = %d
2221 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2222 AND `item`.`starred` = 1
2223 AND `contact`.`id` = `item`.`contact-id`
2224 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2227 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2234 $ret = api_format_items($r, $user_info, false, $type);
2237 $data = array('status' => $ret);
2241 $data = api_rss_extra($a, $data, $user_info);
2244 return api_format_data("statuses", $type, $data);
2247 /// @TODO move to top of file or somwhere better
2248 api_register_func('api/favorites', 'api_favorites', true);
2250 function api_format_messages($item, $recipient, $sender)
2252 // standard meta information
2254 'id' => $item['id'],
2255 'sender_id' => $sender['id'] ,
2257 'recipient_id' => $recipient['id'],
2258 'created_at' => api_date($item['created']),
2259 'sender_screen_name' => $sender['screen_name'],
2260 'recipient_screen_name' => $recipient['screen_name'],
2261 'sender' => $sender,
2262 'recipient' => $recipient,
2264 'friendica_seen' => $item['seen'],
2265 'friendica_parent_uri' => $item['parent-uri'],
2268 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2269 unset($ret["sender"]["uid"]);
2270 unset($ret["sender"]["self"]);
2271 unset($ret["recipient"]["uid"]);
2272 unset($ret["recipient"]["self"]);
2274 //don't send title to regular StatusNET requests to avoid confusing these apps
2275 if (x($_GET, 'getText')) {
2276 $ret['title'] = $item['title'];
2277 if ($_GET['getText'] == 'html') {
2278 $ret['text'] = bbcode($item['body'], false, false);
2279 } elseif ($_GET['getText'] == 'plain') {
2280 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2281 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2284 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2286 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2287 unset($ret['sender']);
2288 unset($ret['recipient']);
2294 function api_convert_item($item)
2296 $body = $item['body'];
2297 $attachments = api_get_attachments($body);
2299 // Workaround for ostatus messages where the title is identically to the body
2300 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2301 $statusbody = trim(html2plain($html, 0));
2303 // handle data: images
2304 $statusbody = api_format_items_embeded_images($item, $statusbody);
2306 $statustitle = trim($item['title']);
2308 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2309 $statustext = trim($statusbody);
2311 $statustext = trim($statustitle."\n\n".$statusbody);
2314 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2315 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2318 $statushtml = trim(bbcode($body, false, false));
2320 // Workaround for clients with limited HTML parser functionality
2321 $search = array("<br>", "<blockquote>", "</blockquote>",
2322 "<h1>", "</h1>", "<h2>", "</h2>",
2323 "<h3>", "</h3>", "<h4>", "</h4>",
2324 "<h5>", "</h5>", "<h6>", "</h6>");
2325 $replace = array("<br>", "<br><blockquote>", "</blockquote><br>",
2326 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2327 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2328 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>");
2329 $statushtml = str_replace($search, $replace, $statushtml);
2331 if ($item['title'] != "") {
2332 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2336 $oldtext = $statushtml;
2337 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2338 } while ($oldtext != $statushtml);
2340 if (substr($statushtml, 0, 4) == '<br>') {
2341 $statushtml = substr($statushtml, 4);
2344 if (substr($statushtml, 0, -4) == '<br>') {
2345 $statushtml = substr($statushtml, -4);
2348 // feeds without body should contain the link
2349 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2350 $statushtml .= bbcode($item['plink']);
2353 $entities = api_get_entitities($statustext, $body);
2356 "text" => $statustext,
2357 "html" => $statushtml,
2358 "attachments" => $attachments,
2359 "entities" => $entities
2363 function api_get_attachments(&$body)
2366 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2368 $URLSearchString = "^\[\]";
2369 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2375 $attachments = array();
2377 foreach ($images[1] as $image) {
2378 $imagedata = get_photo_info($image);
2381 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2385 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2386 foreach ($images[0] as $orig) {
2387 $body = str_replace($orig, "", $body);
2391 return $attachments;
2394 function api_get_entitities(&$text, $bbcode)
2398 * Links at the first character of the post
2403 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2405 if ($include_entities != "true") {
2406 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2408 foreach ($images[1] as $image) {
2409 $replace = proxy_url($image);
2410 $text = str_replace($image, $replace, $text);
2415 $bbcode = bb_CleanPictureLinks($bbcode);
2417 // Change pure links in text to bbcode uris
2418 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2420 $entities = array();
2421 $entities["hashtags"] = array();
2422 $entities["symbols"] = array();
2423 $entities["urls"] = array();
2424 $entities["user_mentions"] = array();
2426 $URLSearchString = "^\[\]";
2428 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2430 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2431 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2432 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2434 $bbcode = preg_replace(
2435 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2436 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2439 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2441 $bbcode = preg_replace(
2442 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2443 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2446 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2448 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2450 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2451 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2453 $ordered_urls = array();
2454 foreach ($urls[1] as $id => $url) {
2455 //$start = strpos($text, $url, $offset);
2456 $start = iconv_strpos($text, $url, 0, "UTF-8");
2457 if (!($start === false)) {
2458 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2462 ksort($ordered_urls);
2465 //foreach ($urls[1] AS $id=>$url) {
2466 foreach ($ordered_urls as $url) {
2467 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2468 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2470 $display_url = $url["title"];
2472 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2473 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2475 if (strlen($display_url) > 26)
2476 $display_url = substr($display_url, 0, 25)."…";
2479 //$start = strpos($text, $url, $offset);
2480 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2481 if (!($start === false)) {
2482 $entities["urls"][] = array("url" => $url["url"],
2483 "expanded_url" => $url["url"],
2484 "display_url" => $display_url,
2485 "indices" => array($start, $start+strlen($url["url"])));
2486 $offset = $start + 1;
2490 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2491 $ordered_images = array();
2492 foreach ($images[1] as $image) {
2493 //$start = strpos($text, $url, $offset);
2494 $start = iconv_strpos($text, $image, 0, "UTF-8");
2495 if (!($start === false))
2496 $ordered_images[$start] = $image;
2498 //$entities["media"] = array();
2501 foreach ($ordered_images as $url) {
2502 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2503 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2505 if (strlen($display_url) > 26)
2506 $display_url = substr($display_url, 0, 25)."…";
2508 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2509 if (!($start === false)) {
2510 $image = get_photo_info($url);
2512 // If image cache is activated, then use the following sizes:
2513 // thumb (150), small (340), medium (600) and large (1024)
2514 if (!Config::get("system", "proxy_disabled")) {
2515 $media_url = proxy_url($url);
2518 $scale = scale_image($image[0], $image[1], 150);
2519 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2521 if (($image[0] > 150) || ($image[1] > 150)) {
2522 $scale = scale_image($image[0], $image[1], 340);
2523 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2526 $scale = scale_image($image[0], $image[1], 600);
2527 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2529 if (($image[0] > 600) || ($image[1] > 600)) {
2530 $scale = scale_image($image[0], $image[1], 1024);
2531 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2535 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2538 $entities["media"][] = array(
2540 "id_str" => (string)$start+1,
2541 "indices" => array($start, $start+strlen($url)),
2542 "media_url" => normalise_link($media_url),
2543 "media_url_https" => $media_url,
2545 "display_url" => $display_url,
2546 "expanded_url" => $url,
2550 $offset = $start + 1;
2556 function api_format_items_embeded_images(&$item, $text)
2558 $text = preg_replace_callback(
2559 "|data:image/([^;]+)[^=]+=*|m",
2560 function ($match) use ($item) {
2561 return System::baseUrl()."/display/".$item['guid'];
2570 * @brief return <a href='url'>name</a> as array
2572 * @param string $txt text
2577 function api_contactlink_to_array($txt)
2580 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2581 if ($r && count($match)==3) {
2583 'name' => $match[2],
2597 * @brief return likes, dislikes and attend status for item
2599 * @param array $item array
2601 * likes => int count
2602 * dislikes => int count
2604 function api_format_items_activities(&$item, $type = "json")
2608 $activities = array(
2610 'dislike' => array(),
2611 'attendyes' => array(),
2612 'attendno' => array(),
2613 'attendmaybe' => array(),
2618 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2619 intval($item['uid']),
2623 foreach ($items as $i) {
2624 // not used as result should be structured like other user data
2625 //builtin_activity_puller($i, $activities);
2627 // get user data and add it to the array of the activity
2628 $user = api_get_user($a, $i['author-link']);
2629 switch ($i['verb']) {
2631 $activities['like'][] = $user;
2633 case ACTIVITY_DISLIKE:
2634 $activities['dislike'][] = $user;
2636 case ACTIVITY_ATTEND:
2637 $activities['attendyes'][] = $user;
2639 case ACTIVITY_ATTENDNO:
2640 $activities['attendno'][] = $user;
2642 case ACTIVITY_ATTENDMAYBE:
2643 $activities['attendmaybe'][] = $user;
2650 if ($type == "xml") {
2651 $xml_activities = array();
2652 foreach ($activities as $k => $v) {
2653 // change xml element from "like" to "friendica:like"
2654 $xml_activities["friendica:".$k] = $v;
2655 // add user data into xml output
2657 foreach ($v as $user)
2658 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2660 $activities = $xml_activities;
2668 * @brief return data from profiles
2670 * @param array $profile array containing data from db table 'profile'
2671 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2674 function api_format_items_profiles(&$profile = null, $type = "json")
2676 if ($profile != null) {
2677 $profile = array('profile_id' => $profile['id'],
2678 'profile_name' => $profile['profile-name'],
2679 'is_default' => $profile['is-default'] ? true : false,
2680 'hide_friends'=> $profile['hide-friends'] ? true : false,
2681 'profile_photo' => $profile['photo'],
2682 'profile_thumb' => $profile['thumb'],
2683 'publish' => $profile['publish'] ? true : false,
2684 'net_publish' => $profile['net-publish'] ? true : false,
2685 'description' => $profile['pdesc'],
2686 'date_of_birth' => $profile['dob'],
2687 'address' => $profile['address'],
2688 'city' => $profile['locality'],
2689 'region' => $profile['region'],
2690 'postal_code' => $profile['postal-code'],
2691 'country' => $profile['country-name'],
2692 'hometown' => $profile['hometown'],
2693 'gender' => $profile['gender'],
2694 'marital' => $profile['marital'],
2695 'marital_with' => $profile['with'],
2696 'marital_since' => $profile['howlong'],
2697 'sexual' => $profile['sexual'],
2698 'politic' => $profile['politic'],
2699 'religion' => $profile['religion'],
2700 'public_keywords' => $profile['pub_keywords'],
2701 'private_keywords' => $profile['prv_keywords'],
2702 'likes' => bbcode(api_clean_plain_items($profile['likes']), false, false, 2, false),
2703 'dislikes' => bbcode(api_clean_plain_items($profile['dislikes']), false, false, 2, false),
2704 'about' => bbcode(api_clean_plain_items($profile['about']), false, false, 2, false),
2705 'music' => bbcode(api_clean_plain_items($profile['music']), false, false, 2, false),
2706 'book' => bbcode(api_clean_plain_items($profile['book']), false, false, 2, false),
2707 'tv' => bbcode(api_clean_plain_items($profile['tv']), false, false, 2, false),
2708 'film' => bbcode(api_clean_plain_items($profile['film']), false, false, 2, false),
2709 'interest' => bbcode(api_clean_plain_items($profile['interest']), false, false, 2, false),
2710 'romance' => bbcode(api_clean_plain_items($profile['romance']), false, false, 2, false),
2711 'work' => bbcode(api_clean_plain_items($profile['work']), false, false, 2, false),
2712 'education' => bbcode(api_clean_plain_items($profile['education']), false, false, 2, false),
2713 'social_networks' => bbcode(api_clean_plain_items($profile['contact']), false, false, 2, false),
2714 'homepage' => $profile['homepage'],
2721 * @brief format items to be returned by api
2723 * @param array $r array of items
2724 * @param array $user_info
2725 * @param bool $filter_user filter items by $user_info
2727 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
2733 foreach ($r as $item) {
2734 localize_item($item);
2735 list($status_user, $owner_user) = api_item_get_user($a, $item);
2737 // Look if the posts are matching if they should be filtered by user id
2738 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2742 $in_reply_to = api_in_reply_to($item);
2744 $converted = api_convert_item($item);
2746 if ($type == "xml") {
2747 $geo = "georss:point";
2753 'text' => $converted["text"],
2754 'truncated' => false,
2755 'created_at'=> api_date($item['created']),
2756 'in_reply_to_status_id' => $in_reply_to['status_id'],
2757 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2758 'source' => (($item['app']) ? $item['app'] : 'web'),
2759 'id' => intval($item['id']),
2760 'id_str' => (string) intval($item['id']),
2761 'in_reply_to_user_id' => $in_reply_to['user_id'],
2762 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2763 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2765 'favorited' => $item['starred'] ? true : false,
2766 'user' => $status_user ,
2767 'friendica_owner' => $owner_user,
2768 //'entities' => NULL,
2769 'statusnet_html' => $converted["html"],
2770 'statusnet_conversation_id' => $item['parent'],
2771 'friendica_activities' => api_format_items_activities($item, $type),
2774 if (count($converted["attachments"]) > 0) {
2775 $status["attachments"] = $converted["attachments"];
2778 if (count($converted["entities"]) > 0) {
2779 $status["entities"] = $converted["entities"];
2782 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
2783 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2784 } elseif (($item['item_network'] != "") && (network_to_name($item['item_network'], $user_info['url']) != $status["source"])) {
2785 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2789 // Retweets are only valid for top postings
2790 // It doesn't work reliable with the link if its a feed
2791 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
2793 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
2796 if ($item["id"] == $item["parent"]) {
2797 $retweeted_item = api_share_as_retweet($item);
2798 if ($retweeted_item !== false) {
2799 $retweeted_status = $status;
2801 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
2802 } catch (BadRequestException $e) {
2803 // user not found. should be found?
2804 /// @todo check if the user should be always found
2805 $retweeted_status["user"] = array();
2808 $rt_converted = api_convert_item($retweeted_item);
2810 $retweeted_status['text'] = $rt_converted["text"];
2811 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2812 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2813 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2814 $status['retweeted_status'] = $retweeted_status;
2818 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2819 unset($status["user"]["uid"]);
2820 unset($status["user"]["self"]);
2822 if ($item["coord"] != "") {
2823 $coords = explode(' ', $item["coord"]);
2824 if (count($coords) == 2) {
2825 if ($type == "json")
2826 $status["geo"] = array('type' => 'Point',
2827 'coordinates' => array((float) $coords[0],
2828 (float) $coords[1]));
2829 else // Not sure if this is the official format - if someone founds a documentation we can check
2830 $status["georss:point"] = $item["coord"];
2838 function api_account_rate_limit_status($type)
2840 if ($type == "xml") {
2842 'remaining-hits' => '150',
2843 '@attributes' => array("type" => "integer"),
2844 'hourly-limit' => '150',
2845 '@attributes2' => array("type" => "integer"),
2846 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
2847 '@attributes3' => array("type" => "datetime"),
2848 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2849 '@attributes4' => array("type" => "integer"),
2853 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2854 'remaining_hits' => '150',
2855 'hourly_limit' => '150',
2856 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
2860 return api_format_data('hash', $type, array('hash' => $hash));
2863 /// @TODO move to top of file or somwhere better
2864 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
2866 function api_help_test($type)
2868 if ($type == 'xml') {
2874 return api_format_data('ok', $type, array("ok" => $ok));
2877 /// @TODO move to top of file or somwhere better
2878 api_register_func('api/help/test', 'api_help_test', false);
2880 function api_lists($type)
2883 /// @TODO $ret is not filled here?
2884 return api_format_data('lists', $type, array("lists_list" => $ret));
2887 /// @TODO move to top of file or somwhere better
2888 api_register_func('api/lists', 'api_lists', true);
2890 function api_lists_list($type)
2893 /// @TODO $ret is not filled here?
2894 return api_format_data('lists', $type, array("lists_list" => $ret));
2897 /// @TODO move to top of file or somwhere better
2898 api_register_func('api/lists/list', 'api_lists_list', true);
2901 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2902 * This function is deprecated by Twitter
2903 * returns: json, xml
2905 function api_statuses_f($type, $qtype)
2909 if (api_user() === false) {
2910 throw new ForbiddenException();
2913 $user_info = api_get_user($a);
2915 if (x($_GET, 'cursor') && $_GET['cursor']=='undefined') {
2916 /* this is to stop Hotot to load friends multiple times
2917 * I'm not sure if I'm missing return something or
2918 * is a bug in hotot. Workaround, meantime
2922 return array('$users' => $ret);*/
2926 if ($qtype == 'friends') {
2927 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2929 if ($qtype == 'followers') {
2930 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2933 // friends and followers only for self
2934 if ($user_info['self'] == 0) {
2935 $sql_extra = " AND false ";
2939 "SELECT `nurl` FROM `contact` WHERE `uid` = %d AND NOT `self` AND (NOT `blocked` OR `pending`) $sql_extra ORDER BY `nick`",
2944 foreach ($r as $cid) {
2945 $user = api_get_user($a, $cid['nurl']);
2946 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2947 unset($user["uid"]);
2948 unset($user["self"]);
2955 return array('user' => $ret);
2959 function api_statuses_friends($type)
2961 $data = api_statuses_f($type, "friends");
2962 if ($data === false) {
2965 return api_format_data("users", $type, $data);
2968 function api_statuses_followers($type)
2970 $data = api_statuses_f($type, "followers");
2971 if ($data === false) {
2974 return api_format_data("users", $type, $data);
2977 /// @TODO move to top of file or somewhere better
2978 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2979 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2981 function api_statusnet_config($type)
2985 $name = $a->config['sitename'];
2986 $server = $a->get_hostname();
2987 $logo = System::baseUrl() . '/images/friendica-64.png';
2988 $email = $a->config['admin_email'];
2989 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2990 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
2991 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2992 if ($a->config['api_import_size']) {
2993 $texlimit = string($a->config['api_import_size']);
2995 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
2996 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
2999 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3000 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3001 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3002 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3003 'shorturllength' => '30',
3004 'friendica' => array(
3005 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3006 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3007 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3008 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3013 return api_format_data('config', $type, array('config' => $config));
3016 /// @TODO move to top of file or somewhere better
3017 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3018 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3020 function api_statusnet_version($type)
3023 $fake_statusnet_version = "0.9.7";
3025 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
3028 /// @TODO move to top of file or somewhere better
3029 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3030 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3033 * @todo use api_format_data() to return data
3035 function api_ff_ids($type,$qtype)
3040 throw new ForbiddenException();
3043 $user_info = api_get_user($a);
3045 if ($qtype == 'friends') {
3046 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3048 if ($qtype == 'followers') {
3049 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3052 if (!$user_info["self"]) {
3053 $sql_extra = " AND false ";
3056 $stringify_ids = (x($_REQUEST, 'stringify_ids') ? $_REQUEST['stringify_ids'] : false);
3059 "SELECT `pcontact`.`id` FROM `contact`
3060 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3061 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3065 if (!DBM::is_result($r)) {
3070 foreach ($r as $rr) {
3071 if ($stringify_ids) {
3074 $ids[] = intval($rr['id']);
3078 return api_format_data("ids", $type, array('id' => $ids));
3081 function api_friends_ids($type)
3083 return api_ff_ids($type, 'friends');
3086 function api_followers_ids($type)
3088 return api_ff_ids($type, 'followers');
3091 /// @TODO move to top of file or somewhere better
3092 api_register_func('api/friends/ids', 'api_friends_ids', true);
3093 api_register_func('api/followers/ids', 'api_followers_ids', true);
3095 function api_direct_messages_new($type)
3100 if (api_user() === false) throw new ForbiddenException();
3102 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) return;
3104 $sender = api_get_user($a);
3106 if ($_POST['screen_name']) {
3108 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3110 dbesc($_POST['screen_name'])
3113 // Selecting the id by priority, friendica first
3114 api_best_nickname($r);
3116 $recipient = api_get_user($a, $r[0]['nurl']);
3118 $recipient = api_get_user($a, $_POST['user_id']);
3123 if (x($_REQUEST, 'replyto')) {
3125 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3127 intval($_REQUEST['replyto'])
3129 $replyto = $r[0]['parent-uri'];
3130 $sub = $r[0]['title'];
3132 if (x($_REQUEST, 'title')) {
3133 $sub = $_REQUEST['title'];
3135 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3139 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
3142 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3143 $ret = api_format_messages($r[0], $recipient, $sender);
3145 $ret = array("error"=>$id);
3148 $data = array('direct_message'=>$ret);
3153 $data = api_rss_extra($a, $data, $user_info);
3156 return api_format_data("direct-messages", $type, $data);
3160 /// @TODO move to top of file or somewhere better
3161 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3164 * @brief delete a direct_message from mail table through api
3166 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3169 function api_direct_messages_destroy($type)
3173 if (api_user() === false) {
3174 throw new ForbiddenException();
3178 $user_info = api_get_user($a);
3180 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3182 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3183 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3184 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3186 $uid = $user_info['uid'];
3187 // error if no id or parenturi specified (for clients posting parent-uri as well)
3188 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3189 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
3190 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3193 // BadRequestException if no id specified (for clients using Twitter API)
3195 throw new BadRequestException('Message id not specified');
3198 // add parent-uri to sql command if specified by calling app
3199 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3201 // get data of the specified message id
3203 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3208 // error message if specified id is not in database
3209 if (!DBM::is_result($r)) {
3210 if ($verbose == "true") {
3211 $answer = array('result' => 'error', 'message' => 'message id not in database');
3212 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3214 /// @todo BadRequestException ok for Twitter API clients?
3215 throw new BadRequestException('message id not in database');
3220 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3225 if ($verbose == "true") {
3228 $answer = array('result' => 'ok', 'message' => 'message deleted');
3229 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
3231 $answer = array('result' => 'error', 'message' => 'unknown error');
3232 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
3235 /// @todo return JSON data like Twitter API not yet implemented
3239 /// @TODO move to top of file or somewhere better
3240 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3242 function api_direct_messages_box($type, $box, $verbose)
3246 if (api_user() === false) {
3247 throw new ForbiddenException();
3251 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3252 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3257 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3258 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3260 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3261 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3264 unset($_REQUEST["user_id"]);
3265 unset($_GET["user_id"]);
3267 unset($_REQUEST["screen_name"]);
3268 unset($_GET["screen_name"]);
3270 $user_info = api_get_user($a);
3271 $profile_url = $user_info["url"];
3274 $start = $page * $count;
3277 if ($box=="sentbox") {
3278 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3279 } elseif ($box == "conversation") {
3280 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3281 } elseif ($box == "all") {
3282 $sql_extra = "true";
3283 } elseif ($box == "inbox") {
3284 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3288 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3291 if ($user_id != "") {
3292 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3293 } elseif ($screen_name !="") {
3294 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3298 "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",
3304 if ($verbose == "true" && !DBM::is_result($r)) {
3305 $answer = array('result' => 'error', 'message' => 'no mails available');
3306 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
3310 foreach ($r as $item) {
3311 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3312 $recipient = $user_info;
3313 $sender = api_get_user($a, normalise_link($item['contact-url']));
3314 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3315 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3316 $sender = $user_info;
3319 $ret[] = api_format_messages($item, $recipient, $sender);
3323 $data = array('direct_message' => $ret);
3327 $data = api_rss_extra($a, $data, $user_info);
3330 return api_format_data("direct-messages", $type, $data);
3333 function api_direct_messages_sentbox($type)
3335 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3336 return api_direct_messages_box($type, "sentbox", $verbose);
3339 function api_direct_messages_inbox($type)
3341 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3342 return api_direct_messages_box($type, "inbox", $verbose);
3345 function api_direct_messages_all($type)
3347 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3348 return api_direct_messages_box($type, "all", $verbose);
3351 function api_direct_messages_conversation($type)
3353 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3354 return api_direct_messages_box($type, "conversation", $verbose);
3357 /// @TODO move to top of file or somewhere better
3358 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3359 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3360 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3361 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3363 function api_oauth_request_token($type)
3366 $oauth = new FKOAuth1();
3367 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3368 } catch (Exception $e) {
3369 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3376 function api_oauth_access_token($type)
3379 $oauth = new FKOAuth1();
3380 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3381 } catch (Exception $e) {
3382 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3389 /// @TODO move to top of file or somewhere better
3390 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3391 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3395 * @brief delete a complete photoalbum with all containing photos from database through api
3397 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3400 function api_fr_photoalbum_delete($type)
3402 if (api_user() === false) {
3403 throw new ForbiddenException();
3406 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3408 // we do not allow calls without album string
3410 throw new BadRequestException("no albumname specified");
3412 // check if album is existing
3414 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3418 if (!DBM::is_result($r))
3419 throw new BadRequestException("album not available");
3421 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3422 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3423 foreach ($r as $rr) {
3425 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3426 intval(local_user()),
3427 dbesc($rr['resource-id'])
3430 if (!DBM::is_result($photo_item)) {
3431 throw new InternalServerErrorException("problem with deleting items occured");
3433 drop_item($photo_item[0]['id'], false);
3436 // now let's delete all photos from the album
3438 "DELETE FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3443 // return success of deletion or error message
3445 $answer = array('result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.');
3446 return api_format_data("photoalbum_delete", $type, array('$result' => $answer));
3448 throw new InternalServerErrorException("unknown error - deleting from database failed");
3453 * @brief update the name of the album for all photos of an album
3455 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3458 function api_fr_photoalbum_update($type)
3460 if (api_user() === false) {
3461 throw new ForbiddenException();
3464 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3465 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
3467 // we do not allow calls without album string
3469 throw new BadRequestException("no albumname specified");
3471 if ($album_new == "") {
3472 throw new BadRequestException("no new albumname specified");
3474 // check if album is existing
3476 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3480 if (!DBM::is_result($r)) {
3481 throw new BadRequestException("album not available");
3483 // now let's update all photos to the albumname
3485 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
3491 // return success of updating or error message
3493 $answer = array('result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.');
3494 return api_format_data("photoalbum_update", $type, array('$result' => $answer));
3496 throw new InternalServerErrorException("unknown error - updating in database failed");
3502 * @brief list all photos of the authenticated user
3504 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3507 function api_fr_photos_list($type)
3509 if (api_user() === false) {
3510 throw new ForbiddenException();
3513 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3514 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3515 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
3516 intval(local_user())
3519 'image/jpeg' => 'jpg',
3520 'image/png' => 'png',
3521 'image/gif' => 'gif'
3523 $data = array('photo'=>array());
3524 if (DBM::is_result($r)) {
3525 foreach ($r as $rr) {
3527 $photo['id'] = $rr['resource-id'];
3528 $photo['album'] = $rr['album'];
3529 $photo['filename'] = $rr['filename'];
3530 $photo['type'] = $rr['type'];
3531 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3532 $photo['created'] = $rr['created'];
3533 $photo['edited'] = $rr['edited'];
3534 $photo['desc'] = $rr['desc'];
3536 if ($type == "xml") {
3537 $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3539 $photo['thumb'] = $thumb;
3540 $data['photo'][] = $photo;
3544 return api_format_data("photos", $type, $data);
3548 * @brief upload a new photo or change an existing photo
3550 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3553 function api_fr_photo_create_update($type)
3555 if (api_user() === false) {
3556 throw new ForbiddenException();
3559 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3560 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
3561 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
3562 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
3563 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
3564 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
3565 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
3566 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
3567 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
3569 // do several checks on input parameters
3570 // we do not allow calls without album string
3571 if ($album == null) {
3572 throw new BadRequestException("no albumname specified");
3574 // if photo_id == null --> we are uploading a new photo
3575 if ($photo_id == null) {
3578 // error if no media posted in create-mode
3579 if (!x($_FILES, 'media')) {
3581 throw new BadRequestException("no media data submitted");
3584 // album_new will be ignored in create-mode
3589 // check if photo is existing in database
3591 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3596 if (!DBM::is_result($r)) {
3597 throw new BadRequestException("photo not available");
3601 // checks on acl strings provided by clients
3602 $acl_input_error = false;
3603 $acl_input_error |= check_acl_input($allow_cid);
3604 $acl_input_error |= check_acl_input($deny_cid);
3605 $acl_input_error |= check_acl_input($allow_gid);
3606 $acl_input_error |= check_acl_input($deny_gid);
3607 if ($acl_input_error) {
3608 throw new BadRequestException("acl data invalid");
3610 // now let's upload the new media in create-mode
3611 if ($mode == "create") {
3612 $media = $_FILES['media'];
3613 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
3615 // return success of updating or error message
3616 if (!is_null($data)) {
3617 return api_format_data("photo_create", $type, $data);
3619 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3623 // now let's do the changes in update-mode
3624 if ($mode == "update") {
3627 if (!is_null($desc)) {
3628 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
3631 if (!is_null($album_new)) {
3632 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
3635 if (!is_null($allow_cid)) {
3636 $allow_cid = trim($allow_cid);
3637 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
3640 if (!is_null($deny_cid)) {
3641 $deny_cid = trim($deny_cid);
3642 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
3645 if (!is_null($allow_gid)) {
3646 $allow_gid = trim($allow_gid);
3647 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
3650 if (!is_null($deny_gid)) {
3651 $deny_gid = trim($deny_gid);
3652 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
3656 if ($sql_extra != "") {
3657 $nothingtodo = false;
3659 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
3661 datetime_convert(), // update edited timestamp
3667 $nothingtodo = true;
3670 if (x($_FILES, 'media')) {
3671 $nothingtodo = false;
3672 $media = $_FILES['media'];
3673 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
3674 if (!is_null($data)) {
3675 return api_format_data("photo_update", $type, $data);
3679 // return success of updating or error message
3681 $answer = array('result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.');
3682 return api_format_data("photo_update", $type, array('$result' => $answer));
3685 $answer = array('result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.');
3686 return api_format_data("photo_update", $type, array('$result' => $answer));
3688 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3691 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3696 * @brief delete a single photo from the database through api
3698 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3701 function api_fr_photo_delete($type)
3703 if (api_user() === false) {
3704 throw new ForbiddenException();
3707 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
3709 // do several checks on input parameters
3710 // we do not allow calls without photo id
3711 if ($photo_id == null) {
3712 throw new BadRequestException("no photo_id specified");
3714 // check if photo is existing in database
3716 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3720 if (!DBM::is_result($r)) {
3721 throw new BadRequestException("photo not available");
3723 // now we can perform on the deletion of the photo
3725 "DELETE FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
3730 // return success of deletion or error message
3732 // retrieve the id of the parent element (the photo element)
3734 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3735 intval(local_user()),
3739 if (!DBM::is_result($photo_item)) {
3740 throw new InternalServerErrorException("problem with deleting items occured");
3742 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3743 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3744 drop_item($photo_item[0]['id'], false);
3746 $answer = array('result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.');
3747 return api_format_data("photo_delete", $type, array('$result' => $answer));
3749 throw new InternalServerErrorException("unknown error on deleting photo from database table");
3755 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3757 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3760 function api_fr_photo_detail($type)
3762 if (api_user() === false) {
3763 throw new ForbiddenException();
3765 if (!x($_REQUEST, 'photo_id')) {
3766 throw new BadRequestException("No photo id.");
3769 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3770 $photo_id = $_REQUEST['photo_id'];
3772 // prepare json/xml output with data from database for the requested photo
3773 $data = prepare_photo_data($type, $scale, $photo_id);
3775 return api_format_data("photo_detail", $type, $data);
3780 * @brief updates the profile image for the user (either a specified profile or the default profile)
3782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3785 function api_account_update_profile_image($type)
3787 if (api_user() === false) {
3788 throw new ForbiddenException();
3791 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
3793 // error if image data is missing
3794 if (!x($_FILES, 'image')) {
3795 throw new BadRequestException("no media data submitted");
3798 // check if specified profile id is valid
3799 if ($profileid != 0) {
3801 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
3805 // error message if specified profile id is not in database
3806 if (!DBM::is_result($r)) {
3807 throw new BadRequestException("profile_id not available");
3809 $is_default_profile = $r['profile'];
3811 $is_default_profile = 1;
3814 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3816 if (x($_FILES, 'image')) {
3817 $media = $_FILES['image'];
3818 } elseif (x($_FILES, 'media')) {
3819 $media = $_FILES['media'];
3821 // save new profile image
3822 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
3825 if (is_array($media['type'])) {
3826 $filetype = $media['type'][0];
3828 $filetype = $media['type'];
3830 if ($filetype == "image/jpeg") {
3832 } elseif ($filetype == "image/png") {
3835 // change specified profile or all profiles to the new resource-id
3836 if ($is_default_profile) {
3838 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
3839 dbesc($data['photo']['id']),
3840 intval(local_user())
3844 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
3845 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
3846 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
3847 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
3848 intval(local_user())
3852 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
3853 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
3854 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
3855 intval($_REQUEST['profile']),
3856 intval(local_user())
3860 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
3861 // so that browsers will do a cache update unconditionally
3864 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
3865 dbesc(datetime_convert()),
3866 intval(local_user())
3869 // Update global directory in background
3870 //$user = api_get_user(get_app());
3871 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
3872 if ($url && strlen(Config::get('system', 'directory'))) {
3873 Worker::add(PRIORITY_LOW, "Directory", $url);
3876 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
3878 // output for client
3880 return api_account_verify_credentials($type);
3882 // SaveMediaToDatabase failed for some reason
3883 throw new InternalServerErrorException("image upload failed");
3887 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3888 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
3889 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
3890 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3891 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3892 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3893 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
3894 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3895 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3898 function check_acl_input($acl_string)
3900 if ($acl_string == null || $acl_string == " ") {
3903 $contact_not_found = false;
3905 // split <x><y><z> into array of cid's
3906 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3908 // check for each cid if it is available on server
3909 $cid_array = $array[0];
3910 foreach ($cid_array as $cid) {
3911 $cid = str_replace("<", "", $cid);
3912 $cid = str_replace(">", "", $cid);
3914 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3918 $contact_not_found |= !DBM::is_result($contact);
3920 return $contact_not_found;
3923 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)
3931 if (is_array($media)) {
3932 if (is_array($media['tmp_name'])) {
3933 $src = $media['tmp_name'][0];
3935 $src = $media['tmp_name'];
3937 if (is_array($media['name'])) {
3938 $filename = basename($media['name'][0]);
3940 $filename = basename($media['name']);
3942 if (is_array($media['size'])) {
3943 $filesize = intval($media['size'][0]);
3945 $filesize = intval($media['size']);
3947 if (is_array($media['type'])) {
3948 $filetype = $media['type'][0];
3950 $filetype = $media['type'];
3954 if ($filetype == "") {
3955 $filetype=guess_image_type($filename);
3957 $imagedata = getimagesize($src);
3959 $filetype = $imagedata['mime'];
3962 "File upload src: " . $src . " - filename: " . $filename .
3963 " - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG
3966 // check if there was a php upload error
3967 if ($filesize == 0 && $media['error'] == 1) {
3968 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3970 // check against max upload size within Friendica instance
3971 $maximagesize = Config::get('system', 'maximagesize');
3972 if (($maximagesize) && ($filesize > $maximagesize)) {
3973 $formattedBytes = formatBytes($maximagesize);
3974 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3977 // create Photo instance with the data of the image
3978 $imagedata = @file_get_contents($src);
3979 $ph = new Photo($imagedata, $filetype);
3980 if (! $ph->is_valid()) {
3981 throw new InternalServerErrorException("unable to process image data");
3984 // check orientation of image
3988 // check max length of images on server
3989 $max_length = Config::get('system', 'max_image_length');
3990 if (! $max_length) {
3991 $max_length = MAX_IMAGE_LENGTH;
3993 if ($max_length > 0) {
3994 $ph->scaleImage($max_length);
3995 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
3997 $width = $ph->getWidth();
3998 $height = $ph->getHeight();
4000 // create a new resource-id if not already provided
4001 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4003 if ($mediatype == "photo") {
4004 // upload normal image (scales 0, 1, 2)
4005 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4007 $r =$ph->store(local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4009 logger("photo upload: image upload with scale 0 (original size) failed");
4011 if ($width > 640 || $height > 640) {
4012 $ph->scaleImage(640);
4013 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4015 logger("photo upload: image upload with scale 1 (640x640) failed");
4019 if ($width > 320 || $height > 320) {
4020 $ph->scaleImage(320);
4021 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4023 logger("photo upload: image upload with scale 2 (320x320) failed");
4026 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4027 } elseif ($mediatype == "profileimage") {
4028 // upload profile image (scales 4, 5, 6)
4029 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4031 if ($width > 175 || $height > 175) {
4032 $ph->scaleImage(175);
4033 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4035 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4039 if ($width > 80 || $height > 80) {
4040 $ph->scaleImage(80);
4041 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4043 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4047 if ($width > 48 || $height > 48) {
4048 $ph->scaleImage(48);
4049 $r = $ph->store(local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4051 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4055 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4059 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4060 if ($photo_id == null && $mediatype == "photo") {
4061 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4063 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4064 return prepare_photo_data($type, false, $hash);
4066 throw new InternalServerErrorException("image upload failed");
4070 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4072 // get data about the api authenticated user
4073 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4074 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4077 $arr['guid'] = get_guid(32);
4078 $arr['uid'] = intval(api_user());
4080 $arr['parent-uri'] = $uri;
4081 $arr['type'] = 'photo';
4083 $arr['resource-id'] = $hash;
4084 $arr['contact-id'] = $owner_record[0]['id'];
4085 $arr['owner-name'] = $owner_record[0]['name'];
4086 $arr['owner-link'] = $owner_record[0]['url'];
4087 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4088 $arr['author-name'] = $owner_record[0]['name'];
4089 $arr['author-link'] = $owner_record[0]['url'];
4090 $arr['author-avatar'] = $owner_record[0]['thumb'];
4092 $arr['allow_cid'] = $allow_cid;
4093 $arr['allow_gid'] = $allow_gid;
4094 $arr['deny_cid'] = $deny_cid;
4095 $arr['deny_gid'] = $deny_gid;
4096 $arr['last-child'] = 1;
4097 $arr['visible'] = $visibility;
4101 'image/jpeg' => 'jpg',
4102 'image/png' => 'png',
4103 'image/gif' => 'gif'
4106 // adds link to the thumbnail scale photo
4107 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4108 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4111 // do the magic for storing the item in the database and trigger the federation to other contacts
4115 function prepare_photo_data($type, $scale, $photo_id)
4117 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4118 $data_sql = ($scale === false ? "" : "data, ");
4120 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4121 // clients needs to convert this in their way for further processing
4123 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4124 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4125 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4126 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4128 intval(local_user()),
4134 'image/jpeg' => 'jpg',
4135 'image/png' => 'png',
4136 'image/gif' => 'gif'
4139 // prepare output data for photo
4140 if (DBM::is_result($r)) {
4141 $data = array('photo' => $r[0]);
4142 $data['photo']['id'] = $data['photo']['resource-id'];
4143 if ($scale !== false) {
4144 $data['photo']['data'] = base64_encode($data['photo']['data']);
4146 unset($data['photo']['datasize']); //needed only with scale param
4148 if ($type == "xml") {
4149 $data['photo']['links'] = array();
4150 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4151 $data['photo']['links'][$k . ":link"]["@attributes"] = array("type" => $data['photo']['type'],
4153 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]);
4156 $data['photo']['link'] = array();
4157 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4159 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4160 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4164 unset($data['photo']['resource-id']);
4165 unset($data['photo']['minscale']);
4166 unset($data['photo']['maxscale']);
4168 throw new NotFoundException();
4171 // retrieve item element for getting activities (like, dislike etc.) related to photo
4173 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4174 intval(local_user()),
4177 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4179 // retrieve comments on photo
4181 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4182 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4183 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4184 `contact`.`id` AS `cid`
4186 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4187 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4188 WHERE `item`.`parent` = %d AND `item`.`visible`
4189 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4190 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4191 intval($item[0]['parent']),
4193 dbesc(ACTIVITY_POST)
4196 // prepare output of comments
4197 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4198 $comments = array();
4199 if ($type == "xml") {
4201 foreach ($commentData as $comment) {
4202 $comments[$k++ . ":comment"] = $comment;
4205 foreach ($commentData as $comment) {
4206 $comments[] = $comment;
4209 $data['photo']['friendica_comments'] = $comments;
4211 // include info if rights on photo and rights on item are mismatching
4212 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4213 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4214 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4215 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4216 $data['photo']['rights_mismatch'] = $rights_mismatch;
4223 * Similar as /mod/redir.php
4224 * redirect to 'url' after dfrn auth
4226 * Why this when there is mod/redir.php already?
4227 * This use api_user() and api_login()
4230 * c_url: url of remote contact to auth to
4231 * url: string, url to redirect after auth
4233 function api_friendica_remoteauth()
4235 $url = ((x($_GET, 'url')) ? $_GET['url'] : '');
4236 $c_url = ((x($_GET, 'c_url')) ? $_GET['c_url'] : '');
4238 if ($url === '' || $c_url === '') {
4239 throw new BadRequestException("Wrong parameters.");
4242 $c_url = normalise_link($c_url);
4247 "SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
4252 if ((! DBM::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN)) {
4253 throw new BadRequestException("Unknown contact");
4258 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
4260 if ($r[0]['duplex'] && $r[0]['issued-id']) {
4261 $orig_id = $r[0]['issued-id'];
4262 $dfrn_id = '1:' . $orig_id;
4264 if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
4265 $orig_id = $r[0]['dfrn-id'];
4266 $dfrn_id = '0:' . $orig_id;
4269 $sec = random_string();
4272 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4273 VALUES( %d, %s, '%s', '%s', %d )",
4281 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
4282 $dest = (($url) ? '&destination_url=' . $url : '');
4284 $r[0]['poll'] . '?dfrn_id=' . $dfrn_id
4285 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4286 . '&type=profile&sec=' . $sec . $dest . $quiet
4289 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4292 * @brief Return the item shared, if the item contains only the [share] tag
4294 * @param array $item Sharer item
4295 * @return array Shared item or false if not a reshare
4297 function api_share_as_retweet(&$item)
4299 $body = trim($item["body"]);
4301 if (Diaspora::is_reshare($body, false)===false) {
4305 /// @TODO "$1" should maybe mean '$1' ?
4306 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4308 * Skip if there is no shared message in there
4309 * we already checked this in diaspora::is_reshare()
4310 * but better one more than one less...
4312 if ($body == $attributes) {
4317 // build the fake reshared item
4318 $reshared_item = $item;
4321 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4322 if ($matches[1] != "") {
4323 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4326 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4327 if ($matches[1] != "") {
4328 $author = $matches[1];
4332 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4333 if ($matches[1] != "") {
4334 $profile = $matches[1];
4337 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4338 if ($matches[1] != "") {
4339 $profile = $matches[1];
4343 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4344 if ($matches[1] != "") {
4345 $avatar = $matches[1];
4348 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4349 if ($matches[1] != "") {
4350 $avatar = $matches[1];
4354 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4355 if ($matches[1] != "") {
4356 $link = $matches[1];
4359 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4360 if ($matches[1] != "") {
4361 $link = $matches[1];
4365 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4366 if ($matches[1] != "")
4367 $posted = $matches[1];
4369 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4370 if ($matches[1] != "") {
4371 $posted = $matches[1];
4374 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
4376 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
4380 $reshared_item["body"] = $shared_body;
4381 $reshared_item["author-name"] = $author;
4382 $reshared_item["author-link"] = $profile;
4383 $reshared_item["author-avatar"] = $avatar;
4384 $reshared_item["plink"] = $link;
4385 $reshared_item["created"] = $posted;
4386 $reshared_item["edited"] = $posted;
4388 return $reshared_item;
4392 function api_get_nick($profile)
4395 - remove trailing junk from profile url
4396 - pump.io check has to check the website
4402 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4403 dbesc(normalise_link($profile))
4406 if (DBM::is_result($r)) {
4407 $nick = $r[0]["nick"];
4412 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
4413 dbesc(normalise_link($profile))
4416 if (DBM::is_result($r)) {
4417 $nick = $r[0]["nick"];
4422 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
4423 if ($friendica != $profile) {
4429 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
4430 if ($diaspora != $profile) {
4436 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
4437 if ($twitter != $profile) {
4444 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
4445 if ($StatusnetHost != $profile) {
4446 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
4447 if ($StatusnetUser != $profile) {
4448 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
4449 $user = json_decode($UserData);
4451 $nick = $user->screen_name;
4457 // To-Do: look at the page if its really a pumpio site
4458 //if (!$nick == "") {
4459 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
4460 // if ($pumpio != $profile)
4462 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
4473 function api_in_reply_to($item)
4475 $in_reply_to = array();
4477 $in_reply_to['status_id'] = null;
4478 $in_reply_to['user_id'] = null;
4479 $in_reply_to['status_id_str'] = null;
4480 $in_reply_to['user_id_str'] = null;
4481 $in_reply_to['screen_name'] = null;
4483 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
4484 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
4485 intval($item['uid']),
4486 dbesc($item['thr-parent']));
4488 if (DBM::is_result($r)) {
4489 $in_reply_to['status_id'] = intval($r[0]['id']);
4491 $in_reply_to['status_id'] = intval($item['parent']);
4494 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4496 $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
4497 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
4498 WHERE `item`.`id` = %d LIMIT 1",
4499 intval($in_reply_to['status_id'])
4502 if (DBM::is_result($r)) {
4503 if ($r[0]['nick'] == "") {
4504 $r[0]['nick'] = api_get_nick($r[0]["url"]);
4507 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
4508 $in_reply_to['user_id'] = intval($r[0]['id']);
4509 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
4512 // There seems to be situation, where both fields are identical:
4513 // https://github.com/friendica/friendica/issues/1010
4514 // This is a bugfix for that.
4515 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4516 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
4517 $in_reply_to['status_id'] = null;
4518 $in_reply_to['user_id'] = null;
4519 $in_reply_to['status_id_str'] = null;
4520 $in_reply_to['user_id_str'] = null;
4521 $in_reply_to['screen_name'] = null;
4525 return $in_reply_to;
4528 function api_clean_plain_items($Text)
4530 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
4532 $Text = bb_CleanPictureLinks($Text);
4533 $URLSearchString = "^\[\]";
4535 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
4537 if ($include_entities == "true") {
4538 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
4541 // Simplify "attachment" element
4542 $Text = api_clean_attachments($Text);
4548 * @brief Removes most sharing information for API text export
4550 * @param string $body The original body
4552 * @return string Cleaned body
4554 function api_clean_attachments($body)
4556 $data = get_attachment_data($body);
4563 if (isset($data["text"]))
4564 $body = $data["text"];
4566 if (($body == "") && (isset($data["title"])))
4567 $body = $data["title"];
4569 if (isset($data["url"]))
4570 $body .= "\n".$data["url"];
4572 $body .= $data["after"];
4577 function api_best_nickname(&$contacts)
4579 $best_contact = array();
4581 if (count($contact) == 0)
4584 foreach ($contacts as $contact)
4585 if ($contact["network"] == "") {
4586 $contact["network"] = "dfrn";
4587 $best_contact = array($contact);
4590 if (sizeof($best_contact) == 0)
4591 foreach ($contacts as $contact)
4592 if ($contact["network"] == "dfrn")
4593 $best_contact = array($contact);
4595 if (sizeof($best_contact) == 0)
4596 foreach ($contacts as $contact)
4597 if ($contact["network"] == "dspr")
4598 $best_contact = array($contact);
4600 if (sizeof($best_contact) == 0)
4601 foreach ($contacts as $contact)
4602 if ($contact["network"] == "stat")
4603 $best_contact = array($contact);
4605 if (sizeof($best_contact) == 0)
4606 foreach ($contacts as $contact)
4607 if ($contact["network"] == "pump")
4608 $best_contact = array($contact);
4610 if (sizeof($best_contact) == 0)
4611 foreach ($contacts as $contact)
4612 if ($contact["network"] == "twit")
4613 $best_contact = array($contact);
4615 if (sizeof($best_contact) == 1) {
4616 $contacts = $best_contact;
4618 $contacts = array($contacts[0]);
4622 // return all or a specified group of the user with the containing contacts
4623 function api_friendica_group_show($type)
4627 if (api_user() === false) throw new ForbiddenException();
4630 $user_info = api_get_user($a);
4631 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4632 $uid = $user_info['uid'];
4634 // get data of the specified group id or all groups if not specified
4637 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
4641 // error message if specified gid is not in database
4642 if (!DBM::is_result($r))
4643 throw new BadRequestException("gid not available");
4646 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
4651 // loop through all groups and retrieve all members for adding data in the user array
4652 foreach ($r as $rr) {
4653 $members = group_get_members($rr['id']);
4656 if ($type == "xml") {
4657 $user_element = "users";
4659 foreach ($members as $member) {
4660 $user = api_get_user($a, $member['nurl']);
4661 $users[$k++.":user"] = $user;
4664 $user_element = "user";
4665 foreach ($members as $member) {
4666 $user = api_get_user($a, $member['nurl']);
4670 $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
4672 return api_format_data("groups", $type, array('group' => $grps));
4674 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4677 // delete the specified group of the user
4678 function api_friendica_group_delete($type)
4682 if (api_user() === false) throw new ForbiddenException();
4685 $user_info = api_get_user($a);
4686 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4687 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4688 $uid = $user_info['uid'];
4690 // error if no gid specified
4691 if ($gid == 0 || $name == "")
4692 throw new BadRequestException('gid or name not specified');
4694 // get data of the specified group id
4696 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
4700 // error message if specified gid is not in database
4701 if (!DBM::is_result($r))
4702 throw new BadRequestException('gid not available');
4704 // get data of the specified group id and group name
4706 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
4711 // error message if specified gid is not in database
4712 if (!DBM::is_result($rname))
4713 throw new BadRequestException('wrong group name');
4716 $ret = group_rmv($uid, $name);
4719 $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
4720 return api_format_data("group_delete", $type, array('result' => $success));
4722 throw new BadRequestException('other API error');
4725 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4728 // create the specified group with the posted array of contacts
4729 function api_friendica_group_create($type)
4733 if (api_user() === false) throw new ForbiddenException();
4736 $user_info = api_get_user($a);
4737 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4738 $uid = $user_info['uid'];
4739 $json = json_decode($_POST['json'], true);
4740 $users = $json['user'];
4742 // error if no name specified
4744 throw new BadRequestException('group name not specified');
4746 // get data of the specified group name
4748 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
4752 // error message if specified group name already exists
4753 if (DBM::is_result($rname))
4754 throw new BadRequestException('group name already exists');
4756 // check if specified group name is a deleted group
4758 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
4762 // error message if specified group name already exists
4763 if (DBM::is_result($rname))
4764 $reactivate_group = true;
4767 $ret = group_add($uid, $name);
4769 $gid = group_byname($uid, $name);
4771 throw new BadRequestException('other API error');
4775 $erroraddinguser = false;
4776 $errorusers = array();
4777 foreach ($users as $user) {
4778 $cid = $user['cid'];
4779 // check if user really exists as contact
4781 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4785 if (count($contact))
4786 $result = group_add_member($uid, $name, $cid, $gid);
4788 $erroraddinguser = true;
4789 $errorusers[] = $cid;
4793 // return success message incl. missing users in array
4794 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
4795 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4796 return api_format_data("group_create", $type, array('result' => $success));
4798 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4801 // update the specified group with the posted array of contacts
4802 function api_friendica_group_update($type)
4806 if (api_user() === false) throw new ForbiddenException();
4809 $user_info = api_get_user($a);
4810 $uid = $user_info['uid'];
4811 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
4812 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
4813 $json = json_decode($_POST['json'], true);
4814 $users = $json['user'];
4816 // error if no name specified
4818 throw new BadRequestException('group name not specified');
4820 // error if no gid specified
4822 throw new BadRequestException('gid not specified');
4825 $members = group_get_members($gid);
4826 foreach ($members as $member) {
4827 $cid = $member['id'];
4828 foreach ($users as $user) {
4829 $found = ($user['cid'] == $cid ? true : false);
4832 $ret = group_rmv_member($uid, $name, $cid);
4837 $erroraddinguser = false;
4838 $errorusers = array();
4839 foreach ($users as $user) {
4840 $cid = $user['cid'];
4841 // check if user really exists as contact
4843 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4848 if (count($contact)) {
4849 $result = group_add_member($uid, $name, $cid, $gid);
4851 $erroraddinguser = true;
4852 $errorusers[] = $cid;
4856 // return success message incl. missing users in array
4857 $status = ($erroraddinguser ? "missing user" : "ok");
4858 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
4859 return api_format_data("group_update", $type, array('result' => $success));
4862 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4864 function api_friendica_activity($type)
4868 if (api_user() === false) throw new ForbiddenException();
4869 $verb = strtolower($a->argv[3]);
4870 $verb = preg_replace("|\..*$|", "", $verb);
4872 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4874 $res = do_like($id, $verb);
4877 if ($type == "xml") {
4882 return api_format_data('ok', $type, array('ok' => $ok));
4884 throw new BadRequestException('Error adding activity');
4888 /// @TODO move to top of file or somwhere better
4889 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
4890 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
4891 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
4892 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
4893 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4894 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
4895 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
4896 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
4897 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
4898 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
4901 * @brief Returns notifications
4903 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4906 function api_friendica_notification($type)
4910 if (api_user() === false) throw new ForbiddenException();
4911 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
4912 $nm = new NotificationsManager();
4914 $notes = $nm->getAll(array(), "+seen -date", 50);
4916 if ($type == "xml") {
4917 $xmlnotes = array();
4918 foreach ($notes as $note)
4919 $xmlnotes[] = array("@attributes" => $note);
4924 return api_format_data("notes", $type, array('note' => $notes));
4928 * @brief Set notification as seen and returns associated item (if possible)
4930 * POST request with 'id' param as notification id
4932 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4935 function api_friendica_notification_seen($type)
4939 if (api_user() === false) throw new ForbiddenException();
4940 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
4942 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
4944 $nm = new NotificationsManager();
4945 $note = $nm->getByID($id);
4946 if (is_null($note)) throw new BadRequestException("Invalid argument");
4948 $nm->setSeen($note);
4949 if ($note['otype']=='item') {
4950 // would be really better with an ItemsManager and $im->getByID() :-P
4952 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
4953 intval($note['iid']),
4954 intval(local_user())
4957 // we found the item, return it to the user
4958 $user_info = api_get_user($a);
4959 $ret = api_format_items($r, $user_info, false, $type);
4960 $data = array('status' => $ret);
4961 return api_format_data("status", $type, $data);
4963 // the item can't be found, but we set the note as seen, so we count this as a success
4965 return api_format_data('result', $type, array('result' => "success"));
4968 /// @TODO move to top of file or somwhere better
4969 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4970 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
4973 * @brief update a direct_message to seen state
4975 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4976 * @return string (success result=ok, error result=error with error message)
4978 function api_friendica_direct_messages_setseen($type)
4981 if (api_user() === false) {
4982 throw new ForbiddenException();
4986 $user_info = api_get_user($a);
4987 $uid = $user_info['uid'];
4988 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
4990 // return error if id is zero
4992 $answer = array('result' => 'error', 'message' => 'message id not specified');
4993 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
4996 // get data of the specified message id
4998 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5003 // error message if specified id is not in database
5004 if (!DBM::is_result($r)) {
5005 $answer = array('result' => 'error', 'message' => 'message id not in database');
5006 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5009 // update seen indicator
5011 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5018 $answer = array('result' => 'ok', 'message' => 'message set to seen');
5019 return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
5021 $answer = array('result' => 'error', 'message' => 'unknown error');
5022 return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
5026 /// @TODO move to top of file or somwhere better
5027 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5030 * @brief search for direct_messages containing a searchstring through api
5032 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5033 * @return string (success: success=true if found and search_result contains found messages
5034 * success=false if nothing was found, search_result='nothing found',
5035 * error: result=error with error message)
5037 function api_friendica_direct_messages_search($type)
5041 if (api_user() === false) {
5042 throw new ForbiddenException();
5046 $user_info = api_get_user($a);
5047 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5048 $uid = $user_info['uid'];
5050 // error if no searchstring specified
5051 if ($searchstring == "") {
5052 $answer = array('result' => 'error', 'message' => 'searchstring not specified');
5053 return api_format_data("direct_messages_search", $type, array('$result' => $answer));
5056 // get data for the specified searchstring
5058 "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",
5060 dbesc('%'.$searchstring.'%')
5063 $profile_url = $user_info["url"];
5065 // message if nothing was found
5066 if (!DBM::is_result($r)) {
5067 $success = array('success' => false, 'search_results' => 'problem with query');
5068 } elseif (count($r) == 0) {
5069 $success = array('success' => false, 'search_results' => 'nothing found');
5072 foreach ($r as $item) {
5073 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5074 $recipient = $user_info;
5075 $sender = api_get_user($a, normalise_link($item['contact-url']));
5076 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5077 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5078 $sender = $user_info;
5081 $ret[] = api_format_messages($item, $recipient, $sender);
5083 $success = array('success' => true, 'search_results' => $ret);
5086 return api_format_data("direct_message_search", $type, array('$result' => $success));
5089 /// @TODO move to top of file or somwhere better
5090 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5093 * @brief return data of all the profiles a user has to the client
5095 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5098 function api_friendica_profile_show($type)
5102 if (api_user() === false) {
5103 throw new ForbiddenException();
5107 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5109 // retrieve general information about profiles for user
5110 $multi_profiles = feature_enabled(api_user(), 'multi_profiles');
5111 $directory = Config::get('system', 'directory');
5113 // get data of the specified profile id or all profiles of the user if not specified
5114 if ($profileid != 0) {
5116 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5121 // error message if specified gid is not in database
5122 if (!DBM::is_result($r)) {
5123 throw new BadRequestException("profile_id not available");
5127 "SELECT * FROM `profile` WHERE `uid` = %d",
5131 // loop through all returned profiles and retrieve data and users
5133 foreach ($r as $rr) {
5134 $profile = api_format_items_profiles($rr, $type);
5136 // select all users from contact table, loop and prepare standard return for user data
5139 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5141 intval($rr['profile_id'])
5144 foreach ($r as $rr) {
5145 $user = api_get_user($a, $rr['nurl']);
5146 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5148 $profile['users'] = $users;
5150 // add prepared profile data to array for final return
5151 if ($type == "xml") {
5152 $profiles[$k++ . ":profile"] = $profile;
5154 $profiles[] = $profile;
5158 // return settings, authenticated user and profiles data
5159 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5161 $result = array('multi_profiles' => $multi_profiles ? true : false,
5162 'global_dir' => $directory,
5163 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5164 'profiles' => $profiles);
5165 return api_format_data("friendica_profiles", $type, array('$result' => $result));
5167 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5170 @TODO Maybe open to implement?
5172 [pagename] => api/1.1/statuses/lookup.json
5173 [id] => 605138389168451584
5174 [include_cards] => true
5175 [cards_platform] => Android-12
5176 [include_entities] => true
5177 [include_my_retweet] => 1
5179 [include_reply_count] => true
5180 [include_descendent_reply_count] => true
5184 Not implemented by now:
5185 statuses/retweets_of_me
5190 account/update_location
5191 account/update_profile_background_image
5194 friendica/profile/update
5195 friendica/profile/create
5196 friendica/profile/delete
5198 Not implemented in status.net:
5199 statuses/retweeted_to_me
5200 statuses/retweeted_by_me
5201 direct_messages/destroy
5203 account/update_delivery_device
5204 notifications/follow