3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\Verb;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\TooManyRequestsException;
55 use Friendica\Network\HTTPException\UnauthorizedException;
56 use Friendica\Object\Image;
57 use Friendica\Protocol\Activity;
58 use Friendica\Protocol\Diaspora;
59 use Friendica\Security\BasicAuth;
60 use Friendica\Security\FKOAuth1;
61 use Friendica\Security\OAuth;
62 use Friendica\Security\OAuth1\OAuthRequest;
63 use Friendica\Security\OAuth1\OAuthUtil;
64 use Friendica\Util\DateTimeFormat;
65 use Friendica\Util\Images;
66 use Friendica\Util\Network;
67 use Friendica\Util\Proxy as ProxyUtils;
68 use Friendica\Util\Strings;
69 use Friendica\Util\XML;
71 require_once __DIR__ . '/../mod/item.php';
72 require_once __DIR__ . '/../mod/wall_upload.php';
74 define('API_METHOD_ANY', '*');
75 define('API_METHOD_GET', 'GET');
76 define('API_METHOD_POST', 'POST,PUT');
77 define('API_METHOD_DELETE', 'POST,DELETE');
79 define('API_LOG_PREFIX', 'API {action} - ');
87 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
88 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
89 * into a page, and visitors will post something without noticing it).
93 $user = OAuth::getCurrentUserID();
98 $user = BasicAuth::getCurrentUserID(false);
103 if (!empty($_SESSION['allow_api'])) {
111 * Get source name from API client
113 * Clients can send 'source' parameter to be show in post metadata
114 * as "sent via <source>".
115 * Some clients doesn't send a source param, we support ones we know
116 * (only Twidere, atm)
119 * Client source name, default to "api" if unset/unknown
122 function api_source()
124 $application = OAuth::getCurrentApplicationToken();
125 if (empty($application)) {
126 $application = BasicAuth::getCurrentApplicationToken();
128 return $application['name'] ?? 'api';
132 * Format date for API
134 * @param string $str Source date, as UTC
135 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
138 function api_date($str)
140 // Wed May 23 06:01:13 +0000 2007
141 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
145 * Register a function to be the endpoint for defined API path.
147 * @param string $path API URL path, relative to DI::baseUrl()
148 * @param string $func Function name to call on path request
149 * @param bool $auth API need logged user
150 * @param string $method HTTP method reqiured to call this endpoint.
151 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152 * Default to API_METHOD_ANY
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
164 // Workaround for hotot
165 $path = str_replace("api/", "api/1.1/", $path);
175 * Log in user via OAuth1 or Simple HTTP Auth.
176 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
179 * @throws ForbiddenException
180 * @throws InternalServerErrorException
181 * @throws UnauthorizedException
182 * @hook 'authenticate'
184 * 'username' => username from login form
185 * 'password' => password from login form
186 * 'authenticated' => return status,
187 * 'user_record' => return authenticated user record
189 function api_login(App $a)
191 $_SESSION["allow_api"] = false;
193 // workaround for HTTP-auth in CGI mode
194 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
195 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
196 if (strlen($userpass)) {
197 list($name, $password) = explode(':', $userpass);
198 $_SERVER['PHP_AUTH_USER'] = $name;
199 $_SERVER['PHP_AUTH_PW'] = $password;
203 if (empty($_SERVER['PHP_AUTH_USER'])) {
204 // Try OAuth when no user is provided
205 $oauth1 = new FKOAuth1();
208 $request = OAuthRequest::from_request();
209 list($consumer, $token) = $oauth1->verify_request($request);
210 if (!is_null($token)) {
211 $oauth1->loginUser($token->uid);
212 Session::set('allow_api', true);
215 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
216 var_dump($consumer, $token);
218 } catch (Exception $e) {
219 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
222 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
223 header('WWW-Authenticate: Basic realm="Friendica"');
224 throw new UnauthorizedException("This API requires login");
227 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
228 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
230 // allow "user@server" login (but ignore 'server' part)
231 $at = strstr($user, "@", true);
236 // next code from mod/auth.php. needs better solution
240 'username' => trim($user),
241 'password' => trim($password),
242 'authenticated' => 0,
243 'user_record' => null,
247 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
248 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
249 * and later addons should not interfere with an earlier one that succeeded.
251 Hook::callAll('authenticate', $addon_auth);
253 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
254 $record = $addon_auth['user_record'];
256 $user_id = User::authenticate(trim($user), trim($password), true);
257 if ($user_id !== false) {
258 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
262 if (!DBA::isResult($record)) {
263 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
264 header('WWW-Authenticate: Basic realm="Friendica"');
265 //header('HTTP/1.0 401 Unauthorized');
266 //die('This api requires login');
267 throw new UnauthorizedException("This API requires login");
270 // Don't refresh the login date more often than twice a day to spare database writes
271 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
273 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
275 $_SESSION["allow_api"] = true;
277 Hook::callAll('logged_in', $a->user);
281 * Check HTTP method of called API
283 * API endpoints can define which HTTP method to accept when called.
284 * This function check the current HTTP method agains endpoint
287 * @param string $method Required methods, uppercase, separated by comma
290 function api_check_method($method)
292 if ($method == "*") {
295 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
299 * Main API entry point
301 * Authenticate user, call registered API function, set HTTP headers
304 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
305 * @return string|array API call result
308 function api_call(App $a, App\Arguments $args = null)
310 global $API, $called_api;
317 if (strpos($args->getCommand(), ".xml") > 0) {
320 if (strpos($args->getCommand(), ".json") > 0) {
323 if (strpos($args->getCommand(), ".rss") > 0) {
326 if (strpos($args->getCommand(), ".atom") > 0) {
331 foreach ($API as $p => $info) {
332 if (strpos($args->getCommand(), $p) === 0) {
333 if (!api_check_method($info['method'])) {
334 throw new MethodNotAllowedException();
337 $called_api = explode("/", $p);
339 if (!empty($info['auth']) && api_user() === false) {
341 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
344 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
346 $stamp = microtime(true);
347 $return = call_user_func($info['func'], $type);
348 $duration = floatval(microtime(true) - $stamp);
350 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
352 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
354 if (false === $return) {
356 * api function returned false withour throw an
357 * exception. This should not happend, throw a 500
359 throw new InternalServerErrorException();
364 header("Content-Type: text/xml");
367 header("Content-Type: application/json");
368 if (!empty($return)) {
369 $json = json_encode(end($return));
370 if (!empty($_GET['callback'])) {
371 $json = $_GET['callback'] . "(" . $json . ")";
377 header("Content-Type: application/rss+xml");
378 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
381 header("Content-Type: application/atom+xml");
382 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
389 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
390 throw new NotFoundException();
391 } catch (HTTPException $e) {
392 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
393 return api_error($type, $e, $args);
398 * Format API error string
400 * @param string $type Return type (xml, json, rss, as)
401 * @param object $e HTTPException Error object
402 * @param App\Arguments $args The App arguments
403 * @return string|array error message formatted as $type
405 function api_error($type, $e, App\Arguments $args)
407 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
408 /// @TODO: https://dev.twitter.com/overview/api/response-codes
410 $error = ["error" => $error,
411 "code" => $e->getCode() . " " . $e->httpdesc,
412 "request" => $args->getQueryString()];
414 $return = api_format_data('status', $type, ['status' => $error]);
418 header("Content-Type: text/xml");
421 header("Content-Type: application/json");
422 $return = json_encode($return);
425 header("Content-Type: application/rss+xml");
428 header("Content-Type: application/atom+xml");
436 * Set values for RSS template
439 * @param array $arr Array to be passed to template
440 * @param array $user_info User info
442 * @throws BadRequestException
443 * @throws ImagickException
444 * @throws InternalServerErrorException
445 * @throws UnauthorizedException
446 * @todo find proper type-hints
448 function api_rss_extra(App $a, $arr, $user_info)
450 if (is_null($user_info)) {
451 $user_info = api_get_user($a);
454 $arr['$user'] = $user_info;
456 'alternate' => $user_info['url'],
457 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
458 'base' => DI::baseUrl(),
459 'updated' => api_date(null),
460 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
461 'language' => $user_info['lang'],
462 'logo' => DI::baseUrl() . "/images/friendica-32.png",
470 * Unique contact to contact url.
472 * @param int $id Contact id
473 * @return bool|string
474 * Contact url or False if contact id is unknown
477 function api_unique_id_to_nurl($id)
479 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
481 if (DBA::isResult($r)) {
489 * Get user info array.
492 * @param int|string $contact_id Contact ID or URL
494 * @throws BadRequestException
495 * @throws ImagickException
496 * @throws InternalServerErrorException
497 * @throws UnauthorizedException
499 function api_get_user(App $a, $contact_id = null)
507 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
509 // Searching for contact URL
510 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
511 $user = DBA::escape(Strings::normaliseLink($contact_id));
513 $extra_query = "AND `contact`.`nurl` = '%s' ";
514 if (api_user() !== false) {
515 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
519 // Searching for contact id with uid = 0
520 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
521 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
524 throw new BadRequestException("User ID ".$contact_id." not found.");
528 $extra_query = "AND `contact`.`nurl` = '%s' ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
534 if (is_null($user) && !empty($_GET['user_id'])) {
535 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
538 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
542 $extra_query = "AND `contact`.`nurl` = '%s' ";
543 if (api_user() !== false) {
544 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
547 if (is_null($user) && !empty($_GET['screen_name'])) {
548 $user = DBA::escape($_GET['screen_name']);
549 $extra_query = "AND `contact`.`nick` = '%s' ";
550 if (api_user() !== false) {
551 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
555 if (is_null($user) && !empty($_GET['profileurl'])) {
556 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
557 $extra_query = "AND `contact`.`nurl` = '%s' ";
558 if (api_user() !== false) {
559 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
563 // $called_api is the API path exploded on / and is expected to have at least 2 elements
564 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
565 $argid = count($called_api);
566 if (!empty($a->argv[$argid])) {
567 $data = explode(".", $a->argv[$argid]);
568 if (count($data) > 1) {
569 list($user, $null) = $data;
572 if (is_numeric($user)) {
573 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
577 $extra_query = "AND `contact`.`nurl` = '%s' ";
578 if (api_user() !== false) {
579 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
583 $user = DBA::escape($user);
584 $extra_query = "AND `contact`.`nick` = '%s' ";
585 if (api_user() !== false) {
586 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
591 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
594 if (api_user() === false) {
599 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
603 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
607 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
613 // Selecting the id by priority, friendica first
614 if (is_array($uinfo)) {
615 api_best_nickname($uinfo);
618 // if the contact wasn't found, fetch it from the contacts with uid = 0
619 if (!DBA::isResult($uinfo)) {
621 throw new BadRequestException("User not found.");
624 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
626 if (DBA::isResult($contact)) {
628 'id' => $contact["id"],
629 'id_str' => (string) $contact["id"],
630 'name' => $contact["name"],
631 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
632 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
633 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
634 'profile_image_url' => $contact["micro"],
635 'profile_image_url_https' => $contact["micro"],
636 'profile_image_url_profile_size' => $contact["thumb"],
637 'profile_image_url_large' => $contact["photo"],
638 'url' => $contact["url"],
639 'protected' => false,
640 'followers_count' => 0,
641 'friends_count' => 0,
643 'created_at' => api_date($contact["created"]),
644 'favourites_count' => 0,
646 'time_zone' => 'UTC',
647 'geo_enabled' => false,
649 'statuses_count' => 0,
651 'contributors_enabled' => false,
652 'is_translator' => false,
653 'is_translation_enabled' => false,
654 'following' => false,
655 'follow_request_sent' => false,
656 'statusnet_blocking' => false,
657 'notifications' => false,
658 'statusnet_profile_url' => $contact["url"],
660 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
661 'pid' => Contact::getIdForURL($contact["url"], 0, false),
663 'network' => $contact["network"],
668 throw new BadRequestException("User ".$url." not found.");
672 if ($uinfo[0]['self']) {
673 if ($uinfo[0]['network'] == "") {
674 $uinfo[0]['network'] = Protocol::DFRN;
677 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
678 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
685 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
687 if (!empty($profile['about'])) {
688 $description = $profile['about'];
690 $description = $uinfo[0]["about"];
693 if (!empty($usr['default-location'])) {
694 $location = $usr['default-location'];
695 } elseif (!empty($uinfo[0]["location"])) {
696 $location = $uinfo[0]["location"];
698 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
702 'id' => intval($pcontact_id),
703 'id_str' => (string) intval($pcontact_id),
704 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
705 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
706 'location' => $location,
707 'description' => BBCode::toPlaintext($description ?? ''),
708 'profile_image_url' => $uinfo[0]['micro'],
709 'profile_image_url_https' => $uinfo[0]['micro'],
710 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
711 'profile_image_url_large' => $uinfo[0]["photo"],
712 'url' => $uinfo[0]['url'],
713 'protected' => false,
714 'followers_count' => intval($countfollowers),
715 'friends_count' => intval($countfriends),
717 'created_at' => api_date($uinfo[0]['created']),
718 'favourites_count' => intval($starred),
720 'time_zone' => 'UTC',
721 'geo_enabled' => false,
723 'statuses_count' => intval($countitems),
725 'contributors_enabled' => false,
726 'is_translator' => false,
727 'is_translation_enabled' => false,
728 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
729 'follow_request_sent' => false,
730 'statusnet_blocking' => false,
731 'notifications' => false,
733 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
734 'statusnet_profile_url' => $uinfo[0]['url'],
735 'uid' => intval($uinfo[0]['uid']),
736 'cid' => intval($uinfo[0]['cid']),
737 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
738 'self' => $uinfo[0]['self'],
739 'network' => $uinfo[0]['network'],
742 // If this is a local user and it uses Frio, we can get its color preferences.
744 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
745 if ($theme_info['theme'] === 'frio') {
746 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
748 if ($schema && ($schema != '---')) {
749 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
750 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
751 require_once $schemefile;
754 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
755 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
756 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
758 if (empty($nav_bg)) {
761 if (empty($link_color)) {
762 $link_color = "#6fdbe8";
764 if (empty($bgcolor)) {
765 $bgcolor = "#ededed";
768 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
769 $ret['profile_link_color'] = str_replace('#', '', $link_color);
770 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
778 * return api-formatted array for item's author and owner
781 * @param array $item item from db
782 * @return array(array:author, array:owner)
783 * @throws BadRequestException
784 * @throws ImagickException
785 * @throws InternalServerErrorException
786 * @throws UnauthorizedException
788 function api_item_get_user(App $a, $item)
790 $status_user = api_get_user($a, $item['author-id'] ?? null);
792 $author_user = $status_user;
794 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
796 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
797 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
799 $owner_user = $author_user;
802 return ([$status_user, $author_user, $owner_user]);
806 * walks recursively through an array with the possibility to change value and key
808 * @param array $array The array to walk through
809 * @param callable $callback The callback function
811 * @return array the transformed array
813 function api_walk_recursive(array &$array, callable $callback)
817 foreach ($array as $k => $v) {
819 if ($callback($v, $k)) {
820 $new_array[$k] = api_walk_recursive($v, $callback);
823 if ($callback($v, $k)) {
834 * Callback function to transform the array in an array that can be transformed in a XML file
836 * @param mixed $item Array item value
837 * @param string $key Array key
839 * @return boolean Should the array item be deleted?
841 function api_reformat_xml(&$item, &$key)
843 if (is_bool($item)) {
844 $item = ($item ? "true" : "false");
847 if (substr($key, 0, 10) == "statusnet_") {
848 $key = "statusnet:".substr($key, 10);
849 } elseif (substr($key, 0, 10) == "friendica_") {
850 $key = "friendica:".substr($key, 10);
852 /// @TODO old-lost code?
854 // $key = "default:".$key;
860 * Creates the XML from a JSON style array
862 * @param array $data JSON style array
863 * @param string $root_element Name of the root element
865 * @return string The XML data
867 function api_create_xml(array $data, $root_element)
869 $childname = key($data);
870 $data2 = array_pop($data);
872 $namespaces = ["" => "http://api.twitter.com",
873 "statusnet" => "http://status.net/schema/api/1/",
874 "friendica" => "http://friendi.ca/schema/api/1/",
875 "georss" => "http://www.georss.org/georss"];
877 /// @todo Auto detection of needed namespaces
878 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
882 if (is_array($data2)) {
884 api_walk_recursive($data2, "api_reformat_xml");
890 foreach ($data2 as $item) {
891 $data4[$i++ . ":" . $childname] = $item;
898 $data3 = [$root_element => $data2];
900 $ret = XML::fromArray($data3, $xml, false, $namespaces);
905 * Formats the data according to the data type
907 * @param string $root_element Name of the root element
908 * @param string $type Return type (atom, rss, xml, json)
909 * @param array $data JSON style array
911 * @return array|string (string|array) XML data or JSON data
913 function api_format_data($root_element, $type, $data)
919 $ret = api_create_xml($data, $root_element);
934 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
935 * returns a 401 status code and an error message if not.
937 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
939 * @param string $type Return type (atom, rss, xml, json)
940 * @return array|string
941 * @throws BadRequestException
942 * @throws ForbiddenException
943 * @throws ImagickException
944 * @throws InternalServerErrorException
945 * @throws UnauthorizedException
947 function api_account_verify_credentials($type)
951 if (api_user() === false) {
952 throw new ForbiddenException();
955 unset($_REQUEST["user_id"]);
956 unset($_GET["user_id"]);
958 unset($_REQUEST["screen_name"]);
959 unset($_GET["screen_name"]);
961 $skip_status = $_REQUEST['skip_status'] ?? false;
963 $user_info = api_get_user($a);
965 // "verified" isn't used here in the standard
966 unset($user_info["verified"]);
968 // - Adding last status
970 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
972 $user_info['status'] = api_format_item($item, $type);
976 // "uid" and "self" are only needed for some internal stuff, so remove it from here
977 unset($user_info["uid"]);
978 unset($user_info["self"]);
980 return api_format_data("user", $type, ['user' => $user_info]);
983 /// @TODO move to top of file or somewhere better
984 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
987 * Get data from $_POST or $_GET
992 function requestdata($k)
994 if (!empty($_POST[$k])) {
997 if (!empty($_GET[$k])) {
1004 * Deprecated function to upload media.
1006 * @param string $type Return type (atom, rss, xml, json)
1008 * @return array|string
1009 * @throws BadRequestException
1010 * @throws ForbiddenException
1011 * @throws ImagickException
1012 * @throws InternalServerErrorException
1013 * @throws UnauthorizedException
1015 function api_statuses_mediap($type)
1019 if (api_user() === false) {
1020 Logger::log('api_statuses_update: no user');
1021 throw new ForbiddenException();
1023 $user_info = api_get_user($a);
1025 $_REQUEST['profile_uid'] = api_user();
1026 $_REQUEST['api_source'] = true;
1027 $txt = requestdata('status') ?? '';
1028 /// @TODO old-lost code?
1029 //$txt = urldecode(requestdata('status'));
1031 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1032 $txt = HTML::toBBCodeVideo($txt);
1033 $config = HTMLPurifier_Config::createDefault();
1034 $config->set('Cache.DefinitionImpl', null);
1035 $purifier = new HTMLPurifier($config);
1036 $txt = $purifier->purify($txt);
1038 $txt = HTML::toBBCode($txt);
1040 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1042 $picture = wall_upload_post($a, false);
1044 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1045 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1046 $item_id = item_post($a);
1048 // output the post that we just posted.
1049 return api_status_show($type, $item_id);
1052 /// @TODO move this to top of file or somewhere better!
1053 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1056 * Updates the user’s current status.
1058 * @param string $type Return type (atom, rss, xml, json)
1060 * @return array|string
1061 * @throws BadRequestException
1062 * @throws ForbiddenException
1063 * @throws ImagickException
1064 * @throws InternalServerErrorException
1065 * @throws TooManyRequestsException
1066 * @throws UnauthorizedException
1067 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1069 function api_statuses_update($type)
1073 if (api_user() === false) {
1074 Logger::log('api_statuses_update: no user');
1075 throw new ForbiddenException();
1080 // convert $_POST array items to the form we use for web posts.
1081 if (requestdata('htmlstatus')) {
1082 $txt = requestdata('htmlstatus') ?? '';
1083 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1084 $txt = HTML::toBBCodeVideo($txt);
1086 $config = HTMLPurifier_Config::createDefault();
1087 $config->set('Cache.DefinitionImpl', null);
1089 $purifier = new HTMLPurifier($config);
1090 $txt = $purifier->purify($txt);
1092 $_REQUEST['body'] = HTML::toBBCode($txt);
1095 $_REQUEST['body'] = requestdata('status');
1098 $_REQUEST['title'] = requestdata('title');
1100 $parent = requestdata('in_reply_to_status_id');
1102 // Twidere sends "-1" if it is no reply ...
1103 if ($parent == -1) {
1107 if (ctype_digit($parent)) {
1108 $_REQUEST['parent'] = $parent;
1110 $_REQUEST['parent_uri'] = $parent;
1113 if (requestdata('lat') && requestdata('long')) {
1114 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1116 $_REQUEST['profile_uid'] = api_user();
1119 // Check for throttling (maximum posts per day, week and month)
1120 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1121 if ($throttle_day > 0) {
1122 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1124 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1125 $posts_day = Post::count($condition);
1127 if ($posts_day > $throttle_day) {
1128 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1129 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1130 throw new TooManyRequestsException(DI::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));
1134 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1135 if ($throttle_week > 0) {
1136 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1138 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1139 $posts_week = Post::count($condition);
1141 if ($posts_week > $throttle_week) {
1142 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1143 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1144 throw new TooManyRequestsException(DI::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));
1148 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1149 if ($throttle_month > 0) {
1150 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1152 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1153 $posts_month = Post::count($condition);
1155 if ($posts_month > $throttle_month) {
1156 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1157 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1158 throw new TooManyRequestsException(DI::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));
1163 if (requestdata('media_ids')) {
1164 $ids = explode(',', requestdata('media_ids') ?? '');
1165 } elseif (!empty($_FILES['media'])) {
1166 // upload the image if we have one
1167 $picture = wall_upload_post($a, false);
1168 if (is_array($picture)) {
1169 $ids[] = $picture['id'];
1177 foreach ($ids as $id) {
1178 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1179 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1180 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1181 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1183 if (!empty($media)) {
1184 $ressources[] = $media[0]['resource-id'];
1185 $phototypes = Images::supportedTypes();
1186 $ext = $phototypes[$media[0]['type']];
1188 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1189 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1190 'size' => $media[0]['datasize'],
1191 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1192 'description' => $media[0]['desc'] ?? '',
1193 'width' => $media[0]['width'],
1194 'height' => $media[0]['height']];
1196 if (count($media) > 1) {
1197 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1198 $attachment['preview-width'] = $media[1]['width'];
1199 $attachment['preview-height'] = $media[1]['height'];
1201 $attachments[] = $attachment;
1205 // We have to avoid that the post is rejected because of an empty body
1206 if (empty($_REQUEST['body'])) {
1207 $_REQUEST['body'] = '[hr]';
1211 if (!empty($attachments)) {
1212 $_REQUEST['attachments'] = $attachments;
1215 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1217 $_REQUEST['api_source'] = true;
1219 if (empty($_REQUEST['source'])) {
1220 $_REQUEST["source"] = api_source();
1223 // call out normal post function
1224 $item_id = item_post($a);
1226 if (!empty($ressources) && !empty($item_id)) {
1227 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1228 foreach ($ressources as $ressource) {
1229 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1233 // output the post that we just posted.
1234 return api_status_show($type, $item_id);
1237 /// @TODO move to top of file or somewhere better
1238 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1239 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1242 * Uploads an image to Friendica.
1245 * @throws BadRequestException
1246 * @throws ForbiddenException
1247 * @throws ImagickException
1248 * @throws InternalServerErrorException
1249 * @throws UnauthorizedException
1250 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1252 function api_media_upload()
1256 if (api_user() === false) {
1257 Logger::log('no user');
1258 throw new ForbiddenException();
1263 if (empty($_FILES['media'])) {
1265 throw new BadRequestException("No media.");
1268 $media = wall_upload_post($a, false);
1271 throw new InternalServerErrorException();
1275 $returndata["media_id"] = $media["id"];
1276 $returndata["media_id_string"] = (string)$media["id"];
1277 $returndata["size"] = $media["size"];
1278 $returndata["image"] = ["w" => $media["width"],
1279 "h" => $media["height"],
1280 "image_type" => $media["type"],
1281 "friendica_preview_url" => $media["preview"]];
1283 Logger::info('Media uploaded', ['return' => $returndata]);
1285 return ["media" => $returndata];
1288 /// @TODO move to top of file or somewhere better
1289 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1292 * Updates media meta data (picture descriptions)
1294 * @param string $type Return type (atom, rss, xml, json)
1296 * @return array|string
1297 * @throws BadRequestException
1298 * @throws ForbiddenException
1299 * @throws ImagickException
1300 * @throws InternalServerErrorException
1301 * @throws TooManyRequestsException
1302 * @throws UnauthorizedException
1303 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1305 * @todo Compare the corresponding Twitter function for correct return values
1307 function api_media_metadata_create($type)
1311 if (api_user() === false) {
1312 Logger::info('no user');
1313 throw new ForbiddenException();
1318 $postdata = Network::postdata();
1320 if (empty($postdata)) {
1321 throw new BadRequestException("No post data");
1324 $data = json_decode($postdata, true);
1326 throw new BadRequestException("Invalid post data");
1329 if (empty($data['media_id']) || empty($data['alt_text'])) {
1330 throw new BadRequestException("Missing post data values");
1333 if (empty($data['alt_text']['text'])) {
1334 throw new BadRequestException("No alt text.");
1337 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1339 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1340 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1341 if (!DBA::isResult($photo)) {
1342 throw new BadRequestException("Metadata not found.");
1345 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1348 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1351 * @param string $type Return format (atom, rss, xml, json)
1352 * @param int $item_id
1353 * @return array|string
1356 function api_status_show($type, $item_id)
1358 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1362 $item = api_get_item(['id' => $item_id]);
1363 if (!empty($item)) {
1364 $status_info = api_format_item($item, $type);
1367 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1369 return api_format_data('statuses', $type, ['status' => $status_info]);
1373 * Retrieves the last public status of the provided user info
1375 * @param int $ownerId Public contact Id
1376 * @param int $uid User Id
1380 function api_get_last_status($ownerId, $uid)
1383 'author-id'=> $ownerId,
1385 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1386 'private' => [Item::PUBLIC, Item::UNLISTED]
1389 $item = api_get_item($condition);
1395 * Retrieves a single item record based on the provided condition and converts it for API use.
1397 * @param array $condition Item table condition array
1401 function api_get_item(array $condition)
1403 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1409 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1410 * The author's most recent status will be returned inline.
1412 * @param string $type Return type (atom, rss, xml, json)
1413 * @return array|string
1414 * @throws BadRequestException
1415 * @throws ImagickException
1416 * @throws InternalServerErrorException
1417 * @throws UnauthorizedException
1418 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1420 function api_users_show($type)
1422 $a = Friendica\DI::app();
1424 $user_info = api_get_user($a);
1426 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1427 if (!empty($item)) {
1428 $user_info['status'] = api_format_item($item, $type);
1431 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1432 unset($user_info['uid']);
1433 unset($user_info['self']);
1435 return api_format_data('user', $type, ['user' => $user_info]);
1438 /// @TODO move to top of file or somewhere better
1439 api_register_func('api/users/show', 'api_users_show');
1440 api_register_func('api/externalprofile/show', 'api_users_show');
1443 * Search a public user account.
1445 * @param string $type Return type (atom, rss, xml, json)
1447 * @return array|string
1448 * @throws BadRequestException
1449 * @throws ImagickException
1450 * @throws InternalServerErrorException
1451 * @throws UnauthorizedException
1452 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1454 function api_users_search($type)
1460 if (!empty($_GET['q'])) {
1461 $contacts = Contact::selectToArray(
1464 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1472 if (DBA::isResult($contacts)) {
1474 foreach ($contacts as $contact) {
1475 $user_info = api_get_user($a, $contact['id']);
1477 if ($type == 'xml') {
1478 $userlist[$k++ . ':user'] = $user_info;
1480 $userlist[] = $user_info;
1483 $userlist = ['users' => $userlist];
1485 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1488 throw new BadRequestException('No search term specified.');
1491 return api_format_data('users', $type, $userlist);
1494 /// @TODO move to top of file or somewhere better
1495 api_register_func('api/users/search', 'api_users_search');
1498 * Return user objects
1500 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1502 * @param string $type Return format: json or xml
1504 * @return array|string
1505 * @throws BadRequestException
1506 * @throws ImagickException
1507 * @throws InternalServerErrorException
1508 * @throws NotFoundException if the results are empty.
1509 * @throws UnauthorizedException
1511 function api_users_lookup($type)
1515 if (!empty($_REQUEST['user_id'])) {
1516 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1518 $users[] = api_get_user(DI::app(), $id);
1523 if (empty($users)) {
1524 throw new NotFoundException;
1527 return api_format_data("users", $type, ['users' => $users]);
1530 /// @TODO move to top of file or somewhere better
1531 api_register_func('api/users/lookup', 'api_users_lookup', true);
1534 * Returns statuses that match a specified query.
1536 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1538 * @param string $type Return format: json, xml, atom, rss
1540 * @return array|string
1541 * @throws BadRequestException if the "q" parameter is missing.
1542 * @throws ForbiddenException
1543 * @throws ImagickException
1544 * @throws InternalServerErrorException
1545 * @throws UnauthorizedException
1547 function api_search($type)
1550 $user_info = api_get_user($a);
1552 if (api_user() === false || $user_info === false) {
1553 throw new ForbiddenException();
1556 if (empty($_REQUEST['q'])) {
1557 throw new BadRequestException('q parameter is required.');
1560 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1563 $data['status'] = [];
1565 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1566 if (!empty($_REQUEST['rpp'])) {
1567 $count = $_REQUEST['rpp'];
1568 } elseif (!empty($_REQUEST['count'])) {
1569 $count = $_REQUEST['count'];
1572 $since_id = $_REQUEST['since_id'] ?? 0;
1573 $max_id = $_REQUEST['max_id'] ?? 0;
1574 $page = $_REQUEST['page'] ?? 1;
1576 $start = max(0, ($page - 1) * $count);
1578 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1579 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1580 $searchTerm = $matches[1];
1581 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1582 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1584 while ($tag = DBA::fetch($tags)) {
1585 $uriids[] = $tag['uri-id'];
1589 if (empty($uriids)) {
1590 return api_format_data('statuses', $type, $data);
1593 $condition = ['uri-id' => $uriids];
1594 if ($exclude_replies) {
1595 $condition['gravity'] = GRAVITY_PARENT;
1598 $params['group_by'] = ['uri-id'];
1600 $condition = ["`id` > ?
1601 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1602 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1603 AND `body` LIKE CONCAT('%',?,'%')",
1604 $since_id, api_user(), $_REQUEST['q']];
1606 $condition[0] .= ' AND `id` <= ?';
1607 $condition[] = $max_id;
1613 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1614 $id = Item::fetchByLink($searchTerm, api_user());
1617 $id = Item::fetchByLink($searchTerm);
1621 $statuses = Post::select([], ['id' => $id]);
1625 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1627 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1629 bindComments($data['status']);
1631 return api_format_data('statuses', $type, $data);
1634 /// @TODO move to top of file or somewhere better
1635 api_register_func('api/search/tweets', 'api_search', true);
1636 api_register_func('api/search', 'api_search', true);
1639 * Returns the most recent statuses posted by the user and the users they follow.
1641 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1643 * @param string $type Return type (atom, rss, xml, json)
1645 * @return array|string
1646 * @throws BadRequestException
1647 * @throws ForbiddenException
1648 * @throws ImagickException
1649 * @throws InternalServerErrorException
1650 * @throws UnauthorizedException
1651 * @todo Optional parameters
1652 * @todo Add reply info
1654 function api_statuses_home_timeline($type)
1657 $user_info = api_get_user($a);
1659 if (api_user() === false || $user_info === false) {
1660 throw new ForbiddenException();
1663 unset($_REQUEST["user_id"]);
1664 unset($_GET["user_id"]);
1666 unset($_REQUEST["screen_name"]);
1667 unset($_GET["screen_name"]);
1669 // get last network messages
1672 $count = $_REQUEST['count'] ?? 20;
1673 $page = $_REQUEST['page']?? 0;
1674 $since_id = $_REQUEST['since_id'] ?? 0;
1675 $max_id = $_REQUEST['max_id'] ?? 0;
1676 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1677 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1679 $start = max(0, ($page - 1) * $count);
1681 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1682 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1685 $condition[0] .= " AND `id` <= ?";
1686 $condition[] = $max_id;
1688 if ($exclude_replies) {
1689 $condition[0] .= ' AND `gravity` = ?';
1690 $condition[] = GRAVITY_PARENT;
1692 if ($conversation_id > 0) {
1693 $condition[0] .= " AND `parent` = ?";
1694 $condition[] = $conversation_id;
1697 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1698 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1700 $items = Post::toArray($statuses);
1702 $ret = api_format_items($items, $user_info, false, $type);
1704 // Set all posts from the query above to seen
1706 foreach ($items as $item) {
1707 $idarray[] = intval($item["id"]);
1710 if (!empty($idarray)) {
1711 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1713 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1719 $data = ['status' => $ret];
1724 $data = api_rss_extra($a, $data, $user_info);
1728 return api_format_data("statuses", $type, $data);
1732 /// @TODO move to top of file or somewhere better
1733 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1734 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1737 * Returns the most recent statuses from public users.
1739 * @param string $type Return type (atom, rss, xml, json)
1741 * @return array|string
1742 * @throws BadRequestException
1743 * @throws ForbiddenException
1744 * @throws ImagickException
1745 * @throws InternalServerErrorException
1746 * @throws UnauthorizedException
1748 function api_statuses_public_timeline($type)
1751 $user_info = api_get_user($a);
1753 if (api_user() === false || $user_info === false) {
1754 throw new ForbiddenException();
1757 // get last network messages
1760 $count = $_REQUEST['count'] ?? 20;
1761 $page = $_REQUEST['page'] ?? 1;
1762 $since_id = $_REQUEST['since_id'] ?? 0;
1763 $max_id = $_REQUEST['max_id'] ?? 0;
1764 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1765 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1767 $start = max(0, ($page - 1) * $count);
1769 if ($exclude_replies && !$conversation_id) {
1770 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1771 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1774 $condition[0] .= " AND `id` <= ?";
1775 $condition[] = $max_id;
1778 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1779 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1781 $r = Post::toArray($statuses);
1783 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1784 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1787 $condition[0] .= " AND `id` <= ?";
1788 $condition[] = $max_id;
1790 if ($conversation_id > 0) {
1791 $condition[0] .= " AND `parent` = ?";
1792 $condition[] = $conversation_id;
1795 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1796 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1798 $r = Post::toArray($statuses);
1801 $ret = api_format_items($r, $user_info, false, $type);
1805 $data = ['status' => $ret];
1810 $data = api_rss_extra($a, $data, $user_info);
1814 return api_format_data("statuses", $type, $data);
1817 /// @TODO move to top of file or somewhere better
1818 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1821 * Returns the most recent statuses posted by users this node knows about.
1823 * @param string $type Return format: json, xml, atom, rss
1824 * @return array|string
1825 * @throws BadRequestException
1826 * @throws ForbiddenException
1827 * @throws ImagickException
1828 * @throws InternalServerErrorException
1829 * @throws UnauthorizedException
1831 function api_statuses_networkpublic_timeline($type)
1834 $user_info = api_get_user($a);
1836 if (api_user() === false || $user_info === false) {
1837 throw new ForbiddenException();
1840 $since_id = $_REQUEST['since_id'] ?? 0;
1841 $max_id = $_REQUEST['max_id'] ?? 0;
1844 $count = $_REQUEST['count'] ?? 20;
1845 $page = $_REQUEST['page'] ?? 1;
1847 $start = max(0, ($page - 1) * $count);
1849 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1850 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1853 $condition[0] .= " AND `id` <= ?";
1854 $condition[] = $max_id;
1857 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1858 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1860 $ret = api_format_items($statuses, $user_info, false, $type);
1864 $data = ['status' => $ret];
1869 $data = api_rss_extra($a, $data, $user_info);
1873 return api_format_data("statuses", $type, $data);
1876 /// @TODO move to top of file or somewhere better
1877 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1880 * Returns a single status.
1882 * @param string $type Return type (atom, rss, xml, json)
1884 * @return array|string
1885 * @throws BadRequestException
1886 * @throws ForbiddenException
1887 * @throws ImagickException
1888 * @throws InternalServerErrorException
1889 * @throws UnauthorizedException
1890 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1892 function api_statuses_show($type)
1895 $user_info = api_get_user($a);
1897 if (api_user() === false || $user_info === false) {
1898 throw new ForbiddenException();
1902 $id = intval($a->argv[3] ?? 0);
1905 $id = intval($_REQUEST['id'] ?? 0);
1910 $id = intval($a->argv[4] ?? 0);
1913 Logger::log('API: api_statuses_show: ' . $id);
1915 $conversation = !empty($_REQUEST['conversation']);
1917 // try to fetch the item for the local user - or the public item, if there is no local one
1918 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1919 if (!DBA::isResult($uri_item)) {
1920 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1923 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1924 if (!DBA::isResult($item)) {
1925 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1930 if ($conversation) {
1931 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1932 $params = ['order' => ['id' => true]];
1934 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1938 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1940 /// @TODO How about copying this to above methods which don't check $r ?
1941 if (!DBA::isResult($statuses)) {
1942 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1945 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1947 if ($conversation) {
1948 $data = ['status' => $ret];
1949 return api_format_data("statuses", $type, $data);
1951 $data = ['status' => $ret[0]];
1952 return api_format_data("status", $type, $data);
1956 /// @TODO move to top of file or somewhere better
1957 api_register_func('api/statuses/show', 'api_statuses_show', true);
1961 * @param string $type Return type (atom, rss, xml, json)
1963 * @return array|string
1964 * @throws BadRequestException
1965 * @throws ForbiddenException
1966 * @throws ImagickException
1967 * @throws InternalServerErrorException
1968 * @throws UnauthorizedException
1969 * @todo nothing to say?
1971 function api_conversation_show($type)
1974 $user_info = api_get_user($a);
1976 if (api_user() === false || $user_info === false) {
1977 throw new ForbiddenException();
1981 $id = intval($a->argv[3] ?? 0);
1982 $since_id = intval($_REQUEST['since_id'] ?? 0);
1983 $max_id = intval($_REQUEST['max_id'] ?? 0);
1984 $count = intval($_REQUEST['count'] ?? 20);
1985 $page = intval($_REQUEST['page'] ?? 1);
1987 $start = max(0, ($page - 1) * $count);
1990 $id = intval($_REQUEST['id'] ?? 0);
1995 $id = intval($a->argv[4] ?? 0);
1998 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2000 // try to fetch the item for the local user - or the public item, if there is no local one
2001 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
2002 if (!DBA::isResult($item)) {
2003 throw new BadRequestException("There is no status with this id.");
2006 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2007 if (!DBA::isResult($parent)) {
2008 throw new BadRequestException("There is no status with this id.");
2011 $id = $parent['id'];
2013 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2014 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2017 $condition[0] .= " AND `id` <= ?";
2018 $condition[] = $max_id;
2021 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2022 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2024 if (!DBA::isResult($statuses)) {
2025 throw new BadRequestException("There is no status with id $id.");
2028 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2030 $data = ['status' => $ret];
2031 return api_format_data("statuses", $type, $data);
2034 /// @TODO move to top of file or somewhere better
2035 api_register_func('api/conversation/show', 'api_conversation_show', true);
2036 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2041 * @param string $type Return type (atom, rss, xml, json)
2043 * @return array|string
2044 * @throws BadRequestException
2045 * @throws ForbiddenException
2046 * @throws ImagickException
2047 * @throws InternalServerErrorException
2048 * @throws UnauthorizedException
2049 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2051 function api_statuses_repeat($type)
2057 if (api_user() === false) {
2058 throw new ForbiddenException();
2064 $id = intval($a->argv[3] ?? 0);
2067 $id = intval($_REQUEST['id'] ?? 0);
2072 $id = intval($a->argv[4] ?? 0);
2075 Logger::log('API: api_statuses_repeat: '.$id);
2077 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2078 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2080 if (DBA::isResult($item) && !empty($item['body'])) {
2081 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2082 if (!Item::performActivity($id, 'announce', local_user())) {
2083 throw new InternalServerErrorException();
2088 if (strpos($item['body'], "[/share]") !== false) {
2089 $pos = strpos($item['body'], "[share");
2090 $post = substr($item['body'], $pos);
2092 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2094 if (!empty($item['title'])) {
2095 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2098 $post .= $item['body'];
2099 $post .= "[/share]";
2101 $_REQUEST['body'] = $post;
2102 $_REQUEST['profile_uid'] = api_user();
2103 $_REQUEST['api_source'] = true;
2105 if (empty($_REQUEST['source'])) {
2106 $_REQUEST["source"] = api_source();
2109 $item_id = item_post($a);
2112 throw new ForbiddenException();
2115 // output the post that we just posted.
2117 return api_status_show($type, $item_id);
2120 /// @TODO move to top of file or somewhere better
2121 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2124 * Destroys a specific status.
2126 * @param string $type Return type (atom, rss, xml, json)
2128 * @return array|string
2129 * @throws BadRequestException
2130 * @throws ForbiddenException
2131 * @throws ImagickException
2132 * @throws InternalServerErrorException
2133 * @throws UnauthorizedException
2134 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2136 function api_statuses_destroy($type)
2140 if (api_user() === false) {
2141 throw new ForbiddenException();
2147 $id = intval($a->argv[3] ?? 0);
2150 $id = intval($_REQUEST['id'] ?? 0);
2155 $id = intval($a->argv[4] ?? 0);
2158 Logger::log('API: api_statuses_destroy: '.$id);
2160 $ret = api_statuses_show($type);
2162 Item::deleteForUser(['id' => $id], api_user());
2167 /// @TODO move to top of file or somewhere better
2168 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2171 * Returns the most recent mentions.
2173 * @param string $type Return type (atom, rss, xml, json)
2175 * @return array|string
2176 * @throws BadRequestException
2177 * @throws ForbiddenException
2178 * @throws ImagickException
2179 * @throws InternalServerErrorException
2180 * @throws UnauthorizedException
2181 * @see http://developer.twitter.com/doc/get/statuses/mentions
2183 function api_statuses_mentions($type)
2186 $user_info = api_get_user($a);
2188 if (api_user() === false || $user_info === false) {
2189 throw new ForbiddenException();
2192 unset($_REQUEST["user_id"]);
2193 unset($_GET["user_id"]);
2195 unset($_REQUEST["screen_name"]);
2196 unset($_GET["screen_name"]);
2198 // get last network messages
2201 $since_id = intval($_REQUEST['since_id'] ?? 0);
2202 $max_id = intval($_REQUEST['max_id'] ?? 0);
2203 $count = intval($_REQUEST['count'] ?? 20);
2204 $page = intval($_REQUEST['page'] ?? 1);
2206 $start = max(0, ($page - 1) * $count);
2208 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2209 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2210 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2212 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2213 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2214 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2215 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2216 api_user(), $since_id];
2219 $query .= " AND `id` <= ?";
2220 $condition[] = $max_id;
2223 array_unshift($condition, $query);
2225 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2226 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2228 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2230 $data = ['status' => $ret];
2235 $data = api_rss_extra($a, $data, $user_info);
2239 return api_format_data("statuses", $type, $data);
2242 /// @TODO move to top of file or somewhere better
2243 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2244 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2247 * Returns the most recent statuses posted by the user.
2249 * @param string $type Either "json" or "xml"
2250 * @return string|array
2251 * @throws BadRequestException
2252 * @throws ForbiddenException
2253 * @throws ImagickException
2254 * @throws InternalServerErrorException
2255 * @throws UnauthorizedException
2256 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2258 function api_statuses_user_timeline($type)
2261 $user_info = api_get_user($a);
2263 if (api_user() === false || $user_info === false) {
2264 throw new ForbiddenException();
2267 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2269 $since_id = $_REQUEST['since_id'] ?? 0;
2270 $max_id = $_REQUEST['max_id'] ?? 0;
2271 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2272 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2275 $count = $_REQUEST['count'] ?? 20;
2276 $page = $_REQUEST['page'] ?? 1;
2278 $start = max(0, ($page - 1) * $count);
2280 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2281 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2283 if ($user_info['self'] == 1) {
2284 $condition[0] .= ' AND `wall` ';
2287 if ($exclude_replies) {
2288 $condition[0] .= ' AND `gravity` = ?';
2289 $condition[] = GRAVITY_PARENT;
2292 if ($conversation_id > 0) {
2293 $condition[0] .= " AND `parent` = ?";
2294 $condition[] = $conversation_id;
2298 $condition[0] .= " AND `id` <= ?";
2299 $condition[] = $max_id;
2301 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2302 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2304 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2308 $data = ['status' => $ret];
2313 $data = api_rss_extra($a, $data, $user_info);
2317 return api_format_data("statuses", $type, $data);
2320 /// @TODO move to top of file or somewhere better
2321 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2324 * Star/unstar an item.
2325 * param: id : id of the item
2327 * @param string $type Return type (atom, rss, xml, json)
2329 * @return array|string
2330 * @throws BadRequestException
2331 * @throws ForbiddenException
2332 * @throws ImagickException
2333 * @throws InternalServerErrorException
2334 * @throws UnauthorizedException
2335 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2337 function api_favorites_create_destroy($type)
2341 if (api_user() === false) {
2342 throw new ForbiddenException();
2345 // for versioned api.
2346 /// @TODO We need a better global soluton
2347 $action_argv_id = 2;
2348 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2349 $action_argv_id = 3;
2352 if ($a->argc <= $action_argv_id) {
2353 throw new BadRequestException("Invalid request.");
2355 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2356 if ($a->argc == $action_argv_id + 2) {
2357 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2359 $itemid = intval($_REQUEST['id'] ?? 0);
2362 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2364 if (!DBA::isResult($item)) {
2365 throw new BadRequestException("Invalid item.");
2370 $item['starred'] = 1;
2373 $item['starred'] = 0;
2376 throw new BadRequestException("Invalid action ".$action);
2379 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2382 throw new InternalServerErrorException("DB error");
2386 $user_info = api_get_user($a);
2387 $rets = api_format_items([$item], $user_info, false, $type);
2390 $data = ['status' => $ret];
2395 $data = api_rss_extra($a, $data, $user_info);
2399 return api_format_data("status", $type, $data);
2402 /// @TODO move to top of file or somewhere better
2403 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2404 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2407 * Returns the most recent favorite statuses.
2409 * @param string $type Return type (atom, rss, xml, json)
2411 * @return string|array
2412 * @throws BadRequestException
2413 * @throws ForbiddenException
2414 * @throws ImagickException
2415 * @throws InternalServerErrorException
2416 * @throws UnauthorizedException
2418 function api_favorites($type)
2423 $user_info = api_get_user($a);
2425 if (api_user() === false || $user_info === false) {
2426 throw new ForbiddenException();
2431 // in friendica starred item are private
2432 // return favorites only for self
2433 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2435 if ($user_info['self'] == 0) {
2439 $since_id = $_REQUEST['since_id'] ?? 0;
2440 $max_id = $_REQUEST['max_id'] ?? 0;
2441 $count = $_GET['count'] ?? 20;
2442 $page = $_REQUEST['page'] ?? 1;
2444 $start = max(0, ($page - 1) * $count);
2446 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2447 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2449 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2452 $condition[0] .= " AND `id` <= ?";
2453 $condition[] = $max_id;
2456 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2458 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2463 $data = ['status' => $ret];
2468 $data = api_rss_extra($a, $data, $user_info);
2472 return api_format_data("statuses", $type, $data);
2475 /// @TODO move to top of file or somewhere better
2476 api_register_func('api/favorites', 'api_favorites', true);
2480 * @param array $item
2481 * @param array $recipient
2482 * @param array $sender
2485 * @throws InternalServerErrorException
2487 function api_format_messages($item, $recipient, $sender)
2489 // standard meta information
2491 'id' => $item['id'],
2492 'sender_id' => $sender['id'],
2494 'recipient_id' => $recipient['id'],
2495 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2496 'sender_screen_name' => $sender['screen_name'],
2497 'recipient_screen_name' => $recipient['screen_name'],
2498 'sender' => $sender,
2499 'recipient' => $recipient,
2501 'friendica_seen' => $item['seen'] ?? 0,
2502 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2505 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2506 if (isset($ret['sender']['uid'])) {
2507 unset($ret['sender']['uid']);
2509 if (isset($ret['sender']['self'])) {
2510 unset($ret['sender']['self']);
2512 if (isset($ret['recipient']['uid'])) {
2513 unset($ret['recipient']['uid']);
2515 if (isset($ret['recipient']['self'])) {
2516 unset($ret['recipient']['self']);
2519 //don't send title to regular StatusNET requests to avoid confusing these apps
2520 if (!empty($_GET['getText'])) {
2521 $ret['title'] = $item['title'];
2522 if ($_GET['getText'] == 'html') {
2523 $ret['text'] = BBCode::convert($item['body'], false);
2524 } elseif ($_GET['getText'] == 'plain') {
2525 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2528 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2530 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2531 unset($ret['sender']);
2532 unset($ret['recipient']);
2540 * @param array $item
2543 * @throws InternalServerErrorException
2545 function api_convert_item($item)
2547 $body = api_add_attachments_to_body($item);
2549 $entities = api_get_entitities($statustext, $body);
2551 // Add pictures to the attachment array and remove them from the body
2552 $attachments = api_get_attachments($body);
2554 // Workaround for ostatus messages where the title is identically to the body
2555 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2556 $statusbody = trim(HTML::toPlaintext($html, 0));
2558 // handle data: images
2559 $statusbody = api_format_items_embeded_images($item, $statusbody);
2561 $statustitle = trim($item['title']);
2563 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2564 $statustext = trim($statusbody);
2566 $statustext = trim($statustitle."\n\n".$statusbody);
2569 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2570 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2573 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2575 // Workaround for clients with limited HTML parser functionality
2576 $search = ["<br>", "<blockquote>", "</blockquote>",
2577 "<h1>", "</h1>", "<h2>", "</h2>",
2578 "<h3>", "</h3>", "<h4>", "</h4>",
2579 "<h5>", "</h5>", "<h6>", "</h6>"];
2580 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2581 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2582 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2583 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2584 $statushtml = str_replace($search, $replace, $statushtml);
2586 if ($item['title'] != "") {
2587 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2591 $oldtext = $statushtml;
2592 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2593 } while ($oldtext != $statushtml);
2595 if (substr($statushtml, 0, 4) == '<br>') {
2596 $statushtml = substr($statushtml, 4);
2599 if (substr($statushtml, 0, -4) == '<br>') {
2600 $statushtml = substr($statushtml, -4);
2603 // feeds without body should contain the link
2604 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2605 $statushtml .= BBCode::convert($item['plink']);
2609 "text" => $statustext,
2610 "html" => $statushtml,
2611 "attachments" => $attachments,
2612 "entities" => $entities
2617 * Add media attachments to the body
2619 * @param array $item
2620 * @return string body with added media
2622 function api_add_attachments_to_body(array $item)
2624 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2626 if (strpos($body, '[/img]') !== false) {
2630 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2631 if (!empty($media['preview'])) {
2632 $description = $media['description'] ?: $media['name'];
2633 if (!empty($description)) {
2634 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2636 $body .= "\n[img]" . $media['preview'] .'[/img]';
2646 * @param string $body
2649 * @throws InternalServerErrorException
2651 function api_get_attachments(&$body)
2653 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2654 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2656 $URLSearchString = "^\[\]";
2657 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2661 // Remove all embedded pictures, since they are added as attachments
2662 foreach ($images[0] as $orig) {
2663 $body = str_replace($orig, '', $body);
2668 foreach ($images[1] as $image) {
2669 $imagedata = Images::getInfoFromURLCached($image);
2672 if (DI::config()->get("system", "proxy_disabled")) {
2673 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2675 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2680 return $attachments;
2685 * @param string $text
2686 * @param string $bbcode
2689 * @throws InternalServerErrorException
2690 * @todo Links at the first character of the post
2692 function api_get_entitities(&$text, $bbcode)
2694 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2696 if ($include_entities != "true") {
2697 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2699 foreach ($images[1] as $image) {
2700 $replace = ProxyUtils::proxifyUrl($image, false);
2701 $text = str_replace($image, $replace, $text);
2706 $bbcode = BBCode::cleanPictureLinks($bbcode);
2708 // Change pure links in text to bbcode uris
2709 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2712 $entities["hashtags"] = [];
2713 $entities["symbols"] = [];
2714 $entities["urls"] = [];
2715 $entities["user_mentions"] = [];
2717 $URLSearchString = "^\[\]";
2719 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2721 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2722 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2724 $bbcode = preg_replace(
2725 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2726 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2729 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2731 $bbcode = preg_replace(
2732 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2733 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2736 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2738 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2740 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2743 foreach ($urls[1] as $id => $url) {
2744 $start = iconv_strpos($text, $url, 0, "UTF-8");
2745 if (!($start === false)) {
2746 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2750 ksort($ordered_urls);
2754 foreach ($ordered_urls as $url) {
2755 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2756 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2758 $display_url = $url["title"];
2760 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2761 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2763 if (strlen($display_url) > 26) {
2764 $display_url = substr($display_url, 0, 25)."…";
2768 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2769 if (!($start === false)) {
2770 $entities["urls"][] = ["url" => $url["url"],
2771 "expanded_url" => $url["url"],
2772 "display_url" => $display_url,
2773 "indices" => [$start, $start+strlen($url["url"])]];
2774 $offset = $start + 1;
2778 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2779 $ordered_images = [];
2780 foreach ($images as $image) {
2781 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2782 if (!($start === false)) {
2783 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2787 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2788 foreach ($images[1] as $image) {
2789 $start = iconv_strpos($text, $image, 0, "UTF-8");
2790 if (!($start === false)) {
2791 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2797 foreach ($ordered_images as $image) {
2798 $url = $image['url'];
2799 $ext_alt_text = $image['alt'];
2801 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2802 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2804 if (strlen($display_url) > 26) {
2805 $display_url = substr($display_url, 0, 25)."…";
2808 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2809 if (!($start === false)) {
2810 $image = Images::getInfoFromURLCached($url);
2812 // If image cache is activated, then use the following sizes:
2813 // thumb (150), small (340), medium (600) and large (1024)
2814 if (!DI::config()->get("system", "proxy_disabled")) {
2815 $media_url = ProxyUtils::proxifyUrl($url, false);
2818 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2819 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2821 if (($image[0] > 150) || ($image[1] > 150)) {
2822 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2823 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2826 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2827 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2829 if (($image[0] > 600) || ($image[1] > 600)) {
2830 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2831 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2835 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2838 $entities["media"][] = [
2840 "id_str" => (string) ($start + 1),
2841 "indices" => [$start, $start+strlen($url)],
2842 "media_url" => Strings::normaliseLink($media_url),
2843 "media_url_https" => $media_url,
2845 "display_url" => $display_url,
2846 "expanded_url" => $url,
2847 "ext_alt_text" => $ext_alt_text,
2851 $offset = $start + 1;
2860 * @param array $item
2861 * @param string $text
2865 function api_format_items_embeded_images($item, $text)
2867 $text = preg_replace_callback(
2868 '|data:image/([^;]+)[^=]+=*|m',
2869 function () use ($item) {
2870 return DI::baseUrl() . '/display/' . $item['guid'];
2878 * return <a href='url'>name</a> as array
2880 * @param string $txt text
2885 function api_contactlink_to_array($txt)
2888 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2889 if ($r && count($match)==3) {
2891 'name' => $match[2],
2905 * return likes, dislikes and attend status for item
2907 * @param array $item array
2908 * @param string $type Return type (atom, rss, xml, json)
2911 * likes => int count,
2912 * dislikes => int count
2913 * @throws BadRequestException
2914 * @throws ImagickException
2915 * @throws InternalServerErrorException
2916 * @throws UnauthorizedException
2918 function api_format_items_activities($item, $type = "json")
2927 'attendmaybe' => [],
2931 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2932 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2934 while ($parent_item = Post::fetch($ret)) {
2935 // not used as result should be structured like other user data
2936 //builtin_activity_puller($i, $activities);
2938 // get user data and add it to the array of the activity
2939 $user = api_get_user($a, $parent_item['author-id']);
2940 switch ($parent_item['verb']) {
2941 case Activity::LIKE:
2942 $activities['like'][] = $user;
2944 case Activity::DISLIKE:
2945 $activities['dislike'][] = $user;
2947 case Activity::ATTEND:
2948 $activities['attendyes'][] = $user;
2950 case Activity::ATTENDNO:
2951 $activities['attendno'][] = $user;
2953 case Activity::ATTENDMAYBE:
2954 $activities['attendmaybe'][] = $user;
2956 case Activity::ANNOUNCE:
2957 $activities['announce'][] = $user;
2966 if ($type == "xml") {
2967 $xml_activities = [];
2968 foreach ($activities as $k => $v) {
2969 // change xml element from "like" to "friendica:like"
2970 $xml_activities["friendica:".$k] = $v;
2971 // add user data into xml output
2973 foreach ($v as $user) {
2974 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2977 $activities = $xml_activities;
2984 * format items to be returned by api
2986 * @param array $items array of items
2987 * @param array $user_info
2988 * @param bool $filter_user filter items by $user_info
2989 * @param string $type Return type (atom, rss, xml, json)
2991 * @throws BadRequestException
2992 * @throws ImagickException
2993 * @throws InternalServerErrorException
2994 * @throws UnauthorizedException
2996 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2998 $a = Friendica\DI::app();
3002 if (empty($items)) {
3006 foreach ((array)$items as $item) {
3007 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3009 // Look if the posts are matching if they should be filtered by user id
3010 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3014 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3023 * @param array $item Item record
3024 * @param string $type Return format (atom, rss, xml, json)
3025 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3026 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3027 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3028 * @return array API-formatted status
3029 * @throws BadRequestException
3030 * @throws ImagickException
3031 * @throws InternalServerErrorException
3032 * @throws UnauthorizedException
3034 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3036 $a = Friendica\DI::app();
3038 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3039 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3042 localize_item($item);
3044 $in_reply_to = api_in_reply_to($item);
3046 $converted = api_convert_item($item);
3048 if ($type == "xml") {
3049 $geo = "georss:point";
3055 'text' => $converted["text"],
3056 'truncated' => false,
3057 'created_at'=> api_date($item['created']),
3058 'in_reply_to_status_id' => $in_reply_to['status_id'],
3059 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3060 'source' => (($item['app']) ? $item['app'] : 'web'),
3061 'id' => intval($item['id']),
3062 'id_str' => (string) intval($item['id']),
3063 'in_reply_to_user_id' => $in_reply_to['user_id'],
3064 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3065 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3067 'favorited' => $item['starred'] ? true : false,
3068 'user' => $status_user,
3069 'friendica_author' => $author_user,
3070 'friendica_owner' => $owner_user,
3071 'friendica_private' => $item['private'] == Item::PRIVATE,
3072 //'entities' => NULL,
3073 'statusnet_html' => $converted["html"],
3074 'statusnet_conversation_id' => $item['parent'],
3075 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3076 'friendica_activities' => api_format_items_activities($item, $type),
3077 'friendica_title' => $item['title'],
3078 'friendica_html' => BBCode::convert($item['body'], false)
3081 if (count($converted["attachments"]) > 0) {
3082 $status["attachments"] = $converted["attachments"];
3085 if (count($converted["entities"]) > 0) {
3086 $status["entities"] = $converted["entities"];
3089 if ($status["source"] == 'web') {
3090 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3091 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3092 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3095 $retweeted_item = [];
3098 if ($item['gravity'] == GRAVITY_PARENT) {
3099 $body = $item['body'];
3100 $retweeted_item = api_share_as_retweet($item);
3101 if ($body != $item['body']) {
3102 $quoted_item = $retweeted_item;
3103 $retweeted_item = [];
3107 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3108 $announce = api_get_announce($item);
3109 if (!empty($announce)) {
3110 $retweeted_item = $item;
3112 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3116 if (!empty($quoted_item)) {
3117 if ($quoted_item['id'] != $item['id']) {
3118 $quoted_status = api_format_item($quoted_item);
3119 /// @todo Only remove the attachments that are also contained in the quotes status
3120 unset($status['attachments']);
3121 unset($status['entities']);
3123 $conv_quoted = api_convert_item($quoted_item);
3124 $quoted_status = $status;
3125 unset($quoted_status['attachments']);
3126 unset($quoted_status['entities']);
3127 unset($quoted_status['statusnet_conversation_id']);
3128 $quoted_status['text'] = $conv_quoted['text'];
3129 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3131 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3132 } catch (BadRequestException $e) {
3133 // user not found. should be found?
3134 /// @todo check if the user should be always found
3135 $quoted_status["user"] = [];
3138 unset($quoted_status['friendica_author']);
3139 unset($quoted_status['friendica_owner']);
3140 unset($quoted_status['friendica_activities']);
3141 unset($quoted_status['friendica_private']);
3144 if (!empty($retweeted_item)) {
3145 $retweeted_status = $status;
3146 unset($retweeted_status['friendica_author']);
3147 unset($retweeted_status['friendica_owner']);
3148 unset($retweeted_status['friendica_activities']);
3149 unset($retweeted_status['friendica_private']);
3150 unset($retweeted_status['statusnet_conversation_id']);
3151 $status['user'] = $status['friendica_owner'];
3153 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3154 } catch (BadRequestException $e) {
3155 // user not found. should be found?
3156 /// @todo check if the user should be always found
3157 $retweeted_status["user"] = [];
3160 $rt_converted = api_convert_item($retweeted_item);
3162 $retweeted_status['text'] = $rt_converted["text"];
3163 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3164 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3166 if (!empty($quoted_status)) {
3167 $retweeted_status['quoted_status'] = $quoted_status;
3170 $status['friendica_author'] = $retweeted_status['user'];
3171 $status['retweeted_status'] = $retweeted_status;
3172 } elseif (!empty($quoted_status)) {
3173 $root_status = api_convert_item($item);
3175 $status['text'] = $root_status["text"];
3176 $status['statusnet_html'] = $root_status["html"];
3177 $status['quoted_status'] = $quoted_status;
3180 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3181 unset($status["user"]["uid"]);
3182 unset($status["user"]["self"]);
3184 if ($item["coord"] != "") {
3185 $coords = explode(' ', $item["coord"]);
3186 if (count($coords) == 2) {
3187 if ($type == "json") {
3188 $status["geo"] = ['type' => 'Point',
3189 'coordinates' => [(float) $coords[0],
3190 (float) $coords[1]]];
3191 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3192 $status["georss:point"] = $item["coord"];
3201 * Returns the remaining number of API requests available to the user before the API limit is reached.
3203 * @param string $type Return type (atom, rss, xml, json)
3205 * @return array|string
3208 function api_account_rate_limit_status($type)
3210 if ($type == "xml") {
3212 'remaining-hits' => '150',
3213 '@attributes' => ["type" => "integer"],
3214 'hourly-limit' => '150',
3215 '@attributes2' => ["type" => "integer"],
3216 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3217 '@attributes3' => ["type" => "datetime"],
3218 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3219 '@attributes4' => ["type" => "integer"],
3223 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3224 'remaining_hits' => '150',
3225 'hourly_limit' => '150',
3226 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3230 return api_format_data('hash', $type, ['hash' => $hash]);
3233 /// @TODO move to top of file or somewhere better
3234 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3237 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3239 * @param string $type Return type (atom, rss, xml, json)
3241 * @return array|string
3243 function api_help_test($type)
3245 if ($type == 'xml') {
3251 return api_format_data('ok', $type, ["ok" => $ok]);
3254 /// @TODO move to top of file or somewhere better
3255 api_register_func('api/help/test', 'api_help_test', false);
3258 * Returns all lists the user subscribes to.
3260 * @param string $type Return type (atom, rss, xml, json)
3262 * @return array|string
3263 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3265 function api_lists_list($type)
3268 /// @TODO $ret is not filled here?
3269 return api_format_data('lists', $type, ["lists_list" => $ret]);
3272 /// @TODO move to top of file or somewhere better
3273 api_register_func('api/lists/list', 'api_lists_list', true);
3274 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3277 * Returns all groups the user owns.
3279 * @param string $type Return type (atom, rss, xml, json)
3281 * @return array|string
3282 * @throws BadRequestException
3283 * @throws ForbiddenException
3284 * @throws ImagickException
3285 * @throws InternalServerErrorException
3286 * @throws UnauthorizedException
3287 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3289 function api_lists_ownerships($type)
3293 if (api_user() === false) {
3294 throw new ForbiddenException();
3298 $user_info = api_get_user($a);
3299 $uid = $user_info['uid'];
3301 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3303 // loop through all groups
3305 foreach ($groups as $group) {
3306 if ($group['visible']) {
3312 'name' => $group['name'],
3313 'id' => intval($group['id']),
3314 'id_str' => (string) $group['id'],
3315 'user' => $user_info,
3319 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3322 /// @TODO move to top of file or somewhere better
3323 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3326 * Returns recent statuses from users in the specified group.
3328 * @param string $type Return type (atom, rss, xml, json)
3330 * @return array|string
3331 * @throws BadRequestException
3332 * @throws ForbiddenException
3333 * @throws ImagickException
3334 * @throws InternalServerErrorException
3335 * @throws UnauthorizedException
3336 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3338 function api_lists_statuses($type)
3342 $user_info = api_get_user($a);
3343 if (api_user() === false || $user_info === false) {
3344 throw new ForbiddenException();
3347 unset($_REQUEST["user_id"]);
3348 unset($_GET["user_id"]);
3350 unset($_REQUEST["screen_name"]);
3351 unset($_GET["screen_name"]);
3353 if (empty($_REQUEST['list_id'])) {
3354 throw new BadRequestException('list_id not specified');
3358 $count = $_REQUEST['count'] ?? 20;
3359 $page = $_REQUEST['page'] ?? 1;
3360 $since_id = $_REQUEST['since_id'] ?? 0;
3361 $max_id = $_REQUEST['max_id'] ?? 0;
3362 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3363 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3365 $start = max(0, ($page - 1) * $count);
3367 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3368 $gids = array_column($groups, 'contact-id');
3369 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3370 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3373 $condition[0] .= " AND `id` <= ?";
3374 $condition[] = $max_id;
3376 if ($exclude_replies > 0) {
3377 $condition[0] .= ' AND `gravity` = ?';
3378 $condition[] = GRAVITY_PARENT;
3380 if ($conversation_id > 0) {
3381 $condition[0] .= " AND `parent` = ?";
3382 $condition[] = $conversation_id;
3385 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3386 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3388 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3390 $data = ['status' => $items];
3395 $data = api_rss_extra($a, $data, $user_info);
3399 return api_format_data("statuses", $type, $data);
3402 /// @TODO move to top of file or somewhere better
3403 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3406 * Returns either the friends of the follower list
3408 * Considers friends and followers lists to be private and won't return
3409 * anything if any user_id parameter is passed.
3411 * @param string $qtype Either "friends" or "followers"
3412 * @return boolean|array
3413 * @throws BadRequestException
3414 * @throws ForbiddenException
3415 * @throws ImagickException
3416 * @throws InternalServerErrorException
3417 * @throws UnauthorizedException
3419 function api_statuses_f($qtype)
3423 if (api_user() === false) {
3424 throw new ForbiddenException();
3428 $count = $_GET['count'] ?? 20;
3429 $page = $_GET['page'] ?? 1;
3431 $start = max(0, ($page - 1) * $count);
3433 $user_info = api_get_user($a);
3435 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3436 /* this is to stop Hotot to load friends multiple times
3437 * I'm not sure if I'm missing return something or
3438 * is a bug in hotot. Workaround, meantime
3442 return array('$users' => $ret);*/
3447 if ($qtype == 'friends') {
3448 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3449 } elseif ($qtype == 'followers') {
3450 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3453 // friends and followers only for self
3454 if ($user_info['self'] == 0) {
3455 $sql_extra = " AND false ";
3458 if ($qtype == 'blocks') {
3459 $sql_filter = 'AND `blocked` AND NOT `pending`';
3460 } elseif ($qtype == 'incoming') {
3461 $sql_filter = 'AND `pending`';
3463 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3481 foreach ($r as $cid) {
3482 $user = api_get_user($a, $cid['nurl']);
3483 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3484 unset($user["uid"]);
3485 unset($user["self"]);
3492 return ['user' => $ret];
3497 * Returns the list of friends of the provided user
3499 * @deprecated By Twitter API in favor of friends/list
3501 * @param string $type Either "json" or "xml"
3502 * @return boolean|string|array
3503 * @throws BadRequestException
3504 * @throws ForbiddenException
3506 function api_statuses_friends($type)
3508 $data = api_statuses_f("friends");
3509 if ($data === false) {
3512 return api_format_data("users", $type, $data);
3516 * Returns the list of followers of the provided user
3518 * @deprecated By Twitter API in favor of friends/list
3520 * @param string $type Either "json" or "xml"
3521 * @return boolean|string|array
3522 * @throws BadRequestException
3523 * @throws ForbiddenException
3525 function api_statuses_followers($type)
3527 $data = api_statuses_f("followers");
3528 if ($data === false) {
3531 return api_format_data("users", $type, $data);
3534 /// @TODO move to top of file or somewhere better
3535 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3536 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3539 * Returns the list of blocked users
3541 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3543 * @param string $type Either "json" or "xml"
3545 * @return boolean|string|array
3546 * @throws BadRequestException
3547 * @throws ForbiddenException
3549 function api_blocks_list($type)
3551 $data = api_statuses_f('blocks');
3552 if ($data === false) {
3555 return api_format_data("users", $type, $data);
3558 /// @TODO move to top of file or somewhere better
3559 api_register_func('api/blocks/list', 'api_blocks_list', true);
3562 * Returns the list of pending users IDs
3564 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3566 * @param string $type Either "json" or "xml"
3568 * @return boolean|string|array
3569 * @throws BadRequestException
3570 * @throws ForbiddenException
3572 function api_friendships_incoming($type)
3574 $data = api_statuses_f('incoming');
3575 if ($data === false) {
3580 foreach ($data['user'] as $user) {
3581 $ids[] = $user['id'];
3584 return api_format_data("ids", $type, ['id' => $ids]);
3587 /// @TODO move to top of file or somewhere better
3588 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3591 * Returns the instance's configuration information.
3593 * @param string $type Return type (atom, rss, xml, json)
3595 * @return array|string
3596 * @throws InternalServerErrorException
3598 function api_statusnet_config($type)
3600 $name = DI::config()->get('config', 'sitename');
3601 $server = DI::baseUrl()->getHostname();
3602 $logo = DI::baseUrl() . '/images/friendica-64.png';
3603 $email = DI::config()->get('config', 'admin_email');
3604 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3605 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3606 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3607 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3608 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3611 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3612 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3613 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3614 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3615 'shorturllength' => '30',
3617 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3618 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3619 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3620 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3625 return api_format_data('config', $type, ['config' => $config]);
3628 /// @TODO move to top of file or somewhere better
3629 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3630 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3634 * @param string $type Return type (atom, rss, xml, json)
3636 * @return array|string
3638 function api_statusnet_version($type)
3641 $fake_statusnet_version = "0.9.7";
3643 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3646 /// @TODO move to top of file or somewhere better
3647 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3648 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3651 * Sends a new direct message.
3653 * @param string $type Return type (atom, rss, xml, json)
3655 * @return array|string
3656 * @throws BadRequestException
3657 * @throws ForbiddenException
3658 * @throws ImagickException
3659 * @throws InternalServerErrorException
3660 * @throws NotFoundException
3661 * @throws UnauthorizedException
3662 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3664 function api_direct_messages_new($type)
3668 if (api_user() === false) {
3669 throw new ForbiddenException();
3672 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3676 $sender = api_get_user($a);
3679 if (!empty($_POST['screen_name'])) {
3681 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3683 DBA::escape($_POST['screen_name'])
3686 if (DBA::isResult($r)) {
3687 // Selecting the id by priority, friendica first
3688 api_best_nickname($r);
3690 $recipient = api_get_user($a, $r[0]['nurl']);
3693 $recipient = api_get_user($a, $_POST['user_id']);
3696 if (empty($recipient)) {
3697 throw new NotFoundException('Recipient not found');
3701 if (!empty($_REQUEST['replyto'])) {
3703 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3705 intval($_REQUEST['replyto'])
3707 $replyto = $r[0]['parent-uri'];
3708 $sub = $r[0]['title'];
3710 if (!empty($_REQUEST['title'])) {
3711 $sub = $_REQUEST['title'];
3713 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3717 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3720 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3721 $ret = api_format_messages($r[0], $recipient, $sender);
3723 $ret = ["error"=>$id];
3726 $data = ['direct_message'=>$ret];
3732 $data = api_rss_extra($a, $data, $sender);
3736 return api_format_data("direct-messages", $type, $data);
3739 /// @TODO move to top of file or somewhere better
3740 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3743 * delete a direct_message from mail table through api
3745 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3746 * @return string|array
3747 * @throws BadRequestException
3748 * @throws ForbiddenException
3749 * @throws ImagickException
3750 * @throws InternalServerErrorException
3751 * @throws UnauthorizedException
3752 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3754 function api_direct_messages_destroy($type)
3758 if (api_user() === false) {
3759 throw new ForbiddenException();
3763 $user_info = api_get_user($a);
3765 $id = $_REQUEST['id'] ?? 0;
3767 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3768 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3769 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3771 $uid = $user_info['uid'];
3772 // error if no id or parenturi specified (for clients posting parent-uri as well)
3773 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3774 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3775 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3778 // BadRequestException if no id specified (for clients using Twitter API)
3780 throw new BadRequestException('Message id not specified');
3783 // add parent-uri to sql command if specified by calling app
3784 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3786 // get data of the specified message id
3788 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3793 // error message if specified id is not in database
3794 if (!DBA::isResult($r)) {
3795 if ($verbose == "true") {
3796 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3797 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3799 /// @todo BadRequestException ok for Twitter API clients?
3800 throw new BadRequestException('message id not in database');
3805 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3810 if ($verbose == "true") {
3813 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3814 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3816 $answer = ['result' => 'error', 'message' => 'unknown error'];
3817 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3820 /// @todo return JSON data like Twitter API not yet implemented
3823 /// @TODO move to top of file or somewhere better
3824 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3829 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3830 * @return string|array
3831 * @throws BadRequestException
3832 * @throws ForbiddenException
3833 * @throws ImagickException
3834 * @throws InternalServerErrorException
3835 * @throws NotFoundException
3836 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3838 function api_friendships_destroy($type)
3842 if ($uid === false) {
3843 throw new ForbiddenException();
3846 $contact_id = $_REQUEST['user_id'] ?? 0;
3848 if (empty($contact_id)) {
3849 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3850 throw new BadRequestException("no user_id specified");
3853 // Get Contact by given id
3854 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3856 if(!DBA::isResult($contact)) {
3857 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3858 throw new NotFoundException("no contact found to given ID");
3861 $url = $contact["url"];
3863 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3864 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3865 Strings::normaliseLink($url), $url];
3866 $contact = DBA::selectFirst('contact', [], $condition);
3868 if (!DBA::isResult($contact)) {
3869 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3870 throw new NotFoundException("Not following Contact");
3873 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3874 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3875 throw new ExpectationFailedException("Not supported");
3878 $dissolve = ($contact['rel'] == Contact::SHARING);
3880 $owner = User::getOwnerDataById($uid);
3882 Contact::terminateFriendship($owner, $contact, $dissolve);
3885 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3886 throw new NotFoundException("Error Processing Request");
3889 // Sharing-only contacts get deleted as there no relationship any more
3891 Contact::remove($contact['id']);
3893 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3896 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3897 unset($contact["uid"]);
3898 unset($contact["self"]);
3900 // Set screen_name since Twidere requests it
3901 $contact["screen_name"] = $contact["nick"];
3903 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3905 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3909 * @param string $type Return type (atom, rss, xml, json)
3910 * @param string $box
3911 * @param string $verbose
3913 * @return array|string
3914 * @throws BadRequestException
3915 * @throws ForbiddenException
3916 * @throws ImagickException
3917 * @throws InternalServerErrorException
3918 * @throws UnauthorizedException
3920 function api_direct_messages_box($type, $box, $verbose)
3923 if (api_user() === false) {
3924 throw new ForbiddenException();
3927 $count = $_GET['count'] ?? 20;
3928 $page = $_REQUEST['page'] ?? 1;
3930 $since_id = $_REQUEST['since_id'] ?? 0;
3931 $max_id = $_REQUEST['max_id'] ?? 0;
3933 $user_id = $_REQUEST['user_id'] ?? '';
3934 $screen_name = $_REQUEST['screen_name'] ?? '';
3937 unset($_REQUEST["user_id"]);
3938 unset($_GET["user_id"]);
3940 unset($_REQUEST["screen_name"]);
3941 unset($_GET["screen_name"]);
3943 $user_info = api_get_user($a);
3944 if ($user_info === false) {
3945 throw new ForbiddenException();
3947 $profile_url = $user_info["url"];
3950 $start = max(0, ($page - 1) * $count);
3955 if ($box=="sentbox") {
3956 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3957 } elseif ($box == "conversation") {
3958 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3959 } elseif ($box == "all") {
3960 $sql_extra = "true";
3961 } elseif ($box == "inbox") {
3962 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3966 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3969 if ($user_id != "") {
3970 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3971 } elseif ($screen_name !="") {
3972 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3976 "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",
3982 if ($verbose == "true" && !DBA::isResult($r)) {
3983 $answer = ['result' => 'error', 'message' => 'no mails available'];
3984 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3988 foreach ($r as $item) {
3989 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3990 $recipient = $user_info;
3991 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3992 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3993 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3994 $sender = $user_info;
3997 if (isset($recipient) && isset($sender)) {
3998 $ret[] = api_format_messages($item, $recipient, $sender);
4003 $data = ['direct_message' => $ret];
4008 $data = api_rss_extra($a, $data, $user_info);
4012 return api_format_data("direct-messages", $type, $data);
4016 * Returns the most recent direct messages sent by the user.
4018 * @param string $type Return type (atom, rss, xml, json)
4020 * @return array|string
4021 * @throws BadRequestException
4022 * @throws ForbiddenException
4023 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4025 function api_direct_messages_sentbox($type)
4027 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4028 return api_direct_messages_box($type, "sentbox", $verbose);
4032 * Returns the most recent direct messages sent to the user.
4034 * @param string $type Return type (atom, rss, xml, json)
4036 * @return array|string
4037 * @throws BadRequestException
4038 * @throws ForbiddenException
4039 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4041 function api_direct_messages_inbox($type)
4043 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4044 return api_direct_messages_box($type, "inbox", $verbose);
4049 * @param string $type Return type (atom, rss, xml, json)
4051 * @return array|string
4052 * @throws BadRequestException
4053 * @throws ForbiddenException
4055 function api_direct_messages_all($type)
4057 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4058 return api_direct_messages_box($type, "all", $verbose);
4063 * @param string $type Return type (atom, rss, xml, json)
4065 * @return array|string
4066 * @throws BadRequestException
4067 * @throws ForbiddenException
4069 function api_direct_messages_conversation($type)
4071 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4072 return api_direct_messages_box($type, "conversation", $verbose);
4075 /// @TODO move to top of file or somewhere better
4076 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4077 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4078 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4079 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4082 * Returns an OAuth Request Token.
4084 * @see https://oauth.net/core/1.0/#auth_step1
4086 function api_oauth_request_token()
4088 $oauth1 = new FKOAuth1();
4090 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4091 } catch (Exception $e) {
4092 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4100 * Returns an OAuth Access Token.
4102 * @return array|string
4103 * @see https://oauth.net/core/1.0/#auth_step3
4105 function api_oauth_access_token()
4107 $oauth1 = new FKOAuth1();
4109 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4110 } catch (Exception $e) {
4111 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4118 /// @TODO move to top of file or somewhere better
4119 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4120 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4124 * delete a complete photoalbum with all containing photos from database through api
4126 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4127 * @return string|array
4128 * @throws BadRequestException
4129 * @throws ForbiddenException
4130 * @throws InternalServerErrorException
4132 function api_fr_photoalbum_delete($type)
4134 if (api_user() === false) {
4135 throw new ForbiddenException();
4138 $album = $_REQUEST['album'] ?? '';
4140 // we do not allow calls without album string
4142 throw new BadRequestException("no albumname specified");
4144 // check if album is existing
4146 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4147 if (!DBA::isResult($photos)) {
4148 throw new BadRequestException("album not available");
4151 $resourceIds = array_column($photos, 'resource-id');
4153 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4154 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4155 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4156 Item::deleteForUser($condition, api_user());
4158 // now let's delete all photos from the album
4159 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4161 // return success of deletion or error message
4163 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4164 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4166 throw new InternalServerErrorException("unknown error - deleting from database failed");
4171 * update the name of the album for all photos of an album
4173 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4174 * @return string|array
4175 * @throws BadRequestException
4176 * @throws ForbiddenException
4177 * @throws InternalServerErrorException
4179 function api_fr_photoalbum_update($type)
4181 if (api_user() === false) {
4182 throw new ForbiddenException();
4185 $album = $_REQUEST['album'] ?? '';
4186 $album_new = $_REQUEST['album_new'] ?? '';
4188 // we do not allow calls without album string
4190 throw new BadRequestException("no albumname specified");
4192 if ($album_new == "") {
4193 throw new BadRequestException("no new albumname specified");
4195 // check if album is existing
4196 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4197 throw new BadRequestException("album not available");
4199 // now let's update all photos to the albumname
4200 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4202 // return success of updating or error message
4204 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4205 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4207 throw new InternalServerErrorException("unknown error - updating in database failed");
4213 * list all photos of the authenticated user
4215 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4216 * @return string|array
4217 * @throws ForbiddenException
4218 * @throws InternalServerErrorException
4220 function api_fr_photos_list($type)
4222 if (api_user() === false) {
4223 throw new ForbiddenException();
4226 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4227 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4228 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4229 intval(local_user())
4232 'image/jpeg' => 'jpg',
4233 'image/png' => 'png',
4234 'image/gif' => 'gif'
4236 $data = ['photo'=>[]];
4237 if (DBA::isResult($r)) {
4238 foreach ($r as $rr) {
4240 $photo['id'] = $rr['resource-id'];
4241 $photo['album'] = $rr['album'];
4242 $photo['filename'] = $rr['filename'];
4243 $photo['type'] = $rr['type'];
4244 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4245 $photo['created'] = $rr['created'];
4246 $photo['edited'] = $rr['edited'];
4247 $photo['desc'] = $rr['desc'];
4249 if ($type == "xml") {
4250 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4252 $photo['thumb'] = $thumb;
4253 $data['photo'][] = $photo;
4257 return api_format_data("photos", $type, $data);
4261 * upload a new photo or change an existing photo
4263 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4264 * @return string|array
4265 * @throws BadRequestException
4266 * @throws ForbiddenException
4267 * @throws ImagickException
4268 * @throws InternalServerErrorException
4269 * @throws NotFoundException
4271 function api_fr_photo_create_update($type)
4273 if (api_user() === false) {
4274 throw new ForbiddenException();
4277 $photo_id = $_REQUEST['photo_id'] ?? null;
4278 $desc = $_REQUEST['desc'] ?? null;
4279 $album = $_REQUEST['album'] ?? null;
4280 $album_new = $_REQUEST['album_new'] ?? null;
4281 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4282 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4283 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4284 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4285 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4287 // do several checks on input parameters
4288 // we do not allow calls without album string
4289 if ($album == null) {
4290 throw new BadRequestException("no albumname specified");
4292 // if photo_id == null --> we are uploading a new photo
4293 if ($photo_id == null) {
4296 // error if no media posted in create-mode
4297 if (empty($_FILES['media'])) {
4299 throw new BadRequestException("no media data submitted");
4302 // album_new will be ignored in create-mode
4307 // check if photo is existing in databasei
4308 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4309 throw new BadRequestException("photo not available");
4313 // checks on acl strings provided by clients
4314 $acl_input_error = false;
4315 $acl_input_error |= check_acl_input($allow_cid);
4316 $acl_input_error |= check_acl_input($deny_cid);
4317 $acl_input_error |= check_acl_input($allow_gid);
4318 $acl_input_error |= check_acl_input($deny_gid);
4319 if ($acl_input_error) {
4320 throw new BadRequestException("acl data invalid");
4322 // now let's upload the new media in create-mode
4323 if ($mode == "create") {
4324 $media = $_FILES['media'];
4325 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4327 // return success of updating or error message
4328 if (!is_null($data)) {
4329 return api_format_data("photo_create", $type, $data);
4331 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4335 // now let's do the changes in update-mode
4336 if ($mode == "update") {
4337 $updated_fields = [];
4339 if (!is_null($desc)) {
4340 $updated_fields['desc'] = $desc;
4343 if (!is_null($album_new)) {
4344 $updated_fields['album'] = $album_new;
4347 if (!is_null($allow_cid)) {
4348 $allow_cid = trim($allow_cid);
4349 $updated_fields['allow_cid'] = $allow_cid;
4352 if (!is_null($deny_cid)) {
4353 $deny_cid = trim($deny_cid);
4354 $updated_fields['deny_cid'] = $deny_cid;
4357 if (!is_null($allow_gid)) {
4358 $allow_gid = trim($allow_gid);
4359 $updated_fields['allow_gid'] = $allow_gid;
4362 if (!is_null($deny_gid)) {
4363 $deny_gid = trim($deny_gid);
4364 $updated_fields['deny_gid'] = $deny_gid;
4368 if (count($updated_fields) > 0) {
4369 $nothingtodo = false;
4370 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4372 $nothingtodo = true;
4375 if (!empty($_FILES['media'])) {
4376 $nothingtodo = false;
4377 $media = $_FILES['media'];
4378 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4379 if (!is_null($data)) {
4380 return api_format_data("photo_update", $type, $data);
4384 // return success of updating or error message
4386 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4387 return api_format_data("photo_update", $type, ['$result' => $answer]);
4390 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4391 return api_format_data("photo_update", $type, ['$result' => $answer]);
4393 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4396 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4400 * delete a single photo from the database through api
4402 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4403 * @return string|array
4404 * @throws BadRequestException
4405 * @throws ForbiddenException
4406 * @throws InternalServerErrorException
4408 function api_fr_photo_delete($type)
4410 if (api_user() === false) {
4411 throw new ForbiddenException();
4415 $photo_id = $_REQUEST['photo_id'] ?? null;
4417 // do several checks on input parameters
4418 // we do not allow calls without photo id
4419 if ($photo_id == null) {
4420 throw new BadRequestException("no photo_id specified");
4423 // check if photo is existing in database
4424 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4425 throw new BadRequestException("photo not available");
4428 // now we can perform on the deletion of the photo
4429 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4431 // return success of deletion or error message
4433 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4434 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4435 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4436 Item::deleteForUser($condition, api_user());
4438 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4439 return api_format_data("photo_delete", $type, ['$result' => $result]);
4441 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4447 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4449 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4450 * @return string|array
4451 * @throws BadRequestException
4452 * @throws ForbiddenException
4453 * @throws InternalServerErrorException
4454 * @throws NotFoundException
4456 function api_fr_photo_detail($type)
4458 if (api_user() === false) {
4459 throw new ForbiddenException();
4461 if (empty($_REQUEST['photo_id'])) {
4462 throw new BadRequestException("No photo id.");
4465 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4466 $photo_id = $_REQUEST['photo_id'];
4468 // prepare json/xml output with data from database for the requested photo
4469 $data = prepare_photo_data($type, $scale, $photo_id);
4471 return api_format_data("photo_detail", $type, $data);
4476 * updates the profile image for the user (either a specified profile or the default profile)
4478 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4480 * @return string|array
4481 * @throws BadRequestException
4482 * @throws ForbiddenException
4483 * @throws ImagickException
4484 * @throws InternalServerErrorException
4485 * @throws NotFoundException
4486 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4488 function api_account_update_profile_image($type)
4490 if (api_user() === false) {
4491 throw new ForbiddenException();
4494 $profile_id = $_REQUEST['profile_id'] ?? 0;
4496 // error if image data is missing
4497 if (empty($_FILES['image'])) {
4498 throw new BadRequestException("no media data submitted");
4501 // check if specified profile id is valid
4502 if ($profile_id != 0) {
4503 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4504 // error message if specified profile id is not in database
4505 if (!DBA::isResult($profile)) {
4506 throw new BadRequestException("profile_id not available");
4508 $is_default_profile = $profile['is-default'];
4510 $is_default_profile = 1;
4513 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4515 if (!empty($_FILES['image'])) {
4516 $media = $_FILES['image'];
4517 } elseif (!empty($_FILES['media'])) {
4518 $media = $_FILES['media'];
4520 // save new profile image
4521 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4524 if (is_array($media['type'])) {
4525 $filetype = $media['type'][0];
4527 $filetype = $media['type'];
4529 if ($filetype == "image/jpeg") {
4531 } elseif ($filetype == "image/png") {
4534 throw new InternalServerErrorException('Unsupported filetype');
4537 // change specified profile or all profiles to the new resource-id
4538 if ($is_default_profile) {
4539 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4540 Photo::update(['profile' => false], $condition);
4542 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4543 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4544 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4547 Contact::updateSelfFromUserID(api_user(), true);
4549 // Update global directory in background
4550 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4551 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4552 Worker::add(PRIORITY_LOW, "Directory", $url);
4555 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4557 // output for client
4559 return api_account_verify_credentials($type);
4561 // SaveMediaToDatabase failed for some reason
4562 throw new InternalServerErrorException("image upload failed");
4566 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4567 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4568 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4569 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4570 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4571 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4572 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4573 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4574 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4577 * Update user profile
4579 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4581 * @return array|string
4582 * @throws BadRequestException
4583 * @throws ForbiddenException
4584 * @throws ImagickException
4585 * @throws InternalServerErrorException
4586 * @throws UnauthorizedException
4588 function api_account_update_profile($type)
4590 $local_user = api_user();
4591 $api_user = api_get_user(DI::app());
4593 if (!empty($_POST['name'])) {
4594 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4595 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4596 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4597 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4600 if (isset($_POST['description'])) {
4601 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4602 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4603 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4606 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4607 // Update global directory in background
4608 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4609 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4612 return api_account_verify_credentials($type);
4615 /// @TODO move to top of file or somewhere better
4616 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4620 * @param string $acl_string
4624 function check_acl_input($acl_string)
4626 if (empty($acl_string)) {
4630 $contact_not_found = false;
4632 // split <x><y><z> into array of cid's
4633 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4635 // check for each cid if it is available on server
4636 $cid_array = $array[0];
4637 foreach ($cid_array as $cid) {
4638 $cid = str_replace("<", "", $cid);
4639 $cid = str_replace(">", "", $cid);
4640 $condition = ['id' => $cid, 'uid' => api_user()];
4641 $contact_not_found |= !DBA::exists('contact', $condition);
4643 return $contact_not_found;
4647 * @param string $mediatype
4648 * @param array $media
4649 * @param string $type
4650 * @param string $album
4651 * @param string $allow_cid
4652 * @param string $deny_cid
4653 * @param string $allow_gid
4654 * @param string $deny_gid
4655 * @param string $desc
4656 * @param integer $profile
4657 * @param boolean $visibility
4658 * @param string $photo_id
4660 * @throws BadRequestException
4661 * @throws ForbiddenException
4662 * @throws ImagickException
4663 * @throws InternalServerErrorException
4664 * @throws NotFoundException
4665 * @throws UnauthorizedException
4667 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)
4675 if (is_array($media)) {
4676 if (is_array($media['tmp_name'])) {
4677 $src = $media['tmp_name'][0];
4679 $src = $media['tmp_name'];
4681 if (is_array($media['name'])) {
4682 $filename = basename($media['name'][0]);
4684 $filename = basename($media['name']);
4686 if (is_array($media['size'])) {
4687 $filesize = intval($media['size'][0]);
4689 $filesize = intval($media['size']);
4691 if (is_array($media['type'])) {
4692 $filetype = $media['type'][0];
4694 $filetype = $media['type'];
4698 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4701 "File upload src: " . $src . " - filename: " . $filename .
4702 " - size: " . $filesize . " - type: " . $filetype,
4706 // check if there was a php upload error
4707 if ($filesize == 0 && $media['error'] == 1) {
4708 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4710 // check against max upload size within Friendica instance
4711 $maximagesize = DI::config()->get('system', 'maximagesize');
4712 if ($maximagesize && ($filesize > $maximagesize)) {
4713 $formattedBytes = Strings::formatBytes($maximagesize);
4714 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4717 // create Photo instance with the data of the image
4718 $imagedata = @file_get_contents($src);
4719 $Image = new Image($imagedata, $filetype);
4720 if (!$Image->isValid()) {
4721 throw new InternalServerErrorException("unable to process image data");
4724 // check orientation of image
4725 $Image->orient($src);
4728 // check max length of images on server
4729 $max_length = DI::config()->get('system', 'max_image_length');
4731 $max_length = MAX_IMAGE_LENGTH;
4733 if ($max_length > 0) {
4734 $Image->scaleDown($max_length);
4735 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4737 $width = $Image->getWidth();
4738 $height = $Image->getHeight();
4740 // create a new resource-id if not already provided
4741 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4743 if ($mediatype == "photo") {
4744 // upload normal image (scales 0, 1, 2)
4745 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4747 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4749 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4751 if ($width > 640 || $height > 640) {
4752 $Image->scaleDown(640);
4753 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4755 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4759 if ($width > 320 || $height > 320) {
4760 $Image->scaleDown(320);
4761 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4763 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4766 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4767 } elseif ($mediatype == "profileimage") {
4768 // upload profile image (scales 4, 5, 6)
4769 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4771 if ($width > 300 || $height > 300) {
4772 $Image->scaleDown(300);
4773 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4775 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4779 if ($width > 80 || $height > 80) {
4780 $Image->scaleDown(80);
4781 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4783 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4787 if ($width > 48 || $height > 48) {
4788 $Image->scaleDown(48);
4789 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4791 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4794 $Image->__destruct();
4795 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4799 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4800 if ($photo_id == null && $mediatype == "photo") {
4801 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4803 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4804 return prepare_photo_data($type, false, $resource_id);
4806 throw new InternalServerErrorException("image upload failed");
4812 * @param string $hash
4813 * @param string $allow_cid
4814 * @param string $deny_cid
4815 * @param string $allow_gid
4816 * @param string $deny_gid
4817 * @param string $filetype
4818 * @param boolean $visibility
4819 * @throws InternalServerErrorException
4821 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4823 // get data about the api authenticated user
4824 $uri = Item::newURI(intval(api_user()));
4825 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4828 $arr['guid'] = System::createUUID();
4829 $arr['uid'] = intval(api_user());
4831 $arr['type'] = 'photo';
4833 $arr['resource-id'] = $hash;
4834 $arr['contact-id'] = $owner_record['id'];
4835 $arr['owner-name'] = $owner_record['name'];
4836 $arr['owner-link'] = $owner_record['url'];
4837 $arr['owner-avatar'] = $owner_record['thumb'];
4838 $arr['author-name'] = $owner_record['name'];
4839 $arr['author-link'] = $owner_record['url'];
4840 $arr['author-avatar'] = $owner_record['thumb'];
4842 $arr['allow_cid'] = $allow_cid;
4843 $arr['allow_gid'] = $allow_gid;
4844 $arr['deny_cid'] = $deny_cid;
4845 $arr['deny_gid'] = $deny_gid;
4846 $arr['visible'] = $visibility;
4850 'image/jpeg' => 'jpg',
4851 'image/png' => 'png',
4852 'image/gif' => 'gif'
4855 // adds link to the thumbnail scale photo
4856 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4857 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4860 // do the magic for storing the item in the database and trigger the federation to other contacts
4866 * @param string $type
4868 * @param string $photo_id
4871 * @throws BadRequestException
4872 * @throws ForbiddenException
4873 * @throws ImagickException
4874 * @throws InternalServerErrorException
4875 * @throws NotFoundException
4876 * @throws UnauthorizedException
4878 function prepare_photo_data($type, $scale, $photo_id)
4881 $user_info = api_get_user($a);
4883 if ($user_info === false) {
4884 throw new ForbiddenException();
4887 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4888 $data_sql = ($scale === false ? "" : "data, ");
4890 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4891 // clients needs to convert this in their way for further processing
4893 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4894 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4895 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4896 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4897 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4898 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4900 intval(local_user()),
4901 DBA::escape($photo_id),
4906 'image/jpeg' => 'jpg',
4907 'image/png' => 'png',
4908 'image/gif' => 'gif'
4911 // prepare output data for photo
4912 if (DBA::isResult($r)) {
4913 $data = ['photo' => $r[0]];
4914 $data['photo']['id'] = $data['photo']['resource-id'];
4915 if ($scale !== false) {
4916 $data['photo']['data'] = base64_encode($data['photo']['data']);
4918 unset($data['photo']['datasize']); //needed only with scale param
4920 if ($type == "xml") {
4921 $data['photo']['links'] = [];
4922 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4923 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4925 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4928 $data['photo']['link'] = [];
4929 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4931 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4932 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4936 unset($data['photo']['resource-id']);
4937 unset($data['photo']['minscale']);
4938 unset($data['photo']['maxscale']);
4940 throw new NotFoundException();
4943 // retrieve item element for getting activities (like, dislike etc.) related to photo
4944 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4945 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4946 if (!DBA::isResult($item)) {
4947 throw new NotFoundException('Photo-related item not found.');
4950 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4952 // retrieve comments on photo
4953 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4954 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4956 $statuses = Post::selectForUser(api_user(), [], $condition);
4958 // prepare output of comments
4959 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4961 if ($type == "xml") {
4963 foreach ($commentData as $comment) {
4964 $comments[$k++ . ":comment"] = $comment;
4967 foreach ($commentData as $comment) {
4968 $comments[] = $comment;
4971 $data['photo']['friendica_comments'] = $comments;
4973 // include info if rights on photo and rights on item are mismatching
4974 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4975 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4976 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4977 $data['photo']['deny_gid'] != $item['deny_gid'];
4978 $data['photo']['rights_mismatch'] = $rights_mismatch;
4985 * Similar as /mod/redir.php
4986 * redirect to 'url' after dfrn auth
4988 * Why this when there is mod/redir.php already?
4989 * This use api_user() and api_login()
4992 * c_url: url of remote contact to auth to
4993 * url: string, url to redirect after auth
4995 function api_friendica_remoteauth()
4997 $url = $_GET['url'] ?? '';
4998 $c_url = $_GET['c_url'] ?? '';
5000 if ($url === '' || $c_url === '') {
5001 throw new BadRequestException("Wrong parameters.");
5004 $c_url = Strings::normaliseLink($c_url);
5008 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5009 if (!DBA::isResult($contact)) {
5010 throw new BadRequestException("Unknown contact");
5013 $cid = $contact['id'];
5015 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5017 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5018 System::externalRedirect($url ?: $c_url);
5021 if ($contact['duplex'] && $contact['issued-id']) {
5022 $orig_id = $contact['issued-id'];
5023 $dfrn_id = '1:' . $orig_id;
5025 if ($contact['duplex'] && $contact['dfrn-id']) {
5026 $orig_id = $contact['dfrn-id'];
5027 $dfrn_id = '0:' . $orig_id;
5030 $sec = Strings::getRandomHex();
5032 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5033 'sec' => $sec, 'expire' => time() + 45];
5034 DBA::insert('profile_check', $fields);
5036 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5037 $dest = ($url ? '&destination_url=' . $url : '');
5039 System::externalRedirect(
5040 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5041 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5042 . '&type=profile&sec=' . $sec . $dest
5045 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5048 * Return an item with announcer data if it had been announced
5050 * @param array $item Item array
5051 * @return array Item array with announce data
5053 function api_get_announce($item)
5055 // Quit if the item already has got a different owner and author
5056 if ($item['owner-id'] != $item['author-id']) {
5060 // Don't change original or Diaspora posts
5061 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5065 // Quit if we do now the original author and it had been a post from a native network
5066 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5070 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5071 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5072 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5073 if (!DBA::isResult($announce)) {
5077 return array_merge($item, $announce);
5081 * Return the item shared, if the item contains only the [share] tag
5083 * @param array $item Sharer item
5084 * @return array|false Shared item or false if not a reshare
5085 * @throws ImagickException
5086 * @throws InternalServerErrorException
5088 function api_share_as_retweet(&$item)
5090 $body = trim($item["body"]);
5092 if (Diaspora::isReshare($body, false) === false) {
5093 if ($item['author-id'] == $item['owner-id']) {
5096 // Reshares from OStatus, ActivityPub and Twitter
5097 $reshared_item = $item;
5098 $reshared_item['owner-id'] = $reshared_item['author-id'];
5099 $reshared_item['owner-link'] = $reshared_item['author-link'];
5100 $reshared_item['owner-name'] = $reshared_item['author-name'];
5101 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5102 return $reshared_item;
5106 $reshared = Item::getShareArray($item);
5107 if (empty($reshared)) {
5111 $reshared_item = $item;
5113 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5117 if (!empty($reshared['comment'])) {
5118 $item['body'] = $reshared['comment'];
5121 $reshared_item["share-pre-body"] = $reshared['comment'];
5122 $reshared_item["body"] = $reshared['shared'];
5123 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5124 $reshared_item["author-name"] = $reshared['author'];
5125 $reshared_item["author-link"] = $reshared['profile'];
5126 $reshared_item["author-avatar"] = $reshared['avatar'];
5127 $reshared_item["plink"] = $reshared['link'] ?? '';
5128 $reshared_item["created"] = $reshared['posted'];
5129 $reshared_item["edited"] = $reshared['posted'];
5131 // Try to fetch the original item
5132 if (!empty($reshared['guid'])) {
5133 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5134 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5135 $condition = ['id' => $original_id];
5140 if (!empty($condition)) {
5141 $original_item = Post::selectFirst([], $condition);
5142 if (DBA::isResult($original_item)) {
5143 $reshared_item = array_merge($reshared_item, $original_item);
5147 return $reshared_item;
5152 * @param array $item
5157 function api_in_reply_to($item)
5161 $in_reply_to['status_id'] = null;
5162 $in_reply_to['user_id'] = null;
5163 $in_reply_to['status_id_str'] = null;
5164 $in_reply_to['user_id_str'] = null;
5165 $in_reply_to['screen_name'] = null;
5167 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5168 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5169 if (DBA::isResult($parent)) {
5170 $in_reply_to['status_id'] = intval($parent['id']);
5172 $in_reply_to['status_id'] = intval($item['parent']);
5175 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5177 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5178 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5180 if (DBA::isResult($parent)) {
5181 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5182 $in_reply_to['user_id'] = intval($parent['author-id']);
5183 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5186 // There seems to be situation, where both fields are identical:
5187 // https://github.com/friendica/friendica/issues/1010
5188 // This is a bugfix for that.
5189 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5190 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']]);
5191 $in_reply_to['status_id'] = null;
5192 $in_reply_to['user_id'] = null;
5193 $in_reply_to['status_id_str'] = null;
5194 $in_reply_to['user_id_str'] = null;
5195 $in_reply_to['screen_name'] = null;
5199 return $in_reply_to;
5204 * @param string $text
5207 * @throws InternalServerErrorException
5209 function api_clean_plain_items($text)
5211 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5213 $text = BBCode::cleanPictureLinks($text);
5214 $URLSearchString = "^\[\]";
5216 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5218 if ($include_entities == "true") {
5219 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5222 // Simplify "attachment" element
5223 $text = BBCode::removeAttachment($text);
5230 * @param array $contacts
5234 function api_best_nickname(&$contacts)
5238 if (count($contacts) == 0) {
5242 foreach ($contacts as $contact) {
5243 if ($contact["network"] == "") {
5244 $contact["network"] = "dfrn";
5245 $best_contact = [$contact];
5249 if (sizeof($best_contact) == 0) {
5250 foreach ($contacts as $contact) {
5251 if ($contact["network"] == "dfrn") {
5252 $best_contact = [$contact];
5257 if (sizeof($best_contact) == 0) {
5258 foreach ($contacts as $contact) {
5259 if ($contact["network"] == "dspr") {
5260 $best_contact = [$contact];
5265 if (sizeof($best_contact) == 0) {
5266 foreach ($contacts as $contact) {
5267 if ($contact["network"] == "stat") {
5268 $best_contact = [$contact];
5273 if (sizeof($best_contact) == 0) {
5274 foreach ($contacts as $contact) {
5275 if ($contact["network"] == "pump") {
5276 $best_contact = [$contact];
5281 if (sizeof($best_contact) == 0) {
5282 foreach ($contacts as $contact) {
5283 if ($contact["network"] == "twit") {
5284 $best_contact = [$contact];
5289 if (sizeof($best_contact) == 1) {
5290 $contacts = $best_contact;
5292 $contacts = [$contacts[0]];
5297 * Return all or a specified group of the user with the containing contacts.
5299 * @param string $type Return type (atom, rss, xml, json)
5301 * @return array|string
5302 * @throws BadRequestException
5303 * @throws ForbiddenException
5304 * @throws ImagickException
5305 * @throws InternalServerErrorException
5306 * @throws UnauthorizedException
5308 function api_friendica_group_show($type)
5312 if (api_user() === false) {
5313 throw new ForbiddenException();
5317 $user_info = api_get_user($a);
5318 $gid = $_REQUEST['gid'] ?? 0;
5319 $uid = $user_info['uid'];
5321 // get data of the specified group id or all groups if not specified
5324 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5328 // error message if specified gid is not in database
5329 if (!DBA::isResult($r)) {
5330 throw new BadRequestException("gid not available");
5334 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5339 // loop through all groups and retrieve all members for adding data in the user array
5341 foreach ($r as $rr) {
5342 $members = Contact\Group::getById($rr['id']);
5345 if ($type == "xml") {
5346 $user_element = "users";
5348 foreach ($members as $member) {
5349 $user = api_get_user($a, $member['nurl']);
5350 $users[$k++.":user"] = $user;
5353 $user_element = "user";
5354 foreach ($members as $member) {
5355 $user = api_get_user($a, $member['nurl']);
5359 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5361 return api_format_data("groups", $type, ['group' => $grps]);
5363 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5367 * Delete the specified group of the user.
5369 * @param string $type Return type (atom, rss, xml, json)
5371 * @return array|string
5372 * @throws BadRequestException
5373 * @throws ForbiddenException
5374 * @throws ImagickException
5375 * @throws InternalServerErrorException
5376 * @throws UnauthorizedException
5378 function api_friendica_group_delete($type)
5382 if (api_user() === false) {
5383 throw new ForbiddenException();
5387 $user_info = api_get_user($a);
5388 $gid = $_REQUEST['gid'] ?? 0;
5389 $name = $_REQUEST['name'] ?? '';
5390 $uid = $user_info['uid'];
5392 // error if no gid specified
5393 if ($gid == 0 || $name == "") {
5394 throw new BadRequestException('gid or name not specified');
5397 // get data of the specified group id
5399 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5403 // error message if specified gid is not in database
5404 if (!DBA::isResult($r)) {
5405 throw new BadRequestException('gid not available');
5408 // get data of the specified group id and group name
5410 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5415 // error message if specified gid is not in database
5416 if (!DBA::isResult($rname)) {
5417 throw new BadRequestException('wrong group name');
5421 $ret = Group::removeByName($uid, $name);
5424 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5425 return api_format_data("group_delete", $type, ['result' => $success]);
5427 throw new BadRequestException('other API error');
5430 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5435 * @param string $type Return type (atom, rss, xml, json)
5437 * @return array|string
5438 * @throws BadRequestException
5439 * @throws ForbiddenException
5440 * @throws ImagickException
5441 * @throws InternalServerErrorException
5442 * @throws UnauthorizedException
5443 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5445 function api_lists_destroy($type)
5449 if (api_user() === false) {
5450 throw new ForbiddenException();
5454 $user_info = api_get_user($a);
5455 $gid = $_REQUEST['list_id'] ?? 0;
5456 $uid = $user_info['uid'];
5458 // error if no gid specified
5460 throw new BadRequestException('gid not specified');
5463 // get data of the specified group id
5464 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5465 // error message if specified gid is not in database
5467 throw new BadRequestException('gid not available');
5470 if (Group::remove($gid)) {
5472 'name' => $group['name'],
5473 'id' => intval($gid),
5474 'id_str' => (string) $gid,
5475 'user' => $user_info
5478 return api_format_data("lists", $type, ['lists' => $list]);
5481 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5484 * Add a new group to the database.
5486 * @param string $name Group name
5487 * @param int $uid User ID
5488 * @param array $users List of users to add to the group
5491 * @throws BadRequestException
5493 function group_create($name, $uid, $users = [])
5495 // error if no name specified
5497 throw new BadRequestException('group name not specified');
5500 // get data of the specified group name
5502 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5506 // error message if specified group name already exists
5507 if (DBA::isResult($rname)) {
5508 throw new BadRequestException('group name already exists');
5511 // check if specified group name is a deleted group
5513 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5517 // error message if specified group name already exists
5518 if (DBA::isResult($rname)) {
5519 $reactivate_group = true;
5523 $ret = Group::create($uid, $name);
5525 $gid = Group::getIdByName($uid, $name);
5527 throw new BadRequestException('other API error');
5531 $erroraddinguser = false;
5533 foreach ($users as $user) {
5534 $cid = $user['cid'];
5535 // check if user really exists as contact
5537 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5541 if (count($contact)) {
5542 Group::addMember($gid, $cid);
5544 $erroraddinguser = true;
5545 $errorusers[] = $cid;
5549 // return success message incl. missing users in array
5550 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5552 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5556 * Create the specified group with the posted array of contacts.
5558 * @param string $type Return type (atom, rss, xml, json)
5560 * @return array|string
5561 * @throws BadRequestException
5562 * @throws ForbiddenException
5563 * @throws ImagickException
5564 * @throws InternalServerErrorException
5565 * @throws UnauthorizedException
5567 function api_friendica_group_create($type)
5571 if (api_user() === false) {
5572 throw new ForbiddenException();
5576 $user_info = api_get_user($a);
5577 $name = $_REQUEST['name'] ?? '';
5578 $uid = $user_info['uid'];
5579 $json = json_decode($_POST['json'], true);
5580 $users = $json['user'];
5582 $success = group_create($name, $uid, $users);
5584 return api_format_data("group_create", $type, ['result' => $success]);
5586 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5589 * Create a new group.
5591 * @param string $type Return type (atom, rss, xml, json)
5593 * @return array|string
5594 * @throws BadRequestException
5595 * @throws ForbiddenException
5596 * @throws ImagickException
5597 * @throws InternalServerErrorException
5598 * @throws UnauthorizedException
5599 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5601 function api_lists_create($type)
5605 if (api_user() === false) {
5606 throw new ForbiddenException();
5610 $user_info = api_get_user($a);
5611 $name = $_REQUEST['name'] ?? '';
5612 $uid = $user_info['uid'];
5614 $success = group_create($name, $uid);
5615 if ($success['success']) {
5617 'name' => $success['name'],
5618 'id' => intval($success['gid']),
5619 'id_str' => (string) $success['gid'],
5620 'user' => $user_info
5623 return api_format_data("lists", $type, ['lists'=>$grp]);
5626 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5629 * Update the specified group with the posted array of contacts.
5631 * @param string $type Return type (atom, rss, xml, json)
5633 * @return array|string
5634 * @throws BadRequestException
5635 * @throws ForbiddenException
5636 * @throws ImagickException
5637 * @throws InternalServerErrorException
5638 * @throws UnauthorizedException
5640 function api_friendica_group_update($type)
5644 if (api_user() === false) {
5645 throw new ForbiddenException();
5649 $user_info = api_get_user($a);
5650 $uid = $user_info['uid'];
5651 $gid = $_REQUEST['gid'] ?? 0;
5652 $name = $_REQUEST['name'] ?? '';
5653 $json = json_decode($_POST['json'], true);
5654 $users = $json['user'];
5656 // error if no name specified
5658 throw new BadRequestException('group name not specified');
5661 // error if no gid specified
5663 throw new BadRequestException('gid not specified');
5667 $members = Contact\Group::getById($gid);
5668 foreach ($members as $member) {
5669 $cid = $member['id'];
5670 foreach ($users as $user) {
5671 $found = ($user['cid'] == $cid ? true : false);
5673 if (!isset($found) || !$found) {
5674 Group::removeMemberByName($uid, $name, $cid);
5679 $erroraddinguser = false;
5681 foreach ($users as $user) {
5682 $cid = $user['cid'];
5683 // check if user really exists as contact
5685 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5690 if (count($contact)) {
5691 Group::addMember($gid, $cid);
5693 $erroraddinguser = true;
5694 $errorusers[] = $cid;
5698 // return success message incl. missing users in array
5699 $status = ($erroraddinguser ? "missing user" : "ok");
5700 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5701 return api_format_data("group_update", $type, ['result' => $success]);
5704 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5707 * Update information about a group.
5709 * @param string $type Return type (atom, rss, xml, json)
5711 * @return array|string
5712 * @throws BadRequestException
5713 * @throws ForbiddenException
5714 * @throws ImagickException
5715 * @throws InternalServerErrorException
5716 * @throws UnauthorizedException
5717 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5719 function api_lists_update($type)
5723 if (api_user() === false) {
5724 throw new ForbiddenException();
5728 $user_info = api_get_user($a);
5729 $gid = $_REQUEST['list_id'] ?? 0;
5730 $name = $_REQUEST['name'] ?? '';
5731 $uid = $user_info['uid'];
5733 // error if no gid specified
5735 throw new BadRequestException('gid not specified');
5738 // get data of the specified group id
5739 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5740 // error message if specified gid is not in database
5742 throw new BadRequestException('gid not available');
5745 if (Group::update($gid, $name)) {
5748 'id' => intval($gid),
5749 'id_str' => (string) $gid,
5750 'user' => $user_info
5753 return api_format_data("lists", $type, ['lists' => $list]);
5757 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5761 * @param string $type Return type (atom, rss, xml, json)
5763 * @return array|string
5764 * @throws BadRequestException
5765 * @throws ForbiddenException
5766 * @throws ImagickException
5767 * @throws InternalServerErrorException
5769 function api_friendica_activity($type)
5773 if (api_user() === false) {
5774 throw new ForbiddenException();
5776 $verb = strtolower($a->argv[3]);
5777 $verb = preg_replace("|\..*$|", "", $verb);
5779 $id = $_REQUEST['id'] ?? 0;
5781 $res = Item::performActivity($id, $verb, api_user());
5784 if ($type == "xml") {
5789 return api_format_data('ok', $type, ['ok' => $ok]);
5791 throw new BadRequestException('Error adding activity');
5795 /// @TODO move to top of file or somewhere better
5796 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5797 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5798 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5799 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5800 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5801 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5802 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5803 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5804 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5805 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5808 * Returns notifications
5810 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5812 * @return string|array
5813 * @throws ForbiddenException
5814 * @throws BadRequestException
5817 function api_friendica_notification($type)
5821 if (api_user() === false) {
5822 throw new ForbiddenException();
5825 throw new BadRequestException("Invalid argument count");
5828 $notifications = DI::notification()->getApiList(local_user());
5830 if ($type == "xml") {
5832 if (!empty($notifications)) {
5833 foreach ($notifications as $notification) {
5834 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5838 $result = $xmlnotes;
5839 } elseif (count($notifications) > 0) {
5840 $result = $notifications->getArrayCopy();
5845 return api_format_data("notes", $type, ['note' => $result]);
5849 * Set notification as seen and returns associated item (if possible)
5851 * POST request with 'id' param as notification id
5853 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5854 * @return string|array
5855 * @throws BadRequestException
5856 * @throws ForbiddenException
5857 * @throws ImagickException
5858 * @throws InternalServerErrorException
5859 * @throws UnauthorizedException
5861 function api_friendica_notification_seen($type)
5864 $user_info = api_get_user($a);
5866 if (api_user() === false || $user_info === false) {
5867 throw new ForbiddenException();
5869 if ($a->argc !== 4) {
5870 throw new BadRequestException("Invalid argument count");
5873 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5876 $notify = DI::notify()->getByID($id, api_user());
5877 DI::notify()->setSeen(true, $notify);
5879 if ($notify->otype === Notification\ObjectType::ITEM) {
5880 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5881 if (DBA::isResult($item)) {
5882 // we found the item, return it to the user
5883 $ret = api_format_items([$item], $user_info, false, $type);
5884 $data = ['status' => $ret];
5885 return api_format_data("status", $type, $data);
5887 // the item can't be found, but we set the notification as seen, so we count this as a success
5889 return api_format_data('result', $type, ['result' => "success"]);
5890 } catch (NotFoundException $e) {
5891 throw new BadRequestException('Invalid argument', $e);
5892 } catch (Exception $e) {
5893 throw new InternalServerErrorException('Internal Server exception', $e);
5897 /// @TODO move to top of file or somewhere better
5898 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5899 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5902 * update a direct_message to seen state
5904 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5905 * @return string|array (success result=ok, error result=error with error message)
5906 * @throws BadRequestException
5907 * @throws ForbiddenException
5908 * @throws ImagickException
5909 * @throws InternalServerErrorException
5910 * @throws UnauthorizedException
5912 function api_friendica_direct_messages_setseen($type)
5915 if (api_user() === false) {
5916 throw new ForbiddenException();
5920 $user_info = api_get_user($a);
5921 $uid = $user_info['uid'];
5922 $id = $_REQUEST['id'] ?? 0;
5924 // return error if id is zero
5926 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5927 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5930 // error message if specified id is not in database
5931 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5932 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5933 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5936 // update seen indicator
5937 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5941 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5942 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5944 $answer = ['result' => 'error', 'message' => 'unknown error'];
5945 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5949 /// @TODO move to top of file or somewhere better
5950 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5953 * search for direct_messages containing a searchstring through api
5955 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5956 * @param string $box
5957 * @return string|array (success: success=true if found and search_result contains found messages,
5958 * success=false if nothing was found, search_result='nothing found',
5959 * error: result=error with error message)
5960 * @throws BadRequestException
5961 * @throws ForbiddenException
5962 * @throws ImagickException
5963 * @throws InternalServerErrorException
5964 * @throws UnauthorizedException
5966 function api_friendica_direct_messages_search($type, $box = "")
5970 if (api_user() === false) {
5971 throw new ForbiddenException();
5975 $user_info = api_get_user($a);
5976 $searchstring = $_REQUEST['searchstring'] ?? '';
5977 $uid = $user_info['uid'];
5979 // error if no searchstring specified
5980 if ($searchstring == "") {
5981 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5982 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5985 // get data for the specified searchstring
5987 "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",
5989 DBA::escape('%'.$searchstring.'%')
5992 $profile_url = $user_info["url"];
5994 // message if nothing was found
5995 if (!DBA::isResult($r)) {
5996 $success = ['success' => false, 'search_results' => 'problem with query'];
5997 } elseif (count($r) == 0) {
5998 $success = ['success' => false, 'search_results' => 'nothing found'];
6001 foreach ($r as $item) {
6002 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6003 $recipient = $user_info;
6004 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6005 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6006 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6007 $sender = $user_info;
6010 if (isset($recipient) && isset($sender)) {
6011 $ret[] = api_format_messages($item, $recipient, $sender);
6014 $success = ['success' => true, 'search_results' => $ret];
6017 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6020 /// @TODO move to top of file or somewhere better
6021 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6024 * Returns a list of saved searches.
6026 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6028 * @param string $type Return format: json or xml
6030 * @return string|array
6033 function api_saved_searches_list($type)
6035 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6038 while ($term = DBA::fetch($terms)) {
6040 'created_at' => api_date(time()),
6041 'id' => intval($term['id']),
6042 'id_str' => $term['id'],
6043 'name' => $term['term'],
6045 'query' => $term['term']
6051 return api_format_data("terms", $type, ['terms' => $result]);
6054 /// @TODO move to top of file or somewhere better
6055 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6058 * Number of comments
6060 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6062 * @param object $data [Status, Status]
6066 function bindComments(&$data)
6068 if (count($data) == 0) {
6074 foreach ($data as $item) {
6075 $ids[] = $item['id'];
6078 $idStr = DBA::escape(implode(', ', $ids));
6079 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6080 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6081 $itemsData = DBA::toArray($items);
6083 foreach ($itemsData as $item) {
6084 $comments[$item['parent']] = $item['comments'];
6087 foreach ($data as $idx => $item) {
6089 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6094 @TODO Maybe open to implement?
6096 [pagename] => api/1.1/statuses/lookup.json
6097 [id] => 605138389168451584
6098 [include_cards] => true
6099 [cards_platform] => Android-12
6100 [include_entities] => true
6101 [include_my_retweet] => 1
6103 [include_reply_count] => true
6104 [include_descendent_reply_count] => true
6108 Not implemented by now:
6109 statuses/retweets_of_me
6114 account/update_location
6115 account/update_profile_background_image
6118 friendica/profile/update
6119 friendica/profile/create
6120 friendica/profile/delete
6122 Not implemented in status.net:
6123 statuses/retweeted_to_me
6124 statuses/retweeted_by_me
6125 direct_messages/destroy
6127 account/update_delivery_device
6128 notifications/follow