3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Session;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Network\FKOAuth1;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPException\BadRequestException;
35 use Friendica\Network\HTTPException\ExpectationFailedException;
36 use Friendica\Network\HTTPException\ForbiddenException;
37 use Friendica\Network\HTTPException\InternalServerErrorException;
38 use Friendica\Network\HTTPException\MethodNotAllowedException;
39 use Friendica\Network\HTTPException\NotFoundException;
40 use Friendica\Network\HTTPException\NotImplementedException;
41 use Friendica\Network\HTTPException\TooManyRequestsException;
42 use Friendica\Network\HTTPException\UnauthorizedException;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Activity;
45 use Friendica\Protocol\Diaspora;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy as ProxyUtils;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
53 require_once __DIR__ . '/../mod/share.php';
54 require_once __DIR__ . '/../mod/item.php';
55 require_once __DIR__ . '/../mod/wall_upload.php';
57 define('API_METHOD_ANY', '*');
58 define('API_METHOD_GET', 'GET');
59 define('API_METHOD_POST', 'POST,PUT');
60 define('API_METHOD_DELETE', 'POST,DELETE');
62 define('API_LOG_PREFIX', 'API {action} - ');
68 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
69 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
70 * into a page, and visitors will post something without noticing it).
72 * @brief Auth API user
76 if (!empty($_SESSION['allow_api'])) {
84 * Clients can send 'source' parameter to be show in post metadata
85 * as "sent via <source>".
86 * Some clients doesn't send a source param, we support ones we know
89 * @brief Get source name from API client
92 * Client source name, default to "api" if unset/unknown
97 if (requestdata('source')) {
98 return requestdata('source');
101 // Support for known clients that doesn't send a source name
102 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
103 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
107 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
109 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
116 * @brief Format date for API
118 * @param string $str Source date, as UTC
119 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
122 function api_date($str)
124 // Wed May 23 06:01:13 +0000 2007
125 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
129 * Register a function to be the endpoint for defined API path.
131 * @brief Register API endpoint
133 * @param string $path API URL path, relative to System::baseUrl()
134 * @param string $func Function name to call on path request
135 * @param bool $auth API need logged user
136 * @param string $method HTTP method reqiured to call this endpoint.
137 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
138 * Default to API_METHOD_ANY
140 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
150 // Workaround for hotot
151 $path = str_replace("api/", "api/1.1/", $path);
161 * Log in user via OAuth1 or Simple HTTP Auth.
162 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
164 * @brief Login API user
167 * @throws ForbiddenException
168 * @throws InternalServerErrorException
169 * @throws UnauthorizedException
170 * @hook 'authenticate'
172 * 'username' => username from login form
173 * 'password' => password from login form
174 * 'authenticated' => return status,
175 * 'user_record' => return authenticated user record
177 function api_login(App $a)
179 $oauth1 = new FKOAuth1();
182 $request = OAuthRequest::from_request();
183 list($consumer, $token) = $oauth1->verify_request($request);
184 if (!is_null($token)) {
185 $oauth1->loginUser($token->uid);
186 Session::set('allow_api', true);
189 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
190 var_dump($consumer, $token);
192 } catch (Exception $e) {
193 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
196 // workaround for HTTP-auth in CGI mode
197 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
198 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
199 if (strlen($userpass)) {
200 list($name, $password) = explode(':', $userpass);
201 $_SERVER['PHP_AUTH_USER'] = $name;
202 $_SERVER['PHP_AUTH_PW'] = $password;
206 if (empty($_SERVER['PHP_AUTH_USER'])) {
207 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
208 header('WWW-Authenticate: Basic realm="Friendica"');
209 throw new UnauthorizedException("This API requires login");
212 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
213 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
215 // allow "user@server" login (but ignore 'server' part)
216 $at = strstr($user, "@", true);
221 // next code from mod/auth.php. needs better solution
225 'username' => trim($user),
226 'password' => trim($password),
227 'authenticated' => 0,
228 'user_record' => null,
232 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
233 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
234 * and later addons should not interfere with an earlier one that succeeded.
236 Hook::callAll('authenticate', $addon_auth);
238 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
239 $record = $addon_auth['user_record'];
241 $user_id = User::authenticate(trim($user), trim($password), true);
242 if ($user_id !== false) {
243 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
247 if (!DBA::isResult($record)) {
248 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
249 header('WWW-Authenticate: Basic realm="Friendica"');
250 //header('HTTP/1.0 401 Unauthorized');
251 //die('This api requires login');
252 throw new UnauthorizedException("This API requires login");
255 DI::auth()->setForUser($a, $record);
257 $_SESSION["allow_api"] = true;
259 Hook::callAll('logged_in', $a->user);
263 * API endpoints can define which HTTP method to accept when called.
264 * This function check the current HTTP method agains endpoint
267 * @brief Check HTTP method of called API
269 * @param string $method Required methods, uppercase, separated by comma
272 function api_check_method($method)
274 if ($method == "*") {
277 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
281 * Authenticate user, call registered API function, set HTTP headers
283 * @brief Main API entry point
286 * @return string|array API call result
289 function api_call(App $a)
291 global $API, $called_api;
294 if (strpos($a->query_string, ".xml") > 0) {
297 if (strpos($a->query_string, ".json") > 0) {
300 if (strpos($a->query_string, ".rss") > 0) {
303 if (strpos($a->query_string, ".atom") > 0) {
308 foreach ($API as $p => $info) {
309 if (strpos($a->query_string, $p) === 0) {
310 if (!api_check_method($info['method'])) {
311 throw new MethodNotAllowedException();
314 $called_api = explode("/", $p);
315 //unset($_SERVER['PHP_AUTH_USER']);
317 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
318 if (!empty($info['auth']) && api_user() === false) {
322 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
323 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
325 $stamp = microtime(true);
326 $return = call_user_func($info['func'], $type);
327 $duration = floatval(microtime(true) - $stamp);
329 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
331 $a->getProfiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
333 if (false === $return) {
335 * api function returned false withour throw an
336 * exception. This should not happend, throw a 500
338 throw new InternalServerErrorException();
343 header("Content-Type: text/xml");
346 header("Content-Type: application/json");
347 if (!empty($return)) {
348 $json = json_encode(end($return));
349 if (!empty($_GET['callback'])) {
350 $json = $_GET['callback'] . "(" . $json . ")";
356 header("Content-Type: application/rss+xml");
357 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
360 header("Content-Type: application/atom+xml");
361 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
368 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
369 throw new NotImplementedException();
370 } catch (HTTPException $e) {
371 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
372 return api_error($type, $e);
377 * @brief Format API error string
379 * @param string $type Return type (xml, json, rss, as)
380 * @param object $e HTTPException Error object
381 * @return string|array error message formatted as $type
383 function api_error($type, $e)
387 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
388 /// @TODO: https://dev.twitter.com/overview/api/response-codes
390 $error = ["error" => $error,
391 "code" => $e->getCode() . " " . $e->httpdesc,
392 "request" => $a->query_string];
394 $return = api_format_data('status', $type, ['status' => $error]);
398 header("Content-Type: text/xml");
401 header("Content-Type: application/json");
402 $return = json_encode($return);
405 header("Content-Type: application/rss+xml");
408 header("Content-Type: application/atom+xml");
416 * @brief Set values for RSS template
419 * @param array $arr Array to be passed to template
420 * @param array $user_info User info
422 * @throws BadRequestException
423 * @throws ImagickException
424 * @throws InternalServerErrorException
425 * @throws UnauthorizedException
426 * @todo find proper type-hints
428 function api_rss_extra(App $a, $arr, $user_info)
430 if (is_null($user_info)) {
431 $user_info = api_get_user($a);
434 $arr['$user'] = $user_info;
436 'alternate' => $user_info['url'],
437 'self' => System::baseUrl() . "/" . $a->query_string,
438 'base' => System::baseUrl(),
439 'updated' => api_date(null),
440 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
441 'language' => $user_info['lang'],
442 'logo' => System::baseUrl() . "/images/friendica-32.png",
450 * @brief Unique contact to contact url.
452 * @param int $id Contact id
453 * @return bool|string
454 * Contact url or False if contact id is unknown
457 function api_unique_id_to_nurl($id)
459 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
461 if (DBA::isResult($r)) {
469 * @brief Get user info array.
472 * @param int|string $contact_id Contact ID or URL
474 * @throws BadRequestException
475 * @throws ImagickException
476 * @throws InternalServerErrorException
477 * @throws UnauthorizedException
479 function api_get_user(App $a, $contact_id = null)
487 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
489 // Searching for contact URL
490 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
491 $user = DBA::escape(Strings::normaliseLink($contact_id));
493 $extra_query = "AND `contact`.`nurl` = '%s' ";
494 if (api_user() !== false) {
495 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
499 // Searching for contact id with uid = 0
500 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
501 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
504 throw new BadRequestException("User ID ".$contact_id." not found.");
508 $extra_query = "AND `contact`.`nurl` = '%s' ";
509 if (api_user() !== false) {
510 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
514 if (is_null($user) && !empty($_GET['user_id'])) {
515 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
518 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && !empty($_GET['screen_name'])) {
528 $user = DBA::escape($_GET['screen_name']);
529 $extra_query = "AND `contact`.`nick` = '%s' ";
530 if (api_user() !== false) {
531 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
535 if (is_null($user) && !empty($_GET['profileurl'])) {
536 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
537 $extra_query = "AND `contact`.`nurl` = '%s' ";
538 if (api_user() !== false) {
539 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
543 // $called_api is the API path exploded on / and is expected to have at least 2 elements
544 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
545 $argid = count($called_api);
546 if (!empty($a->argv[$argid])) {
547 $data = explode(".", $a->argv[$argid]);
548 if (count($data) > 1) {
549 list($user, $null) = $data;
552 if (is_numeric($user)) {
553 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
557 $extra_query = "AND `contact`.`nurl` = '%s' ";
558 if (api_user() !== false) {
559 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
563 $user = DBA::escape($user);
564 $extra_query = "AND `contact`.`nick` = '%s' ";
565 if (api_user() !== false) {
566 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
571 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
574 if (api_user() === false) {
578 $user = $_SESSION['uid'];
579 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
583 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
587 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
593 // Selecting the id by priority, friendica first
594 if (is_array($uinfo)) {
595 api_best_nickname($uinfo);
598 // if the contact wasn't found, fetch it from the contacts with uid = 0
599 if (!DBA::isResult($uinfo)) {
601 throw new BadRequestException("User not found.");
604 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
606 if (DBA::isResult($contact)) {
608 'id' => $contact["id"],
609 'id_str' => (string) $contact["id"],
610 'name' => $contact["name"],
611 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
612 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
613 'description' => BBCode::toPlaintext($contact["about"]),
614 'profile_image_url' => $contact["micro"],
615 'profile_image_url_https' => $contact["micro"],
616 'profile_image_url_profile_size' => $contact["thumb"],
617 'profile_image_url_large' => $contact["photo"],
618 'url' => $contact["url"],
619 'protected' => false,
620 'followers_count' => 0,
621 'friends_count' => 0,
623 'created_at' => api_date($contact["created"]),
624 'favourites_count' => 0,
626 'time_zone' => 'UTC',
627 'geo_enabled' => false,
629 'statuses_count' => 0,
631 'contributors_enabled' => false,
632 'is_translator' => false,
633 'is_translation_enabled' => false,
634 'following' => false,
635 'follow_request_sent' => false,
636 'statusnet_blocking' => false,
637 'notifications' => false,
638 'statusnet_profile_url' => $contact["url"],
640 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
641 'pid' => Contact::getIdForURL($contact["url"], 0, true),
643 'network' => $contact["network"],
648 throw new BadRequestException("User ".$url." not found.");
652 if ($uinfo[0]['self']) {
653 if ($uinfo[0]['network'] == "") {
654 $uinfo[0]['network'] = Protocol::DFRN;
657 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
658 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
665 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
667 if (!empty($profile['about'])) {
668 $description = $profile['about'];
670 $description = $uinfo[0]["about"];
673 if (!empty($usr['default-location'])) {
674 $location = $usr['default-location'];
675 } elseif (!empty($uinfo[0]["location"])) {
676 $location = $uinfo[0]["location"];
678 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
682 'id' => intval($pcontact_id),
683 'id_str' => (string) intval($pcontact_id),
684 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
685 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
686 'location' => $location,
687 'description' => BBCode::toPlaintext($description),
688 'profile_image_url' => $uinfo[0]['micro'],
689 'profile_image_url_https' => $uinfo[0]['micro'],
690 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
691 'profile_image_url_large' => $uinfo[0]["photo"],
692 'url' => $uinfo[0]['url'],
693 'protected' => false,
694 'followers_count' => intval($countfollowers),
695 'friends_count' => intval($countfriends),
697 'created_at' => api_date($uinfo[0]['created']),
698 'favourites_count' => intval($starred),
700 'time_zone' => 'UTC',
701 'geo_enabled' => false,
703 'statuses_count' => intval($countitems),
705 'contributors_enabled' => false,
706 'is_translator' => false,
707 'is_translation_enabled' => false,
708 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
709 'follow_request_sent' => false,
710 'statusnet_blocking' => false,
711 'notifications' => false,
713 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
714 'statusnet_profile_url' => $uinfo[0]['url'],
715 'uid' => intval($uinfo[0]['uid']),
716 'cid' => intval($uinfo[0]['cid']),
717 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
718 'self' => $uinfo[0]['self'],
719 'network' => $uinfo[0]['network'],
722 // If this is a local user and it uses Frio, we can get its color preferences.
724 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
725 if ($theme_info['theme'] === 'frio') {
726 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
728 if ($schema && ($schema != '---')) {
729 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
730 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
731 require_once $schemefile;
734 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
735 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
736 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
738 if (empty($nav_bg)) {
741 if (empty($link_color)) {
742 $link_color = "#6fdbe8";
744 if (empty($bgcolor)) {
745 $bgcolor = "#ededed";
748 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
749 $ret['profile_link_color'] = str_replace('#', '', $link_color);
750 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
758 * @brief return api-formatted array for item's author and owner
761 * @param array $item item from db
762 * @return array(array:author, array:owner)
763 * @throws BadRequestException
764 * @throws ImagickException
765 * @throws InternalServerErrorException
766 * @throws UnauthorizedException
768 function api_item_get_user(App $a, $item)
770 $status_user = api_get_user($a, $item['author-id'] ?? null);
772 $author_user = $status_user;
774 $status_user["protected"] = $item['private'] ?? 0;
776 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
777 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
779 $owner_user = $author_user;
782 return ([$status_user, $author_user, $owner_user]);
786 * @brief walks recursively through an array with the possibility to change value and key
788 * @param array $array The array to walk through
789 * @param callable $callback The callback function
791 * @return array the transformed array
793 function api_walk_recursive(array &$array, callable $callback)
797 foreach ($array as $k => $v) {
799 if ($callback($v, $k)) {
800 $new_array[$k] = api_walk_recursive($v, $callback);
803 if ($callback($v, $k)) {
814 * @brief Callback function to transform the array in an array that can be transformed in a XML file
816 * @param mixed $item Array item value
817 * @param string $key Array key
819 * @return boolean Should the array item be deleted?
821 function api_reformat_xml(&$item, &$key)
823 if (is_bool($item)) {
824 $item = ($item ? "true" : "false");
827 if (substr($key, 0, 10) == "statusnet_") {
828 $key = "statusnet:".substr($key, 10);
829 } elseif (substr($key, 0, 10) == "friendica_") {
830 $key = "friendica:".substr($key, 10);
832 /// @TODO old-lost code?
834 // $key = "default:".$key;
840 * @brief Creates the XML from a JSON style array
842 * @param array $data JSON style array
843 * @param string $root_element Name of the root element
845 * @return string The XML data
847 function api_create_xml(array $data, $root_element)
849 $childname = key($data);
850 $data2 = array_pop($data);
852 $namespaces = ["" => "http://api.twitter.com",
853 "statusnet" => "http://status.net/schema/api/1/",
854 "friendica" => "http://friendi.ca/schema/api/1/",
855 "georss" => "http://www.georss.org/georss"];
857 /// @todo Auto detection of needed namespaces
858 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
862 if (is_array($data2)) {
864 api_walk_recursive($data2, "api_reformat_xml");
870 foreach ($data2 as $item) {
871 $data4[$i++ . ":" . $childname] = $item;
878 $data3 = [$root_element => $data2];
880 $ret = XML::fromArray($data3, $xml, false, $namespaces);
885 * @brief Formats the data according to the data type
887 * @param string $root_element Name of the root element
888 * @param string $type Return type (atom, rss, xml, json)
889 * @param array $data JSON style array
891 * @return array|string (string|array) XML data or JSON data
893 function api_format_data($root_element, $type, $data)
899 $ret = api_create_xml($data, $root_element);
914 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
915 * returns a 401 status code and an error message if not.
917 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
919 * @param string $type Return type (atom, rss, xml, json)
920 * @return array|string
921 * @throws BadRequestException
922 * @throws ForbiddenException
923 * @throws ImagickException
924 * @throws InternalServerErrorException
925 * @throws UnauthorizedException
927 function api_account_verify_credentials($type)
931 if (api_user() === false) {
932 throw new ForbiddenException();
935 unset($_REQUEST["user_id"]);
936 unset($_GET["user_id"]);
938 unset($_REQUEST["screen_name"]);
939 unset($_GET["screen_name"]);
941 $skip_status = $_REQUEST['skip_status'] ?? false;
943 $user_info = api_get_user($a);
945 // "verified" isn't used here in the standard
946 unset($user_info["verified"]);
948 // - Adding last status
950 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
952 $user_info['status'] = api_format_item($item, $type);
956 // "uid" and "self" are only needed for some internal stuff, so remove it from here
957 unset($user_info["uid"]);
958 unset($user_info["self"]);
960 return api_format_data("user", $type, ['user' => $user_info]);
963 /// @TODO move to top of file or somewhere better
964 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
967 * Get data from $_POST or $_GET
972 function requestdata($k)
974 if (!empty($_POST[$k])) {
977 if (!empty($_GET[$k])) {
984 * Deprecated function to upload media.
986 * @param string $type Return type (atom, rss, xml, json)
988 * @return array|string
989 * @throws BadRequestException
990 * @throws ForbiddenException
991 * @throws ImagickException
992 * @throws InternalServerErrorException
993 * @throws UnauthorizedException
995 function api_statuses_mediap($type)
999 if (api_user() === false) {
1000 Logger::log('api_statuses_update: no user');
1001 throw new ForbiddenException();
1003 $user_info = api_get_user($a);
1005 $_REQUEST['profile_uid'] = api_user();
1006 $_REQUEST['api_source'] = true;
1007 $txt = requestdata('status');
1008 /// @TODO old-lost code?
1009 //$txt = urldecode(requestdata('status'));
1011 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1012 $txt = HTML::toBBCodeVideo($txt);
1013 $config = HTMLPurifier_Config::createDefault();
1014 $config->set('Cache.DefinitionImpl', null);
1015 $purifier = new HTMLPurifier($config);
1016 $txt = $purifier->purify($txt);
1018 $txt = HTML::toBBCode($txt);
1020 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1022 $picture = wall_upload_post($a, false);
1024 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1025 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1026 $item_id = item_post($a);
1028 // output the post that we just posted.
1029 return api_status_show($type, $item_id);
1032 /// @TODO move this to top of file or somewhere better!
1033 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1036 * Updates the user’s current status.
1038 * @param string $type Return type (atom, rss, xml, json)
1040 * @return array|string
1041 * @throws BadRequestException
1042 * @throws ForbiddenException
1043 * @throws ImagickException
1044 * @throws InternalServerErrorException
1045 * @throws TooManyRequestsException
1046 * @throws UnauthorizedException
1047 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1049 function api_statuses_update($type)
1053 if (api_user() === false) {
1054 Logger::log('api_statuses_update: no user');
1055 throw new ForbiddenException();
1060 // convert $_POST array items to the form we use for web posts.
1061 if (requestdata('htmlstatus')) {
1062 $txt = requestdata('htmlstatus');
1063 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1064 $txt = HTML::toBBCodeVideo($txt);
1066 $config = HTMLPurifier_Config::createDefault();
1067 $config->set('Cache.DefinitionImpl', null);
1069 $purifier = new HTMLPurifier($config);
1070 $txt = $purifier->purify($txt);
1072 $_REQUEST['body'] = HTML::toBBCode($txt);
1075 $_REQUEST['body'] = requestdata('status');
1078 $_REQUEST['title'] = requestdata('title');
1080 $parent = requestdata('in_reply_to_status_id');
1082 // Twidere sends "-1" if it is no reply ...
1083 if ($parent == -1) {
1087 if (ctype_digit($parent)) {
1088 $_REQUEST['parent'] = $parent;
1090 $_REQUEST['parent_uri'] = $parent;
1093 if (requestdata('lat') && requestdata('long')) {
1094 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1096 $_REQUEST['profile_uid'] = api_user();
1099 // Check for throttling (maximum posts per day, week and month)
1100 $throttle_day = Config::get('system', 'throttle_limit_day');
1101 if ($throttle_day > 0) {
1102 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1104 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1105 $posts_day = DBA::count('thread', $condition);
1107 if ($posts_day > $throttle_day) {
1108 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1109 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1110 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1114 $throttle_week = Config::get('system', 'throttle_limit_week');
1115 if ($throttle_week > 0) {
1116 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1118 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1119 $posts_week = DBA::count('thread', $condition);
1121 if ($posts_week > $throttle_week) {
1122 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1123 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1124 throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1128 $throttle_month = Config::get('system', 'throttle_limit_month');
1129 if ($throttle_month > 0) {
1130 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1132 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1133 $posts_month = DBA::count('thread', $condition);
1135 if ($posts_month > $throttle_month) {
1136 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1137 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1138 throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1143 if (!empty($_FILES['media'])) {
1144 // upload the image if we have one
1145 $picture = wall_upload_post($a, false);
1146 if (is_array($picture)) {
1147 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1151 if (requestdata('media_ids')) {
1152 $ids = explode(',', requestdata('media_ids'));
1153 foreach ($ids as $id) {
1155 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` 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",
1159 if (DBA::isResult($r)) {
1160 $phototypes = Images::supportedTypes();
1161 $ext = $phototypes[$r[0]['type']];
1162 $description = $r[0]['desc'] ?? '';
1163 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1164 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1169 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1171 $_REQUEST['api_source'] = true;
1173 if (empty($_REQUEST['source'])) {
1174 $_REQUEST["source"] = api_source();
1177 // call out normal post function
1178 $item_id = item_post($a);
1180 // output the post that we just posted.
1181 return api_status_show($type, $item_id);
1184 /// @TODO move to top of file or somewhere better
1185 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1186 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1189 * Uploads an image to Friendica.
1192 * @throws BadRequestException
1193 * @throws ForbiddenException
1194 * @throws ImagickException
1195 * @throws InternalServerErrorException
1196 * @throws UnauthorizedException
1197 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1199 function api_media_upload()
1203 if (api_user() === false) {
1204 Logger::log('no user');
1205 throw new ForbiddenException();
1210 if (empty($_FILES['media'])) {
1212 throw new BadRequestException("No media.");
1215 $media = wall_upload_post($a, false);
1218 throw new InternalServerErrorException();
1222 $returndata["media_id"] = $media["id"];
1223 $returndata["media_id_string"] = (string)$media["id"];
1224 $returndata["size"] = $media["size"];
1225 $returndata["image"] = ["w" => $media["width"],
1226 "h" => $media["height"],
1227 "image_type" => $media["type"],
1228 "friendica_preview_url" => $media["preview"]];
1230 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1232 return ["media" => $returndata];
1235 /// @TODO move to top of file or somewhere better
1236 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1239 * Updates media meta data (picture descriptions)
1241 * @param string $type Return type (atom, rss, xml, json)
1243 * @return array|string
1244 * @throws BadRequestException
1245 * @throws ForbiddenException
1246 * @throws ImagickException
1247 * @throws InternalServerErrorException
1248 * @throws TooManyRequestsException
1249 * @throws UnauthorizedException
1250 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1252 * @todo Compare the corresponding Twitter function for correct return values
1254 function api_media_metadata_create($type)
1258 if (api_user() === false) {
1259 Logger::info('no user');
1260 throw new ForbiddenException();
1265 $postdata = Network::postdata();
1267 if (empty($postdata)) {
1268 throw new BadRequestException("No post data");
1271 $data = json_decode($postdata, true);
1273 throw new BadRequestException("Invalid post data");
1276 if (empty($data['media_id']) || empty($data['alt_text'])) {
1277 throw new BadRequestException("Missing post data values");
1280 if (empty($data['alt_text']['text'])) {
1281 throw new BadRequestException("No alt text.");
1284 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1286 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1287 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1288 if (!DBA::isResult($photo)) {
1289 throw new BadRequestException("Metadata not found.");
1292 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1295 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1298 * @param string $type Return format (atom, rss, xml, json)
1299 * @param int $item_id
1303 function api_status_show($type, $item_id)
1305 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1309 $item = api_get_item(['id' => $item_id]);
1310 if (!empty($item)) {
1311 $status_info = api_format_item($item, $type);
1314 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1316 return api_format_data('statuses', $type, ['status' => $status_info]);
1320 * Retrieves the last public status of the provided user info
1322 * @param int $ownerId Public contact Id
1323 * @param int $uid User Id
1327 function api_get_last_status($ownerId, $uid)
1330 'author-id'=> $ownerId,
1332 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1336 $item = api_get_item($condition);
1342 * Retrieves a single item record based on the provided condition and converts it for API use.
1344 * @param array $condition Item table condition array
1348 function api_get_item(array $condition)
1350 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1356 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1357 * The author's most recent status will be returned inline.
1359 * @param string $type Return type (atom, rss, xml, json)
1360 * @return array|string
1361 * @throws BadRequestException
1362 * @throws ImagickException
1363 * @throws InternalServerErrorException
1364 * @throws UnauthorizedException
1365 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1367 function api_users_show($type)
1369 $a = Friendica\DI::app();
1371 $user_info = api_get_user($a);
1373 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1374 if (!empty($item)) {
1375 $user_info['status'] = api_format_item($item, $type);
1378 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1379 unset($user_info['uid']);
1380 unset($user_info['self']);
1382 return api_format_data('user', $type, ['user' => $user_info]);
1385 /// @TODO move to top of file or somewhere better
1386 api_register_func('api/users/show', 'api_users_show');
1387 api_register_func('api/externalprofile/show', 'api_users_show');
1390 * Search a public user account.
1392 * @param string $type Return type (atom, rss, xml, json)
1394 * @return array|string
1395 * @throws BadRequestException
1396 * @throws ImagickException
1397 * @throws InternalServerErrorException
1398 * @throws UnauthorizedException
1399 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1401 function api_users_search($type)
1407 if (!empty($_GET['q'])) {
1408 $contacts = Contact::selectToArray(
1411 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1419 if (DBA::isResult($contacts)) {
1421 foreach ($contacts as $contact) {
1422 $user_info = api_get_user($a, $contact['id']);
1424 if ($type == 'xml') {
1425 $userlist[$k++ . ':user'] = $user_info;
1427 $userlist[] = $user_info;
1430 $userlist = ['users' => $userlist];
1432 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1435 throw new BadRequestException('No search term specified.');
1438 return api_format_data('users', $type, $userlist);
1441 /// @TODO move to top of file or somewhere better
1442 api_register_func('api/users/search', 'api_users_search');
1445 * Return user objects
1447 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1449 * @param string $type Return format: json or xml
1451 * @return array|string
1452 * @throws BadRequestException
1453 * @throws ImagickException
1454 * @throws InternalServerErrorException
1455 * @throws NotFoundException if the results are empty.
1456 * @throws UnauthorizedException
1458 function api_users_lookup($type)
1462 if (!empty($_REQUEST['user_id'])) {
1463 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1465 $users[] = api_get_user(get_app(), $id);
1470 if (empty($users)) {
1471 throw new NotFoundException;
1474 return api_format_data("users", $type, ['users' => $users]);
1477 /// @TODO move to top of file or somewhere better
1478 api_register_func('api/users/lookup', 'api_users_lookup', true);
1481 * Returns statuses that match a specified query.
1483 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1485 * @param string $type Return format: json, xml, atom, rss
1487 * @return array|string
1488 * @throws BadRequestException if the "q" parameter is missing.
1489 * @throws ForbiddenException
1490 * @throws ImagickException
1491 * @throws InternalServerErrorException
1492 * @throws UnauthorizedException
1494 function api_search($type)
1497 $user_info = api_get_user($a);
1499 if (api_user() === false || $user_info === false) {
1500 throw new ForbiddenException();
1503 if (empty($_REQUEST['q'])) {
1504 throw new BadRequestException('q parameter is required.');
1507 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1510 $data['status'] = [];
1512 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1513 if (!empty($_REQUEST['rpp'])) {
1514 $count = $_REQUEST['rpp'];
1515 } elseif (!empty($_REQUEST['count'])) {
1516 $count = $_REQUEST['count'];
1519 $since_id = $_REQUEST['since_id'] ?? 0;
1520 $max_id = $_REQUEST['max_id'] ?? 0;
1521 $page = $_REQUEST['page'] ?? 1;
1523 $start = max(0, ($page - 1) * $count);
1525 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1526 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1527 $searchTerm = $matches[1];
1528 $condition = ["`oid` > ?
1529 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1530 AND `otype` = ? AND `type` = ? AND `term` = ?",
1531 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1533 $condition[0] .= ' AND `oid` <= ?';
1534 $condition[] = $max_id;
1536 $terms = DBA::select('term', ['oid'], $condition, []);
1538 while ($term = DBA::fetch($terms)) {
1539 $itemIds[] = $term['oid'];
1543 if (empty($itemIds)) {
1544 return api_format_data('statuses', $type, $data);
1547 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1548 if ($exclude_replies) {
1549 $preCondition[] = '`id` = `parent`';
1552 $condition = [implode(' AND ', $preCondition)];
1554 $condition = ["`id` > ?
1555 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1556 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1557 AND `body` LIKE CONCAT('%',?,'%')",
1558 $since_id, api_user(), $_REQUEST['q']];
1560 $condition[0] .= ' AND `id` <= ?';
1561 $condition[] = $max_id;
1567 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1568 $id = Item::fetchByLink($searchTerm, api_user());
1571 $id = Item::fetchByLink($searchTerm);
1575 $statuses = Item::select([], ['id' => $id]);
1579 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1581 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1583 bindComments($data['status']);
1585 return api_format_data('statuses', $type, $data);
1588 /// @TODO move to top of file or somewhere better
1589 api_register_func('api/search/tweets', 'api_search', true);
1590 api_register_func('api/search', 'api_search', true);
1593 * Returns the most recent statuses posted by the user and the users they follow.
1595 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1597 * @param string $type Return type (atom, rss, xml, json)
1599 * @return array|string
1600 * @throws BadRequestException
1601 * @throws ForbiddenException
1602 * @throws ImagickException
1603 * @throws InternalServerErrorException
1604 * @throws UnauthorizedException
1605 * @todo Optional parameters
1606 * @todo Add reply info
1608 function api_statuses_home_timeline($type)
1611 $user_info = api_get_user($a);
1613 if (api_user() === false || $user_info === false) {
1614 throw new ForbiddenException();
1617 unset($_REQUEST["user_id"]);
1618 unset($_GET["user_id"]);
1620 unset($_REQUEST["screen_name"]);
1621 unset($_GET["screen_name"]);
1623 // get last network messages
1626 $count = $_REQUEST['count'] ?? 20;
1627 $page = $_REQUEST['page']?? 0;
1628 $since_id = $_REQUEST['since_id'] ?? 0;
1629 $max_id = $_REQUEST['max_id'] ?? 0;
1630 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1631 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1633 $start = max(0, ($page - 1) * $count);
1635 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1636 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1639 $condition[0] .= " AND `item`.`id` <= ?";
1640 $condition[] = $max_id;
1642 if ($exclude_replies) {
1643 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1645 if ($conversation_id > 0) {
1646 $condition[0] .= " AND `item`.`parent` = ?";
1647 $condition[] = $conversation_id;
1650 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1651 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1653 $items = Item::inArray($statuses);
1655 $ret = api_format_items($items, $user_info, false, $type);
1657 // Set all posts from the query above to seen
1659 foreach ($items as $item) {
1660 $idarray[] = intval($item["id"]);
1663 if (!empty($idarray)) {
1664 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1666 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1672 $data = ['status' => $ret];
1677 $data = api_rss_extra($a, $data, $user_info);
1681 return api_format_data("statuses", $type, $data);
1685 /// @TODO move to top of file or somewhere better
1686 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1687 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1690 * Returns the most recent statuses from public users.
1692 * @param string $type Return type (atom, rss, xml, json)
1694 * @return array|string
1695 * @throws BadRequestException
1696 * @throws ForbiddenException
1697 * @throws ImagickException
1698 * @throws InternalServerErrorException
1699 * @throws UnauthorizedException
1701 function api_statuses_public_timeline($type)
1704 $user_info = api_get_user($a);
1706 if (api_user() === false || $user_info === false) {
1707 throw new ForbiddenException();
1710 // get last network messages
1713 $count = $_REQUEST['count'] ?? 20;
1714 $page = $_REQUEST['page'] ?? 1;
1715 $since_id = $_REQUEST['since_id'] ?? 0;
1716 $max_id = $_REQUEST['max_id'] ?? 0;
1717 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1718 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1720 $start = max(0, ($page - 1) * $count);
1722 if ($exclude_replies && !$conversation_id) {
1723 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1724 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1727 $condition[0] .= " AND `thread`.`iid` <= ?";
1728 $condition[] = $max_id;
1731 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1732 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1734 $r = Item::inArray($statuses);
1736 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1737 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1740 $condition[0] .= " AND `item`.`id` <= ?";
1741 $condition[] = $max_id;
1743 if ($conversation_id > 0) {
1744 $condition[0] .= " AND `item`.`parent` = ?";
1745 $condition[] = $conversation_id;
1748 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1749 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1751 $r = Item::inArray($statuses);
1754 $ret = api_format_items($r, $user_info, false, $type);
1758 $data = ['status' => $ret];
1763 $data = api_rss_extra($a, $data, $user_info);
1767 return api_format_data("statuses", $type, $data);
1770 /// @TODO move to top of file or somewhere better
1771 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1774 * Returns the most recent statuses posted by users this node knows about.
1776 * @brief Returns the list of public federated posts this node knows about
1778 * @param string $type Return format: json, xml, atom, rss
1779 * @return array|string
1780 * @throws BadRequestException
1781 * @throws ForbiddenException
1782 * @throws ImagickException
1783 * @throws InternalServerErrorException
1784 * @throws UnauthorizedException
1786 function api_statuses_networkpublic_timeline($type)
1789 $user_info = api_get_user($a);
1791 if (api_user() === false || $user_info === false) {
1792 throw new ForbiddenException();
1795 $since_id = $_REQUEST['since_id'] ?? 0;
1796 $max_id = $_REQUEST['max_id'] ?? 0;
1799 $count = $_REQUEST['count'] ?? 20;
1800 $page = $_REQUEST['page'] ?? 1;
1802 $start = max(0, ($page - 1) * $count);
1804 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1805 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1808 $condition[0] .= " AND `thread`.`iid` <= ?";
1809 $condition[] = $max_id;
1812 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1813 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1815 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1819 $data = ['status' => $ret];
1824 $data = api_rss_extra($a, $data, $user_info);
1828 return api_format_data("statuses", $type, $data);
1831 /// @TODO move to top of file or somewhere better
1832 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1835 * Returns a single status.
1837 * @param string $type Return type (atom, rss, xml, json)
1839 * @return array|string
1840 * @throws BadRequestException
1841 * @throws ForbiddenException
1842 * @throws ImagickException
1843 * @throws InternalServerErrorException
1844 * @throws UnauthorizedException
1845 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1847 function api_statuses_show($type)
1850 $user_info = api_get_user($a);
1852 if (api_user() === false || $user_info === false) {
1853 throw new ForbiddenException();
1857 $id = intval($a->argv[3] ?? 0);
1860 $id = intval($_REQUEST['id'] ?? 0);
1865 $id = intval($a->argv[4] ?? 0);
1868 Logger::log('API: api_statuses_show: ' . $id);
1870 $conversation = !empty($_REQUEST['conversation']);
1872 // try to fetch the item for the local user - or the public item, if there is no local one
1873 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1874 if (!DBA::isResult($uri_item)) {
1875 throw new BadRequestException("There is no status with this id.");
1878 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1879 if (!DBA::isResult($item)) {
1880 throw new BadRequestException("There is no status with this id.");
1885 if ($conversation) {
1886 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1887 $params = ['order' => ['id' => true]];
1889 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1893 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1895 /// @TODO How about copying this to above methods which don't check $r ?
1896 if (!DBA::isResult($statuses)) {
1897 throw new BadRequestException("There is no status with this id.");
1900 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1902 if ($conversation) {
1903 $data = ['status' => $ret];
1904 return api_format_data("statuses", $type, $data);
1906 $data = ['status' => $ret[0]];
1907 return api_format_data("status", $type, $data);
1911 /// @TODO move to top of file or somewhere better
1912 api_register_func('api/statuses/show', 'api_statuses_show', true);
1916 * @param string $type Return type (atom, rss, xml, json)
1918 * @return array|string
1919 * @throws BadRequestException
1920 * @throws ForbiddenException
1921 * @throws ImagickException
1922 * @throws InternalServerErrorException
1923 * @throws UnauthorizedException
1924 * @todo nothing to say?
1926 function api_conversation_show($type)
1929 $user_info = api_get_user($a);
1931 if (api_user() === false || $user_info === false) {
1932 throw new ForbiddenException();
1936 $id = intval($a->argv[3] ?? 0);
1937 $since_id = intval($_REQUEST['since_id'] ?? 0);
1938 $max_id = intval($_REQUEST['max_id'] ?? 0);
1939 $count = intval($_REQUEST['count'] ?? 20);
1940 $page = intval($_REQUEST['page'] ?? 1);
1942 $start = max(0, ($page - 1) * $count);
1945 $id = intval($_REQUEST['id'] ?? 0);
1950 $id = intval($a->argv[4] ?? 0);
1953 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1955 // try to fetch the item for the local user - or the public item, if there is no local one
1956 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1957 if (!DBA::isResult($item)) {
1958 throw new BadRequestException("There is no status with this id.");
1961 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1962 if (!DBA::isResult($parent)) {
1963 throw new BadRequestException("There is no status with this id.");
1966 $id = $parent['id'];
1968 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1969 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1972 $condition[0] .= " AND `item`.`id` <= ?";
1973 $condition[] = $max_id;
1976 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1977 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1979 if (!DBA::isResult($statuses)) {
1980 throw new BadRequestException("There is no status with id $id.");
1983 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1985 $data = ['status' => $ret];
1986 return api_format_data("statuses", $type, $data);
1989 /// @TODO move to top of file or somewhere better
1990 api_register_func('api/conversation/show', 'api_conversation_show', true);
1991 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1996 * @param string $type Return type (atom, rss, xml, json)
1998 * @return array|string
1999 * @throws BadRequestException
2000 * @throws ForbiddenException
2001 * @throws ImagickException
2002 * @throws InternalServerErrorException
2003 * @throws UnauthorizedException
2004 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2006 function api_statuses_repeat($type)
2012 if (api_user() === false) {
2013 throw new ForbiddenException();
2019 $id = intval($a->argv[3] ?? 0);
2022 $id = intval($_REQUEST['id'] ?? 0);
2027 $id = intval($a->argv[4] ?? 0);
2030 Logger::log('API: api_statuses_repeat: '.$id);
2032 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2033 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2035 if (DBA::isResult($item) && $item['body'] != "") {
2036 if (strpos($item['body'], "[/share]") !== false) {
2037 $pos = strpos($item['body'], "[share");
2038 $post = substr($item['body'], $pos);
2040 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2042 if (!empty($item['title'])) {
2043 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2046 $post .= $item['body'];
2047 $post .= "[/share]";
2049 $_REQUEST['body'] = $post;
2050 $_REQUEST['tag'] = $item['tag'];
2051 $_REQUEST['attach'] = $item['attach'];
2052 $_REQUEST['profile_uid'] = api_user();
2053 $_REQUEST['api_source'] = true;
2055 if (empty($_REQUEST['source'])) {
2056 $_REQUEST["source"] = api_source();
2059 $item_id = item_post($a);
2061 throw new ForbiddenException();
2064 // output the post that we just posted.
2066 return api_status_show($type, $item_id);
2069 /// @TODO move to top of file or somewhere better
2070 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2073 * Destroys a specific status.
2075 * @param string $type Return type (atom, rss, xml, json)
2077 * @return array|string
2078 * @throws BadRequestException
2079 * @throws ForbiddenException
2080 * @throws ImagickException
2081 * @throws InternalServerErrorException
2082 * @throws UnauthorizedException
2083 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2085 function api_statuses_destroy($type)
2089 if (api_user() === false) {
2090 throw new ForbiddenException();
2096 $id = intval($a->argv[3] ?? 0);
2099 $id = intval($_REQUEST['id'] ?? 0);
2104 $id = intval($a->argv[4] ?? 0);
2107 Logger::log('API: api_statuses_destroy: '.$id);
2109 $ret = api_statuses_show($type);
2111 Item::deleteForUser(['id' => $id], api_user());
2116 /// @TODO move to top of file or somewhere better
2117 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2120 * Returns the most recent mentions.
2122 * @param string $type Return type (atom, rss, xml, json)
2124 * @return array|string
2125 * @throws BadRequestException
2126 * @throws ForbiddenException
2127 * @throws ImagickException
2128 * @throws InternalServerErrorException
2129 * @throws UnauthorizedException
2130 * @see http://developer.twitter.com/doc/get/statuses/mentions
2132 function api_statuses_mentions($type)
2135 $user_info = api_get_user($a);
2137 if (api_user() === false || $user_info === false) {
2138 throw new ForbiddenException();
2141 unset($_REQUEST["user_id"]);
2142 unset($_GET["user_id"]);
2144 unset($_REQUEST["screen_name"]);
2145 unset($_GET["screen_name"]);
2147 // get last network messages
2150 $since_id = $_REQUEST['since_id'] ?? 0;
2151 $max_id = $_REQUEST['max_id'] ?? 0;
2152 $count = $_REQUEST['count'] ?? 20;
2153 $page = $_REQUEST['page'] ?? 1;
2155 $start = max(0, ($page - 1) * $count);
2157 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ? AND `mention`
2158 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND NOT `thread`.`ignored`)",
2159 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2162 $condition[0] .= " AND `item`.`id` <= ?";
2163 $condition[] = $max_id;
2166 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2167 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2169 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2171 $data = ['status' => $ret];
2176 $data = api_rss_extra($a, $data, $user_info);
2180 return api_format_data("statuses", $type, $data);
2183 /// @TODO move to top of file or somewhere better
2184 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2185 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2188 * Returns the most recent statuses posted by the user.
2190 * @brief Returns a user's public timeline
2192 * @param string $type Either "json" or "xml"
2193 * @return string|array
2194 * @throws BadRequestException
2195 * @throws ForbiddenException
2196 * @throws ImagickException
2197 * @throws InternalServerErrorException
2198 * @throws UnauthorizedException
2199 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2201 function api_statuses_user_timeline($type)
2204 $user_info = api_get_user($a);
2206 if (api_user() === false || $user_info === false) {
2207 throw new ForbiddenException();
2211 "api_statuses_user_timeline: api_user: ". api_user() .
2212 "\nuser_info: ".print_r($user_info, true) .
2213 "\n_REQUEST: ".print_r($_REQUEST, true),
2217 $since_id = $_REQUEST['since_id'] ?? 0;
2218 $max_id = $_REQUEST['max_id'] ?? 0;
2219 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2220 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2223 $count = $_REQUEST['count'] ?? 20;
2224 $page = $_REQUEST['page'] ?? 1;
2226 $start = max(0, ($page - 1) * $count);
2228 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2229 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2231 if ($user_info['self'] == 1) {
2232 $condition[0] .= ' AND `item`.`wall` ';
2235 if ($exclude_replies) {
2236 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2239 if ($conversation_id > 0) {
2240 $condition[0] .= " AND `item`.`parent` = ?";
2241 $condition[] = $conversation_id;
2245 $condition[0] .= " AND `item`.`id` <= ?";
2246 $condition[] = $max_id;
2249 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2250 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2252 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2256 $data = ['status' => $ret];
2261 $data = api_rss_extra($a, $data, $user_info);
2265 return api_format_data("statuses", $type, $data);
2268 /// @TODO move to top of file or somewhere better
2269 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2272 * Star/unstar an item.
2273 * param: id : id of the item
2275 * @param string $type Return type (atom, rss, xml, json)
2277 * @return array|string
2278 * @throws BadRequestException
2279 * @throws ForbiddenException
2280 * @throws ImagickException
2281 * @throws InternalServerErrorException
2282 * @throws UnauthorizedException
2283 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2285 function api_favorites_create_destroy($type)
2289 if (api_user() === false) {
2290 throw new ForbiddenException();
2293 // for versioned api.
2294 /// @TODO We need a better global soluton
2295 $action_argv_id = 2;
2296 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2297 $action_argv_id = 3;
2300 if ($a->argc <= $action_argv_id) {
2301 throw new BadRequestException("Invalid request.");
2303 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2304 if ($a->argc == $action_argv_id + 2) {
2305 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2307 $itemid = intval($_REQUEST['id'] ?? 0);
2310 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2312 if (!DBA::isResult($item)) {
2313 throw new BadRequestException("Invalid item.");
2318 $item['starred'] = 1;
2321 $item['starred'] = 0;
2324 throw new BadRequestException("Invalid action ".$action);
2327 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2330 throw new InternalServerErrorException("DB error");
2334 $user_info = api_get_user($a);
2335 $rets = api_format_items([$item], $user_info, false, $type);
2338 $data = ['status' => $ret];
2343 $data = api_rss_extra($a, $data, $user_info);
2347 return api_format_data("status", $type, $data);
2350 /// @TODO move to top of file or somewhere better
2351 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2352 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2355 * Returns the most recent favorite statuses.
2357 * @param string $type Return type (atom, rss, xml, json)
2359 * @return string|array
2360 * @throws BadRequestException
2361 * @throws ForbiddenException
2362 * @throws ImagickException
2363 * @throws InternalServerErrorException
2364 * @throws UnauthorizedException
2366 function api_favorites($type)
2371 $user_info = api_get_user($a);
2373 if (api_user() === false || $user_info === false) {
2374 throw new ForbiddenException();
2379 // in friendica starred item are private
2380 // return favorites only for self
2381 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2383 if ($user_info['self'] == 0) {
2387 $since_id = $_REQUEST['since_id'] ?? 0;
2388 $max_id = $_REQUEST['max_id'] ?? 0;
2389 $count = $_GET['count'] ?? 20;
2390 $page = $_REQUEST['page'] ?? 1;
2392 $start = max(0, ($page - 1) * $count);
2394 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2395 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2397 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2400 $condition[0] .= " AND `item`.`id` <= ?";
2401 $condition[] = $max_id;
2404 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2406 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2411 $data = ['status' => $ret];
2416 $data = api_rss_extra($a, $data, $user_info);
2420 return api_format_data("statuses", $type, $data);
2423 /// @TODO move to top of file or somewhere better
2424 api_register_func('api/favorites', 'api_favorites', true);
2428 * @param array $item
2429 * @param array $recipient
2430 * @param array $sender
2433 * @throws InternalServerErrorException
2435 function api_format_messages($item, $recipient, $sender)
2437 // standard meta information
2439 'id' => $item['id'],
2440 'sender_id' => $sender['id'],
2442 'recipient_id' => $recipient['id'],
2443 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2444 'sender_screen_name' => $sender['screen_name'],
2445 'recipient_screen_name' => $recipient['screen_name'],
2446 'sender' => $sender,
2447 'recipient' => $recipient,
2449 'friendica_seen' => $item['seen'] ?? 0,
2450 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2453 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2454 if (isset($ret['sender']['uid'])) {
2455 unset($ret['sender']['uid']);
2457 if (isset($ret['sender']['self'])) {
2458 unset($ret['sender']['self']);
2460 if (isset($ret['recipient']['uid'])) {
2461 unset($ret['recipient']['uid']);
2463 if (isset($ret['recipient']['self'])) {
2464 unset($ret['recipient']['self']);
2467 //don't send title to regular StatusNET requests to avoid confusing these apps
2468 if (!empty($_GET['getText'])) {
2469 $ret['title'] = $item['title'];
2470 if ($_GET['getText'] == 'html') {
2471 $ret['text'] = BBCode::convert($item['body'], false);
2472 } elseif ($_GET['getText'] == 'plain') {
2473 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2476 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2478 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2479 unset($ret['sender']);
2480 unset($ret['recipient']);
2488 * @param array $item
2491 * @throws InternalServerErrorException
2493 function api_convert_item($item)
2495 $body = $item['body'];
2496 $entities = api_get_entitities($statustext, $body);
2498 // Add pictures to the attachment array and remove them from the body
2499 $attachments = api_get_attachments($body);
2501 // Workaround for ostatus messages where the title is identically to the body
2502 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2503 $statusbody = trim(HTML::toPlaintext($html, 0));
2505 // handle data: images
2506 $statusbody = api_format_items_embeded_images($item, $statusbody);
2508 $statustitle = trim($item['title']);
2510 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2511 $statustext = trim($statusbody);
2513 $statustext = trim($statustitle."\n\n".$statusbody);
2516 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2517 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2520 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2522 // Workaround for clients with limited HTML parser functionality
2523 $search = ["<br>", "<blockquote>", "</blockquote>",
2524 "<h1>", "</h1>", "<h2>", "</h2>",
2525 "<h3>", "</h3>", "<h4>", "</h4>",
2526 "<h5>", "</h5>", "<h6>", "</h6>"];
2527 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2528 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2529 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2530 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2531 $statushtml = str_replace($search, $replace, $statushtml);
2533 if ($item['title'] != "") {
2534 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2538 $oldtext = $statushtml;
2539 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2540 } while ($oldtext != $statushtml);
2542 if (substr($statushtml, 0, 4) == '<br>') {
2543 $statushtml = substr($statushtml, 4);
2546 if (substr($statushtml, 0, -4) == '<br>') {
2547 $statushtml = substr($statushtml, -4);
2550 // feeds without body should contain the link
2551 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2552 $statushtml .= BBCode::convert($item['plink']);
2556 "text" => $statustext,
2557 "html" => $statushtml,
2558 "attachments" => $attachments,
2559 "entities" => $entities
2565 * @param string $body
2568 * @throws InternalServerErrorException
2570 function api_get_attachments(&$body)
2572 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2573 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2575 $URLSearchString = "^\[\]";
2576 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2580 // Remove all embedded pictures, since they are added as attachments
2581 foreach ($images[0] as $orig) {
2582 $body = str_replace($orig, '', $body);
2587 foreach ($images[1] as $image) {
2588 $imagedata = Images::getInfoFromURLCached($image);
2591 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2595 return $attachments;
2600 * @param string $text
2601 * @param string $bbcode
2604 * @throws InternalServerErrorException
2605 * @todo Links at the first character of the post
2607 function api_get_entitities(&$text, $bbcode)
2609 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2611 if ($include_entities != "true") {
2612 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2614 foreach ($images[1] as $image) {
2615 $replace = ProxyUtils::proxifyUrl($image);
2616 $text = str_replace($image, $replace, $text);
2621 $bbcode = BBCode::cleanPictureLinks($bbcode);
2623 // Change pure links in text to bbcode uris
2624 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2627 $entities["hashtags"] = [];
2628 $entities["symbols"] = [];
2629 $entities["urls"] = [];
2630 $entities["user_mentions"] = [];
2632 $URLSearchString = "^\[\]";
2634 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2636 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2637 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2639 $bbcode = preg_replace(
2640 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2641 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2644 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2646 $bbcode = preg_replace(
2647 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2648 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2651 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2653 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2655 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2658 foreach ($urls[1] as $id => $url) {
2659 $start = iconv_strpos($text, $url, 0, "UTF-8");
2660 if (!($start === false)) {
2661 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2665 ksort($ordered_urls);
2669 foreach ($ordered_urls as $url) {
2670 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2671 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2673 $display_url = $url["title"];
2675 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2676 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2678 if (strlen($display_url) > 26) {
2679 $display_url = substr($display_url, 0, 25)."…";
2683 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2684 if (!($start === false)) {
2685 $entities["urls"][] = ["url" => $url["url"],
2686 "expanded_url" => $url["url"],
2687 "display_url" => $display_url,
2688 "indices" => [$start, $start+strlen($url["url"])]];
2689 $offset = $start + 1;
2693 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2694 $ordered_images = [];
2695 foreach ($images as $image) {
2696 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2697 if (!($start === false)) {
2698 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2702 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2703 foreach ($images[1] as $image) {
2704 $start = iconv_strpos($text, $image, 0, "UTF-8");
2705 if (!($start === false)) {
2706 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2712 foreach ($ordered_images as $image) {
2713 $url = $image['url'];
2714 $ext_alt_text = $image['alt'];
2716 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2717 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2719 if (strlen($display_url) > 26) {
2720 $display_url = substr($display_url, 0, 25)."…";
2723 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2724 if (!($start === false)) {
2725 $image = Images::getInfoFromURLCached($url);
2727 // If image cache is activated, then use the following sizes:
2728 // thumb (150), small (340), medium (600) and large (1024)
2729 if (!Config::get("system", "proxy_disabled")) {
2730 $media_url = ProxyUtils::proxifyUrl($url);
2733 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2734 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2736 if (($image[0] > 150) || ($image[1] > 150)) {
2737 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2738 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2741 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2742 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2744 if (($image[0] > 600) || ($image[1] > 600)) {
2745 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2746 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2750 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2753 $entities["media"][] = [
2755 "id_str" => (string) ($start + 1),
2756 "indices" => [$start, $start+strlen($url)],
2757 "media_url" => Strings::normaliseLink($media_url),
2758 "media_url_https" => $media_url,
2760 "display_url" => $display_url,
2761 "expanded_url" => $url,
2762 "ext_alt_text" => $ext_alt_text,
2766 $offset = $start + 1;
2775 * @param array $item
2776 * @param string $text
2780 function api_format_items_embeded_images($item, $text)
2782 $text = preg_replace_callback(
2783 '|data:image/([^;]+)[^=]+=*|m',
2784 function () use ($item) {
2785 return System::baseUrl() . '/display/' . $item['guid'];
2793 * @brief return <a href='url'>name</a> as array
2795 * @param string $txt text
2800 function api_contactlink_to_array($txt)
2803 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2804 if ($r && count($match)==3) {
2806 'name' => $match[2],
2820 * @brief return likes, dislikes and attend status for item
2822 * @param array $item array
2823 * @param string $type Return type (atom, rss, xml, json)
2826 * likes => int count,
2827 * dislikes => int count
2828 * @throws BadRequestException
2829 * @throws ImagickException
2830 * @throws InternalServerErrorException
2831 * @throws UnauthorizedException
2833 function api_format_items_activities($item, $type = "json")
2842 'attendmaybe' => [],
2846 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2847 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2849 while ($parent_item = Item::fetch($ret)) {
2850 // not used as result should be structured like other user data
2851 //builtin_activity_puller($i, $activities);
2853 // get user data and add it to the array of the activity
2854 $user = api_get_user($a, $parent_item['author-id']);
2855 switch ($parent_item['verb']) {
2856 case Activity::LIKE:
2857 $activities['like'][] = $user;
2859 case Activity::DISLIKE:
2860 $activities['dislike'][] = $user;
2862 case Activity::ATTEND:
2863 $activities['attendyes'][] = $user;
2865 case Activity::ATTENDNO:
2866 $activities['attendno'][] = $user;
2868 case Activity::ATTENDMAYBE:
2869 $activities['attendmaybe'][] = $user;
2871 case Activity::ANNOUNCE:
2872 $activities['announce'][] = $user;
2881 if ($type == "xml") {
2882 $xml_activities = [];
2883 foreach ($activities as $k => $v) {
2884 // change xml element from "like" to "friendica:like"
2885 $xml_activities["friendica:".$k] = $v;
2886 // add user data into xml output
2888 foreach ($v as $user) {
2889 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2892 $activities = $xml_activities;
2900 * @brief return data from profiles
2902 * @param array $profile_row array containing data from db table 'profile'
2904 * @throws InternalServerErrorException
2906 function api_format_items_profiles($profile_row)
2909 'profile_id' => $profile_row['id'],
2910 'profile_name' => $profile_row['profile-name'],
2911 'is_default' => $profile_row['is-default'] ? true : false,
2912 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2913 'profile_photo' => $profile_row['photo'],
2914 'profile_thumb' => $profile_row['thumb'],
2915 'publish' => $profile_row['publish'] ? true : false,
2916 'net_publish' => $profile_row['net-publish'] ? true : false,
2917 'description' => $profile_row['pdesc'],
2918 'date_of_birth' => $profile_row['dob'],
2919 'address' => $profile_row['address'],
2920 'city' => $profile_row['locality'],
2921 'region' => $profile_row['region'],
2922 'postal_code' => $profile_row['postal-code'],
2923 'country' => $profile_row['country-name'],
2924 'hometown' => $profile_row['hometown'],
2925 'gender' => $profile_row['gender'],
2926 'marital' => $profile_row['marital'],
2927 'marital_with' => $profile_row['with'],
2928 'marital_since' => $profile_row['howlong'],
2929 'sexual' => $profile_row['sexual'],
2930 'politic' => $profile_row['politic'],
2931 'religion' => $profile_row['religion'],
2932 'public_keywords' => $profile_row['pub_keywords'],
2933 'private_keywords' => $profile_row['prv_keywords'],
2934 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2935 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2936 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2937 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2938 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2939 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2940 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2941 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2942 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2943 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2944 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2945 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2946 'homepage' => $profile_row['homepage'],
2953 * @brief format items to be returned by api
2955 * @param array $items array of items
2956 * @param array $user_info
2957 * @param bool $filter_user filter items by $user_info
2958 * @param string $type Return type (atom, rss, xml, json)
2960 * @throws BadRequestException
2961 * @throws ImagickException
2962 * @throws InternalServerErrorException
2963 * @throws UnauthorizedException
2965 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2967 $a = Friendica\DI::app();
2971 foreach ((array)$items as $item) {
2972 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2974 // Look if the posts are matching if they should be filtered by user id
2975 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2979 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2988 * @param array $item Item record
2989 * @param string $type Return format (atom, rss, xml, json)
2990 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2991 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2992 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2993 * @return array API-formatted status
2994 * @throws BadRequestException
2995 * @throws ImagickException
2996 * @throws InternalServerErrorException
2997 * @throws UnauthorizedException
2999 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3001 $a = Friendica\DI::app();
3003 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3004 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3007 localize_item($item);
3009 $in_reply_to = api_in_reply_to($item);
3011 $converted = api_convert_item($item);
3013 if ($type == "xml") {
3014 $geo = "georss:point";
3020 'text' => $converted["text"],
3021 'truncated' => false,
3022 'created_at'=> api_date($item['created']),
3023 'in_reply_to_status_id' => $in_reply_to['status_id'],
3024 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3025 'source' => (($item['app']) ? $item['app'] : 'web'),
3026 'id' => intval($item['id']),
3027 'id_str' => (string) intval($item['id']),
3028 'in_reply_to_user_id' => $in_reply_to['user_id'],
3029 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3030 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3032 'favorited' => $item['starred'] ? true : false,
3033 'user' => $status_user,
3034 'friendica_author' => $author_user,
3035 'friendica_owner' => $owner_user,
3036 'friendica_private' => $item['private'] == 1,
3037 //'entities' => NULL,
3038 'statusnet_html' => $converted["html"],
3039 'statusnet_conversation_id' => $item['parent'],
3040 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3041 'friendica_activities' => api_format_items_activities($item, $type),
3042 'friendica_title' => $item['title'],
3043 'friendica_html' => BBCode::convert($item['body'], false)
3046 if (count($converted["attachments"]) > 0) {
3047 $status["attachments"] = $converted["attachments"];
3050 if (count($converted["entities"]) > 0) {
3051 $status["entities"] = $converted["entities"];
3054 if ($status["source"] == 'web') {
3055 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3056 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3057 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3060 $retweeted_item = [];
3063 if ($item["id"] == $item["parent"]) {
3064 $body = $item['body'];
3065 $retweeted_item = api_share_as_retweet($item);
3066 if ($body != $item['body']) {
3067 $quoted_item = $retweeted_item;
3068 $retweeted_item = [];
3072 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3073 $announce = api_get_announce($item);
3074 if (!empty($announce)) {
3075 $retweeted_item = $item;
3077 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3081 if (!empty($quoted_item)) {
3082 if ($quoted_item['id'] != $item['id']) {
3083 $quoted_status = api_format_item($quoted_item);
3084 /// @todo Only remove the attachments that are also contained in the quotes status
3085 unset($status['attachments']);
3086 unset($status['entities']);
3088 $conv_quoted = api_convert_item($quoted_item);
3089 $quoted_status = $status;
3090 unset($quoted_status['attachments']);
3091 unset($quoted_status['entities']);
3092 unset($quoted_status['statusnet_conversation_id']);
3093 $quoted_status['text'] = $conv_quoted['text'];
3094 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3096 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3097 } catch (BadRequestException $e) {
3098 // user not found. should be found?
3099 /// @todo check if the user should be always found
3100 $quoted_status["user"] = [];
3103 unset($quoted_status['friendica_author']);
3104 unset($quoted_status['friendica_owner']);
3105 unset($quoted_status['friendica_activities']);
3106 unset($quoted_status['friendica_private']);
3109 if (!empty($retweeted_item)) {
3110 $retweeted_status = $status;
3111 unset($retweeted_status['friendica_author']);
3112 unset($retweeted_status['friendica_owner']);
3113 unset($retweeted_status['friendica_activities']);
3114 unset($retweeted_status['friendica_private']);
3115 unset($retweeted_status['statusnet_conversation_id']);
3116 $status['user'] = $status['friendica_owner'];
3118 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3119 } catch (BadRequestException $e) {
3120 // user not found. should be found?
3121 /// @todo check if the user should be always found
3122 $retweeted_status["user"] = [];
3125 $rt_converted = api_convert_item($retweeted_item);
3127 $retweeted_status['text'] = $rt_converted["text"];
3128 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3129 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3131 if (!empty($quoted_status)) {
3132 $retweeted_status['quoted_status'] = $quoted_status;
3135 $status['friendica_author'] = $retweeted_status['user'];
3136 $status['retweeted_status'] = $retweeted_status;
3137 } elseif (!empty($quoted_status)) {
3138 $root_status = api_convert_item($item);
3140 $status['text'] = $root_status["text"];
3141 $status['statusnet_html'] = $root_status["html"];
3142 $status['quoted_status'] = $quoted_status;
3145 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3146 unset($status["user"]["uid"]);
3147 unset($status["user"]["self"]);
3149 if ($item["coord"] != "") {
3150 $coords = explode(' ', $item["coord"]);
3151 if (count($coords) == 2) {
3152 if ($type == "json") {
3153 $status["geo"] = ['type' => 'Point',
3154 'coordinates' => [(float) $coords[0],
3155 (float) $coords[1]]];
3156 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3157 $status["georss:point"] = $item["coord"];
3166 * Returns the remaining number of API requests available to the user before the API limit is reached.
3168 * @param string $type Return type (atom, rss, xml, json)
3170 * @return array|string
3173 function api_account_rate_limit_status($type)
3175 if ($type == "xml") {
3177 'remaining-hits' => '150',
3178 '@attributes' => ["type" => "integer"],
3179 'hourly-limit' => '150',
3180 '@attributes2' => ["type" => "integer"],
3181 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3182 '@attributes3' => ["type" => "datetime"],
3183 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3184 '@attributes4' => ["type" => "integer"],
3188 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3189 'remaining_hits' => '150',
3190 'hourly_limit' => '150',
3191 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3195 return api_format_data('hash', $type, ['hash' => $hash]);
3198 /// @TODO move to top of file or somewhere better
3199 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3202 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3204 * @param string $type Return type (atom, rss, xml, json)
3206 * @return array|string
3208 function api_help_test($type)
3210 if ($type == 'xml') {
3216 return api_format_data('ok', $type, ["ok" => $ok]);
3219 /// @TODO move to top of file or somewhere better
3220 api_register_func('api/help/test', 'api_help_test', false);
3223 * Returns all lists the user subscribes to.
3225 * @param string $type Return type (atom, rss, xml, json)
3227 * @return array|string
3228 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3230 function api_lists_list($type)
3233 /// @TODO $ret is not filled here?
3234 return api_format_data('lists', $type, ["lists_list" => $ret]);
3237 /// @TODO move to top of file or somewhere better
3238 api_register_func('api/lists/list', 'api_lists_list', true);
3239 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3242 * Returns all groups the user owns.
3244 * @param string $type Return type (atom, rss, xml, json)
3246 * @return array|string
3247 * @throws BadRequestException
3248 * @throws ForbiddenException
3249 * @throws ImagickException
3250 * @throws InternalServerErrorException
3251 * @throws UnauthorizedException
3252 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3254 function api_lists_ownerships($type)
3258 if (api_user() === false) {
3259 throw new ForbiddenException();
3263 $user_info = api_get_user($a);
3264 $uid = $user_info['uid'];
3266 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3268 // loop through all groups
3270 foreach ($groups as $group) {
3271 if ($group['visible']) {
3277 'name' => $group['name'],
3278 'id' => intval($group['id']),
3279 'id_str' => (string) $group['id'],
3280 'user' => $user_info,
3284 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3287 /// @TODO move to top of file or somewhere better
3288 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3291 * Returns recent statuses from users in the specified group.
3293 * @param string $type Return type (atom, rss, xml, json)
3295 * @return array|string
3296 * @throws BadRequestException
3297 * @throws ForbiddenException
3298 * @throws ImagickException
3299 * @throws InternalServerErrorException
3300 * @throws UnauthorizedException
3301 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3303 function api_lists_statuses($type)
3307 $user_info = api_get_user($a);
3308 if (api_user() === false || $user_info === false) {
3309 throw new ForbiddenException();
3312 unset($_REQUEST["user_id"]);
3313 unset($_GET["user_id"]);
3315 unset($_REQUEST["screen_name"]);
3316 unset($_GET["screen_name"]);
3318 if (empty($_REQUEST['list_id'])) {
3319 throw new BadRequestException('list_id not specified');
3323 $count = $_REQUEST['count'] ?? 20;
3324 $page = $_REQUEST['page'] ?? 1;
3325 $since_id = $_REQUEST['since_id'] ?? 0;
3326 $max_id = $_REQUEST['max_id'] ?? 0;
3327 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3328 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3330 $start = max(0, ($page - 1) * $count);
3332 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3333 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3336 $condition[0] .= " AND `item`.`id` <= ?";
3337 $condition[] = $max_id;
3339 if ($exclude_replies > 0) {
3340 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3342 if ($conversation_id > 0) {
3343 $condition[0] .= " AND `item`.`parent` = ?";
3344 $condition[] = $conversation_id;
3347 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3348 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3350 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3352 $data = ['status' => $items];
3357 $data = api_rss_extra($a, $data, $user_info);
3361 return api_format_data("statuses", $type, $data);
3364 /// @TODO move to top of file or somewhere better
3365 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3368 * Considers friends and followers lists to be private and won't return
3369 * anything if any user_id parameter is passed.
3371 * @brief Returns either the friends of the follower list
3373 * @param string $qtype Either "friends" or "followers"
3374 * @return boolean|array
3375 * @throws BadRequestException
3376 * @throws ForbiddenException
3377 * @throws ImagickException
3378 * @throws InternalServerErrorException
3379 * @throws UnauthorizedException
3381 function api_statuses_f($qtype)
3385 if (api_user() === false) {
3386 throw new ForbiddenException();
3390 $count = $_GET['count'] ?? 20;
3391 $page = $_GET['page'] ?? 1;
3393 $start = max(0, ($page - 1) * $count);
3395 $user_info = api_get_user($a);
3397 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3398 /* this is to stop Hotot to load friends multiple times
3399 * I'm not sure if I'm missing return something or
3400 * is a bug in hotot. Workaround, meantime
3404 return array('$users' => $ret);*/
3409 if ($qtype == 'friends') {
3410 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3411 } elseif ($qtype == 'followers') {
3412 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3415 // friends and followers only for self
3416 if ($user_info['self'] == 0) {
3417 $sql_extra = " AND false ";
3420 if ($qtype == 'blocks') {
3421 $sql_filter = 'AND `blocked` AND NOT `pending`';
3422 } elseif ($qtype == 'incoming') {
3423 $sql_filter = 'AND `pending`';
3425 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3443 foreach ($r as $cid) {
3444 $user = api_get_user($a, $cid['nurl']);
3445 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3446 unset($user["uid"]);
3447 unset($user["self"]);
3454 return ['user' => $ret];
3459 * Returns the user's friends.
3461 * @brief Returns the list of friends of the provided user
3463 * @deprecated By Twitter API in favor of friends/list
3465 * @param string $type Either "json" or "xml"
3466 * @return boolean|string|array
3467 * @throws BadRequestException
3468 * @throws ForbiddenException
3470 function api_statuses_friends($type)
3472 $data = api_statuses_f("friends");
3473 if ($data === false) {
3476 return api_format_data("users", $type, $data);
3480 * Returns the user's followers.
3482 * @brief Returns the list of followers of the provided user
3484 * @deprecated By Twitter API in favor of friends/list
3486 * @param string $type Either "json" or "xml"
3487 * @return boolean|string|array
3488 * @throws BadRequestException
3489 * @throws ForbiddenException
3491 function api_statuses_followers($type)
3493 $data = api_statuses_f("followers");
3494 if ($data === false) {
3497 return api_format_data("users", $type, $data);
3500 /// @TODO move to top of file or somewhere better
3501 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3502 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3505 * Returns the list of blocked users
3507 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3509 * @param string $type Either "json" or "xml"
3511 * @return boolean|string|array
3512 * @throws BadRequestException
3513 * @throws ForbiddenException
3515 function api_blocks_list($type)
3517 $data = api_statuses_f('blocks');
3518 if ($data === false) {
3521 return api_format_data("users", $type, $data);
3524 /// @TODO move to top of file or somewhere better
3525 api_register_func('api/blocks/list', 'api_blocks_list', true);
3528 * Returns the list of pending users IDs
3530 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3532 * @param string $type Either "json" or "xml"
3534 * @return boolean|string|array
3535 * @throws BadRequestException
3536 * @throws ForbiddenException
3538 function api_friendships_incoming($type)
3540 $data = api_statuses_f('incoming');
3541 if ($data === false) {
3546 foreach ($data['user'] as $user) {
3547 $ids[] = $user['id'];
3550 return api_format_data("ids", $type, ['id' => $ids]);
3553 /// @TODO move to top of file or somewhere better
3554 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3557 * Returns the instance's configuration information.
3559 * @param string $type Return type (atom, rss, xml, json)
3561 * @return array|string
3562 * @throws InternalServerErrorException
3564 function api_statusnet_config($type)
3568 $name = Config::get('config', 'sitename');
3569 $server = $a->getHostName();
3570 $logo = System::baseUrl() . '/images/friendica-64.png';
3571 $email = Config::get('config', 'admin_email');
3572 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3573 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3574 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3575 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3576 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3579 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3580 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3581 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3582 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3583 'shorturllength' => '30',
3585 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3586 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3587 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3588 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3593 return api_format_data('config', $type, ['config' => $config]);
3596 /// @TODO move to top of file or somewhere better
3597 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3598 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3602 * @param string $type Return type (atom, rss, xml, json)
3604 * @return array|string
3606 function api_statusnet_version($type)
3609 $fake_statusnet_version = "0.9.7";
3611 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3614 /// @TODO move to top of file or somewhere better
3615 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3616 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3620 * @param string $type Return type (atom, rss, xml, json)
3622 * @param int $rel A contact relationship constant
3623 * @return array|string|void
3624 * @throws BadRequestException
3625 * @throws ForbiddenException
3626 * @throws ImagickException
3627 * @throws InternalServerErrorException
3628 * @throws UnauthorizedException
3629 * @todo use api_format_data() to return data
3631 function api_ff_ids($type, int $rel)
3634 throw new ForbiddenException();
3641 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3643 $contacts = DBA::p("SELECT `pcontact`.`id`
3645 INNER JOIN `contact` AS `pcontact`
3646 ON `contact`.`nurl` = `pcontact`.`nurl`
3647 AND `pcontact`.`uid` = 0
3648 WHERE `contact`.`uid` = ?
3649 AND NOT `contact`.`self`
3650 AND `contact`.`rel` IN (?, ?)",
3657 foreach (DBA::toArray($contacts) as $contact) {
3658 if ($stringify_ids) {
3659 $ids[] = $contact['id'];
3661 $ids[] = intval($contact['id']);
3665 return api_format_data('ids', $type, ['id' => $ids]);
3669 * Returns the ID of every user the user is following.
3671 * @param string $type Return type (atom, rss, xml, json)
3673 * @return array|string
3674 * @throws BadRequestException
3675 * @throws ForbiddenException
3676 * @throws ImagickException
3677 * @throws InternalServerErrorException
3678 * @throws UnauthorizedException
3679 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3681 function api_friends_ids($type)
3683 return api_ff_ids($type, Contact::SHARING);
3687 * Returns the ID of every user following the user.
3689 * @param string $type Return type (atom, rss, xml, json)
3691 * @return array|string
3692 * @throws BadRequestException
3693 * @throws ForbiddenException
3694 * @throws ImagickException
3695 * @throws InternalServerErrorException
3696 * @throws UnauthorizedException
3697 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3699 function api_followers_ids($type)
3701 return api_ff_ids($type, Contact::FOLLOWER);
3704 /// @TODO move to top of file or somewhere better
3705 api_register_func('api/friends/ids', 'api_friends_ids', true);
3706 api_register_func('api/followers/ids', 'api_followers_ids', true);
3709 * Sends a new direct message.
3711 * @param string $type Return type (atom, rss, xml, json)
3713 * @return array|string
3714 * @throws BadRequestException
3715 * @throws ForbiddenException
3716 * @throws ImagickException
3717 * @throws InternalServerErrorException
3718 * @throws NotFoundException
3719 * @throws UnauthorizedException
3720 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3722 function api_direct_messages_new($type)
3726 if (api_user() === false) {
3727 throw new ForbiddenException();
3730 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3734 $sender = api_get_user($a);
3737 if (!empty($_POST['screen_name'])) {
3739 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3741 DBA::escape($_POST['screen_name'])
3744 if (DBA::isResult($r)) {
3745 // Selecting the id by priority, friendica first
3746 api_best_nickname($r);
3748 $recipient = api_get_user($a, $r[0]['nurl']);
3751 $recipient = api_get_user($a, $_POST['user_id']);
3754 if (empty($recipient)) {
3755 throw new NotFoundException('Recipient not found');
3759 if (!empty($_REQUEST['replyto'])) {
3761 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3763 intval($_REQUEST['replyto'])
3765 $replyto = $r[0]['parent-uri'];
3766 $sub = $r[0]['title'];
3768 if (!empty($_REQUEST['title'])) {
3769 $sub = $_REQUEST['title'];
3771 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3775 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3778 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3779 $ret = api_format_messages($r[0], $recipient, $sender);
3781 $ret = ["error"=>$id];
3784 $data = ['direct_message'=>$ret];
3790 $data = api_rss_extra($a, $data, $sender);
3794 return api_format_data("direct-messages", $type, $data);
3797 /// @TODO move to top of file or somewhere better
3798 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3801 * Destroys a direct message.
3803 * @brief delete a direct_message from mail table through api
3805 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3806 * @return string|array
3807 * @throws BadRequestException
3808 * @throws ForbiddenException
3809 * @throws ImagickException
3810 * @throws InternalServerErrorException
3811 * @throws UnauthorizedException
3812 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3814 function api_direct_messages_destroy($type)
3818 if (api_user() === false) {
3819 throw new ForbiddenException();
3823 $user_info = api_get_user($a);
3825 $id = $_REQUEST['id'] ?? 0;
3827 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3828 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3829 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3831 $uid = $user_info['uid'];
3832 // error if no id or parenturi specified (for clients posting parent-uri as well)
3833 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3834 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3835 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3838 // BadRequestException if no id specified (for clients using Twitter API)
3840 throw new BadRequestException('Message id not specified');
3843 // add parent-uri to sql command if specified by calling app
3844 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3846 // get data of the specified message id
3848 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3853 // error message if specified id is not in database
3854 if (!DBA::isResult($r)) {
3855 if ($verbose == "true") {
3856 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3857 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3859 /// @todo BadRequestException ok for Twitter API clients?
3860 throw new BadRequestException('message id not in database');
3865 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3870 if ($verbose == "true") {
3873 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3874 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3876 $answer = ['result' => 'error', 'message' => 'unknown error'];
3877 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3880 /// @todo return JSON data like Twitter API not yet implemented
3883 /// @TODO move to top of file or somewhere better
3884 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3889 * @brief unfollow contact
3891 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3892 * @return string|array
3893 * @throws BadRequestException
3894 * @throws ForbiddenException
3895 * @throws ImagickException
3896 * @throws InternalServerErrorException
3897 * @throws NotFoundException
3898 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3900 function api_friendships_destroy($type)
3904 if ($uid === false) {
3905 throw new ForbiddenException();
3908 $contact_id = $_REQUEST['user_id'] ?? 0;
3910 if (empty($contact_id)) {
3911 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3912 throw new BadRequestException("no user_id specified");
3915 // Get Contact by given id
3916 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3918 if(!DBA::isResult($contact)) {
3919 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3920 throw new NotFoundException("no contact found to given ID");
3923 $url = $contact["url"];
3925 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3926 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3927 Strings::normaliseLink($url), $url];
3928 $contact = DBA::selectFirst('contact', [], $condition);
3930 if (!DBA::isResult($contact)) {
3931 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3932 throw new NotFoundException("Not following Contact");
3935 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3936 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3937 throw new ExpectationFailedException("Not supported");
3940 $dissolve = ($contact['rel'] == Contact::SHARING);
3942 $owner = User::getOwnerDataById($uid);
3944 Contact::terminateFriendship($owner, $contact, $dissolve);
3947 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3948 throw new NotFoundException("Error Processing Request");
3951 // Sharing-only contacts get deleted as there no relationship any more
3953 Contact::remove($contact['id']);
3955 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3958 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3959 unset($contact["uid"]);
3960 unset($contact["self"]);
3962 // Set screen_name since Twidere requests it
3963 $contact["screen_name"] = $contact["nick"];
3965 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3967 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3971 * @param string $type Return type (atom, rss, xml, json)
3972 * @param string $box
3973 * @param string $verbose
3975 * @return array|string
3976 * @throws BadRequestException
3977 * @throws ForbiddenException
3978 * @throws ImagickException
3979 * @throws InternalServerErrorException
3980 * @throws UnauthorizedException
3982 function api_direct_messages_box($type, $box, $verbose)
3985 if (api_user() === false) {
3986 throw new ForbiddenException();
3989 $count = $_GET['count'] ?? 20;
3990 $page = $_REQUEST['page'] ?? 1;
3992 $since_id = $_REQUEST['since_id'] ?? 0;
3993 $max_id = $_REQUEST['max_id'] ?? 0;
3995 $user_id = $_REQUEST['user_id'] ?? '';
3996 $screen_name = $_REQUEST['screen_name'] ?? '';
3999 unset($_REQUEST["user_id"]);
4000 unset($_GET["user_id"]);
4002 unset($_REQUEST["screen_name"]);
4003 unset($_GET["screen_name"]);
4005 $user_info = api_get_user($a);
4006 if ($user_info === false) {
4007 throw new ForbiddenException();
4009 $profile_url = $user_info["url"];
4012 $start = max(0, ($page - 1) * $count);
4017 if ($box=="sentbox") {
4018 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4019 } elseif ($box == "conversation") {
4020 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4021 } elseif ($box == "all") {
4022 $sql_extra = "true";
4023 } elseif ($box == "inbox") {
4024 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4028 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4031 if ($user_id != "") {
4032 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4033 } elseif ($screen_name !="") {
4034 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4038 "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",
4044 if ($verbose == "true" && !DBA::isResult($r)) {
4045 $answer = ['result' => 'error', 'message' => 'no mails available'];
4046 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4050 foreach ($r as $item) {
4051 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4052 $recipient = $user_info;
4053 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4054 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4055 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4056 $sender = $user_info;
4059 if (isset($recipient) && isset($sender)) {
4060 $ret[] = api_format_messages($item, $recipient, $sender);
4065 $data = ['direct_message' => $ret];
4070 $data = api_rss_extra($a, $data, $user_info);
4074 return api_format_data("direct-messages", $type, $data);
4078 * Returns the most recent direct messages sent by the user.
4080 * @param string $type Return type (atom, rss, xml, json)
4082 * @return array|string
4083 * @throws BadRequestException
4084 * @throws ForbiddenException
4085 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4087 function api_direct_messages_sentbox($type)
4089 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4090 return api_direct_messages_box($type, "sentbox", $verbose);
4094 * Returns the most recent direct messages sent to the user.
4096 * @param string $type Return type (atom, rss, xml, json)
4098 * @return array|string
4099 * @throws BadRequestException
4100 * @throws ForbiddenException
4101 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4103 function api_direct_messages_inbox($type)
4105 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4106 return api_direct_messages_box($type, "inbox", $verbose);
4111 * @param string $type Return type (atom, rss, xml, json)
4113 * @return array|string
4114 * @throws BadRequestException
4115 * @throws ForbiddenException
4117 function api_direct_messages_all($type)
4119 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4120 return api_direct_messages_box($type, "all", $verbose);
4125 * @param string $type Return type (atom, rss, xml, json)
4127 * @return array|string
4128 * @throws BadRequestException
4129 * @throws ForbiddenException
4131 function api_direct_messages_conversation($type)
4133 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4134 return api_direct_messages_box($type, "conversation", $verbose);
4137 /// @TODO move to top of file or somewhere better
4138 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4139 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4140 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4141 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4144 * Returns an OAuth Request Token.
4146 * @see https://oauth.net/core/1.0/#auth_step1
4148 function api_oauth_request_token()
4150 $oauth1 = new FKOAuth1();
4152 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4153 } catch (Exception $e) {
4154 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4162 * Returns an OAuth Access Token.
4164 * @return array|string
4165 * @see https://oauth.net/core/1.0/#auth_step3
4167 function api_oauth_access_token()
4169 $oauth1 = new FKOAuth1();
4171 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4172 } catch (Exception $e) {
4173 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4180 /// @TODO move to top of file or somewhere better
4181 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4182 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4186 * @brief delete a complete photoalbum with all containing photos from database through api
4188 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4189 * @return string|array
4190 * @throws BadRequestException
4191 * @throws ForbiddenException
4192 * @throws InternalServerErrorException
4194 function api_fr_photoalbum_delete($type)
4196 if (api_user() === false) {
4197 throw new ForbiddenException();
4200 $album = $_REQUEST['album'] ?? '';
4202 // we do not allow calls without album string
4204 throw new BadRequestException("no albumname specified");
4206 // check if album is existing
4208 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4212 if (!DBA::isResult($r)) {
4213 throw new BadRequestException("album not available");
4216 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4217 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4218 foreach ($r as $rr) {
4219 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4220 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4222 if (!DBA::isResult($photo_item)) {
4223 throw new InternalServerErrorException("problem with deleting items occured");
4225 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4228 // now let's delete all photos from the album
4229 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4231 // return success of deletion or error message
4233 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4234 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4236 throw new InternalServerErrorException("unknown error - deleting from database failed");
4241 * @brief update the name of the album for all photos of an album
4243 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4244 * @return string|array
4245 * @throws BadRequestException
4246 * @throws ForbiddenException
4247 * @throws InternalServerErrorException
4249 function api_fr_photoalbum_update($type)
4251 if (api_user() === false) {
4252 throw new ForbiddenException();
4255 $album = $_REQUEST['album'] ?? '';
4256 $album_new = $_REQUEST['album_new'] ?? '';
4258 // we do not allow calls without album string
4260 throw new BadRequestException("no albumname specified");
4262 if ($album_new == "") {
4263 throw new BadRequestException("no new albumname specified");
4265 // check if album is existing
4266 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4267 throw new BadRequestException("album not available");
4269 // now let's update all photos to the albumname
4270 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4272 // return success of updating or error message
4274 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4275 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4277 throw new InternalServerErrorException("unknown error - updating in database failed");
4283 * @brief list all photos of the authenticated user
4285 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4286 * @return string|array
4287 * @throws ForbiddenException
4288 * @throws InternalServerErrorException
4290 function api_fr_photos_list($type)
4292 if (api_user() === false) {
4293 throw new ForbiddenException();
4296 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4297 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4298 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4299 intval(local_user())
4302 'image/jpeg' => 'jpg',
4303 'image/png' => 'png',
4304 'image/gif' => 'gif'
4306 $data = ['photo'=>[]];
4307 if (DBA::isResult($r)) {
4308 foreach ($r as $rr) {
4310 $photo['id'] = $rr['resource-id'];
4311 $photo['album'] = $rr['album'];
4312 $photo['filename'] = $rr['filename'];
4313 $photo['type'] = $rr['type'];
4314 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4315 $photo['created'] = $rr['created'];
4316 $photo['edited'] = $rr['edited'];
4317 $photo['desc'] = $rr['desc'];
4319 if ($type == "xml") {
4320 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4322 $photo['thumb'] = $thumb;
4323 $data['photo'][] = $photo;
4327 return api_format_data("photos", $type, $data);
4331 * @brief upload a new photo or change an existing photo
4333 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4334 * @return string|array
4335 * @throws BadRequestException
4336 * @throws ForbiddenException
4337 * @throws ImagickException
4338 * @throws InternalServerErrorException
4339 * @throws NotFoundException
4341 function api_fr_photo_create_update($type)
4343 if (api_user() === false) {
4344 throw new ForbiddenException();
4347 $photo_id = $_REQUEST['photo_id'] ?? null;
4348 $desc = $_REQUEST['desc'] ?? null;
4349 $album = $_REQUEST['album'] ?? null;
4350 $album_new = $_REQUEST['album_new'] ?? null;
4351 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4352 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4353 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4354 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4355 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4357 // do several checks on input parameters
4358 // we do not allow calls without album string
4359 if ($album == null) {
4360 throw new BadRequestException("no albumname specified");
4362 // if photo_id == null --> we are uploading a new photo
4363 if ($photo_id == null) {
4366 // error if no media posted in create-mode
4367 if (empty($_FILES['media'])) {
4369 throw new BadRequestException("no media data submitted");
4372 // album_new will be ignored in create-mode
4377 // check if photo is existing in databasei
4378 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4379 throw new BadRequestException("photo not available");
4383 // checks on acl strings provided by clients
4384 $acl_input_error = false;
4385 $acl_input_error |= check_acl_input($allow_cid);
4386 $acl_input_error |= check_acl_input($deny_cid);
4387 $acl_input_error |= check_acl_input($allow_gid);
4388 $acl_input_error |= check_acl_input($deny_gid);
4389 if ($acl_input_error) {
4390 throw new BadRequestException("acl data invalid");
4392 // now let's upload the new media in create-mode
4393 if ($mode == "create") {
4394 $media = $_FILES['media'];
4395 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4397 // return success of updating or error message
4398 if (!is_null($data)) {
4399 return api_format_data("photo_create", $type, $data);
4401 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4405 // now let's do the changes in update-mode
4406 if ($mode == "update") {
4407 $updated_fields = [];
4409 if (!is_null($desc)) {
4410 $updated_fields['desc'] = $desc;
4413 if (!is_null($album_new)) {
4414 $updated_fields['album'] = $album_new;
4417 if (!is_null($allow_cid)) {
4418 $allow_cid = trim($allow_cid);
4419 $updated_fields['allow_cid'] = $allow_cid;
4422 if (!is_null($deny_cid)) {
4423 $deny_cid = trim($deny_cid);
4424 $updated_fields['deny_cid'] = $deny_cid;
4427 if (!is_null($allow_gid)) {
4428 $allow_gid = trim($allow_gid);
4429 $updated_fields['allow_gid'] = $allow_gid;
4432 if (!is_null($deny_gid)) {
4433 $deny_gid = trim($deny_gid);
4434 $updated_fields['deny_gid'] = $deny_gid;
4438 if (count($updated_fields) > 0) {
4439 $nothingtodo = false;
4440 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4442 $nothingtodo = true;
4445 if (!empty($_FILES['media'])) {
4446 $nothingtodo = false;
4447 $media = $_FILES['media'];
4448 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4449 if (!is_null($data)) {
4450 return api_format_data("photo_update", $type, $data);
4454 // return success of updating or error message
4456 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4457 return api_format_data("photo_update", $type, ['$result' => $answer]);
4460 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4461 return api_format_data("photo_update", $type, ['$result' => $answer]);
4463 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4466 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4470 * @brief delete a single photo from the database through api
4472 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4473 * @return string|array
4474 * @throws BadRequestException
4475 * @throws ForbiddenException
4476 * @throws InternalServerErrorException
4478 function api_fr_photo_delete($type)
4480 if (api_user() === false) {
4481 throw new ForbiddenException();
4485 $photo_id = $_REQUEST['photo_id'] ?? null;
4487 // do several checks on input parameters
4488 // we do not allow calls without photo id
4489 if ($photo_id == null) {
4490 throw new BadRequestException("no photo_id specified");
4493 // check if photo is existing in database
4494 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4495 throw new BadRequestException("photo not available");
4498 // now we can perform on the deletion of the photo
4499 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4501 // return success of deletion or error message
4503 // retrieve the id of the parent element (the photo element)
4504 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4505 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4507 if (!DBA::isResult($photo_item)) {
4508 throw new InternalServerErrorException("problem with deleting items occured");
4510 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4511 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4512 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4514 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4515 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4517 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4523 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4525 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4526 * @return string|array
4527 * @throws BadRequestException
4528 * @throws ForbiddenException
4529 * @throws InternalServerErrorException
4530 * @throws NotFoundException
4532 function api_fr_photo_detail($type)
4534 if (api_user() === false) {
4535 throw new ForbiddenException();
4537 if (empty($_REQUEST['photo_id'])) {
4538 throw new BadRequestException("No photo id.");
4541 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4542 $photo_id = $_REQUEST['photo_id'];
4544 // prepare json/xml output with data from database for the requested photo
4545 $data = prepare_photo_data($type, $scale, $photo_id);
4547 return api_format_data("photo_detail", $type, $data);
4552 * Updates the user’s profile image.
4554 * @brief updates the profile image for the user (either a specified profile or the default profile)
4556 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4558 * @return string|array
4559 * @throws BadRequestException
4560 * @throws ForbiddenException
4561 * @throws ImagickException
4562 * @throws InternalServerErrorException
4563 * @throws NotFoundException
4564 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4566 function api_account_update_profile_image($type)
4568 if (api_user() === false) {
4569 throw new ForbiddenException();
4572 $profile_id = $_REQUEST['profile_id'] ?? 0;
4574 // error if image data is missing
4575 if (empty($_FILES['image'])) {
4576 throw new BadRequestException("no media data submitted");
4579 // check if specified profile id is valid
4580 if ($profile_id != 0) {
4581 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4582 // error message if specified profile id is not in database
4583 if (!DBA::isResult($profile)) {
4584 throw new BadRequestException("profile_id not available");
4586 $is_default_profile = $profile['is-default'];
4588 $is_default_profile = 1;
4591 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4593 if (!empty($_FILES['image'])) {
4594 $media = $_FILES['image'];
4595 } elseif (!empty($_FILES['media'])) {
4596 $media = $_FILES['media'];
4598 // save new profile image
4599 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4602 if (is_array($media['type'])) {
4603 $filetype = $media['type'][0];
4605 $filetype = $media['type'];
4607 if ($filetype == "image/jpeg") {
4609 } elseif ($filetype == "image/png") {
4612 throw new InternalServerErrorException('Unsupported filetype');
4615 // change specified profile or all profiles to the new resource-id
4616 if ($is_default_profile) {
4617 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4618 Photo::update(['profile' => false], $condition);
4620 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4621 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4622 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4625 Contact::updateSelfFromUserID(api_user(), true);
4627 // Update global directory in background
4628 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4629 if ($url && strlen(Config::get('system', 'directory'))) {
4630 Worker::add(PRIORITY_LOW, "Directory", $url);
4633 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4635 // output for client
4637 return api_account_verify_credentials($type);
4639 // SaveMediaToDatabase failed for some reason
4640 throw new InternalServerErrorException("image upload failed");
4644 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4645 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4646 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4647 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4648 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4649 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4650 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4651 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4652 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4655 * Update user profile
4657 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4659 * @return array|string
4660 * @throws BadRequestException
4661 * @throws ForbiddenException
4662 * @throws ImagickException
4663 * @throws InternalServerErrorException
4664 * @throws UnauthorizedException
4666 function api_account_update_profile($type)
4668 $local_user = api_user();
4669 $api_user = api_get_user(get_app());
4671 if (!empty($_POST['name'])) {
4672 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4673 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4674 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4675 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4678 if (isset($_POST['description'])) {
4679 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4680 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4681 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4684 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4685 // Update global directory in background
4686 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4687 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4690 return api_account_verify_credentials($type);
4693 /// @TODO move to top of file or somewhere better
4694 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4698 * @param string $acl_string
4702 function check_acl_input($acl_string)
4704 if (empty($acl_string)) {
4708 $contact_not_found = false;
4710 // split <x><y><z> into array of cid's
4711 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4713 // check for each cid if it is available on server
4714 $cid_array = $array[0];
4715 foreach ($cid_array as $cid) {
4716 $cid = str_replace("<", "", $cid);
4717 $cid = str_replace(">", "", $cid);
4718 $condition = ['id' => $cid, 'uid' => api_user()];
4719 $contact_not_found |= !DBA::exists('contact', $condition);
4721 return $contact_not_found;
4725 * @param string $mediatype
4726 * @param array $media
4727 * @param string $type
4728 * @param string $album
4729 * @param string $allow_cid
4730 * @param string $deny_cid
4731 * @param string $allow_gid
4732 * @param string $deny_gid
4733 * @param string $desc
4734 * @param integer $profile
4735 * @param boolean $visibility
4736 * @param string $photo_id
4738 * @throws BadRequestException
4739 * @throws ForbiddenException
4740 * @throws ImagickException
4741 * @throws InternalServerErrorException
4742 * @throws NotFoundException
4743 * @throws UnauthorizedException
4745 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)
4753 if (is_array($media)) {
4754 if (is_array($media['tmp_name'])) {
4755 $src = $media['tmp_name'][0];
4757 $src = $media['tmp_name'];
4759 if (is_array($media['name'])) {
4760 $filename = basename($media['name'][0]);
4762 $filename = basename($media['name']);
4764 if (is_array($media['size'])) {
4765 $filesize = intval($media['size'][0]);
4767 $filesize = intval($media['size']);
4769 if (is_array($media['type'])) {
4770 $filetype = $media['type'][0];
4772 $filetype = $media['type'];
4776 if ($filetype == "") {
4777 $filetype = Images::guessType($filename);
4779 $imagedata = @getimagesize($src);
4781 $filetype = $imagedata['mime'];
4784 "File upload src: " . $src . " - filename: " . $filename .
4785 " - size: " . $filesize . " - type: " . $filetype,
4789 // check if there was a php upload error
4790 if ($filesize == 0 && $media['error'] == 1) {
4791 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4793 // check against max upload size within Friendica instance
4794 $maximagesize = Config::get('system', 'maximagesize');
4795 if ($maximagesize && ($filesize > $maximagesize)) {
4796 $formattedBytes = Strings::formatBytes($maximagesize);
4797 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4800 // create Photo instance with the data of the image
4801 $imagedata = @file_get_contents($src);
4802 $Image = new Image($imagedata, $filetype);
4803 if (!$Image->isValid()) {
4804 throw new InternalServerErrorException("unable to process image data");
4807 // check orientation of image
4808 $Image->orient($src);
4811 // check max length of images on server
4812 $max_length = Config::get('system', 'max_image_length');
4814 $max_length = MAX_IMAGE_LENGTH;
4816 if ($max_length > 0) {
4817 $Image->scaleDown($max_length);
4818 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4820 $width = $Image->getWidth();
4821 $height = $Image->getHeight();
4823 // create a new resource-id if not already provided
4824 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4826 if ($mediatype == "photo") {
4827 // upload normal image (scales 0, 1, 2)
4828 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4830 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4832 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4834 if ($width > 640 || $height > 640) {
4835 $Image->scaleDown(640);
4836 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4838 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4842 if ($width > 320 || $height > 320) {
4843 $Image->scaleDown(320);
4844 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4846 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4849 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4850 } elseif ($mediatype == "profileimage") {
4851 // upload profile image (scales 4, 5, 6)
4852 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4854 if ($width > 300 || $height > 300) {
4855 $Image->scaleDown(300);
4856 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4858 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4862 if ($width > 80 || $height > 80) {
4863 $Image->scaleDown(80);
4864 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4866 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4870 if ($width > 48 || $height > 48) {
4871 $Image->scaleDown(48);
4872 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4874 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4877 $Image->__destruct();
4878 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4881 if (isset($r) && $r) {
4882 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4883 if ($photo_id == null && $mediatype == "photo") {
4884 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4886 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4887 return prepare_photo_data($type, false, $resource_id);
4889 throw new InternalServerErrorException("image upload failed");
4895 * @param string $hash
4896 * @param string $allow_cid
4897 * @param string $deny_cid
4898 * @param string $allow_gid
4899 * @param string $deny_gid
4900 * @param string $filetype
4901 * @param boolean $visibility
4902 * @throws InternalServerErrorException
4904 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4906 // get data about the api authenticated user
4907 $uri = Item::newURI(intval(api_user()));
4908 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4911 $arr['guid'] = System::createUUID();
4912 $arr['uid'] = intval(api_user());
4914 $arr['parent-uri'] = $uri;
4915 $arr['type'] = 'photo';
4917 $arr['resource-id'] = $hash;
4918 $arr['contact-id'] = $owner_record['id'];
4919 $arr['owner-name'] = $owner_record['name'];
4920 $arr['owner-link'] = $owner_record['url'];
4921 $arr['owner-avatar'] = $owner_record['thumb'];
4922 $arr['author-name'] = $owner_record['name'];
4923 $arr['author-link'] = $owner_record['url'];
4924 $arr['author-avatar'] = $owner_record['thumb'];
4926 $arr['allow_cid'] = $allow_cid;
4927 $arr['allow_gid'] = $allow_gid;
4928 $arr['deny_cid'] = $deny_cid;
4929 $arr['deny_gid'] = $deny_gid;
4930 $arr['visible'] = $visibility;
4934 'image/jpeg' => 'jpg',
4935 'image/png' => 'png',
4936 'image/gif' => 'gif'
4939 // adds link to the thumbnail scale photo
4940 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4941 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4944 // do the magic for storing the item in the database and trigger the federation to other contacts
4950 * @param string $type
4952 * @param string $photo_id
4955 * @throws BadRequestException
4956 * @throws ForbiddenException
4957 * @throws ImagickException
4958 * @throws InternalServerErrorException
4959 * @throws NotFoundException
4960 * @throws UnauthorizedException
4962 function prepare_photo_data($type, $scale, $photo_id)
4965 $user_info = api_get_user($a);
4967 if ($user_info === false) {
4968 throw new ForbiddenException();
4971 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4972 $data_sql = ($scale === false ? "" : "data, ");
4974 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4975 // clients needs to convert this in their way for further processing
4977 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4978 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4979 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4980 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4981 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4982 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4984 intval(local_user()),
4985 DBA::escape($photo_id),
4990 'image/jpeg' => 'jpg',
4991 'image/png' => 'png',
4992 'image/gif' => 'gif'
4995 // prepare output data for photo
4996 if (DBA::isResult($r)) {
4997 $data = ['photo' => $r[0]];
4998 $data['photo']['id'] = $data['photo']['resource-id'];
4999 if ($scale !== false) {
5000 $data['photo']['data'] = base64_encode($data['photo']['data']);
5002 unset($data['photo']['datasize']); //needed only with scale param
5004 if ($type == "xml") {
5005 $data['photo']['links'] = [];
5006 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5007 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5009 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5012 $data['photo']['link'] = [];
5013 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5015 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5016 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5020 unset($data['photo']['resource-id']);
5021 unset($data['photo']['minscale']);
5022 unset($data['photo']['maxscale']);
5024 throw new NotFoundException();
5027 // retrieve item element for getting activities (like, dislike etc.) related to photo
5028 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5029 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5031 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5033 // retrieve comments on photo
5034 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5035 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5037 $statuses = Item::selectForUser(api_user(), [], $condition);
5039 // prepare output of comments
5040 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5042 if ($type == "xml") {
5044 foreach ($commentData as $comment) {
5045 $comments[$k++ . ":comment"] = $comment;
5048 foreach ($commentData as $comment) {
5049 $comments[] = $comment;
5052 $data['photo']['friendica_comments'] = $comments;
5054 // include info if rights on photo and rights on item are mismatching
5055 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5056 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5057 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5058 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5059 $data['photo']['rights_mismatch'] = $rights_mismatch;
5066 * Similar as /mod/redir.php
5067 * redirect to 'url' after dfrn auth
5069 * Why this when there is mod/redir.php already?
5070 * This use api_user() and api_login()
5073 * c_url: url of remote contact to auth to
5074 * url: string, url to redirect after auth
5076 function api_friendica_remoteauth()
5078 $url = $_GET['url'] ?? '';
5079 $c_url = $_GET['c_url'] ?? '';
5081 if ($url === '' || $c_url === '') {
5082 throw new BadRequestException("Wrong parameters.");
5085 $c_url = Strings::normaliseLink($c_url);
5089 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5090 if (!DBA::isResult($contact)) {
5091 throw new BadRequestException("Unknown contact");
5094 $cid = $contact['id'];
5096 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5098 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5099 System::externalRedirect($url ?: $c_url);
5102 if ($contact['duplex'] && $contact['issued-id']) {
5103 $orig_id = $contact['issued-id'];
5104 $dfrn_id = '1:' . $orig_id;
5106 if ($contact['duplex'] && $contact['dfrn-id']) {
5107 $orig_id = $contact['dfrn-id'];
5108 $dfrn_id = '0:' . $orig_id;
5111 $sec = Strings::getRandomHex();
5113 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5114 'sec' => $sec, 'expire' => time() + 45];
5115 DBA::insert('profile_check', $fields);
5117 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5118 $dest = ($url ? '&destination_url=' . $url : '');
5120 System::externalRedirect(
5121 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5122 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5123 . '&type=profile&sec=' . $sec . $dest
5126 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5129 * Return an item with announcer data if it had been announced
5131 * @param array $item Item array
5132 * @return array Item array with announce data
5134 function api_get_announce($item)
5136 // Quit if the item already has got a different owner and author
5137 if ($item['owner-id'] != $item['author-id']) {
5141 // Don't change original or Diaspora posts
5142 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5146 // Quit if we do now the original author and it had been a post from a native network
5147 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5151 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5152 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5153 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5154 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5155 if (!DBA::isResult($announce)) {
5159 return array_merge($item, $announce);
5163 * @brief Return the item shared, if the item contains only the [share] tag
5165 * @param array $item Sharer item
5166 * @return array|false Shared item or false if not a reshare
5167 * @throws ImagickException
5168 * @throws InternalServerErrorException
5170 function api_share_as_retweet(&$item)
5172 $body = trim($item["body"]);
5174 if (Diaspora::isReshare($body, false) === false) {
5175 if ($item['author-id'] == $item['owner-id']) {
5178 // Reshares from OStatus, ActivityPub and Twitter
5179 $reshared_item = $item;
5180 $reshared_item['owner-id'] = $reshared_item['author-id'];
5181 $reshared_item['owner-link'] = $reshared_item['author-link'];
5182 $reshared_item['owner-name'] = $reshared_item['author-name'];
5183 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5184 return $reshared_item;
5188 $reshared = Item::getShareArray($item);
5189 if (empty($reshared)) {
5193 $reshared_item = $item;
5195 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5199 if (!empty($reshared['comment'])) {
5200 $item['body'] = $reshared['comment'];
5203 $reshared_item["share-pre-body"] = $reshared['comment'];
5204 $reshared_item["body"] = $reshared['shared'];
5205 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5206 $reshared_item["author-name"] = $reshared['author'];
5207 $reshared_item["author-link"] = $reshared['profile'];
5208 $reshared_item["author-avatar"] = $reshared['avatar'];
5209 $reshared_item["plink"] = $reshared['link'] ?? '';
5210 $reshared_item["created"] = $reshared['posted'];
5211 $reshared_item["edited"] = $reshared['posted'];
5213 // Try to fetch the original item
5214 if (!empty($reshared['guid'])) {
5215 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5216 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5217 $condition = ['id' => $original_id];
5222 if (!empty($condition)) {
5223 $original_item = Item::selectFirst([], $condition);
5224 if (DBA::isResult($original_item)) {
5225 $reshared_item = array_merge($reshared_item, $original_item);
5229 return $reshared_item;
5234 * @param array $item
5239 function api_in_reply_to($item)
5243 $in_reply_to['status_id'] = null;
5244 $in_reply_to['user_id'] = null;
5245 $in_reply_to['status_id_str'] = null;
5246 $in_reply_to['user_id_str'] = null;
5247 $in_reply_to['screen_name'] = null;
5249 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5250 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5251 if (DBA::isResult($parent)) {
5252 $in_reply_to['status_id'] = intval($parent['id']);
5254 $in_reply_to['status_id'] = intval($item['parent']);
5257 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5259 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5260 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5262 if (DBA::isResult($parent)) {
5263 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5264 $in_reply_to['user_id'] = intval($parent['author-id']);
5265 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5268 // There seems to be situation, where both fields are identical:
5269 // https://github.com/friendica/friendica/issues/1010
5270 // This is a bugfix for that.
5271 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5272 Logger::warning(API_LOG_PREFIX . 'ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5273 $in_reply_to['status_id'] = null;
5274 $in_reply_to['user_id'] = null;
5275 $in_reply_to['status_id_str'] = null;
5276 $in_reply_to['user_id_str'] = null;
5277 $in_reply_to['screen_name'] = null;
5281 return $in_reply_to;
5286 * @param string $text
5289 * @throws InternalServerErrorException
5291 function api_clean_plain_items($text)
5293 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5295 $text = BBCode::cleanPictureLinks($text);
5296 $URLSearchString = "^\[\]";
5298 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5300 if ($include_entities == "true") {
5301 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5304 // Simplify "attachment" element
5305 $text = BBCode::removeAttachment($text);
5312 * @param array $contacts
5316 function api_best_nickname(&$contacts)
5320 if (count($contacts) == 0) {
5324 foreach ($contacts as $contact) {
5325 if ($contact["network"] == "") {
5326 $contact["network"] = "dfrn";
5327 $best_contact = [$contact];
5331 if (sizeof($best_contact) == 0) {
5332 foreach ($contacts as $contact) {
5333 if ($contact["network"] == "dfrn") {
5334 $best_contact = [$contact];
5339 if (sizeof($best_contact) == 0) {
5340 foreach ($contacts as $contact) {
5341 if ($contact["network"] == "dspr") {
5342 $best_contact = [$contact];
5347 if (sizeof($best_contact) == 0) {
5348 foreach ($contacts as $contact) {
5349 if ($contact["network"] == "stat") {
5350 $best_contact = [$contact];
5355 if (sizeof($best_contact) == 0) {
5356 foreach ($contacts as $contact) {
5357 if ($contact["network"] == "pump") {
5358 $best_contact = [$contact];
5363 if (sizeof($best_contact) == 0) {
5364 foreach ($contacts as $contact) {
5365 if ($contact["network"] == "twit") {
5366 $best_contact = [$contact];
5371 if (sizeof($best_contact) == 1) {
5372 $contacts = $best_contact;
5374 $contacts = [$contacts[0]];
5379 * Return all or a specified group of the user with the containing contacts.
5381 * @param string $type Return type (atom, rss, xml, json)
5383 * @return array|string
5384 * @throws BadRequestException
5385 * @throws ForbiddenException
5386 * @throws ImagickException
5387 * @throws InternalServerErrorException
5388 * @throws UnauthorizedException
5390 function api_friendica_group_show($type)
5394 if (api_user() === false) {
5395 throw new ForbiddenException();
5399 $user_info = api_get_user($a);
5400 $gid = $_REQUEST['gid'] ?? 0;
5401 $uid = $user_info['uid'];
5403 // get data of the specified group id or all groups if not specified
5406 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5410 // error message if specified gid is not in database
5411 if (!DBA::isResult($r)) {
5412 throw new BadRequestException("gid not available");
5416 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5421 // loop through all groups and retrieve all members for adding data in the user array
5423 foreach ($r as $rr) {
5424 $members = Contact::getByGroupId($rr['id']);
5427 if ($type == "xml") {
5428 $user_element = "users";
5430 foreach ($members as $member) {
5431 $user = api_get_user($a, $member['nurl']);
5432 $users[$k++.":user"] = $user;
5435 $user_element = "user";
5436 foreach ($members as $member) {
5437 $user = api_get_user($a, $member['nurl']);
5441 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5443 return api_format_data("groups", $type, ['group' => $grps]);
5445 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5449 * Delete the specified group of the user.
5451 * @param string $type Return type (atom, rss, xml, json)
5453 * @return array|string
5454 * @throws BadRequestException
5455 * @throws ForbiddenException
5456 * @throws ImagickException
5457 * @throws InternalServerErrorException
5458 * @throws UnauthorizedException
5460 function api_friendica_group_delete($type)
5464 if (api_user() === false) {
5465 throw new ForbiddenException();
5469 $user_info = api_get_user($a);
5470 $gid = $_REQUEST['gid'] ?? 0;
5471 $name = $_REQUEST['name'] ?? '';
5472 $uid = $user_info['uid'];
5474 // error if no gid specified
5475 if ($gid == 0 || $name == "") {
5476 throw new BadRequestException('gid or name not specified');
5479 // get data of the specified group id
5481 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5485 // error message if specified gid is not in database
5486 if (!DBA::isResult($r)) {
5487 throw new BadRequestException('gid not available');
5490 // get data of the specified group id and group name
5492 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5497 // error message if specified gid is not in database
5498 if (!DBA::isResult($rname)) {
5499 throw new BadRequestException('wrong group name');
5503 $ret = Group::removeByName($uid, $name);
5506 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5507 return api_format_data("group_delete", $type, ['result' => $success]);
5509 throw new BadRequestException('other API error');
5512 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5517 * @param string $type Return type (atom, rss, xml, json)
5519 * @return array|string
5520 * @throws BadRequestException
5521 * @throws ForbiddenException
5522 * @throws ImagickException
5523 * @throws InternalServerErrorException
5524 * @throws UnauthorizedException
5525 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5527 function api_lists_destroy($type)
5531 if (api_user() === false) {
5532 throw new ForbiddenException();
5536 $user_info = api_get_user($a);
5537 $gid = $_REQUEST['list_id'] ?? 0;
5538 $uid = $user_info['uid'];
5540 // error if no gid specified
5542 throw new BadRequestException('gid not specified');
5545 // get data of the specified group id
5546 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5547 // error message if specified gid is not in database
5549 throw new BadRequestException('gid not available');
5552 if (Group::remove($gid)) {
5554 'name' => $group['name'],
5555 'id' => intval($gid),
5556 'id_str' => (string) $gid,
5557 'user' => $user_info
5560 return api_format_data("lists", $type, ['lists' => $list]);
5563 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5566 * Add a new group to the database.
5568 * @param string $name Group name
5569 * @param int $uid User ID
5570 * @param array $users List of users to add to the group
5573 * @throws BadRequestException
5575 function group_create($name, $uid, $users = [])
5577 // error if no name specified
5579 throw new BadRequestException('group name not specified');
5582 // get data of the specified group name
5584 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5588 // error message if specified group name already exists
5589 if (DBA::isResult($rname)) {
5590 throw new BadRequestException('group name already exists');
5593 // check if specified group name is a deleted group
5595 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5599 // error message if specified group name already exists
5600 if (DBA::isResult($rname)) {
5601 $reactivate_group = true;
5605 $ret = Group::create($uid, $name);
5607 $gid = Group::getIdByName($uid, $name);
5609 throw new BadRequestException('other API error');
5613 $erroraddinguser = false;
5615 foreach ($users as $user) {
5616 $cid = $user['cid'];
5617 // check if user really exists as contact
5619 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5623 if (count($contact)) {
5624 Group::addMember($gid, $cid);
5626 $erroraddinguser = true;
5627 $errorusers[] = $cid;
5631 // return success message incl. missing users in array
5632 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5634 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5638 * Create the specified group with the posted array of contacts.
5640 * @param string $type Return type (atom, rss, xml, json)
5642 * @return array|string
5643 * @throws BadRequestException
5644 * @throws ForbiddenException
5645 * @throws ImagickException
5646 * @throws InternalServerErrorException
5647 * @throws UnauthorizedException
5649 function api_friendica_group_create($type)
5653 if (api_user() === false) {
5654 throw new ForbiddenException();
5658 $user_info = api_get_user($a);
5659 $name = $_REQUEST['name'] ?? '';
5660 $uid = $user_info['uid'];
5661 $json = json_decode($_POST['json'], true);
5662 $users = $json['user'];
5664 $success = group_create($name, $uid, $users);
5666 return api_format_data("group_create", $type, ['result' => $success]);
5668 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5671 * Create a new group.
5673 * @param string $type Return type (atom, rss, xml, json)
5675 * @return array|string
5676 * @throws BadRequestException
5677 * @throws ForbiddenException
5678 * @throws ImagickException
5679 * @throws InternalServerErrorException
5680 * @throws UnauthorizedException
5681 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5683 function api_lists_create($type)
5687 if (api_user() === false) {
5688 throw new ForbiddenException();
5692 $user_info = api_get_user($a);
5693 $name = $_REQUEST['name'] ?? '';
5694 $uid = $user_info['uid'];
5696 $success = group_create($name, $uid);
5697 if ($success['success']) {
5699 'name' => $success['name'],
5700 'id' => intval($success['gid']),
5701 'id_str' => (string) $success['gid'],
5702 'user' => $user_info
5705 return api_format_data("lists", $type, ['lists'=>$grp]);
5708 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5711 * Update the specified group with the posted array of contacts.
5713 * @param string $type Return type (atom, rss, xml, json)
5715 * @return array|string
5716 * @throws BadRequestException
5717 * @throws ForbiddenException
5718 * @throws ImagickException
5719 * @throws InternalServerErrorException
5720 * @throws UnauthorizedException
5722 function api_friendica_group_update($type)
5726 if (api_user() === false) {
5727 throw new ForbiddenException();
5731 $user_info = api_get_user($a);
5732 $uid = $user_info['uid'];
5733 $gid = $_REQUEST['gid'] ?? 0;
5734 $name = $_REQUEST['name'] ?? '';
5735 $json = json_decode($_POST['json'], true);
5736 $users = $json['user'];
5738 // error if no name specified
5740 throw new BadRequestException('group name not specified');
5743 // error if no gid specified
5745 throw new BadRequestException('gid not specified');
5749 $members = Contact::getByGroupId($gid);
5750 foreach ($members as $member) {
5751 $cid = $member['id'];
5752 foreach ($users as $user) {
5753 $found = ($user['cid'] == $cid ? true : false);
5755 if (!isset($found) || !$found) {
5756 Group::removeMemberByName($uid, $name, $cid);
5761 $erroraddinguser = false;
5763 foreach ($users as $user) {
5764 $cid = $user['cid'];
5765 // check if user really exists as contact
5767 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5772 if (count($contact)) {
5773 Group::addMember($gid, $cid);
5775 $erroraddinguser = true;
5776 $errorusers[] = $cid;
5780 // return success message incl. missing users in array
5781 $status = ($erroraddinguser ? "missing user" : "ok");
5782 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5783 return api_format_data("group_update", $type, ['result' => $success]);
5786 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5789 * Update information about a group.
5791 * @param string $type Return type (atom, rss, xml, json)
5793 * @return array|string
5794 * @throws BadRequestException
5795 * @throws ForbiddenException
5796 * @throws ImagickException
5797 * @throws InternalServerErrorException
5798 * @throws UnauthorizedException
5799 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5801 function api_lists_update($type)
5805 if (api_user() === false) {
5806 throw new ForbiddenException();
5810 $user_info = api_get_user($a);
5811 $gid = $_REQUEST['list_id'] ?? 0;
5812 $name = $_REQUEST['name'] ?? '';
5813 $uid = $user_info['uid'];
5815 // error if no gid specified
5817 throw new BadRequestException('gid not specified');
5820 // get data of the specified group id
5821 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5822 // error message if specified gid is not in database
5824 throw new BadRequestException('gid not available');
5827 if (Group::update($gid, $name)) {
5830 'id' => intval($gid),
5831 'id_str' => (string) $gid,
5832 'user' => $user_info
5835 return api_format_data("lists", $type, ['lists' => $list]);
5839 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5843 * @param string $type Return type (atom, rss, xml, json)
5845 * @return array|string
5846 * @throws BadRequestException
5847 * @throws ForbiddenException
5848 * @throws ImagickException
5849 * @throws InternalServerErrorException
5851 function api_friendica_activity($type)
5855 if (api_user() === false) {
5856 throw new ForbiddenException();
5858 $verb = strtolower($a->argv[3]);
5859 $verb = preg_replace("|\..*$|", "", $verb);
5861 $id = $_REQUEST['id'] ?? 0;
5863 $res = Item::performLike($id, $verb);
5866 if ($type == "xml") {
5871 return api_format_data('ok', $type, ['ok' => $ok]);
5873 throw new BadRequestException('Error adding activity');
5877 /// @TODO move to top of file or somewhere better
5878 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5879 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5880 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5881 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5882 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5883 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5884 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5885 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5886 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5887 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5890 * @brief Returns notifications
5892 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5893 * @return string|array
5894 * @throws BadRequestException
5895 * @throws ForbiddenException
5896 * @throws InternalServerErrorException
5898 function api_friendica_notification($type)
5902 if (api_user() === false) {
5903 throw new ForbiddenException();
5906 throw new BadRequestException("Invalid argument count");
5908 $notes = DI::notify()->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5910 if ($type == "xml") {
5912 if (!empty($notes)) {
5913 foreach ($notes as $note) {
5914 $xmlnotes[] = ["@attributes" => $note];
5920 return api_format_data("notes", $type, ['note' => $notes]);
5924 * POST request with 'id' param as notification id
5926 * @brief Set notification as seen and returns associated item (if possible)
5928 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5929 * @return string|array
5930 * @throws BadRequestException
5931 * @throws ForbiddenException
5932 * @throws ImagickException
5933 * @throws InternalServerErrorException
5934 * @throws UnauthorizedException
5936 function api_friendica_notification_seen($type)
5939 $user_info = api_get_user($a);
5941 if (api_user() === false || $user_info === false) {
5942 throw new ForbiddenException();
5945 throw new BadRequestException("Invalid argument count");
5948 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5951 $note = $nm->getByID($id);
5952 if (is_null($note)) {
5953 throw new BadRequestException("Invalid argument");
5956 $nm->setSeen($note);
5957 if ($note['otype']=='item') {
5958 // would be really better with an ItemsManager and $im->getByID() :-P
5959 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5960 if (DBA::isResult($item)) {
5961 // we found the item, return it to the user
5962 $ret = api_format_items([$item], $user_info, false, $type);
5963 $data = ['status' => $ret];
5964 return api_format_data("status", $type, $data);
5966 // the item can't be found, but we set the note as seen, so we count this as a success
5968 return api_format_data('result', $type, ['result' => "success"]);
5971 /// @TODO move to top of file or somewhere better
5972 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5973 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5976 * @brief update a direct_message to seen state
5978 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5979 * @return string|array (success result=ok, error result=error with error message)
5980 * @throws BadRequestException
5981 * @throws ForbiddenException
5982 * @throws ImagickException
5983 * @throws InternalServerErrorException
5984 * @throws UnauthorizedException
5986 function api_friendica_direct_messages_setseen($type)
5989 if (api_user() === false) {
5990 throw new ForbiddenException();
5994 $user_info = api_get_user($a);
5995 $uid = $user_info['uid'];
5996 $id = $_REQUEST['id'] ?? 0;
5998 // return error if id is zero
6000 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6001 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6004 // error message if specified id is not in database
6005 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6006 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6007 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6010 // update seen indicator
6011 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6015 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6016 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6018 $answer = ['result' => 'error', 'message' => 'unknown error'];
6019 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6023 /// @TODO move to top of file or somewhere better
6024 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6027 * @brief search for direct_messages containing a searchstring through api
6029 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6030 * @param string $box
6031 * @return string|array (success: success=true if found and search_result contains found messages,
6032 * success=false if nothing was found, search_result='nothing found',
6033 * error: result=error with error message)
6034 * @throws BadRequestException
6035 * @throws ForbiddenException
6036 * @throws ImagickException
6037 * @throws InternalServerErrorException
6038 * @throws UnauthorizedException
6040 function api_friendica_direct_messages_search($type, $box = "")
6044 if (api_user() === false) {
6045 throw new ForbiddenException();
6049 $user_info = api_get_user($a);
6050 $searchstring = $_REQUEST['searchstring'] ?? '';
6051 $uid = $user_info['uid'];
6053 // error if no searchstring specified
6054 if ($searchstring == "") {
6055 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6056 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6059 // get data for the specified searchstring
6061 "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",
6063 DBA::escape('%'.$searchstring.'%')
6066 $profile_url = $user_info["url"];
6068 // message if nothing was found
6069 if (!DBA::isResult($r)) {
6070 $success = ['success' => false, 'search_results' => 'problem with query'];
6071 } elseif (count($r) == 0) {
6072 $success = ['success' => false, 'search_results' => 'nothing found'];
6075 foreach ($r as $item) {
6076 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6077 $recipient = $user_info;
6078 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6079 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6080 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6081 $sender = $user_info;
6084 if (isset($recipient) && isset($sender)) {
6085 $ret[] = api_format_messages($item, $recipient, $sender);
6088 $success = ['success' => true, 'search_results' => $ret];
6091 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6094 /// @TODO move to top of file or somewhere better
6095 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6098 * @brief return data of all the profiles a user has to the client
6100 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6101 * @return string|array
6102 * @throws BadRequestException
6103 * @throws ForbiddenException
6104 * @throws ImagickException
6105 * @throws InternalServerErrorException
6106 * @throws UnauthorizedException
6108 function api_friendica_profile_show($type)
6112 if (api_user() === false) {
6113 throw new ForbiddenException();
6117 $profile_id = $_REQUEST['profile_id'] ?? 0;
6119 // retrieve general information about profiles for user
6120 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6121 $directory = Config::get('system', 'directory');
6123 // get data of the specified profile id or all profiles of the user if not specified
6124 if ($profile_id != 0) {
6125 $r = Profile::getById(api_user(), $profile_id);
6126 // error message if specified gid is not in database
6127 if (!DBA::isResult($r)) {
6128 throw new BadRequestException("profile_id not available");
6131 $r = Profile::getListByUser(api_user());
6133 // loop through all returned profiles and retrieve data and users
6136 if (DBA::isResult($r)) {
6137 foreach ($r as $rr) {
6138 $profile = api_format_items_profiles($rr);
6140 // select all users from contact table, loop and prepare standard return for user data
6142 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6143 foreach ($nurls as $nurl) {
6144 $user = api_get_user($a, $nurl['nurl']);
6145 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6147 $profile['users'] = $users;
6149 // add prepared profile data to array for final return
6150 if ($type == "xml") {
6151 $profiles[$k++ . ":profile"] = $profile;
6153 $profiles[] = $profile;
6158 // return settings, authenticated user and profiles data
6159 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6161 $result = ['multi_profiles' => $multi_profiles ? true : false,
6162 'global_dir' => $directory,
6163 'friendica_owner' => api_get_user($a, $self['nurl']),
6164 'profiles' => $profiles];
6165 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6167 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6170 * Returns a list of saved searches.
6172 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6174 * @param string $type Return format: json or xml
6176 * @return string|array
6179 function api_saved_searches_list($type)
6181 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6184 while ($term = DBA::fetch($terms)) {
6186 'created_at' => api_date(time()),
6187 'id' => intval($term['id']),
6188 'id_str' => $term['id'],
6189 'name' => $term['term'],
6191 'query' => $term['term']
6197 return api_format_data("terms", $type, ['terms' => $result]);
6200 /// @TODO move to top of file or somewhere better
6201 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6204 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6206 * @brief Number of comments
6208 * @param object $data [Status, Status]
6212 function bindComments(&$data)
6214 if (count($data) == 0) {
6220 foreach ($data as $item) {
6221 $ids[] = $item['id'];
6224 $idStr = DBA::escape(implode(', ', $ids));
6225 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6226 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6227 $itemsData = DBA::toArray($items);
6229 foreach ($itemsData as $item) {
6230 $comments[$item['parent']] = $item['comments'];
6233 foreach ($data as $idx => $item) {
6235 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6240 @TODO Maybe open to implement?
6242 [pagename] => api/1.1/statuses/lookup.json
6243 [id] => 605138389168451584
6244 [include_cards] => true
6245 [cards_platform] => Android-12
6246 [include_entities] => true
6247 [include_my_retweet] => 1
6249 [include_reply_count] => true
6250 [include_descendent_reply_count] => true
6254 Not implemented by now:
6255 statuses/retweets_of_me
6260 account/update_location
6261 account/update_profile_background_image
6264 friendica/profile/update
6265 friendica/profile/create
6266 friendica/profile/delete
6268 Not implemented in status.net:
6269 statuses/retweeted_to_me
6270 statuses/retweeted_by_me
6271 direct_messages/destroy
6273 account/update_delivery_device
6274 notifications/follow