3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
9 use Friendica\Content\ContactSelector;
10 use Friendica\Content\Feature;
11 use Friendica\Core\Addon;
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
14 use Friendica\Core\NotificationsManager;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Group;
20 use Friendica\Model\Mail;
21 use Friendica\Model\Photo;
22 use Friendica\Model\User;
23 use Friendica\Model\Item;
24 use Friendica\Network\FKOAuth1;
25 use Friendica\Network\HTTPException;
26 use Friendica\Network\HTTPException\BadRequestException;
27 use Friendica\Network\HTTPException\ForbiddenException;
28 use Friendica\Network\HTTPException\InternalServerErrorException;
29 use Friendica\Network\HTTPException\MethodNotAllowedException;
30 use Friendica\Network\HTTPException\NotFoundException;
31 use Friendica\Network\HTTPException\NotImplementedException;
32 use Friendica\Network\HTTPException\UnauthorizedException;
33 use Friendica\Network\HTTPException\TooManyRequestsException;
34 use Friendica\Object\Image;
35 use Friendica\Protocol\Diaspora;
36 use Friendica\Util\XML;
38 require_once 'include/bbcode.php';
39 require_once 'include/datetime.php';
40 require_once 'include/conversation.php';
41 require_once 'include/html2plain.php';
42 require_once 'mod/share.php';
43 require_once 'mod/item.php';
44 require_once 'include/security.php';
45 require_once 'include/html2bbcode.php';
46 require_once 'mod/wall_upload.php';
47 require_once 'mod/proxy.php';
48 require_once 'include/like.php';
49 require_once 'include/plaintext.php';
51 define('API_METHOD_ANY', '*');
52 define('API_METHOD_GET', 'GET');
53 define('API_METHOD_POST', 'POST,PUT');
54 define('API_METHOD_DELETE', 'POST,DELETE');
60 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
61 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
62 * into a page, and visitors will post something without noticing it).
64 * @brief Auth API user
68 if (x($_SESSION, 'allow_api')) {
76 * Clients can send 'source' parameter to be show in post metadata
77 * as "sent via <source>".
78 * Some clients doesn't send a source param, we support ones we know
81 * @brief Get source name from API client
84 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
97 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
103 * @brief Format date for API
105 * @param string $str Source date, as UTC
106 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
108 function api_date($str)
110 // Wed May 23 06:01:13 +0000 2007
111 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y");
115 * Register a function to be the endpoint for defined API path.
117 * @brief Register API endpoint
119 * @param string $path API URL path, relative to System::baseUrl()
120 * @param string $func Function name to call on path request
121 * @param bool $auth API need logged user
122 * @param string $method HTTP method reqiured to call this endpoint.
123 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
124 * Default to API_METHOD_ANY
126 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
136 // Workaround for hotot
137 $path = str_replace("api/", "api/1.1/", $path);
147 * Log in user via OAuth1 or Simple HTTP Auth.
148 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
150 * @brief Login API user
152 * @param object $a App
153 * @hook 'authenticate'
155 * 'username' => username from login form
156 * 'password' => password from login form
157 * 'authenticated' => return status,
158 * 'user_record' => return authenticated user record
160 * array $user logged user record
162 function api_login(App $a)
164 $oauth1 = new FKOAuth1();
167 list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
168 if (!is_null($token)) {
169 $oauth1->loginUser($token->uid);
170 Addon::callHooks('logged_in', $a->user);
173 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
174 var_dump($consumer, $token);
176 } catch (Exception $e) {
180 // workaround for HTTP-auth in CGI mode
181 if (x($_SERVER, 'REDIRECT_REMOTE_USER')) {
182 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)) ;
183 if (strlen($userpass)) {
184 list($name, $password) = explode(':', $userpass);
185 $_SERVER['PHP_AUTH_USER'] = $name;
186 $_SERVER['PHP_AUTH_PW'] = $password;
190 if (!x($_SERVER, 'PHP_AUTH_USER')) {
191 logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
192 header('WWW-Authenticate: Basic realm="Friendica"');
193 throw new UnauthorizedException("This API requires login");
196 $user = $_SERVER['PHP_AUTH_USER'];
197 $password = $_SERVER['PHP_AUTH_PW'];
199 // allow "user@server" login (but ignore 'server' part)
200 $at = strstr($user, "@", true);
205 // next code from mod/auth.php. needs better solution
209 'username' => trim($user),
210 'password' => trim($password),
211 'authenticated' => 0,
212 'user_record' => null,
216 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
217 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
218 * and later addons should not interfere with an earlier one that succeeded.
220 Addon::callHooks('authenticate', $addon_auth);
222 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
223 $record = $addon_auth['user_record'];
225 $user_id = User::authenticate(trim($user), trim($password));
227 $record = dba::selectFirst('user', [], ['uid' => $user_id]);
231 if (!DBM::is_result($record)) {
232 logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 //header('HTTP/1.0 401 Unauthorized');
235 //die('This api requires login');
236 throw new UnauthorizedException("This API requires login");
239 authenticate_success($record);
241 $_SESSION["allow_api"] = true;
243 Addon::callHooks('logged_in', $a->user);
247 * API endpoints can define which HTTP method to accept when called.
248 * This function check the current HTTP method agains endpoint
251 * @brief Check HTTP method of called API
253 * @param string $method Required methods, uppercase, separated by comma
256 function api_check_method($method)
258 if ($method == "*") {
261 return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
265 * Authenticate user, call registered API function, set HTTP headers
267 * @brief Main API entry point
269 * @param object $a App
270 * @return string API call result
272 function api_call(App $a)
274 global $API, $called_api;
277 if (strpos($a->query_string, ".xml") > 0) {
280 if (strpos($a->query_string, ".json") > 0) {
283 if (strpos($a->query_string, ".rss") > 0) {
286 if (strpos($a->query_string, ".atom") > 0) {
291 foreach ($API as $p => $info) {
292 if (strpos($a->query_string, $p) === 0) {
293 if (!api_check_method($info['method'])) {
294 throw new MethodNotAllowedException();
297 $called_api = explode("/", $p);
298 //unset($_SERVER['PHP_AUTH_USER']);
300 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
301 if ($info['auth'] === true && api_user() === false) {
305 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
306 logger('API parameters: ' . print_r($_REQUEST, true));
308 $stamp = microtime(true);
309 $return = call_user_func($info['func'], $type);
310 $duration = (float) (microtime(true) - $stamp);
311 logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
313 if (Config::get("system", "profiler")) {
314 $duration = microtime(true)-$a->performance["start"];
316 /// @TODO round() really everywhere?
318 parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
319 "Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
320 round($a->performance["database"] - $a->performance["database_write"], 3),
321 round($a->performance["database_write"], 3),
322 round($a->performance["network"], 2),
323 round($a->performance["file"], 2),
324 round($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
330 if (Config::get("rendertime", "callstack")) {
331 $o = "Database Read:\n";
332 foreach ($a->callstack["database"] as $func => $time) {
333 $time = round($time, 3);
335 $o .= $func . ": " . $time . "\n";
338 $o .= "\nDatabase Write:\n";
339 foreach ($a->callstack["database_write"] as $func => $time) {
340 $time = round($time, 3);
342 $o .= $func . ": " . $time . "\n";
346 $o .= "\nNetwork:\n";
347 foreach ($a->callstack["network"] as $func => $time) {
348 $time = round($time, 3);
350 $o .= $func . ": " . $time . "\n";
353 logger($o, LOGGER_DEBUG);
357 if (false === $return) {
359 * api function returned false withour throw an
360 * exception. This should not happend, throw a 500
362 throw new InternalServerErrorException();
367 header("Content-Type: text/xml");
370 header("Content-Type: application/json");
371 foreach ($return as $rr) {
372 $json = json_encode($rr);
374 if (x($_GET, 'callback')) {
375 $json = $_GET['callback'] . "(" . $json . ")";
380 header("Content-Type: application/rss+xml");
381 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
384 header("Content-Type: application/atom+xml");
385 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
392 logger('API call not implemented: ' . $a->query_string);
393 throw new NotImplementedException();
394 } catch (HTTPException $e) {
395 header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
396 return api_error($type, $e);
401 * @brief Format API error string
403 * @param string $type Return type (xml, json, rss, as)
404 * @param object $e HTTPException Error object
405 * @return string error message formatted as $type
407 function api_error($type, $e)
411 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
412 /// @TODO: https://dev.twitter.com/overview/api/response-codes
414 $error = ["error" => $error,
415 "code" => $e->httpcode . " " . $e->httpdesc,
416 "request" => $a->query_string];
418 $return = api_format_data('status', $type, ['status' => $error]);
422 header("Content-Type: text/xml");
425 header("Content-Type: application/json");
426 $return = json_encode($return);
429 header("Content-Type: application/rss+xml");
432 header("Content-Type: application/atom+xml");
440 * @brief Set values for RSS template
443 * @param array $arr Array to be passed to template
444 * @param array $user_info User info
446 * @todo find proper type-hints
448 function api_rss_extra(App $a, $arr, $user_info)
450 if (is_null($user_info)) {
451 $user_info = api_get_user($a);
454 $arr['$user'] = $user_info;
456 'alternate' => $user_info['url'],
457 'self' => System::baseUrl() . "/" . $a->query_string,
458 'base' => System::baseUrl(),
459 'updated' => api_date(null),
460 'atom_updated' => datetime_convert('UTC', 'UTC', 'now', ATOM_TIME),
461 'language' => $user_info['language'],
462 'logo' => System::baseUrl() . "/images/friendica-32.png",
470 * @brief Unique contact to contact url.
472 * @param int $id Contact id
473 * @return bool|string
474 * Contact url or False if contact id is unknown
476 function api_unique_id_to_nurl($id)
478 $r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
480 if (DBM::is_result($r)) {
488 * @brief Get user info array.
490 * @param object $a App
491 * @param int|string $contact_id Contact ID or URL
493 function api_get_user(App $a, $contact_id = null)
501 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
503 // Searching for contact URL
504 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
505 $user = dbesc(normalise_link($contact_id));
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 // Searching for contact id with uid = 0
514 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
515 $user = dbesc(api_unique_id_to_nurl($contact_id));
518 throw new BadRequestException("User not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && x($_GET, 'user_id')) {
529 $user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
532 throw new BadRequestException("User not found.");
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 if (is_null($user) && x($_GET, 'screen_name')) {
542 $user = dbesc($_GET['screen_name']);
543 $extra_query = "AND `contact`.`nick` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 if (is_null($user) && x($_GET, 'profileurl')) {
550 $user = dbesc(normalise_link($_GET['profileurl']));
551 $extra_query = "AND `contact`.`nurl` = '%s' ";
552 if (api_user() !== false) {
553 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
557 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
558 $argid = count($called_api);
559 list($user, $null) = explode(".", $a->argv[$argid]);
560 if (is_numeric($user)) {
561 $user = dbesc(api_unique_id_to_nurl($user));
568 $extra_query = "AND `contact`.`nurl` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
573 $user = dbesc($user);
574 $extra_query = "AND `contact`.`nick` = '%s' ";
575 if (api_user() !== false) {
576 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
581 logger("api_get_user: user ".$user, LOGGER_DEBUG);
584 if (api_user() === false) {
588 $user = $_SESSION['uid'];
589 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
593 logger('api_user: ' . $extra_query . ', user: ' . $user);
597 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
603 // Selecting the id by priority, friendica first
604 api_best_nickname($uinfo);
606 // if the contact wasn't found, fetch it from the contacts with uid = 0
607 if (!DBM::is_result($uinfo)) {
611 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
614 if (DBM::is_result($r)) {
615 $network_name = ContactSelector::networkToName($r[0]['network'], $r[0]['url']);
617 // If no nick where given, extract it from the address
618 if (($r[0]['nick'] == "") || ($r[0]['name'] == $r[0]['nick'])) {
619 $r[0]['nick'] = api_get_nick($r[0]["url"]);
624 'id_str' => (string) $r[0]["id"],
625 'name' => $r[0]["name"],
626 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
627 'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
628 'description' => $r[0]["about"],
629 'profile_image_url' => $r[0]["micro"],
630 'profile_image_url_https' => $r[0]["micro"],
631 'url' => $r[0]["url"],
632 'protected' => false,
633 'followers_count' => 0,
634 'friends_count' => 0,
636 'created_at' => api_date($r[0]["created"]),
637 'favourites_count' => 0,
639 'time_zone' => 'UTC',
640 'geo_enabled' => false,
642 'statuses_count' => 0,
644 'contributors_enabled' => false,
645 'is_translator' => false,
646 'is_translation_enabled' => false,
647 'following' => false,
648 'follow_request_sent' => false,
649 'statusnet_blocking' => false,
650 'notifications' => false,
651 'statusnet_profile_url' => $r[0]["url"],
653 'cid' => Contact::getIdForURL($r[0]["url"], api_user(), true),
655 'network' => $r[0]["network"],
660 throw new BadRequestException("User not found.");
664 if ($uinfo[0]['self']) {
665 if ($uinfo[0]['network'] == "") {
666 $uinfo[0]['network'] = NETWORK_DFRN;
670 "SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
674 "SELECT * FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
678 /// @TODO old-lost code? (twice)
679 // Counting is deactivated by now, due to performance issues
680 // count public wall messages
681 //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
682 // intval($uinfo[0]['uid'])
684 //$countitms = $r[0]['count'];
687 // Counting is deactivated by now, due to performance issues
688 //$r = q("SELECT count(*) as `count` FROM `item`
689 // WHERE `contact-id` = %d",
690 // intval($uinfo[0]['id'])
692 //$countitms = $r[0]['count'];
696 /// @TODO old-lost code? (twice)
698 // Counting is deactivated by now, due to performance issues
700 $r = q("SELECT count(*) as `count` FROM `contact`
701 WHERE `uid` = %d AND `rel` IN ( %d, %d )
702 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
703 intval($uinfo[0]['uid']),
704 intval(CONTACT_IS_SHARING),
705 intval(CONTACT_IS_FRIEND)
707 $countfriends = $r[0]['count'];
709 $r = q("SELECT count(*) as `count` FROM `contact`
710 WHERE `uid` = %d AND `rel` IN ( %d, %d )
711 AND `self`=0 AND NOT `blocked` AND NOT `pending` AND `hidden`=0",
712 intval($uinfo[0]['uid']),
713 intval(CONTACT_IS_FOLLOWER),
714 intval(CONTACT_IS_FRIEND)
716 $countfollowers = $r[0]['count'];
718 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
719 intval($uinfo[0]['uid'])
721 $starred = $r[0]['count'];
724 if (! $uinfo[0]['self']) {
734 // Add a nick if it isn't present there
735 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
736 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
739 $network_name = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
741 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
743 if (!empty($profile[0]['about'])) {
744 $description = $profile[0]['about'];
746 $description = $uinfo[0]["about"];
749 if (!empty($usr[0]['default-location'])) {
750 $location = $usr[0]['default-location'];
751 } elseif (!empty($uinfo[0]["location"])) {
752 $location = $uinfo[0]["location"];
754 $location = $network_name;
758 'id' => intval($pcontact_id),
759 'id_str' => (string) intval($pcontact_id),
760 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
761 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
762 'location' => $location,
763 'description' => $description,
764 'profile_image_url' => $uinfo[0]['micro'],
765 'profile_image_url_https' => $uinfo[0]['micro'],
766 'url' => $uinfo[0]['url'],
767 'protected' => false,
768 'followers_count' => intval($countfollowers),
769 'friends_count' => intval($countfriends),
771 'created_at' => api_date($uinfo[0]['created']),
772 'favourites_count' => intval($starred),
774 'time_zone' => 'UTC',
775 'geo_enabled' => false,
777 'statuses_count' => intval($countitms),
779 'contributors_enabled' => false,
780 'is_translator' => false,
781 'is_translation_enabled' => false,
782 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) || ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
783 'follow_request_sent' => false,
784 'statusnet_blocking' => false,
785 'notifications' => false,
787 //'statusnet_profile_url' => System::baseUrl()."/contacts/".$uinfo[0]['cid'],
788 'statusnet_profile_url' => $uinfo[0]['url'],
789 'uid' => intval($uinfo[0]['uid']),
790 'cid' => intval($uinfo[0]['cid']),
791 'self' => $uinfo[0]['self'],
792 'network' => $uinfo[0]['network'],
795 // If this is a local user and it uses Frio, we can get its color preferences.
797 $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
798 if ($theme_info['theme'] === 'frio') {
799 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
800 if ($schema && ($schema != '---')) {
801 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
802 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
803 require_once $schemefile;
806 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
807 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
808 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
814 $link_color = "#6fdbe8";
817 $bgcolor = "#ededed";
820 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
821 $ret['profile_link_color'] = str_replace('#', '', $link_color);
822 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
830 * @brief return api-formatted array for item's author and owner
832 * @param object $a App
833 * @param array $item item from db
834 * @return array(array:author, array:owner)
836 function api_item_get_user(App $a, $item)
838 $status_user = api_get_user($a, $item["author-link"]);
840 $status_user["protected"] = (($item["allow_cid"] != "") ||
841 ($item["allow_gid"] != "") ||
842 ($item["deny_cid"] != "") ||
843 ($item["deny_gid"] != "") ||
846 if ($item['thr-parent'] == $item['uri']) {
847 $owner_user = api_get_user($a, $item["owner-link"]);
849 $owner_user = $status_user;
852 return ([$status_user, $owner_user]);
856 * @brief walks recursively through an array with the possibility to change value and key
858 * @param array $array The array to walk through
859 * @param string $callback The callback function
861 * @return array the transformed array
863 function api_walk_recursive(array &$array, callable $callback)
867 foreach ($array as $k => $v) {
869 if ($callback($v, $k)) {
870 $new_array[$k] = api_walk_recursive($v, $callback);
873 if ($callback($v, $k)) {
884 * @brief Callback function to transform the array in an array that can be transformed in a XML file
886 * @param mixed $item Array item value
887 * @param string $key Array key
889 * @return boolean Should the array item be deleted?
891 function api_reformat_xml(&$item, &$key)
893 if (is_bool($item)) {
894 $item = ($item ? "true" : "false");
897 if (substr($key, 0, 10) == "statusnet_") {
898 $key = "statusnet:".substr($key, 10);
899 } elseif (substr($key, 0, 10) == "friendica_") {
900 $key = "friendica:".substr($key, 10);
902 /// @TODO old-lost code?
904 // $key = "default:".$key;
910 * @brief Creates the XML from a JSON style array
912 * @param array $data JSON style array
913 * @param string $root_element Name of the root element
915 * @return string The XML data
917 function api_create_xml($data, $root_element)
919 $childname = key($data);
920 $data2 = array_pop($data);
923 $namespaces = ["" => "http://api.twitter.com",
924 "statusnet" => "http://status.net/schema/api/1/",
925 "friendica" => "http://friendi.ca/schema/api/1/",
926 "georss" => "http://www.georss.org/georss"];
928 /// @todo Auto detection of needed namespaces
929 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
933 if (is_array($data2)) {
934 api_walk_recursive($data2, "api_reformat_xml");
941 foreach ($data2 as $item) {
942 $data4[$i++.":".$childname] = $item;
948 $data3 = [$root_element => $data2];
950 $ret = XML::fromArray($data3, $xml, false, $namespaces);
955 * @brief Formats the data according to the data type
957 * @param string $root_element Name of the root element
958 * @param string $type Return type (atom, rss, xml, json)
959 * @param array $data JSON style array
961 * @return (string|object|array) XML data or JSON data
963 function api_format_data($root_element, $type, $data)
969 $ret = api_create_xml($data, $root_element);
984 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
985 * returns a 401 status code and an error message if not.
986 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
988 * @param string $type Return type (atom, rss, xml, json)
990 function api_account_verify_credentials($type)
995 if (api_user() === false) {
996 throw new ForbiddenException();
999 unset($_REQUEST["user_id"]);
1000 unset($_GET["user_id"]);
1002 unset($_REQUEST["screen_name"]);
1003 unset($_GET["screen_name"]);
1005 $skip_status = (x($_REQUEST, 'skip_status')?$_REQUEST['skip_status'] : false);
1007 $user_info = api_get_user($a);
1009 // "verified" isn't used here in the standard
1010 unset($user_info["verified"]);
1012 // - Adding last status
1013 if (!$skip_status) {
1014 $user_info["status"] = api_status_show("raw");
1015 if (!count($user_info["status"])) {
1016 unset($user_info["status"]);
1018 unset($user_info["status"]["user"]);
1022 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1023 unset($user_info["uid"]);
1024 unset($user_info["self"]);
1026 return api_format_data("user", $type, ['user' => $user_info]);
1029 /// @TODO move to top of file or somewhere better
1030 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1033 * Get data from $_POST or $_GET
1037 function requestdata($k)
1039 if (x($_POST, $k)) {
1049 * Waitman Gobble Mod
1051 * @param string $type Return type (atom, rss, xml, json)
1053 * @return array|string
1055 function api_statuses_mediap($type)
1059 if (api_user() === false) {
1060 logger('api_statuses_update: no user');
1061 throw new ForbiddenException();
1063 $user_info = api_get_user($a);
1065 $_REQUEST['type'] = 'wall';
1066 $_REQUEST['profile_uid'] = api_user();
1067 $_REQUEST['api_source'] = true;
1068 $txt = requestdata('status');
1069 /// @TODO old-lost code?
1070 //$txt = urldecode(requestdata('status'));
1072 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1073 $txt = html2bb_video($txt);
1074 $config = HTMLPurifier_Config::createDefault();
1075 $config->set('Cache.DefinitionImpl', null);
1076 $purifier = new HTMLPurifier($config);
1077 $txt = $purifier->purify($txt);
1079 $txt = html2bbcode($txt);
1081 $a->argv[1]=$user_info['screen_name']; //should be set to username?
1083 // tell wall_upload function to return img info instead of echo
1084 $_REQUEST['hush'] = 'yeah';
1085 $bebop = wall_upload_post($a);
1087 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1088 $_REQUEST['body'] = $txt . "\n\n" . $bebop;
1091 // this should output the last post (the one we just posted).
1092 return api_status_show($type);
1095 /// @TODO move this to top of file or somewhere better!
1096 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1099 * Updates the user’s current status.
1101 * @param string $type Return type (atom, rss, xml, json)
1103 * @return array|string
1104 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1106 function api_statuses_update($type)
1111 if (api_user() === false) {
1112 logger('api_statuses_update: no user');
1113 throw new ForbiddenException();
1118 // convert $_POST array items to the form we use for web posts.
1119 if (requestdata('htmlstatus')) {
1120 $txt = requestdata('htmlstatus');
1121 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1122 $txt = html2bb_video($txt);
1124 $config = HTMLPurifier_Config::createDefault();
1125 $config->set('Cache.DefinitionImpl', null);
1127 $purifier = new HTMLPurifier($config);
1128 $txt = $purifier->purify($txt);
1130 $_REQUEST['body'] = html2bbcode($txt);
1133 $_REQUEST['body'] = requestdata('status');
1136 $_REQUEST['title'] = requestdata('title');
1138 $parent = requestdata('in_reply_to_status_id');
1140 // Twidere sends "-1" if it is no reply ...
1141 if ($parent == -1) {
1145 if (ctype_digit($parent)) {
1146 $_REQUEST['parent'] = $parent;
1148 $_REQUEST['parent_uri'] = $parent;
1151 if (requestdata('lat') && requestdata('long')) {
1152 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1154 $_REQUEST['profile_uid'] = api_user();
1157 $_REQUEST['type'] = 'net-comment';
1159 // Check for throttling (maximum posts per day, week and month)
1160 $throttle_day = Config::get('system', 'throttle_limit_day');
1161 if ($throttle_day > 0) {
1162 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1165 "SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1166 AND `created` > '%s' AND `id` = `parent`",
1171 if (DBM::is_result($r)) {
1172 $posts_day = $r[0]["posts_day"];
1177 if ($posts_day > $throttle_day) {
1178 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1179 // die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1180 throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1184 $throttle_week = Config::get('system', 'throttle_limit_week');
1185 if ($throttle_week > 0) {
1186 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1189 "SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1190 AND `created` > '%s' AND `id` = `parent`",
1195 if (DBM::is_result($r)) {
1196 $posts_week = $r[0]["posts_week"];
1201 if ($posts_week > $throttle_week) {
1202 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1203 // die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1204 throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1208 $throttle_month = Config::get('system', 'throttle_limit_month');
1209 if ($throttle_month > 0) {
1210 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1213 "SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1214 AND `created` > '%s' AND `id` = `parent`",
1219 if (DBM::is_result($r)) {
1220 $posts_month = $r[0]["posts_month"];
1225 if ($posts_month > $throttle_month) {
1226 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1227 // die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1228 throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1232 $_REQUEST['type'] = 'wall';
1235 if (x($_FILES, 'media')) {
1236 // upload the image if we have one
1237 $_REQUEST['hush'] = 'yeah'; //tell wall_upload function to return img info instead of echo
1238 $media = wall_upload_post($a);
1239 if (strlen($media) > 0) {
1240 $_REQUEST['body'] .= "\n\n" . $media;
1244 // To-Do: Multiple IDs
1245 if (requestdata('media_ids')) {
1247 "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",
1248 intval(requestdata('media_ids')),
1251 if (DBM::is_result($r)) {
1252 $phototypes = Image::supportedTypes();
1253 $ext = $phototypes[$r[0]['type']];
1254 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1255 $_REQUEST['body'] .= '[img]' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . '[/img][/url]';
1259 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1261 $_REQUEST['api_source'] = true;
1263 if (!x($_REQUEST, "source")) {
1264 $_REQUEST["source"] = api_source();
1267 // call out normal post function
1270 // this should output the last post (the one we just posted).
1271 return api_status_show($type);
1274 /// @TODO move to top of file or somewhere better
1275 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1276 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1279 * Uploads an image to Friendica.
1282 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1284 function api_media_upload()
1288 if (api_user() === false) {
1290 throw new ForbiddenException();
1295 if (!x($_FILES, 'media')) {
1297 throw new BadRequestException("No media.");
1300 $media = wall_upload_post($a, false);
1303 throw new InternalServerErrorException();
1307 $returndata["media_id"] = $media["id"];
1308 $returndata["media_id_string"] = (string)$media["id"];
1309 $returndata["size"] = $media["size"];
1310 $returndata["image"] = ["w" => $media["width"],
1311 "h" => $media["height"],
1312 "image_type" => $media["type"]];
1314 logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG);
1316 return ["media" => $returndata];
1319 /// @TODO move to top of file or somewhere better
1320 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1324 * @param string $type Return type (atom, rss, xml, json)
1326 * @return array|string
1328 function api_status_show($type)
1332 $user_info = api_get_user($a);
1334 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1336 if ($type == "raw") {
1337 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1342 // get last public wall message
1346 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1347 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1348 AND `item`.`type` != 'activity' $privacy_sql
1349 ORDER BY `item`.`id` DESC
1351 intval($user_info['cid']),
1353 dbesc($user_info['url']),
1354 dbesc(normalise_link($user_info['url'])),
1355 dbesc($user_info['url']),
1356 dbesc(normalise_link($user_info['url']))
1359 if (DBM::is_result($lastwall)) {
1360 $lastwall = $lastwall[0];
1362 $in_reply_to = api_in_reply_to($lastwall);
1364 $converted = api_convert_item($lastwall);
1366 if ($type == "xml") {
1367 $geo = "georss:point";
1373 'created_at' => api_date($lastwall['created']),
1374 'id' => intval($lastwall['id']),
1375 'id_str' => (string) $lastwall['id'],
1376 'text' => $converted["text"],
1377 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1378 'truncated' => false,
1379 'in_reply_to_status_id' => $in_reply_to['status_id'],
1380 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1381 'in_reply_to_user_id' => $in_reply_to['user_id'],
1382 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1383 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1384 'user' => $user_info,
1386 'coordinates' => "",
1388 'contributors' => "",
1389 'is_quote_status' => false,
1390 'retweet_count' => 0,
1391 'favorite_count' => 0,
1392 'favorited' => $lastwall['starred'] ? true : false,
1393 'retweeted' => false,
1394 'possibly_sensitive' => false,
1396 'statusnet_html' => $converted["html"],
1397 'statusnet_conversation_id' => $lastwall['parent'],
1398 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1401 if (count($converted["attachments"]) > 0) {
1402 $status_info["attachments"] = $converted["attachments"];
1405 if (count($converted["entities"]) > 0) {
1406 $status_info["entities"] = $converted["entities"];
1409 if (($lastwall['item_network'] != "") && ($status["source"] == 'web')) {
1410 $status_info["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1411 } elseif (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $status_info["source"])) {
1412 $status_info["source"] = trim($status_info["source"].' ('.ContactSelector::networkToName($lastwall['item_network'], $user_info['url']).')');
1415 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1416 unset($status_info["user"]["uid"]);
1417 unset($status_info["user"]["self"]);
1420 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1422 if ($type == "raw") {
1423 return $status_info;
1426 return api_format_data("statuses", $type, ['status' => $status_info]);
1430 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1431 * The author's most recent status will be returned inline.
1433 * @param string $type Return type (atom, rss, xml, json)
1434 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1436 function api_users_show($type)
1440 $user_info = api_get_user($a);
1444 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1445 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1446 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1447 AND `type`!='activity'
1448 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1452 dbesc(ACTIVITY_POST),
1453 intval($user_info['cid']),
1454 dbesc($user_info['url']),
1455 dbesc(normalise_link($user_info['url'])),
1456 dbesc($user_info['url']),
1457 dbesc(normalise_link($user_info['url']))
1460 if (DBM::is_result($lastwall)) {
1461 $lastwall = $lastwall[0];
1463 $in_reply_to = api_in_reply_to($lastwall);
1465 $converted = api_convert_item($lastwall);
1467 if ($type == "xml") {
1468 $geo = "georss:point";
1473 $user_info['status'] = [
1474 'text' => $converted["text"],
1475 'truncated' => false,
1476 'created_at' => api_date($lastwall['created']),
1477 'in_reply_to_status_id' => $in_reply_to['status_id'],
1478 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1479 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1480 'id' => intval($lastwall['contact-id']),
1481 'id_str' => (string) $lastwall['contact-id'],
1482 'in_reply_to_user_id' => $in_reply_to['user_id'],
1483 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1484 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1486 'favorited' => $lastwall['starred'] ? true : false,
1487 'statusnet_html' => $converted["html"],
1488 'statusnet_conversation_id' => $lastwall['parent'],
1489 'external_url' => System::baseUrl() . "/display/" . $lastwall['guid'],
1492 if (count($converted["attachments"]) > 0) {
1493 $user_info["status"]["attachments"] = $converted["attachments"];
1496 if (count($converted["entities"]) > 0) {
1497 $user_info["status"]["entities"] = $converted["entities"];
1500 if (($lastwall['item_network'] != "") && ($user_info["status"]["source"] == 'web')) {
1501 $user_info["status"]["source"] = ContactSelector::networkToName($lastwall['item_network'], $user_info['url']);
1504 if (($lastwall['item_network'] != "") && (ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"])) {
1505 $user_info["status"]["source"] = trim($user_info["status"]["source"] . ' (' . ContactSelector::networkToName($lastwall['item_network'], $user_info['url']) . ')');
1509 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1510 unset($user_info["uid"]);
1511 unset($user_info["self"]);
1513 return api_format_data("user", $type, ['user' => $user_info]);
1516 /// @TODO move to top of file or somewhere better
1517 api_register_func('api/users/show', 'api_users_show');
1518 api_register_func('api/externalprofile/show', 'api_users_show');
1521 * Search a public user account.
1523 * @param string $type Return type (atom, rss, xml, json)
1525 * @return array|string
1526 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1528 function api_users_search($type)
1534 if (x($_GET, 'q')) {
1535 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1537 if (!DBM::is_result($r)) {
1538 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1541 if (DBM::is_result($r)) {
1543 foreach ($r as $user) {
1544 $user_info = api_get_user($a, $user["id"]);
1546 if ($type == "xml") {
1547 $userlist[$k++.":user"] = $user_info;
1549 $userlist[] = $user_info;
1552 $userlist = ["users" => $userlist];
1554 throw new BadRequestException("User not found.");
1557 throw new BadRequestException("User not found.");
1560 return api_format_data("users", $type, $userlist);
1563 /// @TODO move to top of file or somewhere better
1564 api_register_func('api/users/search', 'api_users_search');
1567 * Return user objects
1569 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1571 * @param string $type Return format: json or xml
1573 * @return array|string
1574 * @throws NotFoundException if the results are empty.
1576 function api_users_lookup($type)
1580 if (x($_REQUEST['user_id'])) {
1581 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1583 $users[] = api_get_user(get_app(), $id);
1588 if (empty($users)) {
1589 throw new NotFoundException;
1592 return api_format_data("users", $type, ['users' => $users]);
1595 /// @TODO move to top of file or somewhere better
1596 api_register_func('api/users/lookup', 'api_users_lookup', true);
1599 * Returns statuses that match a specified query.
1601 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1603 * @param string $type Return format: json, xml, atom, rss
1605 * @return array|string
1606 * @throws BadRequestException if the "q" parameter is missing.
1608 function api_search($type)
1612 if (!x($_REQUEST, 'q')) {
1613 throw new BadRequestException("q parameter is required.");
1616 if (x($_REQUEST, 'rpp')) {
1617 $count = $_REQUEST['rpp'];
1618 } elseif (x($_REQUEST, 'count')) {
1619 $count = $_REQUEST['count'];
1624 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1625 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1626 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1628 $start = $page * $count;
1631 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1635 "SELECT ".item_fieldlists()."
1636 FROM `item` ".item_joins()."
1637 WHERE ".item_condition()." AND (`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))
1638 AND `item`.`body` LIKE CONCAT('%',?,'%')
1641 ORDER BY `item`.`id` DESC LIMIT ".intval($start)." ,".intval($count)." ",
1647 $data['status'] = api_format_items(dba::inArray($r), api_get_user(get_app()));
1649 return api_format_data("statuses", $type, $data);
1652 /// @TODO move to top of file or somewhere better
1653 api_register_func('api/search/tweets', 'api_search', true);
1654 api_register_func('api/search', 'api_search', true);
1657 * Returns the most recent statuses posted by the user and the users they follow.
1659 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1661 * @param string $type Return type (atom, rss, xml, json)
1663 * @todo Optional parameters
1664 * @todo Add reply info
1666 function api_statuses_home_timeline($type)
1670 if (api_user() === false) {
1671 throw new ForbiddenException();
1674 unset($_REQUEST["user_id"]);
1675 unset($_GET["user_id"]);
1677 unset($_REQUEST["screen_name"]);
1678 unset($_GET["screen_name"]);
1680 $user_info = api_get_user($a);
1681 // get last newtork messages
1684 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1685 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
1689 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1690 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1691 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1692 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1693 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1695 $start = $page * $count;
1699 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
1701 if ($exclude_replies > 0) {
1702 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1704 if ($conversation_id > 0) {
1705 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1709 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1710 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1711 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1712 `contact`.`id` AS `cid`
1714 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1715 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1716 WHERE `item`.`uid` = %d AND `verb` = '%s'
1717 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1720 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1722 dbesc(ACTIVITY_POST),
1728 $ret = api_format_items($r, $user_info, false, $type);
1730 // Set all posts from the query above to seen
1732 foreach ($r as $item) {
1733 $idarray[] = intval($item["id"]);
1736 $idlist = implode(",", $idarray);
1738 if ($idlist != "") {
1739 $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1742 q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1746 $data = ['status' => $ret];
1750 $data = api_rss_extra($a, $data, $user_info);
1754 return api_format_data("statuses", $type, $data);
1757 /// @TODO move to top of file or somewhere better
1758 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1759 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1762 * Returns the most recent statuses from public users.
1764 * @param string $type Return type (atom, rss, xml, json)
1766 * @return array|string
1768 function api_statuses_public_timeline($type)
1772 if (api_user() === false) {
1773 throw new ForbiddenException();
1776 $user_info = api_get_user($a);
1777 // get last newtork messages
1780 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
1781 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
1785 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
1786 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
1787 //$since_id = 0;//$since_id = (x($_REQUEST, 'since_id')?$_REQUEST['since_id'] : 0);
1788 $exclude_replies = (x($_REQUEST, 'exclude_replies') ? 1 : 0);
1789 $conversation_id = (x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0);
1791 $start = $page * $count;
1793 if ($exclude_replies && !$conversation_id) {
1795 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1799 "SELECT " . item_fieldlists() . "
1801 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1802 " . item_joins() . "
1803 STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid`
1804 AND NOT `user`.`hidewall`
1806 AND NOT `thread`.`private`
1808 AND `thread`.`visible`
1809 AND NOT `thread`.`deleted`
1810 AND NOT `thread`.`moderated`
1811 AND `thread`.`iid` > ?
1813 ORDER BY `thread`.`iid` DESC
1814 LIMIT " . intval($start) . ", " . intval($count),
1819 $r = dba::inArray($r);
1822 $sql_extra = 'AND `item`.`id` <= ' . intval($max_id);
1824 if ($conversation_id > 0) {
1825 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
1829 "SELECT " . item_fieldlists() . "
1831 " . item_joins() . "
1832 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1833 AND NOT `user`.`hidewall`
1835 AND NOT `item`.`private`
1837 AND `item`.`visible`
1838 AND NOT `item`.`deleted`
1839 AND NOT `item`.`moderated`
1842 ORDER BY `item`.`id` DESC
1843 LIMIT " . intval($start) . ", " . intval($count),
1848 $r = dba::inArray($r);
1851 $ret = api_format_items($r, $user_info, false, $type);
1853 $data = ['status' => $ret];
1857 $data = api_rss_extra($a, $data, $user_info);
1861 return api_format_data("statuses", $type, $data);
1864 /// @TODO move to top of file or somewhere better
1865 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1868 * Returns the most recent statuses posted by users this node knows about.
1870 * @brief Returns the list of public federated posts this node knows about
1872 * @param string $type Return format: json, xml, atom, rss
1873 * @return array|string
1874 * @throws ForbiddenException
1876 function api_statuses_networkpublic_timeline($type)
1880 if (api_user() === false) {
1881 throw new ForbiddenException();
1884 $user_info = api_get_user($a);
1886 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
1887 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
1890 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
1891 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
1895 $start = ($page - 1) * $count;
1899 $sql_extra = 'AND `thread`.`iid` <= ' . intval($max_id);
1903 "SELECT " . item_fieldlists() . "
1905 STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid`
1906 " . item_joins() . "
1907 WHERE `thread`.`uid` = 0
1909 AND NOT `thread`.`private`
1910 AND `thread`.`visible`
1911 AND NOT `thread`.`deleted`
1912 AND NOT `thread`.`moderated`
1913 AND `thread`.`iid` > ?
1915 ORDER BY `thread`.`iid` DESC
1916 LIMIT " . intval($start) . ", " . intval($count),
1921 $r = dba::inArray($r);
1923 $ret = api_format_items($r, $user_info, false, $type);
1925 $data = ['status' => $ret];
1929 $data = api_rss_extra($a, $data, $user_info);
1933 return api_format_data("statuses", $type, $data);
1936 /// @TODO move to top of file or somewhere better
1937 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1940 * Returns a single status.
1942 * @param string $type Return type (atom, rss, xml, json)
1944 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1946 function api_statuses_show($type)
1950 if (api_user() === false) {
1951 throw new ForbiddenException();
1954 $user_info = api_get_user($a);
1957 $id = intval($a->argv[3]);
1960 $id = intval($_REQUEST["id"]);
1965 $id = intval($a->argv[4]);
1968 logger('API: api_statuses_show: ' . $id);
1970 $conversation = (x($_REQUEST, 'conversation') ? 1 : 0);
1973 if ($conversation) {
1974 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1976 $sql_extra .= " AND `item`.`id` = %d";
1980 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1981 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1982 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1983 `contact`.`id` AS `cid`
1985 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1986 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1987 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1988 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1991 dbesc(ACTIVITY_POST),
1995 /// @TODO How about copying this to above methods which don't check $r ?
1996 if (!DBM::is_result($r)) {
1997 throw new BadRequestException("There is no status with this id.");
2000 $ret = api_format_items($r, $user_info, false, $type);
2002 if ($conversation) {
2003 $data = ['status' => $ret];
2004 return api_format_data("statuses", $type, $data);
2006 $data = ['status' => $ret[0]];
2007 return api_format_data("status", $type, $data);
2011 /// @TODO move to top of file or somewhere better
2012 api_register_func('api/statuses/show', 'api_statuses_show', true);
2016 * @param string $type Return type (atom, rss, xml, json)
2018 * @todo nothing to say?
2020 function api_conversation_show($type)
2024 if (api_user() === false) {
2025 throw new ForbiddenException();
2028 $user_info = api_get_user($a);
2031 $id = intval($a->argv[3]);
2032 $count = (x($_REQUEST, 'count') ? $_REQUEST['count'] : 20);
2033 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0);
2037 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2038 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2040 $start = $page*$count;
2043 $id = intval($_REQUEST["id"]);
2048 $id = intval($a->argv[4]);
2051 logger('API: api_conversation_show: '.$id);
2053 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
2054 if (DBM::is_result($r)) {
2055 $id = $r[0]["parent"];
2061 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2064 // Not sure why this query was so complicated. We should keep it here for a while,
2065 // just to make sure that we really don't need it.
2066 // FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
2067 // ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
2070 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2071 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2072 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2073 `contact`.`id` AS `cid`
2075 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2076 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2077 WHERE `item`.`parent` = %d AND `item`.`visible`
2078 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2079 AND `item`.`uid` = %d AND `item`.`verb` = '%s'
2080 AND `item`.`id`>%d $sql_extra
2081 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
2084 dbesc(ACTIVITY_POST),
2090 if (!DBM::is_result($r)) {
2091 throw new BadRequestException("There is no status with this id.");
2094 $ret = api_format_items($r, $user_info, false, $type);
2096 $data = ['status' => $ret];
2097 return api_format_data("statuses", $type, $data);
2100 /// @TODO move to top of file or somewhere better
2101 api_register_func('api/conversation/show', 'api_conversation_show', true);
2102 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2107 * @param string $type Return type (atom, rss, xml, json)
2109 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2111 function api_statuses_repeat($type)
2117 if (api_user() === false) {
2118 throw new ForbiddenException();
2124 $id = intval($a->argv[3]);
2127 $id = intval($_REQUEST["id"]);
2132 $id = intval($a->argv[4]);
2135 logger('API: api_statuses_repeat: '.$id);
2138 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
2139 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
2140 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2141 `contact`.`id` AS `cid`
2143 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2144 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2145 WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2146 AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
2147 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2149 AND `item`.`id`=%d",
2153 /// @TODO other style than above functions!
2154 if (DBM::is_result($r) && $r[0]['body'] != "") {
2155 if (strpos($r[0]['body'], "[/share]") !== false) {
2156 $pos = strpos($r[0]['body'], "[share");
2157 $post = substr($r[0]['body'], $pos);
2159 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
2161 $post .= $r[0]['body'];
2162 $post .= "[/share]";
2164 $_REQUEST['body'] = $post;
2165 $_REQUEST['profile_uid'] = api_user();
2166 $_REQUEST['type'] = 'wall';
2167 $_REQUEST['api_source'] = true;
2169 if (!x($_REQUEST, "source")) {
2170 $_REQUEST["source"] = api_source();
2175 throw new ForbiddenException();
2178 // this should output the last post (the one we just posted).
2180 return api_status_show($type);
2183 /// @TODO move to top of file or somewhere better
2184 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2187 * Destroys a specific status.
2189 * @param string $type Return type (atom, rss, xml, json)
2191 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2193 function api_statuses_destroy($type)
2197 if (api_user() === false) {
2198 throw new ForbiddenException();
2204 $id = intval($a->argv[3]);
2207 $id = intval($_REQUEST["id"]);
2212 $id = intval($a->argv[4]);
2215 logger('API: api_statuses_destroy: '.$id);
2217 $ret = api_statuses_show($type);
2224 /// @TODO move to top of file or somewhere better
2225 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2228 * Returns the most recent mentions.
2230 * @param string $type Return type (atom, rss, xml, json)
2232 * @see http://developer.twitter.com/doc/get/statuses/mentions
2234 function api_statuses_mentions($type)
2238 if (api_user() === false) {
2239 throw new ForbiddenException();
2242 unset($_REQUEST["user_id"]);
2243 unset($_GET["user_id"]);
2245 unset($_REQUEST["screen_name"]);
2246 unset($_GET["screen_name"]);
2248 $user_info = api_get_user($a);
2249 // get last newtork messages
2253 $since_id = defaults($_REQUEST, 'since_id', 0);
2254 $max_id = defaults($_REQUEST, 'max_id' , 0);
2255 $count = defaults($_REQUEST, 'count' , 20);
2256 $page = defaults($_REQUEST, 'page' , 1);
2261 $start = ($page - 1) * $count;
2263 // Ugly code - should be changed
2264 $myurl = System::baseUrl() . '/profile/'. $a->user['nickname'];
2265 $myurl = substr($myurl, strpos($myurl, '://') + 3);
2266 $myurl = str_replace('www.', '', $myurl);
2269 $sql_extra = ' AND `item`.`id` <= ' . intval($max_id);
2273 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2274 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2275 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2276 `contact`.`id` AS `cid`
2277 FROM `item` FORCE INDEX (`uid_id`)
2278 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2279 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2280 WHERE `item`.`uid` = %d AND `verb` = '%s'
2281 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
2282 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2283 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
2286 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2288 dbesc(ACTIVITY_POST),
2289 dbesc(protect_sprintf($myurl)),
2290 dbesc(protect_sprintf($myurl)),
2297 $ret = api_format_items($r, $user_info, false, $type);
2299 $data = ['status' => $ret];
2303 $data = api_rss_extra($a, $data, $user_info);
2307 return api_format_data("statuses", $type, $data);
2310 /// @TODO move to top of file or somewhere better
2311 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2312 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2315 * Returns the most recent statuses posted by the user.
2317 * @brief Returns a user's public timeline
2319 * @param string $type Either "json" or "xml"
2320 * @return string|array
2321 * @throws ForbiddenException
2322 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2324 function api_statuses_user_timeline($type)
2328 if (api_user() === false) {
2329 throw new ForbiddenException();
2332 $user_info = api_get_user($a);
2335 "api_statuses_user_timeline: api_user: ". api_user() .
2336 "\nuser_info: ".print_r($user_info, true) .
2337 "\n_REQUEST: ".print_r($_REQUEST, true),
2341 $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
2342 $max_id = x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0;
2343 $exclude_replies = x($_REQUEST, 'exclude_replies') ? 1 : 0;
2344 $conversation_id = x($_REQUEST, 'conversation_id') ? $_REQUEST['conversation_id'] : 0;
2347 $count = x($_REQUEST, 'count') ? $_REQUEST['count'] : 20;
2348 $page = x($_REQUEST, 'page') ? $_REQUEST['page'] : 1;
2352 $start = ($page - 1) * $count;
2355 if ($user_info['self'] == 1) {
2356 $sql_extra .= " AND `item`.`wall` = 1 ";
2359 if ($exclude_replies > 0) {
2360 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
2363 if ($conversation_id > 0) {
2364 $sql_extra .= ' AND `item`.`parent` = ' . intval($conversation_id);
2368 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2372 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2373 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2374 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2375 `contact`.`id` AS `cid`
2376 FROM `item` FORCE INDEX (`uid_contactid_id`)
2377 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
2378 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2379 WHERE `item`.`uid` = %d AND `verb` = '%s'
2380 AND `item`.`contact-id` = %d
2381 AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
2383 AND `item`.`id` > %d
2384 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2386 dbesc(ACTIVITY_POST),
2387 intval($user_info['cid']),
2393 $ret = api_format_items($r, $user_info, true, $type);
2395 $data = ['status' => $ret];
2399 $data = api_rss_extra($a, $data, $user_info);
2403 return api_format_data("statuses", $type, $data);
2406 /// @TODO move to top of file or somewhere better
2407 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2410 * Star/unstar an item.
2411 * param: id : id of the item
2413 * @param string $type Return type (atom, rss, xml, json)
2415 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2417 function api_favorites_create_destroy($type)
2421 if (api_user() === false) {
2422 throw new ForbiddenException();
2425 // for versioned api.
2426 /// @TODO We need a better global soluton
2427 $action_argv_id = 2;
2428 if ($a->argv[1] == "1.1") {
2429 $action_argv_id = 3;
2432 if ($a->argc <= $action_argv_id) {
2433 throw new BadRequestException("Invalid request.");
2435 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2436 if ($a->argc == $action_argv_id + 2) {
2437 $itemid = intval($a->argv[$action_argv_id + 1]);
2439 /// @TODO use x() to check if _REQUEST contains 'id'
2440 $itemid = intval($_REQUEST['id']);
2443 $item = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d LIMIT 1", $itemid, api_user());
2445 if (!DBM::is_result($item) || count($item) == 0) {
2446 throw new BadRequestException("Invalid item.");
2451 $item[0]['starred'] = 1;
2454 $item[0]['starred'] = 0;
2457 throw new BadRequestException("Invalid action ".$action);
2460 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2462 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d", $item[0]['starred'], $itemid, api_user());
2465 throw new InternalServerErrorException("DB error");
2469 $user_info = api_get_user($a);
2470 $rets = api_format_items($item, $user_info, false, $type);
2473 $data = ['status' => $ret];
2477 $data = api_rss_extra($a, $data, $user_info);
2480 return api_format_data("status", $type, $data);
2483 /// @TODO move to top of file or somewhere better
2484 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2485 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2488 * Returns the most recent favorite statuses.
2490 * @param string $type Return type (atom, rss, xml, json)
2492 * @return string|array
2494 function api_favorites($type)
2500 if (api_user() === false) {
2501 throw new ForbiddenException();
2506 $user_info = api_get_user($a);
2508 // in friendica starred item are private
2509 // return favorites only for self
2510 logger('api_favorites: self:' . $user_info['self']);
2512 if ($user_info['self'] == 0) {
2518 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
2519 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
2520 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
2521 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
2526 $start = $page*$count;
2529 $sql_extra .= ' AND `item`.`id` <= ' . intval($max_id);
2533 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
2534 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
2535 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
2536 `contact`.`id` AS `cid`
2537 FROM `item`, `contact`
2538 WHERE `item`.`uid` = %d
2539 AND `item`.`visible` = 1 AND `item`.`moderated` = 0 AND `item`.`deleted` = 0
2540 AND `item`.`starred` = 1
2541 AND `contact`.`id` = `item`.`contact-id`
2542 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
2545 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
2552 $ret = api_format_items($r, $user_info, false, $type);
2555 $data = ['status' => $ret];
2559 $data = api_rss_extra($a, $data, $user_info);
2562 return api_format_data("statuses", $type, $data);
2565 /// @TODO move to top of file or somewhere better
2566 api_register_func('api/favorites', 'api_favorites', true);
2570 * @param array $item
2571 * @param array $recipient
2572 * @param array $sender
2576 function api_format_messages($item, $recipient, $sender)
2578 // standard meta information
2580 'id' => $item['id'],
2581 'sender_id' => $sender['id'] ,
2583 'recipient_id' => $recipient['id'],
2584 'created_at' => api_date($item['created']),
2585 'sender_screen_name' => $sender['screen_name'],
2586 'recipient_screen_name' => $recipient['screen_name'],
2587 'sender' => $sender,
2588 'recipient' => $recipient,
2590 'friendica_seen' => $item['seen'],
2591 'friendica_parent_uri' => $item['parent-uri'],
2594 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2595 unset($ret["sender"]["uid"]);
2596 unset($ret["sender"]["self"]);
2597 unset($ret["recipient"]["uid"]);
2598 unset($ret["recipient"]["self"]);
2600 //don't send title to regular StatusNET requests to avoid confusing these apps
2601 if (x($_GET, 'getText')) {
2602 $ret['title'] = $item['title'];
2603 if ($_GET['getText'] == 'html') {
2604 $ret['text'] = bbcode($item['body'], false, false);
2605 } elseif ($_GET['getText'] == 'plain') {
2606 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2607 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2610 $ret['text'] = $item['title'] . "\n" . html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2612 if (x($_GET, 'getUserObjects') && $_GET['getUserObjects'] == 'false') {
2613 unset($ret['sender']);
2614 unset($ret['recipient']);
2622 * @param array $item
2626 function api_convert_item($item)
2628 $body = $item['body'];
2629 $attachments = api_get_attachments($body);
2631 // Workaround for ostatus messages where the title is identically to the body
2632 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2633 $statusbody = trim(html2plain($html, 0));
2635 // handle data: images
2636 $statusbody = api_format_items_embeded_images($item, $statusbody);
2638 $statustitle = trim($item['title']);
2640 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2641 $statustext = trim($statusbody);
2643 $statustext = trim($statustitle."\n\n".$statusbody);
2646 if (($item["network"] == NETWORK_FEED) && (strlen($statustext)> 1000)) {
2647 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2650 $statushtml = trim(bbcode($body, false, false));
2652 // Workaround for clients with limited HTML parser functionality
2653 $search = ["<br>", "<blockquote>", "</blockquote>",
2654 "<h1>", "</h1>", "<h2>", "</h2>",
2655 "<h3>", "</h3>", "<h4>", "</h4>",
2656 "<h5>", "</h5>", "<h6>", "</h6>"];
2657 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2658 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2659 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2660 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2661 $statushtml = str_replace($search, $replace, $statushtml);
2663 if ($item['title'] != "") {
2664 $statushtml = "<br><h4>" . bbcode($item['title']) . "</h4><br>" . $statushtml;
2668 $oldtext = $statushtml;
2669 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2670 } while ($oldtext != $statushtml);
2672 if (substr($statushtml, 0, 4) == '<br>') {
2673 $statushtml = substr($statushtml, 4);
2676 if (substr($statushtml, 0, -4) == '<br>') {
2677 $statushtml = substr($statushtml, -4);
2680 // feeds without body should contain the link
2681 if (($item['network'] == NETWORK_FEED) && (strlen($item['body']) == 0)) {
2682 $statushtml .= bbcode($item['plink']);
2685 $entities = api_get_entitities($statustext, $body);
2688 "text" => $statustext,
2689 "html" => $statushtml,
2690 "attachments" => $attachments,
2691 "entities" => $entities
2697 * @param string $body
2699 * @return array|false
2701 function api_get_attachments(&$body)
2704 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2706 $URLSearchString = "^\[\]";
2707 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2715 foreach ($images[1] as $image) {
2716 $imagedata = Image::getInfoFromURL($image);
2719 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2723 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus")) {
2724 foreach ($images[0] as $orig) {
2725 $body = str_replace($orig, "", $body);
2729 return $attachments;
2734 * @param string $text
2735 * @param string $bbcode
2738 * @todo Links at the first character of the post
2740 function api_get_entitities(&$text, $bbcode)
2742 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
2744 if ($include_entities != "true") {
2745 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2747 foreach ($images[1] as $image) {
2748 $replace = proxy_url($image);
2749 $text = str_replace($image, $replace, $text);
2754 $bbcode = bb_CleanPictureLinks($bbcode);
2756 // Change pure links in text to bbcode uris
2757 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2760 $entities["hashtags"] = [];
2761 $entities["symbols"] = [];
2762 $entities["urls"] = [];
2763 $entities["user_mentions"] = [];
2765 $URLSearchString = "^\[\]";
2767 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2769 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2770 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2771 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2773 $bbcode = preg_replace(
2774 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2775 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2778 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2780 $bbcode = preg_replace(
2781 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2782 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2785 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2787 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2789 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2790 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2793 foreach ($urls[1] as $id => $url) {
2794 //$start = strpos($text, $url, $offset);
2795 $start = iconv_strpos($text, $url, 0, "UTF-8");
2796 if (!($start === false)) {
2797 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2801 ksort($ordered_urls);
2804 //foreach ($urls[1] AS $id=>$url) {
2805 foreach ($ordered_urls as $url) {
2806 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2807 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2809 $display_url = $url["title"];
2811 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2812 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2814 if (strlen($display_url) > 26) {
2815 $display_url = substr($display_url, 0, 25)."…";
2819 //$start = strpos($text, $url, $offset);
2820 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2821 if (!($start === false)) {
2822 $entities["urls"][] = ["url" => $url["url"],
2823 "expanded_url" => $url["url"],
2824 "display_url" => $display_url,
2825 "indices" => [$start, $start+strlen($url["url"])]];
2826 $offset = $start + 1;
2830 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2831 $ordered_images = [];
2832 foreach ($images[1] as $image) {
2833 //$start = strpos($text, $url, $offset);
2834 $start = iconv_strpos($text, $image, 0, "UTF-8");
2835 if (!($start === false)) {
2836 $ordered_images[$start] = $image;
2839 //$entities["media"] = array();
2842 foreach ($ordered_images as $url) {
2843 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2844 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2846 if (strlen($display_url) > 26) {
2847 $display_url = substr($display_url, 0, 25)."…";
2850 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2851 if (!($start === false)) {
2852 $image = Image::getInfoFromURL($url);
2854 // If image cache is activated, then use the following sizes:
2855 // thumb (150), small (340), medium (600) and large (1024)
2856 if (!Config::get("system", "proxy_disabled")) {
2857 $media_url = proxy_url($url);
2860 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2861 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2863 if (($image[0] > 150) || ($image[1] > 150)) {
2864 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2865 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2868 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2869 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2871 if (($image[0] > 600) || ($image[1] > 600)) {
2872 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2873 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2877 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2880 $entities["media"][] = [
2882 "id_str" => (string)$start+1,
2883 "indices" => [$start, $start+strlen($url)],
2884 "media_url" => normalise_link($media_url),
2885 "media_url_https" => $media_url,
2887 "display_url" => $display_url,
2888 "expanded_url" => $url,
2892 $offset = $start + 1;
2901 * @param array $item
2902 * @param string $text
2906 function api_format_items_embeded_images($item, $text)
2908 $text = preg_replace_callback(
2909 '|data:image/([^;]+)[^=]+=*|m',
2910 function () use ($item) {
2911 return System::baseUrl() . '/display/' . $item['guid'];
2919 * @brief return <a href='url'>name</a> as array
2921 * @param string $txt text
2926 function api_contactlink_to_array($txt)
2929 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2930 if ($r && count($match)==3) {
2932 'name' => $match[2],
2946 * @brief return likes, dislikes and attend status for item
2948 * @param array $item array
2949 * @param string $type Return type (atom, rss, xml, json)
2952 * likes => int count,
2953 * dislikes => int count
2955 function api_format_items_activities(&$item, $type = "json")
2964 'attendmaybe' => [],
2969 WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2970 intval($item['uid']),
2974 foreach ($items as $i) {
2975 // not used as result should be structured like other user data
2976 //builtin_activity_puller($i, $activities);
2978 // get user data and add it to the array of the activity
2979 $user = api_get_user($a, $i['author-link']);
2980 switch ($i['verb']) {
2982 $activities['like'][] = $user;
2984 case ACTIVITY_DISLIKE:
2985 $activities['dislike'][] = $user;
2987 case ACTIVITY_ATTEND:
2988 $activities['attendyes'][] = $user;
2990 case ACTIVITY_ATTENDNO:
2991 $activities['attendno'][] = $user;
2993 case ACTIVITY_ATTENDMAYBE:
2994 $activities['attendmaybe'][] = $user;
3001 if ($type == "xml") {
3002 $xml_activities = [];
3003 foreach ($activities as $k => $v) {
3004 // change xml element from "like" to "friendica:like"
3005 $xml_activities["friendica:".$k] = $v;
3006 // add user data into xml output
3008 foreach ($v as $user) {
3009 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
3012 $activities = $xml_activities;
3020 * @brief return data from profiles
3022 * @param array $profile_row array containing data from db table 'profile'
3025 function api_format_items_profiles($profile_row)
3028 'profile_id' => $profile_row['id'],
3029 'profile_name' => $profile_row['profile-name'],
3030 'is_default' => $profile_row['is-default'] ? true : false,
3031 'hide_friends' => $profile_row['hide-friends'] ? true : false,
3032 'profile_photo' => $profile_row['photo'],
3033 'profile_thumb' => $profile_row['thumb'],
3034 'publish' => $profile_row['publish'] ? true : false,
3035 'net_publish' => $profile_row['net-publish'] ? true : false,
3036 'description' => $profile_row['pdesc'],
3037 'date_of_birth' => $profile_row['dob'],
3038 'address' => $profile_row['address'],
3039 'city' => $profile_row['locality'],
3040 'region' => $profile_row['region'],
3041 'postal_code' => $profile_row['postal-code'],
3042 'country' => $profile_row['country-name'],
3043 'hometown' => $profile_row['hometown'],
3044 'gender' => $profile_row['gender'],
3045 'marital' => $profile_row['marital'],
3046 'marital_with' => $profile_row['with'],
3047 'marital_since' => $profile_row['howlong'],
3048 'sexual' => $profile_row['sexual'],
3049 'politic' => $profile_row['politic'],
3050 'religion' => $profile_row['religion'],
3051 'public_keywords' => $profile_row['pub_keywords'],
3052 'private_keywords' => $profile_row['prv_keywords'],
3053 'likes' => bbcode(api_clean_plain_items($profile_row['likes']) , false, false, 2, false),
3054 'dislikes' => bbcode(api_clean_plain_items($profile_row['dislikes']) , false, false, 2, false),
3055 'about' => bbcode(api_clean_plain_items($profile_row['about']) , false, false, 2, false),
3056 'music' => bbcode(api_clean_plain_items($profile_row['music']) , false, false, 2, false),
3057 'book' => bbcode(api_clean_plain_items($profile_row['book']) , false, false, 2, false),
3058 'tv' => bbcode(api_clean_plain_items($profile_row['tv']) , false, false, 2, false),
3059 'film' => bbcode(api_clean_plain_items($profile_row['film']) , false, false, 2, false),
3060 'interest' => bbcode(api_clean_plain_items($profile_row['interest']) , false, false, 2, false),
3061 'romance' => bbcode(api_clean_plain_items($profile_row['romance']) , false, false, 2, false),
3062 'work' => bbcode(api_clean_plain_items($profile_row['work']) , false, false, 2, false),
3063 'education' => bbcode(api_clean_plain_items($profile_row['education']), false, false, 2, false),
3064 'social_networks' => bbcode(api_clean_plain_items($profile_row['contact']) , false, false, 2, false),
3065 'homepage' => $profile_row['homepage'],
3072 * @brief format items to be returned by api
3074 * @param array $r array of items
3075 * @param array $user_info
3076 * @param bool $filter_user filter items by $user_info
3077 * @param string $type Return type (atom, rss, xml, json)
3079 function api_format_items($r, $user_info, $filter_user = false, $type = "json")
3085 foreach ($r as $item) {
3086 localize_item($item);
3087 list($status_user, $owner_user) = api_item_get_user($a, $item);
3089 // Look if the posts are matching if they should be filtered by user id
3090 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3094 $in_reply_to = api_in_reply_to($item);
3096 $converted = api_convert_item($item);
3098 if ($type == "xml") {
3099 $geo = "georss:point";
3105 'text' => $converted["text"],
3106 'truncated' => false,
3107 'created_at'=> api_date($item['created']),
3108 'in_reply_to_status_id' => $in_reply_to['status_id'],
3109 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3110 'source' => (($item['app']) ? $item['app'] : 'web'),
3111 'id' => intval($item['id']),
3112 'id_str' => (string) intval($item['id']),
3113 'in_reply_to_user_id' => $in_reply_to['user_id'],
3114 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3115 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3117 'favorited' => $item['starred'] ? true : false,
3118 'user' => $status_user ,
3119 'friendica_owner' => $owner_user,
3120 //'entities' => NULL,
3121 'statusnet_html' => $converted["html"],
3122 'statusnet_conversation_id' => $item['parent'],
3123 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3124 'friendica_activities' => api_format_items_activities($item, $type),
3127 if (count($converted["attachments"]) > 0) {
3128 $status["attachments"] = $converted["attachments"];
3131 if (count($converted["entities"]) > 0) {
3132 $status["entities"] = $converted["entities"];
3135 if (($item['item_network'] != "") && ($status["source"] == 'web')) {
3136 $status["source"] = ContactSelector::networkToName($item['item_network'], $user_info['url']);
3137 } elseif (($item['item_network'] != "") && (ContactSelector::networkToName($item['item_network'], $user_info['url']) != $status["source"])) {
3138 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['item_network'], $user_info['url']).')');
3142 // Retweets are only valid for top postings
3143 // It doesn't work reliable with the link if its a feed
3144 //$IsRetweet = ($item['owner-link'] != $item['author-link']);
3146 // $IsRetweet = (($item['owner-name'] != $item['author-name']) || ($item['owner-avatar'] != $item['author-avatar']));
3149 if ($item["id"] == $item["parent"]) {
3150 $retweeted_item = api_share_as_retweet($item);
3151 if ($retweeted_item !== false) {
3152 $retweeted_status = $status;
3154 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-link"]);
3155 } catch (BadRequestException $e) {
3156 // user not found. should be found?
3157 /// @todo check if the user should be always found
3158 $retweeted_status["user"] = [];
3161 $rt_converted = api_convert_item($retweeted_item);
3163 $retweeted_status['text'] = $rt_converted["text"];
3164 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3165 $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
3166 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3167 $status['retweeted_status'] = $retweeted_status;
3171 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3172 unset($status["user"]["uid"]);
3173 unset($status["user"]["self"]);
3175 if ($item["coord"] != "") {
3176 $coords = explode(' ', $item["coord"]);
3177 if (count($coords) == 2) {
3178 if ($type == "json") {
3179 $status["geo"] = ['type' => 'Point',
3180 'coordinates' => [(float) $coords[0],
3181 (float) $coords[1]]];
3182 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3183 $status["georss:point"] = $item["coord"];
3193 * Returns the remaining number of API requests available to the user before the API limit is reached.
3195 * @param string $type Return type (atom, rss, xml, json)
3197 * @return array|string
3199 function api_account_rate_limit_status($type)
3201 if ($type == "xml") {
3203 'remaining-hits' => '150',
3204 '@attributes' => ["type" => "integer"],
3205 'hourly-limit' => '150',
3206 '@attributes2' => ["type" => "integer"],
3207 'reset-time' => datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME),
3208 '@attributes3' => ["type" => "datetime"],
3209 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3210 '@attributes4' => ["type" => "integer"],
3214 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3215 'remaining_hits' => '150',
3216 'hourly_limit' => '150',
3217 'reset_time' => api_date(datetime_convert('UTC', 'UTC', 'now + 1 hour', ATOM_TIME)),
3221 return api_format_data('hash', $type, ['hash' => $hash]);
3224 /// @TODO move to top of file or somewhere better
3225 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3228 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3230 * @param string $type Return type (atom, rss, xml, json)
3232 * @return array|string
3234 function api_help_test($type)
3236 if ($type == 'xml') {
3242 return api_format_data('ok', $type, ["ok" => $ok]);
3245 /// @TODO move to top of file or somewhere better
3246 api_register_func('api/help/test', 'api_help_test', false);
3250 * @param string $type Return type (atom, rss, xml, json)
3252 * @return array|string
3254 function api_lists($type)
3257 /// @TODO $ret is not filled here?
3258 return api_format_data('lists', $type, ["lists_list" => $ret]);
3261 /// @TODO move to top of file or somewhere better
3262 api_register_func('api/lists', 'api_lists', true);
3265 * Returns all lists the user subscribes to.
3267 * @param string $type Return type (atom, rss, xml, json)
3269 * @return array|string
3270 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3272 function api_lists_list($type)
3275 /// @TODO $ret is not filled here?
3276 return api_format_data('lists', $type, ["lists_list" => $ret]);
3279 /// @TODO move to top of file or somewhere better
3280 api_register_func('api/lists/list', 'api_lists_list', true);
3283 * Considers friends and followers lists to be private and won't return
3284 * anything if any user_id parameter is passed.
3286 * @brief Returns either the friends of the follower list
3288 * @param string $qtype Either "friends" or "followers"
3289 * @return boolean|array
3290 * @throws ForbiddenException
3292 function api_statuses_f($qtype)
3296 if (api_user() === false) {
3297 throw new ForbiddenException();
3301 $count = x($_GET, 'count') ? $_GET['count'] : 20;
3302 $page = x($_GET, 'page') ? $_GET['page'] : 1;
3306 $start = ($page - 1) * $count;
3308 $user_info = api_get_user($a);
3310 if (x($_GET, 'cursor') && $_GET['cursor'] == 'undefined') {
3311 /* this is to stop Hotot to load friends multiple times
3312 * I'm not sure if I'm missing return something or
3313 * is a bug in hotot. Workaround, meantime
3317 return array('$users' => $ret);*/
3322 if ($qtype == 'friends') {
3323 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
3324 } elseif ($qtype == 'followers') {
3325 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
3328 // friends and followers only for self
3329 if ($user_info['self'] == 0) {
3330 $sql_extra = " AND false ";
3333 if ($qtype == 'blocks') {
3334 $sql_filter = 'AND `blocked` AND NOT `pending`';
3335 } elseif ($qtype == 'incoming') {
3336 $sql_filter = 'AND `pending`';
3338 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3356 foreach ($r as $cid) {
3357 $user = api_get_user($a, $cid['nurl']);
3358 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3359 unset($user["uid"]);
3360 unset($user["self"]);
3367 return ['user' => $ret];
3372 * Returns the user's friends.
3374 * @brief Returns the list of friends of the provided user
3376 * @deprecated By Twitter API in favor of friends/list
3378 * @param string $type Either "json" or "xml"
3379 * @return boolean|string|array
3381 function api_statuses_friends($type)
3383 $data = api_statuses_f("friends");
3384 if ($data === false) {
3387 return api_format_data("users", $type, $data);
3391 * Returns the user's followers.
3393 * @brief Returns the list of followers of the provided user
3395 * @deprecated By Twitter API in favor of friends/list
3397 * @param string $type Either "json" or "xml"
3398 * @return boolean|string|array
3400 function api_statuses_followers($type)
3402 $data = api_statuses_f("followers");
3403 if ($data === false) {
3406 return api_format_data("users", $type, $data);
3409 /// @TODO move to top of file or somewhere better
3410 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3411 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3414 * Returns the list of blocked users
3416 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3418 * @param string $type Either "json" or "xml"
3420 * @return boolean|string|array
3422 function api_blocks_list($type)
3424 $data = api_statuses_f('blocks');
3425 if ($data === false) {
3428 return api_format_data("users", $type, $data);
3431 /// @TODO move to top of file or somewhere better
3432 api_register_func('api/blocks/list', 'api_blocks_list', true);
3435 * Returns the list of pending users IDs
3437 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3439 * @param string $type Either "json" or "xml"
3441 * @return boolean|string|array
3443 function api_friendships_incoming($type)
3445 $data = api_statuses_f('incoming');
3446 if ($data === false) {
3451 foreach ($data['user'] as $user) {
3452 $ids[] = $user['id'];
3455 return api_format_data("ids", $type, ['id' => $ids]);
3458 /// @TODO move to top of file or somewhere better
3459 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3462 * Returns the instance's configuration information.
3464 * @param string $type Return type (atom, rss, xml, json)
3466 * @return array|string
3468 function api_statusnet_config($type)
3472 $name = $a->config['sitename'];
3473 $server = $a->get_hostname();
3474 $logo = System::baseUrl() . '/images/friendica-64.png';
3475 $email = $a->config['admin_email'];
3476 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
3477 $private = ((Config::get('system', 'block_public')) ? 'true' : 'false');
3478 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
3479 if ($a->config['api_import_size']) {
3480 $textlimit = (string) $a->config['api_import_size'];
3482 $ssl = ((Config::get('system', 'have_ssl')) ? 'true' : 'false');
3483 $sslserver = (($ssl === 'true') ? str_replace('http:', 'https:', System::baseUrl()) : '');
3486 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3487 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3488 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3489 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3490 'shorturllength' => '30',
3492 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3493 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3494 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3495 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3500 return api_format_data('config', $type, ['config' => $config]);
3503 /// @TODO move to top of file or somewhere better
3504 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3505 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3509 * @param string $type Return type (atom, rss, xml, json)
3511 * @return array|string
3513 function api_statusnet_version($type)
3516 $fake_statusnet_version = "0.9.7";
3518 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3521 /// @TODO move to top of file or somewhere better
3522 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3523 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3527 * @param string $type Return type (atom, rss, xml, json)
3529 * @todo use api_format_data() to return data
3531 function api_ff_ids($type)
3534 throw new ForbiddenException();
3539 $stringify_ids = defaults($_REQUEST, 'stringify_ids', false);
3542 "SELECT `pcontact`.`id` FROM `contact`
3543 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3544 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3547 if (!DBM::is_result($r)) {
3552 foreach ($r as $rr) {
3553 if ($stringify_ids) {
3556 $ids[] = intval($rr['id']);
3560 return api_format_data("ids", $type, ['id' => $ids]);
3564 * Returns the ID of every user the user is following.
3566 * @param string $type Return type (atom, rss, xml, json)
3568 * @return array|string
3569 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3571 function api_friends_ids($type)
3573 return api_ff_ids($type);
3577 * Returns the ID of every user following the user.
3579 * @param string $type Return type (atom, rss, xml, json)
3581 * @return array|string
3582 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3584 function api_followers_ids($type)
3586 return api_ff_ids($type);
3589 /// @TODO move to top of file or somewhere better
3590 api_register_func('api/friends/ids', 'api_friends_ids', true);
3591 api_register_func('api/followers/ids', 'api_followers_ids', true);
3594 * Sends a new direct message.
3596 * @param string $type Return type (atom, rss, xml, json)
3598 * @return array|string
3599 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3601 function api_direct_messages_new($type)
3606 if (api_user() === false) {
3607 throw new ForbiddenException();
3610 if (!x($_POST, "text") || (!x($_POST, "screen_name") && !x($_POST, "user_id"))) {
3614 $sender = api_get_user($a);
3616 if ($_POST['screen_name']) {
3618 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3620 dbesc($_POST['screen_name'])
3623 // Selecting the id by priority, friendica first
3624 api_best_nickname($r);
3626 $recipient = api_get_user($a, $r[0]['nurl']);
3628 $recipient = api_get_user($a, $_POST['user_id']);
3633 if (x($_REQUEST, 'replyto')) {
3635 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3637 intval($_REQUEST['replyto'])
3639 $replyto = $r[0]['parent-uri'];
3640 $sub = $r[0]['title'];
3642 if (x($_REQUEST, 'title')) {
3643 $sub = $_REQUEST['title'];
3645 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3649 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3652 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3653 $ret = api_format_messages($r[0], $recipient, $sender);
3655 $ret = ["error"=>$id];
3658 $data = ['direct_message'=>$ret];
3663 $data = api_rss_extra($a, $data, $user_info);
3666 return api_format_data("direct-messages", $type, $data);
3669 /// @TODO move to top of file or somewhere better
3670 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3673 * Destroys a direct message.
3675 * @brief delete a direct_message from mail table through api
3677 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3679 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3681 function api_direct_messages_destroy($type)
3685 if (api_user() === false) {
3686 throw new ForbiddenException();
3690 $user_info = api_get_user($a);
3692 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3694 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
3695 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3696 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3698 $uid = $user_info['uid'];
3699 // error if no id or parenturi specified (for clients posting parent-uri as well)
3700 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3701 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3702 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3705 // BadRequestException if no id specified (for clients using Twitter API)
3707 throw new BadRequestException('Message id not specified');
3710 // add parent-uri to sql command if specified by calling app
3711 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
3713 // get data of the specified message id
3715 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3720 // error message if specified id is not in database
3721 if (!DBM::is_result($r)) {
3722 if ($verbose == "true") {
3723 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3724 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3726 /// @todo BadRequestException ok for Twitter API clients?
3727 throw new BadRequestException('message id not in database');
3732 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3737 if ($verbose == "true") {
3740 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3741 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3743 $answer = ['result' => 'error', 'message' => 'unknown error'];
3744 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3747 /// @todo return JSON data like Twitter API not yet implemented
3750 /// @TODO move to top of file or somewhere better
3751 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3755 * @param string $type Return type (atom, rss, xml, json)
3756 * @param string $box
3757 * @param string $verbose
3759 * @return array|string
3761 function api_direct_messages_box($type, $box, $verbose)
3765 if (api_user() === false) {
3766 throw new ForbiddenException();
3770 $count = (x($_GET, 'count') ? $_GET['count'] : 20);
3771 $page = (x($_REQUEST, 'page') ? $_REQUEST['page'] -1 : 0);
3776 $since_id = (x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0);
3777 $max_id = (x($_REQUEST, 'max_id') ? $_REQUEST['max_id'] : 0);
3779 $user_id = (x($_REQUEST, 'user_id') ? $_REQUEST['user_id'] : "");
3780 $screen_name = (x($_REQUEST, 'screen_name') ? $_REQUEST['screen_name'] : "");
3783 unset($_REQUEST["user_id"]);
3784 unset($_GET["user_id"]);
3786 unset($_REQUEST["screen_name"]);
3787 unset($_GET["screen_name"]);
3789 $user_info = api_get_user($a);
3790 $profile_url = $user_info["url"];
3793 $start = $page * $count;
3796 if ($box=="sentbox") {
3797 $sql_extra = "`mail`.`from-url`='" . dbesc($profile_url) . "'";
3798 } elseif ($box == "conversation") {
3799 $sql_extra = "`mail`.`parent-uri`='" . dbesc($_GET["uri"]) . "'";
3800 } elseif ($box == "all") {
3801 $sql_extra = "true";
3802 } elseif ($box == "inbox") {
3803 $sql_extra = "`mail`.`from-url`!='" . dbesc($profile_url) . "'";
3807 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3810 if ($user_id != "") {
3811 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3812 } elseif ($screen_name !="") {
3813 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
3817 "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",
3823 if ($verbose == "true" && !DBM::is_result($r)) {
3824 $answer = ['result' => 'error', 'message' => 'no mails available'];
3825 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3829 foreach ($r as $item) {
3830 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3831 $recipient = $user_info;
3832 $sender = api_get_user($a, normalise_link($item['contact-url']));
3833 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3834 $recipient = api_get_user($a, normalise_link($item['contact-url']));
3835 $sender = $user_info;
3838 $ret[] = api_format_messages($item, $recipient, $sender);
3842 $data = ['direct_message' => $ret];
3846 $data = api_rss_extra($a, $data, $user_info);
3849 return api_format_data("direct-messages", $type, $data);
3853 * Returns the most recent direct messages sent by the user.
3855 * @param string $type Return type (atom, rss, xml, json)
3857 * @return array|string
3858 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3860 function api_direct_messages_sentbox($type)
3862 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3863 return api_direct_messages_box($type, "sentbox", $verbose);
3867 * Returns the most recent direct messages sent to the user.
3869 * @param string $type Return type (atom, rss, xml, json)
3871 * @return array|string
3872 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3874 function api_direct_messages_inbox($type)
3876 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3877 return api_direct_messages_box($type, "inbox", $verbose);
3882 * @param string $type Return type (atom, rss, xml, json)
3884 * @return array|string
3886 function api_direct_messages_all($type)
3888 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3889 return api_direct_messages_box($type, "all", $verbose);
3894 * @param string $type Return type (atom, rss, xml, json)
3896 * @return array|string
3898 function api_direct_messages_conversation($type)
3900 $verbose = (x($_GET, 'friendica_verbose') ? strtolower($_GET['friendica_verbose']) : "false");
3901 return api_direct_messages_box($type, "conversation", $verbose);
3904 /// @TODO move to top of file or somewhere better
3905 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3906 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3907 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3908 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3911 * Returns an OAuth Request Token.
3913 * @see https://oauth.net/core/1.0/#auth_step1
3915 function api_oauth_request_token()
3917 $oauth1 = new FKOAuth1();
3919 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
3920 } catch (Exception $e) {
3921 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
3929 * Returns an OAuth Access Token.
3931 * @return array|string
3932 * @see https://oauth.net/core/1.0/#auth_step3
3934 function api_oauth_access_token()
3936 $oauth1 = new FKOAuth1();
3938 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
3939 } catch (Exception $e) {
3940 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
3947 /// @TODO move to top of file or somewhere better
3948 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3949 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3953 * @brief delete a complete photoalbum with all containing photos from database through api
3955 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3958 function api_fr_photoalbum_delete($type)
3960 if (api_user() === false) {
3961 throw new ForbiddenException();
3964 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
3966 // we do not allow calls without album string
3968 throw new BadRequestException("no albumname specified");
3970 // check if album is existing
3972 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
3976 if (!DBM::is_result($r)) {
3977 throw new BadRequestException("album not available");
3980 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3981 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3982 foreach ($r as $rr) {
3984 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
3985 intval(local_user()),
3986 dbesc($rr['resource-id'])
3989 if (!DBM::is_result($photo_item)) {
3990 throw new InternalServerErrorException("problem with deleting items occured");
3992 Item::delete($photo_item[0]['id']);
3995 // now let's delete all photos from the album
3996 $result = dba::delete('photo', ['uid' => api_user(), 'album' => $album]);
3998 // return success of deletion or error message
4000 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4001 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4003 throw new InternalServerErrorException("unknown error - deleting from database failed");
4008 * @brief update the name of the album for all photos of an album
4010 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4013 function api_fr_photoalbum_update($type)
4015 if (api_user() === false) {
4016 throw new ForbiddenException();
4019 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : "");
4020 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : "");
4022 // we do not allow calls without album string
4024 throw new BadRequestException("no albumname specified");
4026 if ($album_new == "") {
4027 throw new BadRequestException("no new albumname specified");
4029 // check if album is existing
4031 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4035 if (!DBM::is_result($r)) {
4036 throw new BadRequestException("album not available");
4038 // now let's update all photos to the albumname
4040 "UPDATE `photo` SET `album` = '%s' WHERE `uid` = %d AND `album` = '%s'",
4046 // return success of updating or error message
4048 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4049 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4051 throw new InternalServerErrorException("unknown error - updating in database failed");
4057 * @brief list all photos of the authenticated user
4059 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4062 function api_fr_photos_list($type)
4064 if (api_user() === false) {
4065 throw new ForbiddenException();
4068 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4069 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4070 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`",
4071 intval(local_user())
4074 'image/jpeg' => 'jpg',
4075 'image/png' => 'png',
4076 'image/gif' => 'gif'
4078 $data = ['photo'=>[]];
4079 if (DBM::is_result($r)) {
4080 foreach ($r as $rr) {
4082 $photo['id'] = $rr['resource-id'];
4083 $photo['album'] = $rr['album'];
4084 $photo['filename'] = $rr['filename'];
4085 $photo['type'] = $rr['type'];
4086 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4087 $photo['created'] = $rr['created'];
4088 $photo['edited'] = $rr['edited'];
4089 $photo['desc'] = $rr['desc'];
4091 if ($type == "xml") {
4092 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4094 $photo['thumb'] = $thumb;
4095 $data['photo'][] = $photo;
4099 return api_format_data("photos", $type, $data);
4103 * @brief upload a new photo or change an existing photo
4105 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4108 function api_fr_photo_create_update($type)
4110 if (api_user() === false) {
4111 throw new ForbiddenException();
4114 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4115 $desc = (x($_REQUEST, 'desc') ? $_REQUEST['desc'] : (array_key_exists('desc', $_REQUEST) ? "" : null)); // extra check necessary to distinguish between 'not provided' and 'empty string'
4116 $album = (x($_REQUEST, 'album') ? $_REQUEST['album'] : null);
4117 $album_new = (x($_REQUEST, 'album_new') ? $_REQUEST['album_new'] : null);
4118 $allow_cid = (x($_REQUEST, 'allow_cid') ? $_REQUEST['allow_cid'] : (array_key_exists('allow_cid', $_REQUEST) ? " " : null));
4119 $deny_cid = (x($_REQUEST, 'deny_cid') ? $_REQUEST['deny_cid'] : (array_key_exists('deny_cid', $_REQUEST) ? " " : null));
4120 $allow_gid = (x($_REQUEST, 'allow_gid') ? $_REQUEST['allow_gid'] : (array_key_exists('allow_gid', $_REQUEST) ? " " : null));
4121 $deny_gid = (x($_REQUEST, 'deny_gid') ? $_REQUEST['deny_gid'] : (array_key_exists('deny_gid', $_REQUEST) ? " " : null));
4122 $visibility = (x($_REQUEST, 'visibility') ? (($_REQUEST['visibility'] == "true" || $_REQUEST['visibility'] == 1) ? true : false) : false);
4124 // do several checks on input parameters
4125 // we do not allow calls without album string
4126 if ($album == null) {
4127 throw new BadRequestException("no albumname specified");
4129 // if photo_id == null --> we are uploading a new photo
4130 if ($photo_id == null) {
4133 // error if no media posted in create-mode
4134 if (!x($_FILES, 'media')) {
4136 throw new BadRequestException("no media data submitted");
4139 // album_new will be ignored in create-mode
4144 // check if photo is existing in database
4146 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4151 if (!DBM::is_result($r)) {
4152 throw new BadRequestException("photo not available");
4156 // checks on acl strings provided by clients
4157 $acl_input_error = false;
4158 $acl_input_error |= check_acl_input($allow_cid);
4159 $acl_input_error |= check_acl_input($deny_cid);
4160 $acl_input_error |= check_acl_input($allow_gid);
4161 $acl_input_error |= check_acl_input($deny_gid);
4162 if ($acl_input_error) {
4163 throw new BadRequestException("acl data invalid");
4165 // now let's upload the new media in create-mode
4166 if ($mode == "create") {
4167 $media = $_FILES['media'];
4168 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4170 // return success of updating or error message
4171 if (!is_null($data)) {
4172 return api_format_data("photo_create", $type, $data);
4174 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4178 // now let's do the changes in update-mode
4179 if ($mode == "update") {
4182 if (!is_null($desc)) {
4183 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`desc` = '$desc'";
4186 if (!is_null($album_new)) {
4187 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`album` = '$album_new'";
4190 if (!is_null($allow_cid)) {
4191 $allow_cid = trim($allow_cid);
4192 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_cid` = '$allow_cid'";
4195 if (!is_null($deny_cid)) {
4196 $deny_cid = trim($deny_cid);
4197 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_cid` = '$deny_cid'";
4200 if (!is_null($allow_gid)) {
4201 $allow_gid = trim($allow_gid);
4202 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`allow_gid` = '$allow_gid'";
4205 if (!is_null($deny_gid)) {
4206 $deny_gid = trim($deny_gid);
4207 $sql_extra .= (($sql_extra != "") ? " ," : "") . "`deny_gid` = '$deny_gid'";
4211 if ($sql_extra != "") {
4212 $nothingtodo = false;
4214 "UPDATE `photo` SET %s, `edited`='%s' WHERE `uid` = %d AND `resource-id` = '%s' AND `album` = '%s'",
4216 datetime_convert(), // update edited timestamp
4222 $nothingtodo = true;
4225 if (x($_FILES, 'media')) {
4226 $nothingtodo = false;
4227 $media = $_FILES['media'];
4228 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4229 if (!is_null($data)) {
4230 return api_format_data("photo_update", $type, $data);
4234 // return success of updating or error message
4236 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4237 return api_format_data("photo_update", $type, ['$result' => $answer]);
4240 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4241 return api_format_data("photo_update", $type, ['$result' => $answer]);
4243 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4246 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4251 * @brief delete a single photo from the database through api
4253 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4256 function api_fr_photo_delete($type)
4258 if (api_user() === false) {
4259 throw new ForbiddenException();
4262 $photo_id = (x($_REQUEST, 'photo_id') ? $_REQUEST['photo_id'] : null);
4264 // do several checks on input parameters
4265 // we do not allow calls without photo id
4266 if ($photo_id == null) {
4267 throw new BadRequestException("no photo_id specified");
4269 // check if photo is existing in database
4271 "SELECT `id` FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s'",
4275 if (!DBM::is_result($r)) {
4276 throw new BadRequestException("photo not available");
4278 // now we can perform on the deletion of the photo
4279 $result = dba::delete('photo', ['uid' => api_user(), 'resource-id' => $photo_id]);
4281 // return success of deletion or error message
4283 // retrieve the id of the parent element (the photo element)
4285 "SELECT `id` FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4286 intval(local_user()),
4290 if (!DBM::is_result($photo_item)) {
4291 throw new InternalServerErrorException("problem with deleting items occured");
4293 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4294 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4295 Item::delete($photo_item[0]['id']);
4297 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4298 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4300 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4306 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4308 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4309 * @return string|array
4311 function api_fr_photo_detail($type)
4313 if (api_user() === false) {
4314 throw new ForbiddenException();
4316 if (!x($_REQUEST, 'photo_id')) {
4317 throw new BadRequestException("No photo id.");
4320 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
4321 $photo_id = $_REQUEST['photo_id'];
4323 // prepare json/xml output with data from database for the requested photo
4324 $data = prepare_photo_data($type, $scale, $photo_id);
4326 return api_format_data("photo_detail", $type, $data);
4331 * Updates the user’s profile image.
4333 * @brief updates the profile image for the user (either a specified profile or the default profile)
4335 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4338 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4340 function api_account_update_profile_image($type)
4342 if (api_user() === false) {
4343 throw new ForbiddenException();
4346 $profileid = defaults($_REQUEST, 'profile_id', 0);
4348 // error if image data is missing
4349 if (!x($_FILES, 'image')) {
4350 throw new BadRequestException("no media data submitted");
4353 // check if specified profile id is valid
4354 if ($profileid != 0) {
4356 "SELECT `id` FROM `profile` WHERE `uid` = %d AND `id` = %d",
4360 // error message if specified profile id is not in database
4361 if (!DBM::is_result($r)) {
4362 throw new BadRequestException("profile_id not available");
4364 $is_default_profile = $r['profile'];
4366 $is_default_profile = 1;
4369 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4371 if (x($_FILES, 'image')) {
4372 $media = $_FILES['image'];
4373 } elseif (x($_FILES, 'media')) {
4374 $media = $_FILES['media'];
4376 // save new profile image
4377 $data = save_media_to_database("profileimage", $media, $type, t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4380 if (is_array($media['type'])) {
4381 $filetype = $media['type'][0];
4383 $filetype = $media['type'];
4385 if ($filetype == "image/jpeg") {
4387 } elseif ($filetype == "image/png") {
4390 // change specified profile or all profiles to the new resource-id
4391 if ($is_default_profile) {
4393 "UPDATE `photo` SET `profile` = 0 WHERE `profile` = 1 AND `resource-id` != '%s' AND `uid` = %d",
4394 dbesc($data['photo']['id']),
4395 intval(local_user())
4399 "UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s' WHERE `self` AND `uid` = %d",
4400 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext),
4401 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext),
4402 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-6.' . $fileext),
4403 intval(local_user())
4407 "UPDATE `profile` SET `photo` = '%s', `thumb` = '%s' WHERE `id` = %d AND `uid` = %d",
4408 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $filetype),
4409 dbesc(System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $filetype),
4410 intval($_REQUEST['profile']),
4411 intval(local_user())
4415 // we'll set the updated profile-photo timestamp even if it isn't the default profile,
4416 // so that browsers will do a cache update unconditionally
4419 "UPDATE `contact` SET `avatar-date` = '%s' WHERE `self` = 1 AND `uid` = %d",
4420 dbesc(datetime_convert()),
4421 intval(local_user())
4424 // Update global directory in background
4425 //$user = api_get_user(get_app());
4426 $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
4427 if ($url && strlen(Config::get('system', 'directory'))) {
4428 Worker::add(PRIORITY_LOW, "Directory", $url);
4431 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4433 // output for client
4435 return api_account_verify_credentials($type);
4437 // SaveMediaToDatabase failed for some reason
4438 throw new InternalServerErrorException("image upload failed");
4442 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4443 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4444 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4445 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4446 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4447 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4448 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4449 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4450 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4453 * Update user profile
4455 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4457 * @return array|string
4459 function api_account_update_profile($type)
4461 $local_user = api_user();
4462 $api_user = api_get_user(get_app());
4464 if (!empty($_POST['name'])) {
4465 dba::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4466 dba::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4467 dba::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4468 dba::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4471 if (isset($_POST['description'])) {
4472 dba::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4473 dba::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4474 dba::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4477 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4478 // Update global directory in background
4479 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4480 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4483 return api_account_verify_credentials($type);
4486 /// @TODO move to top of file or somewhere better
4487 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4491 * @param string $acl_string
4493 function check_acl_input($acl_string)
4495 if ($acl_string == null || $acl_string == " ") {
4498 $contact_not_found = false;
4500 // split <x><y><z> into array of cid's
4501 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4503 // check for each cid if it is available on server
4504 $cid_array = $array[0];
4505 foreach ($cid_array as $cid) {
4506 $cid = str_replace("<", "", $cid);
4507 $cid = str_replace(">", "", $cid);
4509 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
4513 $contact_not_found |= !DBM::is_result($contact);
4515 return $contact_not_found;
4520 * @param string $mediatype
4521 * @param array $media
4522 * @param string $type
4523 * @param string $album
4524 * @param string $allow_cid
4525 * @param string $deny_cid
4526 * @param string $allow_gid
4527 * @param string $deny_gid
4528 * @param string $desc
4529 * @param integer $profile
4530 * @param boolean $visibility
4531 * @param string $photo_id
4533 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)
4541 if (is_array($media)) {
4542 if (is_array($media['tmp_name'])) {
4543 $src = $media['tmp_name'][0];
4545 $src = $media['tmp_name'];
4547 if (is_array($media['name'])) {
4548 $filename = basename($media['name'][0]);
4550 $filename = basename($media['name']);
4552 if (is_array($media['size'])) {
4553 $filesize = intval($media['size'][0]);
4555 $filesize = intval($media['size']);
4557 if (is_array($media['type'])) {
4558 $filetype = $media['type'][0];
4560 $filetype = $media['type'];
4564 if ($filetype == "") {
4565 $filetype=Image::guessType($filename);
4567 $imagedata = getimagesize($src);
4569 $filetype = $imagedata['mime'];
4572 "File upload src: " . $src . " - filename: " . $filename .
4573 " - size: " . $filesize . " - type: " . $filetype,
4577 // check if there was a php upload error
4578 if ($filesize == 0 && $media['error'] == 1) {
4579 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4581 // check against max upload size within Friendica instance
4582 $maximagesize = Config::get('system', 'maximagesize');
4583 if ($maximagesize && ($filesize > $maximagesize)) {
4584 $formattedBytes = formatBytes($maximagesize);
4585 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4588 // create Photo instance with the data of the image
4589 $imagedata = @file_get_contents($src);
4590 $Image = new Image($imagedata, $filetype);
4591 if (! $Image->isValid()) {
4592 throw new InternalServerErrorException("unable to process image data");
4595 // check orientation of image
4596 $Image->orient($src);
4599 // check max length of images on server
4600 $max_length = Config::get('system', 'max_image_length');
4601 if (! $max_length) {
4602 $max_length = MAX_IMAGE_LENGTH;
4604 if ($max_length > 0) {
4605 $Image->scaleDown($max_length);
4606 logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG);
4608 $width = $Image->getWidth();
4609 $height = $Image->getHeight();
4611 // create a new resource-id if not already provided
4612 $hash = ($photo_id == null) ? photo_new_resource() : $photo_id;
4614 if ($mediatype == "photo") {
4615 // upload normal image (scales 0, 1, 2)
4616 logger("photo upload: starting new photo upload", LOGGER_DEBUG);
4618 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4620 logger("photo upload: image upload with scale 0 (original size) failed");
4622 if ($width > 640 || $height > 640) {
4623 $Image->scaleDown(640);
4624 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4626 logger("photo upload: image upload with scale 1 (640x640) failed");
4630 if ($width > 320 || $height > 320) {
4631 $Image->scaleDown(320);
4632 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4634 logger("photo upload: image upload with scale 2 (320x320) failed");
4637 logger("photo upload: new photo upload ended", LOGGER_DEBUG);
4638 } elseif ($mediatype == "profileimage") {
4639 // upload profile image (scales 4, 5, 6)
4640 logger("photo upload: starting new profile image upload", LOGGER_DEBUG);
4642 if ($width > 175 || $height > 175) {
4643 $Image->scaleDown(175);
4644 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4646 logger("photo upload: profile image upload with scale 4 (175x175) failed");
4650 if ($width > 80 || $height > 80) {
4651 $Image->scaleDown(80);
4652 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4654 logger("photo upload: profile image upload with scale 5 (80x80) failed");
4658 if ($width > 48 || $height > 48) {
4659 $Image->scaleDown(48);
4660 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4662 logger("photo upload: profile image upload with scale 6 (48x48) failed");
4665 $Image->__destruct();
4666 logger("photo upload: new profile image upload ended", LOGGER_DEBUG);
4670 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4671 if ($photo_id == null && $mediatype == "photo") {
4672 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4674 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4675 return prepare_photo_data($type, false, $hash);
4677 throw new InternalServerErrorException("image upload failed");
4683 * @param string $hash
4684 * @param string $allow_cid
4685 * @param string $deny_cid
4686 * @param string $allow_gid
4687 * @param string $deny_gid
4688 * @param string $filetype
4689 * @param boolean $visibility
4691 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4693 // get data about the api authenticated user
4694 $uri = item_new_uri(get_app()->get_hostname(), intval(api_user()));
4695 $owner_record = q("SELECT * FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
4698 $arr['guid'] = get_guid(32);
4699 $arr['uid'] = intval(api_user());
4701 $arr['parent-uri'] = $uri;
4702 $arr['type'] = 'photo';
4704 $arr['resource-id'] = $hash;
4705 $arr['contact-id'] = $owner_record[0]['id'];
4706 $arr['owner-name'] = $owner_record[0]['name'];
4707 $arr['owner-link'] = $owner_record[0]['url'];
4708 $arr['owner-avatar'] = $owner_record[0]['thumb'];
4709 $arr['author-name'] = $owner_record[0]['name'];
4710 $arr['author-link'] = $owner_record[0]['url'];
4711 $arr['author-avatar'] = $owner_record[0]['thumb'];
4713 $arr['allow_cid'] = $allow_cid;
4714 $arr['allow_gid'] = $allow_gid;
4715 $arr['deny_cid'] = $deny_cid;
4716 $arr['deny_gid'] = $deny_gid;
4717 $arr['visible'] = $visibility;
4721 'image/jpeg' => 'jpg',
4722 'image/png' => 'png',
4723 'image/gif' => 'gif'
4726 // adds link to the thumbnail scale photo
4727 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record[0]['nick'] . '/image/' . $hash . ']'
4728 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4731 // do the magic for storing the item in the database and trigger the federation to other contacts
4737 * @param string $type
4739 * @param string $photo_id
4743 function prepare_photo_data($type, $scale, $photo_id)
4745 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4746 $data_sql = ($scale === false ? "" : "data, ");
4748 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4749 // clients needs to convert this in their way for further processing
4751 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4752 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4753 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4754 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY `resource-id`",
4756 intval(local_user()),
4762 'image/jpeg' => 'jpg',
4763 'image/png' => 'png',
4764 'image/gif' => 'gif'
4767 // prepare output data for photo
4768 if (DBM::is_result($r)) {
4769 $data = ['photo' => $r[0]];
4770 $data['photo']['id'] = $data['photo']['resource-id'];
4771 if ($scale !== false) {
4772 $data['photo']['data'] = base64_encode($data['photo']['data']);
4774 unset($data['photo']['datasize']); //needed only with scale param
4776 if ($type == "xml") {
4777 $data['photo']['links'] = [];
4778 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4779 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4781 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4784 $data['photo']['link'] = [];
4785 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4787 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4788 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4792 unset($data['photo']['resource-id']);
4793 unset($data['photo']['minscale']);
4794 unset($data['photo']['maxscale']);
4796 throw new NotFoundException();
4799 // retrieve item element for getting activities (like, dislike etc.) related to photo
4801 "SELECT * FROM `item` WHERE `uid` = %d AND `resource-id` = '%s' AND `type` = 'photo'",
4802 intval(local_user()),
4805 $data['photo']['friendica_activities'] = api_format_items_activities($item[0], $type);
4807 // retrieve comments on photo
4809 "SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
4810 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
4811 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
4812 `contact`.`id` AS `cid`
4814 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
4815 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
4816 WHERE `item`.`parent` = %d AND `item`.`visible`
4817 AND NOT `item`.`moderated` AND NOT `item`.`deleted`
4818 AND `item`.`uid` = %d AND (`item`.`verb`='%s' OR `type`='photo')",
4819 intval($item[0]['parent']),
4821 dbesc(ACTIVITY_POST)
4824 // prepare output of comments
4825 $commentData = api_format_items($r, api_get_user(get_app()), false, $type);
4827 if ($type == "xml") {
4829 foreach ($commentData as $comment) {
4830 $comments[$k++ . ":comment"] = $comment;
4833 foreach ($commentData as $comment) {
4834 $comments[] = $comment;
4837 $data['photo']['friendica_comments'] = $comments;
4839 // include info if rights on photo and rights on item are mismatching
4840 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
4841 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
4842 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
4843 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
4844 $data['photo']['rights_mismatch'] = $rights_mismatch;
4851 * Similar as /mod/redir.php
4852 * redirect to 'url' after dfrn auth
4854 * Why this when there is mod/redir.php already?
4855 * This use api_user() and api_login()
4858 * c_url: url of remote contact to auth to
4859 * url: string, url to redirect after auth
4861 function api_friendica_remoteauth()
4863 $url = (x($_GET, 'url') ? $_GET['url'] : '');
4864 $c_url = (x($_GET, 'c_url') ? $_GET['c_url'] : '');
4866 if ($url === '' || $c_url === '') {
4867 throw new BadRequestException("Wrong parameters.");
4870 $c_url = normalise_link($c_url);
4874 $contact = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4876 if (!DBM::is_result($contact) || ($contact['network'] !== NETWORK_DFRN)) {
4877 throw new BadRequestException("Unknown contact");
4880 $cid = $contact['id'];
4882 $dfrn_id = defaults($contact, 'issued-id', $contact['dfrn-id']);
4884 if ($contact['duplex'] && $contact['issued-id']) {
4885 $orig_id = $contact['issued-id'];
4886 $dfrn_id = '1:' . $orig_id;
4888 if ($contact['duplex'] && $contact['dfrn-id']) {
4889 $orig_id = $contact['dfrn-id'];
4890 $dfrn_id = '0:' . $orig_id;
4893 $sec = random_string();
4896 "INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
4897 VALUES( %d, %s, '%s', '%s', %d )",
4905 logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG);
4906 $dest = ($url ? '&destination_url=' . $url : '');
4908 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4909 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4910 . '&type=profile&sec=' . $sec . $dest . $quiet
4913 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4916 * @brief Return the item shared, if the item contains only the [share] tag
4918 * @param array $item Sharer item
4919 * @return array|false Shared item or false if not a reshare
4921 function api_share_as_retweet(&$item)
4923 $body = trim($item["body"]);
4925 if (Diaspora::isReshare($body, false)===false) {
4929 /// @TODO "$1" should maybe mean '$1' ?
4930 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
4932 * Skip if there is no shared message in there
4933 * we already checked this in diaspora::isReshare()
4934 * but better one more than one less...
4936 if ($body == $attributes) {
4941 // build the fake reshared item
4942 $reshared_item = $item;
4945 preg_match("/author='(.*?)'/ism", $attributes, $matches);
4946 if ($matches[1] != "") {
4947 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
4950 preg_match('/author="(.*?)"/ism', $attributes, $matches);
4951 if ($matches[1] != "") {
4952 $author = $matches[1];
4956 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
4957 if ($matches[1] != "") {
4958 $profile = $matches[1];
4961 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
4962 if ($matches[1] != "") {
4963 $profile = $matches[1];
4967 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
4968 if ($matches[1] != "") {
4969 $avatar = $matches[1];
4972 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
4973 if ($matches[1] != "") {
4974 $avatar = $matches[1];
4978 preg_match("/link='(.*?)'/ism", $attributes, $matches);
4979 if ($matches[1] != "") {
4980 $link = $matches[1];
4983 preg_match('/link="(.*?)"/ism', $attributes, $matches);
4984 if ($matches[1] != "") {
4985 $link = $matches[1];
4989 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
4990 if ($matches[1] != "") {
4991 $posted = $matches[1];
4994 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
4995 if ($matches[1] != "") {
4996 $posted = $matches[1];
4999 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$2", $body);
5001 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5005 $reshared_item["body"] = $shared_body;
5006 $reshared_item["author-name"] = $author;
5007 $reshared_item["author-link"] = $profile;
5008 $reshared_item["author-avatar"] = $avatar;
5009 $reshared_item["plink"] = $link;
5010 $reshared_item["created"] = $posted;
5011 $reshared_item["edited"] = $posted;
5013 return $reshared_item;
5018 * @param string $profile
5020 * @return string|false
5021 * @todo remove trailing junk from profile url
5022 * @todo pump.io check has to check the website
5024 function api_get_nick($profile)
5029 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5030 dbesc(normalise_link($profile))
5033 if (DBM::is_result($r)) {
5034 $nick = $r[0]["nick"];
5039 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5040 dbesc(normalise_link($profile))
5043 if (DBM::is_result($r)) {
5044 $nick = $r[0]["nick"];
5049 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5050 if ($friendica != $profile) {
5056 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5057 if ($diaspora != $profile) {
5063 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5064 if ($twitter != $profile) {
5071 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5072 if ($StatusnetHost != $profile) {
5073 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5074 if ($StatusnetUser != $profile) {
5075 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5076 $user = json_decode($UserData);
5078 $nick = $user->screen_name;
5084 // To-Do: look at the page if its really a pumpio site
5085 //if (!$nick == "") {
5086 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5087 // if ($pumpio != $profile)
5089 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5102 * @param array $item
5106 function api_in_reply_to($item)
5110 $in_reply_to['status_id'] = null;
5111 $in_reply_to['user_id'] = null;
5112 $in_reply_to['status_id_str'] = null;
5113 $in_reply_to['user_id_str'] = null;
5114 $in_reply_to['screen_name'] = null;
5116 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5118 "SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
5119 intval($item['uid']),
5120 dbesc($item['thr-parent'])
5123 if (DBM::is_result($r)) {
5124 $in_reply_to['status_id'] = intval($r[0]['id']);
5126 $in_reply_to['status_id'] = intval($item['parent']);
5129 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5132 "SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
5133 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
5134 WHERE `item`.`id` = %d LIMIT 1",
5135 intval($in_reply_to['status_id'])
5138 if (DBM::is_result($r)) {
5139 if ($r[0]['nick'] == "") {
5140 $r[0]['nick'] = api_get_nick($r[0]["url"]);
5143 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
5144 $in_reply_to['user_id'] = intval($r[0]['id']);
5145 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
5148 // There seems to be situation, where both fields are identical:
5149 // https://github.com/friendica/friendica/issues/1010
5150 // This is a bugfix for that.
5151 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5152 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
5153 $in_reply_to['status_id'] = null;
5154 $in_reply_to['user_id'] = null;
5155 $in_reply_to['status_id_str'] = null;
5156 $in_reply_to['user_id_str'] = null;
5157 $in_reply_to['screen_name'] = null;
5161 return $in_reply_to;
5166 * @param string $Text
5170 function api_clean_plain_items($Text)
5172 $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
5174 $Text = bb_CleanPictureLinks($Text);
5175 $URLSearchString = "^\[\]";
5177 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text);
5179 if ($include_entities == "true") {
5180 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text);
5183 // Simplify "attachment" element
5184 $Text = api_clean_attachments($Text);
5190 * @brief Removes most sharing information for API text export
5192 * @param string $body The original body
5194 * @return string Cleaned body
5196 function api_clean_attachments($body)
5198 $data = get_attachment_data($body);
5205 if (isset($data["text"])) {
5206 $body = $data["text"];
5208 if (($body == "") && isset($data["title"])) {
5209 $body = $data["title"];
5211 if (isset($data["url"])) {
5212 $body .= "\n".$data["url"];
5214 $body .= $data["after"];
5221 * @param array $contacts
5225 function api_best_nickname(&$contacts)
5229 if (count($contact) == 0) {
5233 foreach ($contacts as $contact) {
5234 if ($contact["network"] == "") {
5235 $contact["network"] = "dfrn";
5236 $best_contact = [$contact];
5240 if (sizeof($best_contact) == 0) {
5241 foreach ($contacts as $contact) {
5242 if ($contact["network"] == "dfrn") {
5243 $best_contact = [$contact];
5248 if (sizeof($best_contact) == 0) {
5249 foreach ($contacts as $contact) {
5250 if ($contact["network"] == "dspr") {
5251 $best_contact = [$contact];
5256 if (sizeof($best_contact) == 0) {
5257 foreach ($contacts as $contact) {
5258 if ($contact["network"] == "stat") {
5259 $best_contact = [$contact];
5264 if (sizeof($best_contact) == 0) {
5265 foreach ($contacts as $contact) {
5266 if ($contact["network"] == "pump") {
5267 $best_contact = [$contact];
5272 if (sizeof($best_contact) == 0) {
5273 foreach ($contacts as $contact) {
5274 if ($contact["network"] == "twit") {
5275 $best_contact = [$contact];
5280 if (sizeof($best_contact) == 1) {
5281 $contacts = $best_contact;
5283 $contacts = [$contacts[0]];
5288 * Return all or a specified group of the user with the containing contacts.
5290 * @param string $type Return type (atom, rss, xml, json)
5292 * @return array|string
5294 function api_friendica_group_show($type)
5298 if (api_user() === false) {
5299 throw new ForbiddenException();
5303 $user_info = api_get_user($a);
5304 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5305 $uid = $user_info['uid'];
5307 // get data of the specified group id or all groups if not specified
5310 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5314 // error message if specified gid is not in database
5315 if (!DBM::is_result($r)) {
5316 throw new BadRequestException("gid not available");
5320 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5325 // loop through all groups and retrieve all members for adding data in the user array
5326 foreach ($r as $rr) {
5327 $members = Contact::getByGroupId($rr['id']);
5330 if ($type == "xml") {
5331 $user_element = "users";
5333 foreach ($members as $member) {
5334 $user = api_get_user($a, $member['nurl']);
5335 $users[$k++.":user"] = $user;
5338 $user_element = "user";
5339 foreach ($members as $member) {
5340 $user = api_get_user($a, $member['nurl']);
5344 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5346 return api_format_data("groups", $type, ['group' => $grps]);
5348 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5352 * Delete the specified group of the user.
5354 * @param string $type Return type (atom, rss, xml, json)
5356 * @return array|string
5358 function api_friendica_group_delete($type)
5362 if (api_user() === false) {
5363 throw new ForbiddenException();
5367 $user_info = api_get_user($a);
5368 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5369 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5370 $uid = $user_info['uid'];
5372 // error if no gid specified
5373 if ($gid == 0 || $name == "") {
5374 throw new BadRequestException('gid or name not specified');
5377 // get data of the specified group id
5379 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5383 // error message if specified gid is not in database
5384 if (!DBM::is_result($r)) {
5385 throw new BadRequestException('gid not available');
5388 // get data of the specified group id and group name
5390 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5395 // error message if specified gid is not in database
5396 if (!DBM::is_result($rname)) {
5397 throw new BadRequestException('wrong group name');
5401 $ret = Group::removeByName($uid, $name);
5404 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5405 return api_format_data("group_delete", $type, ['result' => $success]);
5407 throw new BadRequestException('other API error');
5410 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5414 * Create the specified group with the posted array of contacts.
5416 * @param string $type Return type (atom, rss, xml, json)
5418 * @return array|string
5420 function api_friendica_group_create($type)
5424 if (api_user() === false) {
5425 throw new ForbiddenException();
5429 $user_info = api_get_user($a);
5430 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5431 $uid = $user_info['uid'];
5432 $json = json_decode($_POST['json'], true);
5433 $users = $json['user'];
5435 // error if no name specified
5437 throw new BadRequestException('group name not specified');
5440 // get data of the specified group name
5442 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5446 // error message if specified group name already exists
5447 if (DBM::is_result($rname)) {
5448 throw new BadRequestException('group name already exists');
5451 // check if specified group name is a deleted group
5453 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5457 // error message if specified group name already exists
5458 if (DBM::is_result($rname)) {
5459 $reactivate_group = true;
5463 $ret = Group::create($uid, $name);
5465 $gid = Group::getIdByName($uid, $name);
5467 throw new BadRequestException('other API error');
5471 $erroraddinguser = false;
5473 foreach ($users as $user) {
5474 $cid = $user['cid'];
5475 // check if user really exists as contact
5477 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5481 if (count($contact)) {
5482 Group::addMember($gid, $cid);
5484 $erroraddinguser = true;
5485 $errorusers[] = $cid;
5489 // return success message incl. missing users in array
5490 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
5491 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5492 return api_format_data("group_create", $type, ['result' => $success]);
5494 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5498 * Update the specified group with the posted array of contacts.
5500 * @param string $type Return type (atom, rss, xml, json)
5502 * @return array|string
5504 function api_friendica_group_update($type)
5508 if (api_user() === false) {
5509 throw new ForbiddenException();
5513 $user_info = api_get_user($a);
5514 $uid = $user_info['uid'];
5515 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
5516 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
5517 $json = json_decode($_POST['json'], true);
5518 $users = $json['user'];
5520 // error if no name specified
5522 throw new BadRequestException('group name not specified');
5525 // error if no gid specified
5527 throw new BadRequestException('gid not specified');
5531 $members = Contact::getByGroupId($gid);
5532 foreach ($members as $member) {
5533 $cid = $member['id'];
5534 foreach ($users as $user) {
5535 $found = ($user['cid'] == $cid ? true : false);
5538 Group::removeMemberByName($uid, $name, $cid);
5543 $erroraddinguser = false;
5545 foreach ($users as $user) {
5546 $cid = $user['cid'];
5547 // check if user really exists as contact
5549 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5554 if (count($contact)) {
5555 Group::addMember($gid, $cid);
5557 $erroraddinguser = true;
5558 $errorusers[] = $cid;
5562 // return success message incl. missing users in array
5563 $status = ($erroraddinguser ? "missing user" : "ok");
5564 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5565 return api_format_data("group_update", $type, ['result' => $success]);
5568 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5572 * @param string $type Return type (atom, rss, xml, json)
5574 * @return array|string
5576 function api_friendica_activity($type)
5580 if (api_user() === false) {
5581 throw new ForbiddenException();
5583 $verb = strtolower($a->argv[3]);
5584 $verb = preg_replace("|\..*$|", "", $verb);
5586 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5588 $res = do_like($id, $verb);
5591 if ($type == "xml") {
5596 return api_format_data('ok', $type, ['ok' => $ok]);
5598 throw new BadRequestException('Error adding activity');
5602 /// @TODO move to top of file or somewhere better
5603 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5604 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5605 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5606 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5607 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5608 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5609 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5610 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5611 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5612 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5615 * @brief Returns notifications
5617 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5620 function api_friendica_notification($type)
5624 if (api_user() === false) {
5625 throw new ForbiddenException();
5628 throw new BadRequestException("Invalid argument count");
5630 $nm = new NotificationsManager();
5632 $notes = $nm->getAll([], "+seen -date", 50);
5634 if ($type == "xml") {
5636 foreach ($notes as $note) {
5637 $xmlnotes[] = ["@attributes" => $note];
5643 return api_format_data("notes", $type, ['note' => $notes]);
5647 * POST request with 'id' param as notification id
5649 * @brief Set notification as seen and returns associated item (if possible)
5651 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5654 function api_friendica_notification_seen($type)
5658 if (api_user() === false) {
5659 throw new ForbiddenException();
5662 throw new BadRequestException("Invalid argument count");
5665 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
5667 $nm = new NotificationsManager();
5668 $note = $nm->getByID($id);
5669 if (is_null($note)) {
5670 throw new BadRequestException("Invalid argument");
5673 $nm->setSeen($note);
5674 if ($note['otype']=='item') {
5675 // would be really better with an ItemsManager and $im->getByID() :-P
5677 "SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
5678 intval($note['iid']),
5679 intval(local_user())
5682 // we found the item, return it to the user
5683 $user_info = api_get_user($a);
5684 $ret = api_format_items($r, $user_info, false, $type);
5685 $data = ['status' => $ret];
5686 return api_format_data("status", $type, $data);
5688 // the item can't be found, but we set the note as seen, so we count this as a success
5690 return api_format_data('result', $type, ['result' => "success"]);
5693 /// @TODO move to top of file or somewhere better
5694 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5695 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5698 * @brief update a direct_message to seen state
5700 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5701 * @return string (success result=ok, error result=error with error message)
5703 function api_friendica_direct_messages_setseen($type)
5706 if (api_user() === false) {
5707 throw new ForbiddenException();
5711 $user_info = api_get_user($a);
5712 $uid = $user_info['uid'];
5713 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
5715 // return error if id is zero
5717 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5718 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5721 // get data of the specified message id
5723 "SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
5728 // error message if specified id is not in database
5729 if (!DBM::is_result($r)) {
5730 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5731 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5734 // update seen indicator
5736 "UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
5743 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5744 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5746 $answer = ['result' => 'error', 'message' => 'unknown error'];
5747 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5751 /// @TODO move to top of file or somewhere better
5752 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5755 * @brief search for direct_messages containing a searchstring through api
5757 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5758 * @return string (success: success=true if found and search_result contains found messages,
5759 * success=false if nothing was found, search_result='nothing found',
5760 * error: result=error with error message)
5762 function api_friendica_direct_messages_search($type)
5766 if (api_user() === false) {
5767 throw new ForbiddenException();
5771 $user_info = api_get_user($a);
5772 $searchstring = (x($_REQUEST, 'searchstring') ? $_REQUEST['searchstring'] : "");
5773 $uid = $user_info['uid'];
5775 // error if no searchstring specified
5776 if ($searchstring == "") {
5777 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5778 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5781 // get data for the specified searchstring
5783 "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",
5785 dbesc('%'.$searchstring.'%')
5788 $profile_url = $user_info["url"];
5790 // message if nothing was found
5791 if (!DBM::is_result($r)) {
5792 $success = ['success' => false, 'search_results' => 'problem with query'];
5793 } elseif (count($r) == 0) {
5794 $success = ['success' => false, 'search_results' => 'nothing found'];
5797 foreach ($r as $item) {
5798 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5799 $recipient = $user_info;
5800 $sender = api_get_user($a, normalise_link($item['contact-url']));
5801 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5802 $recipient = api_get_user($a, normalise_link($item['contact-url']));
5803 $sender = $user_info;
5806 $ret[] = api_format_messages($item, $recipient, $sender);
5808 $success = ['success' => true, 'search_results' => $ret];
5811 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5814 /// @TODO move to top of file or somewhere better
5815 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5818 * @brief return data of all the profiles a user has to the client
5820 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5823 function api_friendica_profile_show($type)
5827 if (api_user() === false) {
5828 throw new ForbiddenException();
5832 $profileid = (x($_REQUEST, 'profile_id') ? $_REQUEST['profile_id'] : 0);
5834 // retrieve general information about profiles for user
5835 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
5836 $directory = Config::get('system', 'directory');
5838 // get data of the specified profile id or all profiles of the user if not specified
5839 if ($profileid != 0) {
5841 "SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
5846 // error message if specified gid is not in database
5847 if (!DBM::is_result($r)) {
5848 throw new BadRequestException("profile_id not available");
5852 "SELECT * FROM `profile` WHERE `uid` = %d",
5856 // loop through all returned profiles and retrieve data and users
5858 foreach ($r as $rr) {
5859 $profile = api_format_items_profiles($rr);
5861 // select all users from contact table, loop and prepare standard return for user data
5864 "SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
5866 intval($rr['profile_id'])
5869 foreach ($r as $rr) {
5870 $user = api_get_user($a, $rr['nurl']);
5871 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
5873 $profile['users'] = $users;
5875 // add prepared profile data to array for final return
5876 if ($type == "xml") {
5877 $profiles[$k++ . ":profile"] = $profile;
5879 $profiles[] = $profile;
5883 // return settings, authenticated user and profiles data
5884 $self = q("SELECT `nurl` FROM `contact` WHERE `uid`= %d AND `self` LIMIT 1", intval(api_user()));
5886 $result = ['multi_profiles' => $multi_profiles ? true : false,
5887 'global_dir' => $directory,
5888 'friendica_owner' => api_get_user($a, $self[0]['nurl']),
5889 'profiles' => $profiles];
5890 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
5892 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
5895 * Returns a list of saved searches.
5897 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5899 * @param string $type Return format: json or xml
5901 * @return string|array
5903 function api_saved_searches_list($type)
5905 $terms = dba::select('search', ['id', 'term'], ['uid' => local_user()]);
5908 while ($term = $terms->fetch()) {
5910 'name' => $term['term'],
5911 'query' => $term['term'],
5912 'id_str' => $term['id'],
5913 'id' => intval($term['id'])
5919 return api_format_data("terms", $type, ['terms' => $result]);
5922 /// @TODO move to top of file or somewhere better
5923 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5926 @TODO Maybe open to implement?
5928 [pagename] => api/1.1/statuses/lookup.json
5929 [id] => 605138389168451584
5930 [include_cards] => true
5931 [cards_platform] => Android-12
5932 [include_entities] => true
5933 [include_my_retweet] => 1
5935 [include_reply_count] => true
5936 [include_descendent_reply_count] => true
5940 Not implemented by now:
5941 statuses/retweets_of_me
5946 account/update_location
5947 account/update_profile_background_image
5950 friendica/profile/update
5951 friendica/profile/create
5952 friendica/profile/delete
5954 Not implemented in status.net:
5955 statuses/retweeted_to_me
5956 statuses/retweeted_by_me
5957 direct_messages/destroy
5959 account/update_delivery_device
5960 notifications/follow