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\FKOAuth1;
60 use Friendica\Security\OAuth;
61 use Friendica\Security\OAuth1\OAuthRequest;
62 use Friendica\Security\OAuth1\OAuthUtil;
63 use Friendica\Util\DateTimeFormat;
64 use Friendica\Util\Images;
65 use Friendica\Util\Network;
66 use Friendica\Util\Proxy as ProxyUtils;
67 use Friendica\Util\Strings;
68 use Friendica\Util\XML;
70 require_once __DIR__ . '/../mod/item.php';
71 require_once __DIR__ . '/../mod/wall_upload.php';
73 define('API_METHOD_ANY', '*');
74 define('API_METHOD_GET', 'GET');
75 define('API_METHOD_POST', 'POST,PUT');
76 define('API_METHOD_DELETE', 'POST,DELETE');
78 define('API_LOG_PREFIX', 'API {action} - ');
86 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
87 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
88 * into a page, and visitors will post something without noticing it).
92 $user = OAuth::getCurrentUserID();
97 if (!empty($_SESSION['allow_api'])) {
105 * Get source name from API client
107 * Clients can send 'source' parameter to be show in post metadata
108 * as "sent via <source>".
109 * Some clients doesn't send a source param, we support ones we know
110 * (only Twidere, atm)
113 * Client source name, default to "api" if unset/unknown
116 function api_source()
118 if (requestdata('source')) {
119 return requestdata('source');
122 // Support for known clients that doesn't send a source name
123 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
124 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
128 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
130 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
137 * Format date for API
139 * @param string $str Source date, as UTC
140 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
143 function api_date($str)
145 // Wed May 23 06:01:13 +0000 2007
146 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
150 * Register a function to be the endpoint for defined API path.
152 * @param string $path API URL path, relative to DI::baseUrl()
153 * @param string $func Function name to call on path request
154 * @param bool $auth API need logged user
155 * @param string $method HTTP method reqiured to call this endpoint.
156 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
157 * Default to API_METHOD_ANY
159 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
169 // Workaround for hotot
170 $path = str_replace("api/", "api/1.1/", $path);
180 * Log in user via OAuth1 or Simple HTTP Auth.
181 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
184 * @param bool $do_login try to log in when not logged in, otherwise quit silently
185 * @throws ForbiddenException
186 * @throws InternalServerErrorException
187 * @throws UnauthorizedException
188 * @hook 'authenticate'
190 * 'username' => username from login form
191 * 'password' => password from login form
192 * 'authenticated' => return status,
193 * 'user_record' => return authenticated user record
195 function api_login(App $a, bool $do_login = true)
197 $_SESSION["allow_api"] = false;
199 // workaround for HTTP-auth in CGI mode
200 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
201 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
202 if (strlen($userpass)) {
203 list($name, $password) = explode(':', $userpass);
204 $_SERVER['PHP_AUTH_USER'] = $name;
205 $_SERVER['PHP_AUTH_PW'] = $password;
209 if (empty($_SERVER['PHP_AUTH_USER'])) {
210 // Try OAuth when no user is provided
211 $oauth1 = new FKOAuth1();
214 $request = OAuthRequest::from_request();
215 list($consumer, $token) = $oauth1->verify_request($request);
216 if (!is_null($token)) {
217 $oauth1->loginUser($token->uid);
218 Session::set('allow_api', true);
221 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
222 var_dump($consumer, $token);
224 } catch (Exception $e) {
225 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
232 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
233 header('WWW-Authenticate: Basic realm="Friendica"');
234 throw new UnauthorizedException("This API requires login");
237 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
238 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
240 // allow "user@server" login (but ignore 'server' part)
241 $at = strstr($user, "@", true);
246 // next code from mod/auth.php. needs better solution
250 'username' => trim($user),
251 'password' => trim($password),
252 'authenticated' => 0,
253 'user_record' => null,
257 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
258 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
259 * and later addons should not interfere with an earlier one that succeeded.
261 Hook::callAll('authenticate', $addon_auth);
263 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
264 $record = $addon_auth['user_record'];
266 $user_id = User::authenticate(trim($user), trim($password), true);
267 if ($user_id !== false) {
268 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
272 if (!DBA::isResult($record)) {
276 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
277 header('WWW-Authenticate: Basic realm="Friendica"');
278 //header('HTTP/1.0 401 Unauthorized');
279 //die('This api requires login');
280 throw new UnauthorizedException("This API requires login");
283 // Don't refresh the login date more often than twice a day to spare database writes
284 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
286 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
288 $_SESSION["allow_api"] = true;
290 Hook::callAll('logged_in', $a->user);
294 * Check HTTP method of called API
296 * API endpoints can define which HTTP method to accept when called.
297 * This function check the current HTTP method agains endpoint
300 * @param string $method Required methods, uppercase, separated by comma
303 function api_check_method($method)
305 if ($method == "*") {
308 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
312 * Main API entry point
314 * Authenticate user, call registered API function, set HTTP headers
317 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
318 * @return string|array API call result
321 function api_call(App $a, App\Arguments $args = null)
323 global $API, $called_api;
330 if (strpos($args->getCommand(), ".xml") > 0) {
333 if (strpos($args->getCommand(), ".json") > 0) {
336 if (strpos($args->getCommand(), ".rss") > 0) {
339 if (strpos($args->getCommand(), ".atom") > 0) {
344 foreach ($API as $p => $info) {
345 if (strpos($args->getCommand(), $p) === 0) {
346 if (!api_check_method($info['method'])) {
347 throw new MethodNotAllowedException();
350 $called_api = explode("/", $p);
352 if (!empty($info['auth']) && api_user() === false) {
354 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
357 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
359 $stamp = microtime(true);
360 $return = call_user_func($info['func'], $type);
361 $duration = floatval(microtime(true) - $stamp);
363 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
365 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
367 if (false === $return) {
369 * api function returned false withour throw an
370 * exception. This should not happend, throw a 500
372 throw new InternalServerErrorException();
377 header("Content-Type: text/xml");
380 header("Content-Type: application/json");
381 if (!empty($return)) {
382 $json = json_encode(end($return));
383 if (!empty($_GET['callback'])) {
384 $json = $_GET['callback'] . "(" . $json . ")";
390 header("Content-Type: application/rss+xml");
391 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
394 header("Content-Type: application/atom+xml");
395 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
402 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
403 throw new NotFoundException();
404 } catch (HTTPException $e) {
405 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
406 return api_error($type, $e, $args);
411 * Format API error string
413 * @param string $type Return type (xml, json, rss, as)
414 * @param object $e HTTPException Error object
415 * @param App\Arguments $args The App arguments
416 * @return string|array error message formatted as $type
418 function api_error($type, $e, App\Arguments $args)
420 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
421 /// @TODO: https://dev.twitter.com/overview/api/response-codes
423 $error = ["error" => $error,
424 "code" => $e->getCode() . " " . $e->httpdesc,
425 "request" => $args->getQueryString()];
427 $return = api_format_data('status', $type, ['status' => $error]);
431 header("Content-Type: text/xml");
434 header("Content-Type: application/json");
435 $return = json_encode($return);
438 header("Content-Type: application/rss+xml");
441 header("Content-Type: application/atom+xml");
449 * Set values for RSS template
452 * @param array $arr Array to be passed to template
453 * @param array $user_info User info
455 * @throws BadRequestException
456 * @throws ImagickException
457 * @throws InternalServerErrorException
458 * @throws UnauthorizedException
459 * @todo find proper type-hints
461 function api_rss_extra(App $a, $arr, $user_info)
463 if (is_null($user_info)) {
464 $user_info = api_get_user($a);
467 $arr['$user'] = $user_info;
469 'alternate' => $user_info['url'],
470 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
471 'base' => DI::baseUrl(),
472 'updated' => api_date(null),
473 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
474 'language' => $user_info['lang'],
475 'logo' => DI::baseUrl() . "/images/friendica-32.png",
483 * Unique contact to contact url.
485 * @param int $id Contact id
486 * @return bool|string
487 * Contact url or False if contact id is unknown
490 function api_unique_id_to_nurl($id)
492 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
494 if (DBA::isResult($r)) {
502 * Get user info array.
505 * @param int|string $contact_id Contact ID or URL
507 * @throws BadRequestException
508 * @throws ImagickException
509 * @throws InternalServerErrorException
510 * @throws UnauthorizedException
512 function api_get_user(App $a, $contact_id = null)
520 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
522 // Searching for contact URL
523 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
524 $user = DBA::escape(Strings::normaliseLink($contact_id));
526 $extra_query = "AND `contact`.`nurl` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
532 // Searching for contact id with uid = 0
533 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
534 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
537 throw new BadRequestException("User ID ".$contact_id." not found.");
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
547 if (is_null($user) && !empty($_GET['user_id'])) {
548 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
551 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
560 if (is_null($user) && !empty($_GET['screen_name'])) {
561 $user = DBA::escape($_GET['screen_name']);
562 $extra_query = "AND `contact`.`nick` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
568 if (is_null($user) && !empty($_GET['profileurl'])) {
569 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
576 // $called_api is the API path exploded on / and is expected to have at least 2 elements
577 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
578 $argid = count($called_api);
579 if (!empty($a->argv[$argid])) {
580 $data = explode(".", $a->argv[$argid]);
581 if (count($data) > 1) {
582 list($user, $null) = $data;
585 if (is_numeric($user)) {
586 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
590 $extra_query = "AND `contact`.`nurl` = '%s' ";
591 if (api_user() !== false) {
592 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
596 $user = DBA::escape($user);
597 $extra_query = "AND `contact`.`nick` = '%s' ";
598 if (api_user() !== false) {
599 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
604 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
607 if (api_user() === false) {
611 $user = $_SESSION['uid'];
612 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
616 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
620 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
626 // Selecting the id by priority, friendica first
627 if (is_array($uinfo)) {
628 api_best_nickname($uinfo);
631 // if the contact wasn't found, fetch it from the contacts with uid = 0
632 if (!DBA::isResult($uinfo)) {
634 throw new BadRequestException("User not found.");
637 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
639 if (DBA::isResult($contact)) {
641 'id' => $contact["id"],
642 'id_str' => (string) $contact["id"],
643 'name' => $contact["name"],
644 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
645 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
646 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
647 'profile_image_url' => $contact["micro"],
648 'profile_image_url_https' => $contact["micro"],
649 'profile_image_url_profile_size' => $contact["thumb"],
650 'profile_image_url_large' => $contact["photo"],
651 'url' => $contact["url"],
652 'protected' => false,
653 'followers_count' => 0,
654 'friends_count' => 0,
656 'created_at' => api_date($contact["created"]),
657 'favourites_count' => 0,
659 'time_zone' => 'UTC',
660 'geo_enabled' => false,
662 'statuses_count' => 0,
664 'contributors_enabled' => false,
665 'is_translator' => false,
666 'is_translation_enabled' => false,
667 'following' => false,
668 'follow_request_sent' => false,
669 'statusnet_blocking' => false,
670 'notifications' => false,
671 'statusnet_profile_url' => $contact["url"],
673 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
674 'pid' => Contact::getIdForURL($contact["url"], 0, false),
676 'network' => $contact["network"],
681 throw new BadRequestException("User ".$url." not found.");
685 if ($uinfo[0]['self']) {
686 if ($uinfo[0]['network'] == "") {
687 $uinfo[0]['network'] = Protocol::DFRN;
690 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
691 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
698 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
700 if (!empty($profile['about'])) {
701 $description = $profile['about'];
703 $description = $uinfo[0]["about"];
706 if (!empty($usr['default-location'])) {
707 $location = $usr['default-location'];
708 } elseif (!empty($uinfo[0]["location"])) {
709 $location = $uinfo[0]["location"];
711 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
715 'id' => intval($pcontact_id),
716 'id_str' => (string) intval($pcontact_id),
717 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
718 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
719 'location' => $location,
720 'description' => BBCode::toPlaintext($description ?? ''),
721 'profile_image_url' => $uinfo[0]['micro'],
722 'profile_image_url_https' => $uinfo[0]['micro'],
723 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
724 'profile_image_url_large' => $uinfo[0]["photo"],
725 'url' => $uinfo[0]['url'],
726 'protected' => false,
727 'followers_count' => intval($countfollowers),
728 'friends_count' => intval($countfriends),
730 'created_at' => api_date($uinfo[0]['created']),
731 'favourites_count' => intval($starred),
733 'time_zone' => 'UTC',
734 'geo_enabled' => false,
736 'statuses_count' => intval($countitems),
738 'contributors_enabled' => false,
739 'is_translator' => false,
740 'is_translation_enabled' => false,
741 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
742 'follow_request_sent' => false,
743 'statusnet_blocking' => false,
744 'notifications' => false,
746 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
747 'statusnet_profile_url' => $uinfo[0]['url'],
748 'uid' => intval($uinfo[0]['uid']),
749 'cid' => intval($uinfo[0]['cid']),
750 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
751 'self' => $uinfo[0]['self'],
752 'network' => $uinfo[0]['network'],
755 // If this is a local user and it uses Frio, we can get its color preferences.
757 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
758 if ($theme_info['theme'] === 'frio') {
759 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
761 if ($schema && ($schema != '---')) {
762 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
763 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
764 require_once $schemefile;
767 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
768 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
769 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
771 if (empty($nav_bg)) {
774 if (empty($link_color)) {
775 $link_color = "#6fdbe8";
777 if (empty($bgcolor)) {
778 $bgcolor = "#ededed";
781 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
782 $ret['profile_link_color'] = str_replace('#', '', $link_color);
783 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
791 * return api-formatted array for item's author and owner
794 * @param array $item item from db
795 * @return array(array:author, array:owner)
796 * @throws BadRequestException
797 * @throws ImagickException
798 * @throws InternalServerErrorException
799 * @throws UnauthorizedException
801 function api_item_get_user(App $a, $item)
803 $status_user = api_get_user($a, $item['author-id'] ?? null);
805 $author_user = $status_user;
807 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
809 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
810 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
812 $owner_user = $author_user;
815 return ([$status_user, $author_user, $owner_user]);
819 * walks recursively through an array with the possibility to change value and key
821 * @param array $array The array to walk through
822 * @param callable $callback The callback function
824 * @return array the transformed array
826 function api_walk_recursive(array &$array, callable $callback)
830 foreach ($array as $k => $v) {
832 if ($callback($v, $k)) {
833 $new_array[$k] = api_walk_recursive($v, $callback);
836 if ($callback($v, $k)) {
847 * Callback function to transform the array in an array that can be transformed in a XML file
849 * @param mixed $item Array item value
850 * @param string $key Array key
852 * @return boolean Should the array item be deleted?
854 function api_reformat_xml(&$item, &$key)
856 if (is_bool($item)) {
857 $item = ($item ? "true" : "false");
860 if (substr($key, 0, 10) == "statusnet_") {
861 $key = "statusnet:".substr($key, 10);
862 } elseif (substr($key, 0, 10) == "friendica_") {
863 $key = "friendica:".substr($key, 10);
865 /// @TODO old-lost code?
867 // $key = "default:".$key;
873 * Creates the XML from a JSON style array
875 * @param array $data JSON style array
876 * @param string $root_element Name of the root element
878 * @return string The XML data
880 function api_create_xml(array $data, $root_element)
882 $childname = key($data);
883 $data2 = array_pop($data);
885 $namespaces = ["" => "http://api.twitter.com",
886 "statusnet" => "http://status.net/schema/api/1/",
887 "friendica" => "http://friendi.ca/schema/api/1/",
888 "georss" => "http://www.georss.org/georss"];
890 /// @todo Auto detection of needed namespaces
891 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
895 if (is_array($data2)) {
897 api_walk_recursive($data2, "api_reformat_xml");
903 foreach ($data2 as $item) {
904 $data4[$i++ . ":" . $childname] = $item;
911 $data3 = [$root_element => $data2];
913 $ret = XML::fromArray($data3, $xml, false, $namespaces);
918 * Formats the data according to the data type
920 * @param string $root_element Name of the root element
921 * @param string $type Return type (atom, rss, xml, json)
922 * @param array $data JSON style array
924 * @return array|string (string|array) XML data or JSON data
926 function api_format_data($root_element, $type, $data)
932 $ret = api_create_xml($data, $root_element);
947 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
948 * returns a 401 status code and an error message if not.
950 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
952 * @param string $type Return type (atom, rss, xml, json)
953 * @return array|string
954 * @throws BadRequestException
955 * @throws ForbiddenException
956 * @throws ImagickException
957 * @throws InternalServerErrorException
958 * @throws UnauthorizedException
960 function api_account_verify_credentials($type)
964 if (api_user() === false) {
965 throw new ForbiddenException();
968 unset($_REQUEST["user_id"]);
969 unset($_GET["user_id"]);
971 unset($_REQUEST["screen_name"]);
972 unset($_GET["screen_name"]);
974 $skip_status = $_REQUEST['skip_status'] ?? false;
976 $user_info = api_get_user($a);
978 // "verified" isn't used here in the standard
979 unset($user_info["verified"]);
981 // - Adding last status
983 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
985 $user_info['status'] = api_format_item($item, $type);
989 // "uid" and "self" are only needed for some internal stuff, so remove it from here
990 unset($user_info["uid"]);
991 unset($user_info["self"]);
993 return api_format_data("user", $type, ['user' => $user_info]);
996 /// @TODO move to top of file or somewhere better
997 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
1000 * Get data from $_POST or $_GET
1005 function requestdata($k)
1007 if (!empty($_POST[$k])) {
1010 if (!empty($_GET[$k])) {
1017 * Deprecated function to upload media.
1019 * @param string $type Return type (atom, rss, xml, json)
1021 * @return array|string
1022 * @throws BadRequestException
1023 * @throws ForbiddenException
1024 * @throws ImagickException
1025 * @throws InternalServerErrorException
1026 * @throws UnauthorizedException
1028 function api_statuses_mediap($type)
1032 if (api_user() === false) {
1033 Logger::log('api_statuses_update: no user');
1034 throw new ForbiddenException();
1036 $user_info = api_get_user($a);
1038 $_REQUEST['profile_uid'] = api_user();
1039 $_REQUEST['api_source'] = true;
1040 $txt = requestdata('status') ?? '';
1041 /// @TODO old-lost code?
1042 //$txt = urldecode(requestdata('status'));
1044 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1045 $txt = HTML::toBBCodeVideo($txt);
1046 $config = HTMLPurifier_Config::createDefault();
1047 $config->set('Cache.DefinitionImpl', null);
1048 $purifier = new HTMLPurifier($config);
1049 $txt = $purifier->purify($txt);
1051 $txt = HTML::toBBCode($txt);
1053 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1055 $picture = wall_upload_post($a, false);
1057 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1058 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1059 $item_id = item_post($a);
1061 // output the post that we just posted.
1062 return api_status_show($type, $item_id);
1065 /// @TODO move this to top of file or somewhere better!
1066 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1069 * Updates the user’s current status.
1071 * @param string $type Return type (atom, rss, xml, json)
1073 * @return array|string
1074 * @throws BadRequestException
1075 * @throws ForbiddenException
1076 * @throws ImagickException
1077 * @throws InternalServerErrorException
1078 * @throws TooManyRequestsException
1079 * @throws UnauthorizedException
1080 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1082 function api_statuses_update($type)
1086 if (api_user() === false) {
1087 Logger::log('api_statuses_update: no user');
1088 throw new ForbiddenException();
1093 // convert $_POST array items to the form we use for web posts.
1094 if (requestdata('htmlstatus')) {
1095 $txt = requestdata('htmlstatus') ?? '';
1096 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1097 $txt = HTML::toBBCodeVideo($txt);
1099 $config = HTMLPurifier_Config::createDefault();
1100 $config->set('Cache.DefinitionImpl', null);
1102 $purifier = new HTMLPurifier($config);
1103 $txt = $purifier->purify($txt);
1105 $_REQUEST['body'] = HTML::toBBCode($txt);
1108 $_REQUEST['body'] = requestdata('status');
1111 $_REQUEST['title'] = requestdata('title');
1113 $parent = requestdata('in_reply_to_status_id');
1115 // Twidere sends "-1" if it is no reply ...
1116 if ($parent == -1) {
1120 if (ctype_digit($parent)) {
1121 $_REQUEST['parent'] = $parent;
1123 $_REQUEST['parent_uri'] = $parent;
1126 if (requestdata('lat') && requestdata('long')) {
1127 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1129 $_REQUEST['profile_uid'] = api_user();
1132 // Check for throttling (maximum posts per day, week and month)
1133 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1134 if ($throttle_day > 0) {
1135 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1137 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1138 $posts_day = Post::count($condition);
1140 if ($posts_day > $throttle_day) {
1141 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1142 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1143 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));
1147 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1148 if ($throttle_week > 0) {
1149 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1151 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1152 $posts_week = Post::count($condition);
1154 if ($posts_week > $throttle_week) {
1155 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1156 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1157 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));
1161 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1162 if ($throttle_month > 0) {
1163 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1165 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1166 $posts_month = Post::count($condition);
1168 if ($posts_month > $throttle_month) {
1169 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1170 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1171 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));
1176 if (requestdata('media_ids')) {
1177 $ids = explode(',', requestdata('media_ids') ?? '');
1178 } elseif (!empty($_FILES['media'])) {
1179 // upload the image if we have one
1180 $picture = wall_upload_post($a, false);
1181 if (is_array($picture)) {
1182 $ids[] = $picture['id'];
1190 foreach ($ids as $id) {
1191 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1192 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1193 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1194 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1196 if (!empty($media)) {
1197 $ressources[] = $media[0]['resource-id'];
1198 $phototypes = Images::supportedTypes();
1199 $ext = $phototypes[$media[0]['type']];
1201 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1202 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1203 'size' => $media[0]['datasize'],
1204 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1205 'description' => $media[0]['desc'] ?? '',
1206 'width' => $media[0]['width'],
1207 'height' => $media[0]['height']];
1209 if (count($media) > 1) {
1210 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1211 $attachment['preview-width'] = $media[1]['width'];
1212 $attachment['preview-height'] = $media[1]['height'];
1214 $attachments[] = $attachment;
1218 // We have to avoid that the post is rejected because of an empty body
1219 if (empty($_REQUEST['body'])) {
1220 $_REQUEST['body'] = '[hr]';
1224 if (!empty($attachments)) {
1225 $_REQUEST['attachments'] = $attachments;
1228 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1230 $_REQUEST['api_source'] = true;
1232 if (empty($_REQUEST['source'])) {
1233 $_REQUEST["source"] = api_source();
1236 // call out normal post function
1237 $item_id = item_post($a);
1239 if (!empty($ressources) && !empty($item_id)) {
1240 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1241 foreach ($ressources as $ressource) {
1242 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1246 // output the post that we just posted.
1247 return api_status_show($type, $item_id);
1250 /// @TODO move to top of file or somewhere better
1251 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1252 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1255 * Uploads an image to Friendica.
1258 * @throws BadRequestException
1259 * @throws ForbiddenException
1260 * @throws ImagickException
1261 * @throws InternalServerErrorException
1262 * @throws UnauthorizedException
1263 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1265 function api_media_upload()
1269 if (api_user() === false) {
1270 Logger::log('no user');
1271 throw new ForbiddenException();
1276 if (empty($_FILES['media'])) {
1278 throw new BadRequestException("No media.");
1281 $media = wall_upload_post($a, false);
1284 throw new InternalServerErrorException();
1288 $returndata["media_id"] = $media["id"];
1289 $returndata["media_id_string"] = (string)$media["id"];
1290 $returndata["size"] = $media["size"];
1291 $returndata["image"] = ["w" => $media["width"],
1292 "h" => $media["height"],
1293 "image_type" => $media["type"],
1294 "friendica_preview_url" => $media["preview"]];
1296 Logger::info('Media uploaded', ['return' => $returndata]);
1298 return ["media" => $returndata];
1301 /// @TODO move to top of file or somewhere better
1302 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1305 * Updates media meta data (picture descriptions)
1307 * @param string $type Return type (atom, rss, xml, json)
1309 * @return array|string
1310 * @throws BadRequestException
1311 * @throws ForbiddenException
1312 * @throws ImagickException
1313 * @throws InternalServerErrorException
1314 * @throws TooManyRequestsException
1315 * @throws UnauthorizedException
1316 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1318 * @todo Compare the corresponding Twitter function for correct return values
1320 function api_media_metadata_create($type)
1324 if (api_user() === false) {
1325 Logger::info('no user');
1326 throw new ForbiddenException();
1331 $postdata = Network::postdata();
1333 if (empty($postdata)) {
1334 throw new BadRequestException("No post data");
1337 $data = json_decode($postdata, true);
1339 throw new BadRequestException("Invalid post data");
1342 if (empty($data['media_id']) || empty($data['alt_text'])) {
1343 throw new BadRequestException("Missing post data values");
1346 if (empty($data['alt_text']['text'])) {
1347 throw new BadRequestException("No alt text.");
1350 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1352 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1353 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1354 if (!DBA::isResult($photo)) {
1355 throw new BadRequestException("Metadata not found.");
1358 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1361 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1364 * @param string $type Return format (atom, rss, xml, json)
1365 * @param int $item_id
1366 * @return array|string
1369 function api_status_show($type, $item_id)
1371 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1375 $item = api_get_item(['id' => $item_id]);
1376 if (!empty($item)) {
1377 $status_info = api_format_item($item, $type);
1380 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1382 return api_format_data('statuses', $type, ['status' => $status_info]);
1386 * Retrieves the last public status of the provided user info
1388 * @param int $ownerId Public contact Id
1389 * @param int $uid User Id
1393 function api_get_last_status($ownerId, $uid)
1396 'author-id'=> $ownerId,
1398 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1399 'private' => [Item::PUBLIC, Item::UNLISTED]
1402 $item = api_get_item($condition);
1408 * Retrieves a single item record based on the provided condition and converts it for API use.
1410 * @param array $condition Item table condition array
1414 function api_get_item(array $condition)
1416 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1422 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1423 * The author's most recent status will be returned inline.
1425 * @param string $type Return type (atom, rss, xml, json)
1426 * @return array|string
1427 * @throws BadRequestException
1428 * @throws ImagickException
1429 * @throws InternalServerErrorException
1430 * @throws UnauthorizedException
1431 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1433 function api_users_show($type)
1435 $a = Friendica\DI::app();
1437 $user_info = api_get_user($a);
1439 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1440 if (!empty($item)) {
1441 $user_info['status'] = api_format_item($item, $type);
1444 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1445 unset($user_info['uid']);
1446 unset($user_info['self']);
1448 return api_format_data('user', $type, ['user' => $user_info]);
1451 /// @TODO move to top of file or somewhere better
1452 api_register_func('api/users/show', 'api_users_show');
1453 api_register_func('api/externalprofile/show', 'api_users_show');
1456 * Search a public user account.
1458 * @param string $type Return type (atom, rss, xml, json)
1460 * @return array|string
1461 * @throws BadRequestException
1462 * @throws ImagickException
1463 * @throws InternalServerErrorException
1464 * @throws UnauthorizedException
1465 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1467 function api_users_search($type)
1473 if (!empty($_GET['q'])) {
1474 $contacts = Contact::selectToArray(
1477 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1485 if (DBA::isResult($contacts)) {
1487 foreach ($contacts as $contact) {
1488 $user_info = api_get_user($a, $contact['id']);
1490 if ($type == 'xml') {
1491 $userlist[$k++ . ':user'] = $user_info;
1493 $userlist[] = $user_info;
1496 $userlist = ['users' => $userlist];
1498 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1501 throw new BadRequestException('No search term specified.');
1504 return api_format_data('users', $type, $userlist);
1507 /// @TODO move to top of file or somewhere better
1508 api_register_func('api/users/search', 'api_users_search');
1511 * Return user objects
1513 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1515 * @param string $type Return format: json or xml
1517 * @return array|string
1518 * @throws BadRequestException
1519 * @throws ImagickException
1520 * @throws InternalServerErrorException
1521 * @throws NotFoundException if the results are empty.
1522 * @throws UnauthorizedException
1524 function api_users_lookup($type)
1528 if (!empty($_REQUEST['user_id'])) {
1529 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1531 $users[] = api_get_user(DI::app(), $id);
1536 if (empty($users)) {
1537 throw new NotFoundException;
1540 return api_format_data("users", $type, ['users' => $users]);
1543 /// @TODO move to top of file or somewhere better
1544 api_register_func('api/users/lookup', 'api_users_lookup', true);
1547 * Returns statuses that match a specified query.
1549 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1551 * @param string $type Return format: json, xml, atom, rss
1553 * @return array|string
1554 * @throws BadRequestException if the "q" parameter is missing.
1555 * @throws ForbiddenException
1556 * @throws ImagickException
1557 * @throws InternalServerErrorException
1558 * @throws UnauthorizedException
1560 function api_search($type)
1563 $user_info = api_get_user($a);
1565 if (api_user() === false || $user_info === false) {
1566 throw new ForbiddenException();
1569 if (empty($_REQUEST['q'])) {
1570 throw new BadRequestException('q parameter is required.');
1573 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1576 $data['status'] = [];
1578 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1579 if (!empty($_REQUEST['rpp'])) {
1580 $count = $_REQUEST['rpp'];
1581 } elseif (!empty($_REQUEST['count'])) {
1582 $count = $_REQUEST['count'];
1585 $since_id = $_REQUEST['since_id'] ?? 0;
1586 $max_id = $_REQUEST['max_id'] ?? 0;
1587 $page = $_REQUEST['page'] ?? 1;
1589 $start = max(0, ($page - 1) * $count);
1591 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1592 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1593 $searchTerm = $matches[1];
1594 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1595 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1597 while ($tag = DBA::fetch($tags)) {
1598 $uriids[] = $tag['uri-id'];
1602 if (empty($uriids)) {
1603 return api_format_data('statuses', $type, $data);
1606 $condition = ['uri-id' => $uriids];
1607 if ($exclude_replies) {
1608 $condition['gravity'] = GRAVITY_PARENT;
1611 $params['group_by'] = ['uri-id'];
1613 $condition = ["`id` > ?
1614 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1615 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1616 AND `body` LIKE CONCAT('%',?,'%')",
1617 $since_id, api_user(), $_REQUEST['q']];
1619 $condition[0] .= ' AND `id` <= ?';
1620 $condition[] = $max_id;
1626 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1627 $id = Item::fetchByLink($searchTerm, api_user());
1630 $id = Item::fetchByLink($searchTerm);
1634 $statuses = Post::select([], ['id' => $id]);
1638 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1640 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1642 bindComments($data['status']);
1644 return api_format_data('statuses', $type, $data);
1647 /// @TODO move to top of file or somewhere better
1648 api_register_func('api/search/tweets', 'api_search', true);
1649 api_register_func('api/search', 'api_search', true);
1652 * Returns the most recent statuses posted by the user and the users they follow.
1654 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1656 * @param string $type Return type (atom, rss, xml, json)
1658 * @return array|string
1659 * @throws BadRequestException
1660 * @throws ForbiddenException
1661 * @throws ImagickException
1662 * @throws InternalServerErrorException
1663 * @throws UnauthorizedException
1664 * @todo Optional parameters
1665 * @todo Add reply info
1667 function api_statuses_home_timeline($type)
1670 $user_info = api_get_user($a);
1672 if (api_user() === false || $user_info === false) {
1673 throw new ForbiddenException();
1676 unset($_REQUEST["user_id"]);
1677 unset($_GET["user_id"]);
1679 unset($_REQUEST["screen_name"]);
1680 unset($_GET["screen_name"]);
1682 // get last network messages
1685 $count = $_REQUEST['count'] ?? 20;
1686 $page = $_REQUEST['page']?? 0;
1687 $since_id = $_REQUEST['since_id'] ?? 0;
1688 $max_id = $_REQUEST['max_id'] ?? 0;
1689 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1690 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1692 $start = max(0, ($page - 1) * $count);
1694 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1695 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1698 $condition[0] .= " AND `id` <= ?";
1699 $condition[] = $max_id;
1701 if ($exclude_replies) {
1702 $condition[0] .= ' AND `gravity` = ?';
1703 $condition[] = GRAVITY_PARENT;
1705 if ($conversation_id > 0) {
1706 $condition[0] .= " AND `parent` = ?";
1707 $condition[] = $conversation_id;
1710 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1711 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1713 $items = Post::toArray($statuses);
1715 $ret = api_format_items($items, $user_info, false, $type);
1717 // Set all posts from the query above to seen
1719 foreach ($items as $item) {
1720 $idarray[] = intval($item["id"]);
1723 if (!empty($idarray)) {
1724 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1726 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1732 $data = ['status' => $ret];
1737 $data = api_rss_extra($a, $data, $user_info);
1741 return api_format_data("statuses", $type, $data);
1745 /// @TODO move to top of file or somewhere better
1746 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1747 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1750 * Returns the most recent statuses from public users.
1752 * @param string $type Return type (atom, rss, xml, json)
1754 * @return array|string
1755 * @throws BadRequestException
1756 * @throws ForbiddenException
1757 * @throws ImagickException
1758 * @throws InternalServerErrorException
1759 * @throws UnauthorizedException
1761 function api_statuses_public_timeline($type)
1764 $user_info = api_get_user($a);
1766 if (api_user() === false || $user_info === false) {
1767 throw new ForbiddenException();
1770 // get last network messages
1773 $count = $_REQUEST['count'] ?? 20;
1774 $page = $_REQUEST['page'] ?? 1;
1775 $since_id = $_REQUEST['since_id'] ?? 0;
1776 $max_id = $_REQUEST['max_id'] ?? 0;
1777 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1778 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1780 $start = max(0, ($page - 1) * $count);
1782 if ($exclude_replies && !$conversation_id) {
1783 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1784 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1787 $condition[0] .= " AND `id` <= ?";
1788 $condition[] = $max_id;
1791 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1792 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1794 $r = Post::toArray($statuses);
1796 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1797 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1800 $condition[0] .= " AND `id` <= ?";
1801 $condition[] = $max_id;
1803 if ($conversation_id > 0) {
1804 $condition[0] .= " AND `parent` = ?";
1805 $condition[] = $conversation_id;
1808 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1809 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1811 $r = Post::toArray($statuses);
1814 $ret = api_format_items($r, $user_info, false, $type);
1818 $data = ['status' => $ret];
1823 $data = api_rss_extra($a, $data, $user_info);
1827 return api_format_data("statuses", $type, $data);
1830 /// @TODO move to top of file or somewhere better
1831 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1834 * Returns the most recent statuses posted by users this node knows about.
1836 * @param string $type Return format: json, xml, atom, rss
1837 * @return array|string
1838 * @throws BadRequestException
1839 * @throws ForbiddenException
1840 * @throws ImagickException
1841 * @throws InternalServerErrorException
1842 * @throws UnauthorizedException
1844 function api_statuses_networkpublic_timeline($type)
1847 $user_info = api_get_user($a);
1849 if (api_user() === false || $user_info === false) {
1850 throw new ForbiddenException();
1853 $since_id = $_REQUEST['since_id'] ?? 0;
1854 $max_id = $_REQUEST['max_id'] ?? 0;
1857 $count = $_REQUEST['count'] ?? 20;
1858 $page = $_REQUEST['page'] ?? 1;
1860 $start = max(0, ($page - 1) * $count);
1862 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1863 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1866 $condition[0] .= " AND `id` <= ?";
1867 $condition[] = $max_id;
1870 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1871 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1873 $ret = api_format_items($statuses, $user_info, false, $type);
1877 $data = ['status' => $ret];
1882 $data = api_rss_extra($a, $data, $user_info);
1886 return api_format_data("statuses", $type, $data);
1889 /// @TODO move to top of file or somewhere better
1890 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1893 * Returns a single status.
1895 * @param string $type Return type (atom, rss, xml, json)
1897 * @return array|string
1898 * @throws BadRequestException
1899 * @throws ForbiddenException
1900 * @throws ImagickException
1901 * @throws InternalServerErrorException
1902 * @throws UnauthorizedException
1903 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1905 function api_statuses_show($type)
1908 $user_info = api_get_user($a);
1910 if (api_user() === false || $user_info === false) {
1911 throw new ForbiddenException();
1915 $id = intval($a->argv[3] ?? 0);
1918 $id = intval($_REQUEST['id'] ?? 0);
1923 $id = intval($a->argv[4] ?? 0);
1926 Logger::log('API: api_statuses_show: ' . $id);
1928 $conversation = !empty($_REQUEST['conversation']);
1930 // try to fetch the item for the local user - or the public item, if there is no local one
1931 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1932 if (!DBA::isResult($uri_item)) {
1933 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1936 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1937 if (!DBA::isResult($item)) {
1938 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1943 if ($conversation) {
1944 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1945 $params = ['order' => ['id' => true]];
1947 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1951 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1953 /// @TODO How about copying this to above methods which don't check $r ?
1954 if (!DBA::isResult($statuses)) {
1955 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1958 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1960 if ($conversation) {
1961 $data = ['status' => $ret];
1962 return api_format_data("statuses", $type, $data);
1964 $data = ['status' => $ret[0]];
1965 return api_format_data("status", $type, $data);
1969 /// @TODO move to top of file or somewhere better
1970 api_register_func('api/statuses/show', 'api_statuses_show', true);
1974 * @param string $type Return type (atom, rss, xml, json)
1976 * @return array|string
1977 * @throws BadRequestException
1978 * @throws ForbiddenException
1979 * @throws ImagickException
1980 * @throws InternalServerErrorException
1981 * @throws UnauthorizedException
1982 * @todo nothing to say?
1984 function api_conversation_show($type)
1987 $user_info = api_get_user($a);
1989 if (api_user() === false || $user_info === false) {
1990 throw new ForbiddenException();
1994 $id = intval($a->argv[3] ?? 0);
1995 $since_id = intval($_REQUEST['since_id'] ?? 0);
1996 $max_id = intval($_REQUEST['max_id'] ?? 0);
1997 $count = intval($_REQUEST['count'] ?? 20);
1998 $page = intval($_REQUEST['page'] ?? 1);
2000 $start = max(0, ($page - 1) * $count);
2003 $id = intval($_REQUEST['id'] ?? 0);
2008 $id = intval($a->argv[4] ?? 0);
2011 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2013 // try to fetch the item for the local user - or the public item, if there is no local one
2014 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
2015 if (!DBA::isResult($item)) {
2016 throw new BadRequestException("There is no status with this id.");
2019 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2020 if (!DBA::isResult($parent)) {
2021 throw new BadRequestException("There is no status with this id.");
2024 $id = $parent['id'];
2026 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2027 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2030 $condition[0] .= " AND `id` <= ?";
2031 $condition[] = $max_id;
2034 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2035 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2037 if (!DBA::isResult($statuses)) {
2038 throw new BadRequestException("There is no status with id $id.");
2041 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2043 $data = ['status' => $ret];
2044 return api_format_data("statuses", $type, $data);
2047 /// @TODO move to top of file or somewhere better
2048 api_register_func('api/conversation/show', 'api_conversation_show', true);
2049 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2054 * @param string $type Return type (atom, rss, xml, json)
2056 * @return array|string
2057 * @throws BadRequestException
2058 * @throws ForbiddenException
2059 * @throws ImagickException
2060 * @throws InternalServerErrorException
2061 * @throws UnauthorizedException
2062 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2064 function api_statuses_repeat($type)
2070 if (api_user() === false) {
2071 throw new ForbiddenException();
2077 $id = intval($a->argv[3] ?? 0);
2080 $id = intval($_REQUEST['id'] ?? 0);
2085 $id = intval($a->argv[4] ?? 0);
2088 Logger::log('API: api_statuses_repeat: '.$id);
2090 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2091 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2093 if (DBA::isResult($item) && !empty($item['body'])) {
2094 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2095 if (!Item::performActivity($id, 'announce', local_user())) {
2096 throw new InternalServerErrorException();
2101 if (strpos($item['body'], "[/share]") !== false) {
2102 $pos = strpos($item['body'], "[share");
2103 $post = substr($item['body'], $pos);
2105 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2107 if (!empty($item['title'])) {
2108 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2111 $post .= $item['body'];
2112 $post .= "[/share]";
2114 $_REQUEST['body'] = $post;
2115 $_REQUEST['profile_uid'] = api_user();
2116 $_REQUEST['api_source'] = true;
2118 if (empty($_REQUEST['source'])) {
2119 $_REQUEST["source"] = api_source();
2122 $item_id = item_post($a);
2125 throw new ForbiddenException();
2128 // output the post that we just posted.
2130 return api_status_show($type, $item_id);
2133 /// @TODO move to top of file or somewhere better
2134 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2137 * Destroys a specific status.
2139 * @param string $type Return type (atom, rss, xml, json)
2141 * @return array|string
2142 * @throws BadRequestException
2143 * @throws ForbiddenException
2144 * @throws ImagickException
2145 * @throws InternalServerErrorException
2146 * @throws UnauthorizedException
2147 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2149 function api_statuses_destroy($type)
2153 if (api_user() === false) {
2154 throw new ForbiddenException();
2160 $id = intval($a->argv[3] ?? 0);
2163 $id = intval($_REQUEST['id'] ?? 0);
2168 $id = intval($a->argv[4] ?? 0);
2171 Logger::log('API: api_statuses_destroy: '.$id);
2173 $ret = api_statuses_show($type);
2175 Item::deleteForUser(['id' => $id], api_user());
2180 /// @TODO move to top of file or somewhere better
2181 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2184 * Returns the most recent mentions.
2186 * @param string $type Return type (atom, rss, xml, json)
2188 * @return array|string
2189 * @throws BadRequestException
2190 * @throws ForbiddenException
2191 * @throws ImagickException
2192 * @throws InternalServerErrorException
2193 * @throws UnauthorizedException
2194 * @see http://developer.twitter.com/doc/get/statuses/mentions
2196 function api_statuses_mentions($type)
2199 $user_info = api_get_user($a);
2201 if (api_user() === false || $user_info === false) {
2202 throw new ForbiddenException();
2205 unset($_REQUEST["user_id"]);
2206 unset($_GET["user_id"]);
2208 unset($_REQUEST["screen_name"]);
2209 unset($_GET["screen_name"]);
2211 // get last network messages
2214 $since_id = intval($_REQUEST['since_id'] ?? 0);
2215 $max_id = intval($_REQUEST['max_id'] ?? 0);
2216 $count = intval($_REQUEST['count'] ?? 20);
2217 $page = intval($_REQUEST['page'] ?? 1);
2219 $start = max(0, ($page - 1) * $count);
2221 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2222 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2223 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2225 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2226 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2227 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2228 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2229 api_user(), $since_id];
2232 $query .= " AND `id` <= ?";
2233 $condition[] = $max_id;
2236 array_unshift($condition, $query);
2238 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2239 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2241 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2243 $data = ['status' => $ret];
2248 $data = api_rss_extra($a, $data, $user_info);
2252 return api_format_data("statuses", $type, $data);
2255 /// @TODO move to top of file or somewhere better
2256 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2257 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2260 * Returns the most recent statuses posted by the user.
2262 * @param string $type Either "json" or "xml"
2263 * @return string|array
2264 * @throws BadRequestException
2265 * @throws ForbiddenException
2266 * @throws ImagickException
2267 * @throws InternalServerErrorException
2268 * @throws UnauthorizedException
2269 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2271 function api_statuses_user_timeline($type)
2274 $user_info = api_get_user($a);
2276 if (api_user() === false || $user_info === false) {
2277 throw new ForbiddenException();
2280 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2282 $since_id = $_REQUEST['since_id'] ?? 0;
2283 $max_id = $_REQUEST['max_id'] ?? 0;
2284 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2285 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2288 $count = $_REQUEST['count'] ?? 20;
2289 $page = $_REQUEST['page'] ?? 1;
2291 $start = max(0, ($page - 1) * $count);
2293 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2294 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2296 if ($user_info['self'] == 1) {
2297 $condition[0] .= ' AND `wall` ';
2300 if ($exclude_replies) {
2301 $condition[0] .= ' AND `gravity` = ?';
2302 $condition[] = GRAVITY_PARENT;
2305 if ($conversation_id > 0) {
2306 $condition[0] .= " AND `parent` = ?";
2307 $condition[] = $conversation_id;
2311 $condition[0] .= " AND `id` <= ?";
2312 $condition[] = $max_id;
2314 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2315 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2317 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2321 $data = ['status' => $ret];
2326 $data = api_rss_extra($a, $data, $user_info);
2330 return api_format_data("statuses", $type, $data);
2333 /// @TODO move to top of file or somewhere better
2334 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2337 * Star/unstar an item.
2338 * param: id : id of the item
2340 * @param string $type Return type (atom, rss, xml, json)
2342 * @return array|string
2343 * @throws BadRequestException
2344 * @throws ForbiddenException
2345 * @throws ImagickException
2346 * @throws InternalServerErrorException
2347 * @throws UnauthorizedException
2348 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2350 function api_favorites_create_destroy($type)
2354 if (api_user() === false) {
2355 throw new ForbiddenException();
2358 // for versioned api.
2359 /// @TODO We need a better global soluton
2360 $action_argv_id = 2;
2361 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2362 $action_argv_id = 3;
2365 if ($a->argc <= $action_argv_id) {
2366 throw new BadRequestException("Invalid request.");
2368 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2369 if ($a->argc == $action_argv_id + 2) {
2370 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2372 $itemid = intval($_REQUEST['id'] ?? 0);
2375 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2377 if (!DBA::isResult($item)) {
2378 throw new BadRequestException("Invalid item.");
2383 $item['starred'] = 1;
2386 $item['starred'] = 0;
2389 throw new BadRequestException("Invalid action ".$action);
2392 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2395 throw new InternalServerErrorException("DB error");
2399 $user_info = api_get_user($a);
2400 $rets = api_format_items([$item], $user_info, false, $type);
2403 $data = ['status' => $ret];
2408 $data = api_rss_extra($a, $data, $user_info);
2412 return api_format_data("status", $type, $data);
2415 /// @TODO move to top of file or somewhere better
2416 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2417 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2420 * Returns the most recent favorite statuses.
2422 * @param string $type Return type (atom, rss, xml, json)
2424 * @return string|array
2425 * @throws BadRequestException
2426 * @throws ForbiddenException
2427 * @throws ImagickException
2428 * @throws InternalServerErrorException
2429 * @throws UnauthorizedException
2431 function api_favorites($type)
2436 $user_info = api_get_user($a);
2438 if (api_user() === false || $user_info === false) {
2439 throw new ForbiddenException();
2444 // in friendica starred item are private
2445 // return favorites only for self
2446 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2448 if ($user_info['self'] == 0) {
2452 $since_id = $_REQUEST['since_id'] ?? 0;
2453 $max_id = $_REQUEST['max_id'] ?? 0;
2454 $count = $_GET['count'] ?? 20;
2455 $page = $_REQUEST['page'] ?? 1;
2457 $start = max(0, ($page - 1) * $count);
2459 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2460 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2462 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2465 $condition[0] .= " AND `id` <= ?";
2466 $condition[] = $max_id;
2469 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2471 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2476 $data = ['status' => $ret];
2481 $data = api_rss_extra($a, $data, $user_info);
2485 return api_format_data("statuses", $type, $data);
2488 /// @TODO move to top of file or somewhere better
2489 api_register_func('api/favorites', 'api_favorites', true);
2493 * @param array $item
2494 * @param array $recipient
2495 * @param array $sender
2498 * @throws InternalServerErrorException
2500 function api_format_messages($item, $recipient, $sender)
2502 // standard meta information
2504 'id' => $item['id'],
2505 'sender_id' => $sender['id'],
2507 'recipient_id' => $recipient['id'],
2508 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2509 'sender_screen_name' => $sender['screen_name'],
2510 'recipient_screen_name' => $recipient['screen_name'],
2511 'sender' => $sender,
2512 'recipient' => $recipient,
2514 'friendica_seen' => $item['seen'] ?? 0,
2515 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2518 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2519 if (isset($ret['sender']['uid'])) {
2520 unset($ret['sender']['uid']);
2522 if (isset($ret['sender']['self'])) {
2523 unset($ret['sender']['self']);
2525 if (isset($ret['recipient']['uid'])) {
2526 unset($ret['recipient']['uid']);
2528 if (isset($ret['recipient']['self'])) {
2529 unset($ret['recipient']['self']);
2532 //don't send title to regular StatusNET requests to avoid confusing these apps
2533 if (!empty($_GET['getText'])) {
2534 $ret['title'] = $item['title'];
2535 if ($_GET['getText'] == 'html') {
2536 $ret['text'] = BBCode::convert($item['body'], false);
2537 } elseif ($_GET['getText'] == 'plain') {
2538 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2541 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2543 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2544 unset($ret['sender']);
2545 unset($ret['recipient']);
2553 * @param array $item
2556 * @throws InternalServerErrorException
2558 function api_convert_item($item)
2560 $body = api_add_attachments_to_body($item);
2562 $entities = api_get_entitities($statustext, $body);
2564 // Add pictures to the attachment array and remove them from the body
2565 $attachments = api_get_attachments($body);
2567 // Workaround for ostatus messages where the title is identically to the body
2568 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2569 $statusbody = trim(HTML::toPlaintext($html, 0));
2571 // handle data: images
2572 $statusbody = api_format_items_embeded_images($item, $statusbody);
2574 $statustitle = trim($item['title']);
2576 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2577 $statustext = trim($statusbody);
2579 $statustext = trim($statustitle."\n\n".$statusbody);
2582 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2583 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2586 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2588 // Workaround for clients with limited HTML parser functionality
2589 $search = ["<br>", "<blockquote>", "</blockquote>",
2590 "<h1>", "</h1>", "<h2>", "</h2>",
2591 "<h3>", "</h3>", "<h4>", "</h4>",
2592 "<h5>", "</h5>", "<h6>", "</h6>"];
2593 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2594 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2595 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2596 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2597 $statushtml = str_replace($search, $replace, $statushtml);
2599 if ($item['title'] != "") {
2600 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2604 $oldtext = $statushtml;
2605 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2606 } while ($oldtext != $statushtml);
2608 if (substr($statushtml, 0, 4) == '<br>') {
2609 $statushtml = substr($statushtml, 4);
2612 if (substr($statushtml, 0, -4) == '<br>') {
2613 $statushtml = substr($statushtml, -4);
2616 // feeds without body should contain the link
2617 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2618 $statushtml .= BBCode::convert($item['plink']);
2622 "text" => $statustext,
2623 "html" => $statushtml,
2624 "attachments" => $attachments,
2625 "entities" => $entities
2630 * Add media attachments to the body
2632 * @param array $item
2633 * @return string body with added media
2635 function api_add_attachments_to_body(array $item)
2637 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2639 if (strpos($body, '[/img]') !== false) {
2643 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2644 if (!empty($media['preview'])) {
2645 $description = $media['description'] ?: $media['name'];
2646 if (!empty($description)) {
2647 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2649 $body .= "\n[img]" . $media['preview'] .'[/img]';
2659 * @param string $body
2662 * @throws InternalServerErrorException
2664 function api_get_attachments(&$body)
2666 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2667 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2669 $URLSearchString = "^\[\]";
2670 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2674 // Remove all embedded pictures, since they are added as attachments
2675 foreach ($images[0] as $orig) {
2676 $body = str_replace($orig, '', $body);
2681 foreach ($images[1] as $image) {
2682 $imagedata = Images::getInfoFromURLCached($image);
2685 if (DI::config()->get("system", "proxy_disabled")) {
2686 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2688 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2693 return $attachments;
2698 * @param string $text
2699 * @param string $bbcode
2702 * @throws InternalServerErrorException
2703 * @todo Links at the first character of the post
2705 function api_get_entitities(&$text, $bbcode)
2707 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2709 if ($include_entities != "true") {
2710 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2712 foreach ($images[1] as $image) {
2713 $replace = ProxyUtils::proxifyUrl($image, false);
2714 $text = str_replace($image, $replace, $text);
2719 $bbcode = BBCode::cleanPictureLinks($bbcode);
2721 // Change pure links in text to bbcode uris
2722 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2725 $entities["hashtags"] = [];
2726 $entities["symbols"] = [];
2727 $entities["urls"] = [];
2728 $entities["user_mentions"] = [];
2730 $URLSearchString = "^\[\]";
2732 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2734 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2735 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2737 $bbcode = preg_replace(
2738 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2739 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2742 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2744 $bbcode = preg_replace(
2745 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2746 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2749 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2751 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2753 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2756 foreach ($urls[1] as $id => $url) {
2757 $start = iconv_strpos($text, $url, 0, "UTF-8");
2758 if (!($start === false)) {
2759 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2763 ksort($ordered_urls);
2767 foreach ($ordered_urls as $url) {
2768 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2769 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2771 $display_url = $url["title"];
2773 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2774 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2776 if (strlen($display_url) > 26) {
2777 $display_url = substr($display_url, 0, 25)."…";
2781 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2782 if (!($start === false)) {
2783 $entities["urls"][] = ["url" => $url["url"],
2784 "expanded_url" => $url["url"],
2785 "display_url" => $display_url,
2786 "indices" => [$start, $start+strlen($url["url"])]];
2787 $offset = $start + 1;
2791 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2792 $ordered_images = [];
2793 foreach ($images as $image) {
2794 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2795 if (!($start === false)) {
2796 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2800 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2801 foreach ($images[1] as $image) {
2802 $start = iconv_strpos($text, $image, 0, "UTF-8");
2803 if (!($start === false)) {
2804 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2810 foreach ($ordered_images as $image) {
2811 $url = $image['url'];
2812 $ext_alt_text = $image['alt'];
2814 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2815 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2817 if (strlen($display_url) > 26) {
2818 $display_url = substr($display_url, 0, 25)."…";
2821 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2822 if (!($start === false)) {
2823 $image = Images::getInfoFromURLCached($url);
2825 // If image cache is activated, then use the following sizes:
2826 // thumb (150), small (340), medium (600) and large (1024)
2827 if (!DI::config()->get("system", "proxy_disabled")) {
2828 $media_url = ProxyUtils::proxifyUrl($url, false);
2831 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2832 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2834 if (($image[0] > 150) || ($image[1] > 150)) {
2835 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2836 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2839 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2840 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2842 if (($image[0] > 600) || ($image[1] > 600)) {
2843 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2844 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2848 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2851 $entities["media"][] = [
2853 "id_str" => (string) ($start + 1),
2854 "indices" => [$start, $start+strlen($url)],
2855 "media_url" => Strings::normaliseLink($media_url),
2856 "media_url_https" => $media_url,
2858 "display_url" => $display_url,
2859 "expanded_url" => $url,
2860 "ext_alt_text" => $ext_alt_text,
2864 $offset = $start + 1;
2873 * @param array $item
2874 * @param string $text
2878 function api_format_items_embeded_images($item, $text)
2880 $text = preg_replace_callback(
2881 '|data:image/([^;]+)[^=]+=*|m',
2882 function () use ($item) {
2883 return DI::baseUrl() . '/display/' . $item['guid'];
2891 * return <a href='url'>name</a> as array
2893 * @param string $txt text
2898 function api_contactlink_to_array($txt)
2901 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2902 if ($r && count($match)==3) {
2904 'name' => $match[2],
2918 * return likes, dislikes and attend status for item
2920 * @param array $item array
2921 * @param string $type Return type (atom, rss, xml, json)
2924 * likes => int count,
2925 * dislikes => int count
2926 * @throws BadRequestException
2927 * @throws ImagickException
2928 * @throws InternalServerErrorException
2929 * @throws UnauthorizedException
2931 function api_format_items_activities($item, $type = "json")
2940 'attendmaybe' => [],
2944 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2945 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2947 while ($parent_item = Post::fetch($ret)) {
2948 // not used as result should be structured like other user data
2949 //builtin_activity_puller($i, $activities);
2951 // get user data and add it to the array of the activity
2952 $user = api_get_user($a, $parent_item['author-id']);
2953 switch ($parent_item['verb']) {
2954 case Activity::LIKE:
2955 $activities['like'][] = $user;
2957 case Activity::DISLIKE:
2958 $activities['dislike'][] = $user;
2960 case Activity::ATTEND:
2961 $activities['attendyes'][] = $user;
2963 case Activity::ATTENDNO:
2964 $activities['attendno'][] = $user;
2966 case Activity::ATTENDMAYBE:
2967 $activities['attendmaybe'][] = $user;
2969 case Activity::ANNOUNCE:
2970 $activities['announce'][] = $user;
2979 if ($type == "xml") {
2980 $xml_activities = [];
2981 foreach ($activities as $k => $v) {
2982 // change xml element from "like" to "friendica:like"
2983 $xml_activities["friendica:".$k] = $v;
2984 // add user data into xml output
2986 foreach ($v as $user) {
2987 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2990 $activities = $xml_activities;
2997 * format items to be returned by api
2999 * @param array $items array of items
3000 * @param array $user_info
3001 * @param bool $filter_user filter items by $user_info
3002 * @param string $type Return type (atom, rss, xml, json)
3004 * @throws BadRequestException
3005 * @throws ImagickException
3006 * @throws InternalServerErrorException
3007 * @throws UnauthorizedException
3009 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
3011 $a = Friendica\DI::app();
3015 if (empty($items)) {
3019 foreach ((array)$items as $item) {
3020 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3022 // Look if the posts are matching if they should be filtered by user id
3023 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3027 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3036 * @param array $item Item record
3037 * @param string $type Return format (atom, rss, xml, json)
3038 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3039 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3040 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3041 * @return array API-formatted status
3042 * @throws BadRequestException
3043 * @throws ImagickException
3044 * @throws InternalServerErrorException
3045 * @throws UnauthorizedException
3047 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3049 $a = Friendica\DI::app();
3051 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3052 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3055 localize_item($item);
3057 $in_reply_to = api_in_reply_to($item);
3059 $converted = api_convert_item($item);
3061 if ($type == "xml") {
3062 $geo = "georss:point";
3068 'text' => $converted["text"],
3069 'truncated' => false,
3070 'created_at'=> api_date($item['created']),
3071 'in_reply_to_status_id' => $in_reply_to['status_id'],
3072 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3073 'source' => (($item['app']) ? $item['app'] : 'web'),
3074 'id' => intval($item['id']),
3075 'id_str' => (string) intval($item['id']),
3076 'in_reply_to_user_id' => $in_reply_to['user_id'],
3077 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3078 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3080 'favorited' => $item['starred'] ? true : false,
3081 'user' => $status_user,
3082 'friendica_author' => $author_user,
3083 'friendica_owner' => $owner_user,
3084 'friendica_private' => $item['private'] == Item::PRIVATE,
3085 //'entities' => NULL,
3086 'statusnet_html' => $converted["html"],
3087 'statusnet_conversation_id' => $item['parent'],
3088 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3089 'friendica_activities' => api_format_items_activities($item, $type),
3090 'friendica_title' => $item['title'],
3091 'friendica_html' => BBCode::convert($item['body'], false)
3094 if (count($converted["attachments"]) > 0) {
3095 $status["attachments"] = $converted["attachments"];
3098 if (count($converted["entities"]) > 0) {
3099 $status["entities"] = $converted["entities"];
3102 if ($status["source"] == 'web') {
3103 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3104 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3105 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3108 $retweeted_item = [];
3111 if ($item['gravity'] == GRAVITY_PARENT) {
3112 $body = $item['body'];
3113 $retweeted_item = api_share_as_retweet($item);
3114 if ($body != $item['body']) {
3115 $quoted_item = $retweeted_item;
3116 $retweeted_item = [];
3120 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3121 $announce = api_get_announce($item);
3122 if (!empty($announce)) {
3123 $retweeted_item = $item;
3125 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3129 if (!empty($quoted_item)) {
3130 if ($quoted_item['id'] != $item['id']) {
3131 $quoted_status = api_format_item($quoted_item);
3132 /// @todo Only remove the attachments that are also contained in the quotes status
3133 unset($status['attachments']);
3134 unset($status['entities']);
3136 $conv_quoted = api_convert_item($quoted_item);
3137 $quoted_status = $status;
3138 unset($quoted_status['attachments']);
3139 unset($quoted_status['entities']);
3140 unset($quoted_status['statusnet_conversation_id']);
3141 $quoted_status['text'] = $conv_quoted['text'];
3142 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3144 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3145 } catch (BadRequestException $e) {
3146 // user not found. should be found?
3147 /// @todo check if the user should be always found
3148 $quoted_status["user"] = [];
3151 unset($quoted_status['friendica_author']);
3152 unset($quoted_status['friendica_owner']);
3153 unset($quoted_status['friendica_activities']);
3154 unset($quoted_status['friendica_private']);
3157 if (!empty($retweeted_item)) {
3158 $retweeted_status = $status;
3159 unset($retweeted_status['friendica_author']);
3160 unset($retweeted_status['friendica_owner']);
3161 unset($retweeted_status['friendica_activities']);
3162 unset($retweeted_status['friendica_private']);
3163 unset($retweeted_status['statusnet_conversation_id']);
3164 $status['user'] = $status['friendica_owner'];
3166 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3167 } catch (BadRequestException $e) {
3168 // user not found. should be found?
3169 /// @todo check if the user should be always found
3170 $retweeted_status["user"] = [];
3173 $rt_converted = api_convert_item($retweeted_item);
3175 $retweeted_status['text'] = $rt_converted["text"];
3176 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3177 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3179 if (!empty($quoted_status)) {
3180 $retweeted_status['quoted_status'] = $quoted_status;
3183 $status['friendica_author'] = $retweeted_status['user'];
3184 $status['retweeted_status'] = $retweeted_status;
3185 } elseif (!empty($quoted_status)) {
3186 $root_status = api_convert_item($item);
3188 $status['text'] = $root_status["text"];
3189 $status['statusnet_html'] = $root_status["html"];
3190 $status['quoted_status'] = $quoted_status;
3193 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3194 unset($status["user"]["uid"]);
3195 unset($status["user"]["self"]);
3197 if ($item["coord"] != "") {
3198 $coords = explode(' ', $item["coord"]);
3199 if (count($coords) == 2) {
3200 if ($type == "json") {
3201 $status["geo"] = ['type' => 'Point',
3202 'coordinates' => [(float) $coords[0],
3203 (float) $coords[1]]];
3204 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3205 $status["georss:point"] = $item["coord"];
3214 * Returns the remaining number of API requests available to the user before the API limit is reached.
3216 * @param string $type Return type (atom, rss, xml, json)
3218 * @return array|string
3221 function api_account_rate_limit_status($type)
3223 if ($type == "xml") {
3225 'remaining-hits' => '150',
3226 '@attributes' => ["type" => "integer"],
3227 'hourly-limit' => '150',
3228 '@attributes2' => ["type" => "integer"],
3229 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3230 '@attributes3' => ["type" => "datetime"],
3231 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3232 '@attributes4' => ["type" => "integer"],
3236 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3237 'remaining_hits' => '150',
3238 'hourly_limit' => '150',
3239 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3243 return api_format_data('hash', $type, ['hash' => $hash]);
3246 /// @TODO move to top of file or somewhere better
3247 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3250 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3252 * @param string $type Return type (atom, rss, xml, json)
3254 * @return array|string
3256 function api_help_test($type)
3258 if ($type == 'xml') {
3264 return api_format_data('ok', $type, ["ok" => $ok]);
3267 /// @TODO move to top of file or somewhere better
3268 api_register_func('api/help/test', 'api_help_test', false);
3271 * Returns all lists the user subscribes to.
3273 * @param string $type Return type (atom, rss, xml, json)
3275 * @return array|string
3276 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3278 function api_lists_list($type)
3281 /// @TODO $ret is not filled here?
3282 return api_format_data('lists', $type, ["lists_list" => $ret]);
3285 /// @TODO move to top of file or somewhere better
3286 api_register_func('api/lists/list', 'api_lists_list', true);
3287 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3290 * Returns all groups the user owns.
3292 * @param string $type Return type (atom, rss, xml, json)
3294 * @return array|string
3295 * @throws BadRequestException
3296 * @throws ForbiddenException
3297 * @throws ImagickException
3298 * @throws InternalServerErrorException
3299 * @throws UnauthorizedException
3300 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3302 function api_lists_ownerships($type)
3306 if (api_user() === false) {
3307 throw new ForbiddenException();
3311 $user_info = api_get_user($a);
3312 $uid = $user_info['uid'];
3314 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3316 // loop through all groups
3318 foreach ($groups as $group) {
3319 if ($group['visible']) {
3325 'name' => $group['name'],
3326 'id' => intval($group['id']),
3327 'id_str' => (string) $group['id'],
3328 'user' => $user_info,
3332 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3335 /// @TODO move to top of file or somewhere better
3336 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3339 * Returns recent statuses from users in the specified group.
3341 * @param string $type Return type (atom, rss, xml, json)
3343 * @return array|string
3344 * @throws BadRequestException
3345 * @throws ForbiddenException
3346 * @throws ImagickException
3347 * @throws InternalServerErrorException
3348 * @throws UnauthorizedException
3349 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3351 function api_lists_statuses($type)
3355 $user_info = api_get_user($a);
3356 if (api_user() === false || $user_info === false) {
3357 throw new ForbiddenException();
3360 unset($_REQUEST["user_id"]);
3361 unset($_GET["user_id"]);
3363 unset($_REQUEST["screen_name"]);
3364 unset($_GET["screen_name"]);
3366 if (empty($_REQUEST['list_id'])) {
3367 throw new BadRequestException('list_id not specified');
3371 $count = $_REQUEST['count'] ?? 20;
3372 $page = $_REQUEST['page'] ?? 1;
3373 $since_id = $_REQUEST['since_id'] ?? 0;
3374 $max_id = $_REQUEST['max_id'] ?? 0;
3375 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3376 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3378 $start = max(0, ($page - 1) * $count);
3380 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3381 $gids = array_column($groups, 'contact-id');
3382 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3383 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3386 $condition[0] .= " AND `id` <= ?";
3387 $condition[] = $max_id;
3389 if ($exclude_replies > 0) {
3390 $condition[0] .= ' AND `gravity` = ?';
3391 $condition[] = GRAVITY_PARENT;
3393 if ($conversation_id > 0) {
3394 $condition[0] .= " AND `parent` = ?";
3395 $condition[] = $conversation_id;
3398 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3399 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3401 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3403 $data = ['status' => $items];
3408 $data = api_rss_extra($a, $data, $user_info);
3412 return api_format_data("statuses", $type, $data);
3415 /// @TODO move to top of file or somewhere better
3416 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3419 * Returns either the friends of the follower list
3421 * Considers friends and followers lists to be private and won't return
3422 * anything if any user_id parameter is passed.
3424 * @param string $qtype Either "friends" or "followers"
3425 * @return boolean|array
3426 * @throws BadRequestException
3427 * @throws ForbiddenException
3428 * @throws ImagickException
3429 * @throws InternalServerErrorException
3430 * @throws UnauthorizedException
3432 function api_statuses_f($qtype)
3436 if (api_user() === false) {
3437 throw new ForbiddenException();
3441 $count = $_GET['count'] ?? 20;
3442 $page = $_GET['page'] ?? 1;
3444 $start = max(0, ($page - 1) * $count);
3446 $user_info = api_get_user($a);
3448 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3449 /* this is to stop Hotot to load friends multiple times
3450 * I'm not sure if I'm missing return something or
3451 * is a bug in hotot. Workaround, meantime
3455 return array('$users' => $ret);*/
3460 if ($qtype == 'friends') {
3461 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3462 } elseif ($qtype == 'followers') {
3463 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3466 // friends and followers only for self
3467 if ($user_info['self'] == 0) {
3468 $sql_extra = " AND false ";
3471 if ($qtype == 'blocks') {
3472 $sql_filter = 'AND `blocked` AND NOT `pending`';
3473 } elseif ($qtype == 'incoming') {
3474 $sql_filter = 'AND `pending`';
3476 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3494 foreach ($r as $cid) {
3495 $user = api_get_user($a, $cid['nurl']);
3496 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3497 unset($user["uid"]);
3498 unset($user["self"]);
3505 return ['user' => $ret];
3510 * Returns the list of friends of the provided user
3512 * @deprecated By Twitter API in favor of friends/list
3514 * @param string $type Either "json" or "xml"
3515 * @return boolean|string|array
3516 * @throws BadRequestException
3517 * @throws ForbiddenException
3519 function api_statuses_friends($type)
3521 $data = api_statuses_f("friends");
3522 if ($data === false) {
3525 return api_format_data("users", $type, $data);
3529 * Returns the list of followers of the provided user
3531 * @deprecated By Twitter API in favor of friends/list
3533 * @param string $type Either "json" or "xml"
3534 * @return boolean|string|array
3535 * @throws BadRequestException
3536 * @throws ForbiddenException
3538 function api_statuses_followers($type)
3540 $data = api_statuses_f("followers");
3541 if ($data === false) {
3544 return api_format_data("users", $type, $data);
3547 /// @TODO move to top of file or somewhere better
3548 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3549 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3552 * Returns the list of blocked users
3554 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3556 * @param string $type Either "json" or "xml"
3558 * @return boolean|string|array
3559 * @throws BadRequestException
3560 * @throws ForbiddenException
3562 function api_blocks_list($type)
3564 $data = api_statuses_f('blocks');
3565 if ($data === false) {
3568 return api_format_data("users", $type, $data);
3571 /// @TODO move to top of file or somewhere better
3572 api_register_func('api/blocks/list', 'api_blocks_list', true);
3575 * Returns the list of pending users IDs
3577 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3579 * @param string $type Either "json" or "xml"
3581 * @return boolean|string|array
3582 * @throws BadRequestException
3583 * @throws ForbiddenException
3585 function api_friendships_incoming($type)
3587 $data = api_statuses_f('incoming');
3588 if ($data === false) {
3593 foreach ($data['user'] as $user) {
3594 $ids[] = $user['id'];
3597 return api_format_data("ids", $type, ['id' => $ids]);
3600 /// @TODO move to top of file or somewhere better
3601 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3604 * Returns the instance's configuration information.
3606 * @param string $type Return type (atom, rss, xml, json)
3608 * @return array|string
3609 * @throws InternalServerErrorException
3611 function api_statusnet_config($type)
3613 $name = DI::config()->get('config', 'sitename');
3614 $server = DI::baseUrl()->getHostname();
3615 $logo = DI::baseUrl() . '/images/friendica-64.png';
3616 $email = DI::config()->get('config', 'admin_email');
3617 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3618 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3619 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3620 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3621 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3624 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3625 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3626 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3627 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3628 'shorturllength' => '30',
3630 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3631 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3632 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3633 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3638 return api_format_data('config', $type, ['config' => $config]);
3641 /// @TODO move to top of file or somewhere better
3642 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3643 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3647 * @param string $type Return type (atom, rss, xml, json)
3649 * @return array|string
3651 function api_statusnet_version($type)
3654 $fake_statusnet_version = "0.9.7";
3656 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3659 /// @TODO move to top of file or somewhere better
3660 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3661 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3664 * Sends a new direct message.
3666 * @param string $type Return type (atom, rss, xml, json)
3668 * @return array|string
3669 * @throws BadRequestException
3670 * @throws ForbiddenException
3671 * @throws ImagickException
3672 * @throws InternalServerErrorException
3673 * @throws NotFoundException
3674 * @throws UnauthorizedException
3675 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3677 function api_direct_messages_new($type)
3681 if (api_user() === false) {
3682 throw new ForbiddenException();
3685 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3689 $sender = api_get_user($a);
3692 if (!empty($_POST['screen_name'])) {
3694 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3696 DBA::escape($_POST['screen_name'])
3699 if (DBA::isResult($r)) {
3700 // Selecting the id by priority, friendica first
3701 api_best_nickname($r);
3703 $recipient = api_get_user($a, $r[0]['nurl']);
3706 $recipient = api_get_user($a, $_POST['user_id']);
3709 if (empty($recipient)) {
3710 throw new NotFoundException('Recipient not found');
3714 if (!empty($_REQUEST['replyto'])) {
3716 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3718 intval($_REQUEST['replyto'])
3720 $replyto = $r[0]['parent-uri'];
3721 $sub = $r[0]['title'];
3723 if (!empty($_REQUEST['title'])) {
3724 $sub = $_REQUEST['title'];
3726 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3730 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3733 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3734 $ret = api_format_messages($r[0], $recipient, $sender);
3736 $ret = ["error"=>$id];
3739 $data = ['direct_message'=>$ret];
3745 $data = api_rss_extra($a, $data, $sender);
3749 return api_format_data("direct-messages", $type, $data);
3752 /// @TODO move to top of file or somewhere better
3753 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3756 * delete a direct_message from mail table through api
3758 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3759 * @return string|array
3760 * @throws BadRequestException
3761 * @throws ForbiddenException
3762 * @throws ImagickException
3763 * @throws InternalServerErrorException
3764 * @throws UnauthorizedException
3765 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3767 function api_direct_messages_destroy($type)
3771 if (api_user() === false) {
3772 throw new ForbiddenException();
3776 $user_info = api_get_user($a);
3778 $id = $_REQUEST['id'] ?? 0;
3780 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3781 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3782 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3784 $uid = $user_info['uid'];
3785 // error if no id or parenturi specified (for clients posting parent-uri as well)
3786 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3787 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3788 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3791 // BadRequestException if no id specified (for clients using Twitter API)
3793 throw new BadRequestException('Message id not specified');
3796 // add parent-uri to sql command if specified by calling app
3797 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3799 // get data of the specified message id
3801 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3806 // error message if specified id is not in database
3807 if (!DBA::isResult($r)) {
3808 if ($verbose == "true") {
3809 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3810 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3812 /// @todo BadRequestException ok for Twitter API clients?
3813 throw new BadRequestException('message id not in database');
3818 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3823 if ($verbose == "true") {
3826 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3827 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3829 $answer = ['result' => 'error', 'message' => 'unknown error'];
3830 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3833 /// @todo return JSON data like Twitter API not yet implemented
3836 /// @TODO move to top of file or somewhere better
3837 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3842 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3843 * @return string|array
3844 * @throws BadRequestException
3845 * @throws ForbiddenException
3846 * @throws ImagickException
3847 * @throws InternalServerErrorException
3848 * @throws NotFoundException
3849 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3851 function api_friendships_destroy($type)
3855 if ($uid === false) {
3856 throw new ForbiddenException();
3859 $contact_id = $_REQUEST['user_id'] ?? 0;
3861 if (empty($contact_id)) {
3862 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3863 throw new BadRequestException("no user_id specified");
3866 // Get Contact by given id
3867 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3869 if(!DBA::isResult($contact)) {
3870 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3871 throw new NotFoundException("no contact found to given ID");
3874 $url = $contact["url"];
3876 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3877 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3878 Strings::normaliseLink($url), $url];
3879 $contact = DBA::selectFirst('contact', [], $condition);
3881 if (!DBA::isResult($contact)) {
3882 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3883 throw new NotFoundException("Not following Contact");
3886 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3887 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3888 throw new ExpectationFailedException("Not supported");
3891 $dissolve = ($contact['rel'] == Contact::SHARING);
3893 $owner = User::getOwnerDataById($uid);
3895 Contact::terminateFriendship($owner, $contact, $dissolve);
3898 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3899 throw new NotFoundException("Error Processing Request");
3902 // Sharing-only contacts get deleted as there no relationship any more
3904 Contact::remove($contact['id']);
3906 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3909 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3910 unset($contact["uid"]);
3911 unset($contact["self"]);
3913 // Set screen_name since Twidere requests it
3914 $contact["screen_name"] = $contact["nick"];
3916 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3918 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3922 * @param string $type Return type (atom, rss, xml, json)
3923 * @param string $box
3924 * @param string $verbose
3926 * @return array|string
3927 * @throws BadRequestException
3928 * @throws ForbiddenException
3929 * @throws ImagickException
3930 * @throws InternalServerErrorException
3931 * @throws UnauthorizedException
3933 function api_direct_messages_box($type, $box, $verbose)
3936 if (api_user() === false) {
3937 throw new ForbiddenException();
3940 $count = $_GET['count'] ?? 20;
3941 $page = $_REQUEST['page'] ?? 1;
3943 $since_id = $_REQUEST['since_id'] ?? 0;
3944 $max_id = $_REQUEST['max_id'] ?? 0;
3946 $user_id = $_REQUEST['user_id'] ?? '';
3947 $screen_name = $_REQUEST['screen_name'] ?? '';
3950 unset($_REQUEST["user_id"]);
3951 unset($_GET["user_id"]);
3953 unset($_REQUEST["screen_name"]);
3954 unset($_GET["screen_name"]);
3956 $user_info = api_get_user($a);
3957 if ($user_info === false) {
3958 throw new ForbiddenException();
3960 $profile_url = $user_info["url"];
3963 $start = max(0, ($page - 1) * $count);
3968 if ($box=="sentbox") {
3969 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3970 } elseif ($box == "conversation") {
3971 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3972 } elseif ($box == "all") {
3973 $sql_extra = "true";
3974 } elseif ($box == "inbox") {
3975 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3979 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3982 if ($user_id != "") {
3983 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3984 } elseif ($screen_name !="") {
3985 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3989 "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",
3995 if ($verbose == "true" && !DBA::isResult($r)) {
3996 $answer = ['result' => 'error', 'message' => 'no mails available'];
3997 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4001 foreach ($r as $item) {
4002 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4003 $recipient = $user_info;
4004 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4005 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4006 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4007 $sender = $user_info;
4010 if (isset($recipient) && isset($sender)) {
4011 $ret[] = api_format_messages($item, $recipient, $sender);
4016 $data = ['direct_message' => $ret];
4021 $data = api_rss_extra($a, $data, $user_info);
4025 return api_format_data("direct-messages", $type, $data);
4029 * Returns the most recent direct messages sent by the user.
4031 * @param string $type Return type (atom, rss, xml, json)
4033 * @return array|string
4034 * @throws BadRequestException
4035 * @throws ForbiddenException
4036 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4038 function api_direct_messages_sentbox($type)
4040 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4041 return api_direct_messages_box($type, "sentbox", $verbose);
4045 * Returns the most recent direct messages sent to the user.
4047 * @param string $type Return type (atom, rss, xml, json)
4049 * @return array|string
4050 * @throws BadRequestException
4051 * @throws ForbiddenException
4052 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4054 function api_direct_messages_inbox($type)
4056 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4057 return api_direct_messages_box($type, "inbox", $verbose);
4062 * @param string $type Return type (atom, rss, xml, json)
4064 * @return array|string
4065 * @throws BadRequestException
4066 * @throws ForbiddenException
4068 function api_direct_messages_all($type)
4070 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4071 return api_direct_messages_box($type, "all", $verbose);
4076 * @param string $type Return type (atom, rss, xml, json)
4078 * @return array|string
4079 * @throws BadRequestException
4080 * @throws ForbiddenException
4082 function api_direct_messages_conversation($type)
4084 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4085 return api_direct_messages_box($type, "conversation", $verbose);
4088 /// @TODO move to top of file or somewhere better
4089 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4090 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4091 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4092 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4095 * Returns an OAuth Request Token.
4097 * @see https://oauth.net/core/1.0/#auth_step1
4099 function api_oauth_request_token()
4101 $oauth1 = new FKOAuth1();
4103 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4104 } catch (Exception $e) {
4105 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4113 * Returns an OAuth Access Token.
4115 * @return array|string
4116 * @see https://oauth.net/core/1.0/#auth_step3
4118 function api_oauth_access_token()
4120 $oauth1 = new FKOAuth1();
4122 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4123 } catch (Exception $e) {
4124 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4131 /// @TODO move to top of file or somewhere better
4132 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4133 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4137 * delete a complete photoalbum with all containing photos from database through api
4139 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4140 * @return string|array
4141 * @throws BadRequestException
4142 * @throws ForbiddenException
4143 * @throws InternalServerErrorException
4145 function api_fr_photoalbum_delete($type)
4147 if (api_user() === false) {
4148 throw new ForbiddenException();
4151 $album = $_REQUEST['album'] ?? '';
4153 // we do not allow calls without album string
4155 throw new BadRequestException("no albumname specified");
4157 // check if album is existing
4159 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4160 if (!DBA::isResult($photos)) {
4161 throw new BadRequestException("album not available");
4164 $resourceIds = array_column($photos, 'resource-id');
4166 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4167 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4168 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4169 Item::deleteForUser($condition, api_user());
4171 // now let's delete all photos from the album
4172 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4174 // return success of deletion or error message
4176 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4177 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4179 throw new InternalServerErrorException("unknown error - deleting from database failed");
4184 * update the name of the album for all photos of an album
4186 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4187 * @return string|array
4188 * @throws BadRequestException
4189 * @throws ForbiddenException
4190 * @throws InternalServerErrorException
4192 function api_fr_photoalbum_update($type)
4194 if (api_user() === false) {
4195 throw new ForbiddenException();
4198 $album = $_REQUEST['album'] ?? '';
4199 $album_new = $_REQUEST['album_new'] ?? '';
4201 // we do not allow calls without album string
4203 throw new BadRequestException("no albumname specified");
4205 if ($album_new == "") {
4206 throw new BadRequestException("no new albumname specified");
4208 // check if album is existing
4209 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4210 throw new BadRequestException("album not available");
4212 // now let's update all photos to the albumname
4213 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4215 // return success of updating or error message
4217 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4218 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4220 throw new InternalServerErrorException("unknown error - updating in database failed");
4226 * list all photos of the authenticated user
4228 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4229 * @return string|array
4230 * @throws ForbiddenException
4231 * @throws InternalServerErrorException
4233 function api_fr_photos_list($type)
4235 if (api_user() === false) {
4236 throw new ForbiddenException();
4239 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4240 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4241 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4242 intval(local_user())
4245 'image/jpeg' => 'jpg',
4246 'image/png' => 'png',
4247 'image/gif' => 'gif'
4249 $data = ['photo'=>[]];
4250 if (DBA::isResult($r)) {
4251 foreach ($r as $rr) {
4253 $photo['id'] = $rr['resource-id'];
4254 $photo['album'] = $rr['album'];
4255 $photo['filename'] = $rr['filename'];
4256 $photo['type'] = $rr['type'];
4257 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4258 $photo['created'] = $rr['created'];
4259 $photo['edited'] = $rr['edited'];
4260 $photo['desc'] = $rr['desc'];
4262 if ($type == "xml") {
4263 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4265 $photo['thumb'] = $thumb;
4266 $data['photo'][] = $photo;
4270 return api_format_data("photos", $type, $data);
4274 * upload a new photo or change an existing photo
4276 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4277 * @return string|array
4278 * @throws BadRequestException
4279 * @throws ForbiddenException
4280 * @throws ImagickException
4281 * @throws InternalServerErrorException
4282 * @throws NotFoundException
4284 function api_fr_photo_create_update($type)
4286 if (api_user() === false) {
4287 throw new ForbiddenException();
4290 $photo_id = $_REQUEST['photo_id'] ?? null;
4291 $desc = $_REQUEST['desc'] ?? null;
4292 $album = $_REQUEST['album'] ?? null;
4293 $album_new = $_REQUEST['album_new'] ?? null;
4294 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4295 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4296 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4297 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4298 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4300 // do several checks on input parameters
4301 // we do not allow calls without album string
4302 if ($album == null) {
4303 throw new BadRequestException("no albumname specified");
4305 // if photo_id == null --> we are uploading a new photo
4306 if ($photo_id == null) {
4309 // error if no media posted in create-mode
4310 if (empty($_FILES['media'])) {
4312 throw new BadRequestException("no media data submitted");
4315 // album_new will be ignored in create-mode
4320 // check if photo is existing in databasei
4321 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4322 throw new BadRequestException("photo not available");
4326 // checks on acl strings provided by clients
4327 $acl_input_error = false;
4328 $acl_input_error |= check_acl_input($allow_cid);
4329 $acl_input_error |= check_acl_input($deny_cid);
4330 $acl_input_error |= check_acl_input($allow_gid);
4331 $acl_input_error |= check_acl_input($deny_gid);
4332 if ($acl_input_error) {
4333 throw new BadRequestException("acl data invalid");
4335 // now let's upload the new media in create-mode
4336 if ($mode == "create") {
4337 $media = $_FILES['media'];
4338 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4340 // return success of updating or error message
4341 if (!is_null($data)) {
4342 return api_format_data("photo_create", $type, $data);
4344 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4348 // now let's do the changes in update-mode
4349 if ($mode == "update") {
4350 $updated_fields = [];
4352 if (!is_null($desc)) {
4353 $updated_fields['desc'] = $desc;
4356 if (!is_null($album_new)) {
4357 $updated_fields['album'] = $album_new;
4360 if (!is_null($allow_cid)) {
4361 $allow_cid = trim($allow_cid);
4362 $updated_fields['allow_cid'] = $allow_cid;
4365 if (!is_null($deny_cid)) {
4366 $deny_cid = trim($deny_cid);
4367 $updated_fields['deny_cid'] = $deny_cid;
4370 if (!is_null($allow_gid)) {
4371 $allow_gid = trim($allow_gid);
4372 $updated_fields['allow_gid'] = $allow_gid;
4375 if (!is_null($deny_gid)) {
4376 $deny_gid = trim($deny_gid);
4377 $updated_fields['deny_gid'] = $deny_gid;
4381 if (count($updated_fields) > 0) {
4382 $nothingtodo = false;
4383 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4385 $nothingtodo = true;
4388 if (!empty($_FILES['media'])) {
4389 $nothingtodo = false;
4390 $media = $_FILES['media'];
4391 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4392 if (!is_null($data)) {
4393 return api_format_data("photo_update", $type, $data);
4397 // return success of updating or error message
4399 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4400 return api_format_data("photo_update", $type, ['$result' => $answer]);
4403 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4404 return api_format_data("photo_update", $type, ['$result' => $answer]);
4406 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4409 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4413 * delete a single photo from the database through api
4415 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4416 * @return string|array
4417 * @throws BadRequestException
4418 * @throws ForbiddenException
4419 * @throws InternalServerErrorException
4421 function api_fr_photo_delete($type)
4423 if (api_user() === false) {
4424 throw new ForbiddenException();
4428 $photo_id = $_REQUEST['photo_id'] ?? null;
4430 // do several checks on input parameters
4431 // we do not allow calls without photo id
4432 if ($photo_id == null) {
4433 throw new BadRequestException("no photo_id specified");
4436 // check if photo is existing in database
4437 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4438 throw new BadRequestException("photo not available");
4441 // now we can perform on the deletion of the photo
4442 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4444 // return success of deletion or error message
4446 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4447 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4448 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4449 Item::deleteForUser($condition, api_user());
4451 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4452 return api_format_data("photo_delete", $type, ['$result' => $result]);
4454 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4460 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4462 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4463 * @return string|array
4464 * @throws BadRequestException
4465 * @throws ForbiddenException
4466 * @throws InternalServerErrorException
4467 * @throws NotFoundException
4469 function api_fr_photo_detail($type)
4471 if (api_user() === false) {
4472 throw new ForbiddenException();
4474 if (empty($_REQUEST['photo_id'])) {
4475 throw new BadRequestException("No photo id.");
4478 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4479 $photo_id = $_REQUEST['photo_id'];
4481 // prepare json/xml output with data from database for the requested photo
4482 $data = prepare_photo_data($type, $scale, $photo_id);
4484 return api_format_data("photo_detail", $type, $data);
4489 * updates the profile image for the user (either a specified profile or the default profile)
4491 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4493 * @return string|array
4494 * @throws BadRequestException
4495 * @throws ForbiddenException
4496 * @throws ImagickException
4497 * @throws InternalServerErrorException
4498 * @throws NotFoundException
4499 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4501 function api_account_update_profile_image($type)
4503 if (api_user() === false) {
4504 throw new ForbiddenException();
4507 $profile_id = $_REQUEST['profile_id'] ?? 0;
4509 // error if image data is missing
4510 if (empty($_FILES['image'])) {
4511 throw new BadRequestException("no media data submitted");
4514 // check if specified profile id is valid
4515 if ($profile_id != 0) {
4516 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4517 // error message if specified profile id is not in database
4518 if (!DBA::isResult($profile)) {
4519 throw new BadRequestException("profile_id not available");
4521 $is_default_profile = $profile['is-default'];
4523 $is_default_profile = 1;
4526 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4528 if (!empty($_FILES['image'])) {
4529 $media = $_FILES['image'];
4530 } elseif (!empty($_FILES['media'])) {
4531 $media = $_FILES['media'];
4533 // save new profile image
4534 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4537 if (is_array($media['type'])) {
4538 $filetype = $media['type'][0];
4540 $filetype = $media['type'];
4542 if ($filetype == "image/jpeg") {
4544 } elseif ($filetype == "image/png") {
4547 throw new InternalServerErrorException('Unsupported filetype');
4550 // change specified profile or all profiles to the new resource-id
4551 if ($is_default_profile) {
4552 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4553 Photo::update(['profile' => false], $condition);
4555 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4556 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4557 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4560 Contact::updateSelfFromUserID(api_user(), true);
4562 // Update global directory in background
4563 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4564 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4565 Worker::add(PRIORITY_LOW, "Directory", $url);
4568 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4570 // output for client
4572 return api_account_verify_credentials($type);
4574 // SaveMediaToDatabase failed for some reason
4575 throw new InternalServerErrorException("image upload failed");
4579 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4580 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4581 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4582 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4583 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4584 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4585 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4586 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4587 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4590 * Update user profile
4592 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4594 * @return array|string
4595 * @throws BadRequestException
4596 * @throws ForbiddenException
4597 * @throws ImagickException
4598 * @throws InternalServerErrorException
4599 * @throws UnauthorizedException
4601 function api_account_update_profile($type)
4603 $local_user = api_user();
4604 $api_user = api_get_user(DI::app());
4606 if (!empty($_POST['name'])) {
4607 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4608 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4609 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4610 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4613 if (isset($_POST['description'])) {
4614 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4615 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4616 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4619 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4620 // Update global directory in background
4621 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4622 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4625 return api_account_verify_credentials($type);
4628 /// @TODO move to top of file or somewhere better
4629 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4633 * @param string $acl_string
4637 function check_acl_input($acl_string)
4639 if (empty($acl_string)) {
4643 $contact_not_found = false;
4645 // split <x><y><z> into array of cid's
4646 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4648 // check for each cid if it is available on server
4649 $cid_array = $array[0];
4650 foreach ($cid_array as $cid) {
4651 $cid = str_replace("<", "", $cid);
4652 $cid = str_replace(">", "", $cid);
4653 $condition = ['id' => $cid, 'uid' => api_user()];
4654 $contact_not_found |= !DBA::exists('contact', $condition);
4656 return $contact_not_found;
4660 * @param string $mediatype
4661 * @param array $media
4662 * @param string $type
4663 * @param string $album
4664 * @param string $allow_cid
4665 * @param string $deny_cid
4666 * @param string $allow_gid
4667 * @param string $deny_gid
4668 * @param string $desc
4669 * @param integer $profile
4670 * @param boolean $visibility
4671 * @param string $photo_id
4673 * @throws BadRequestException
4674 * @throws ForbiddenException
4675 * @throws ImagickException
4676 * @throws InternalServerErrorException
4677 * @throws NotFoundException
4678 * @throws UnauthorizedException
4680 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)
4688 if (is_array($media)) {
4689 if (is_array($media['tmp_name'])) {
4690 $src = $media['tmp_name'][0];
4692 $src = $media['tmp_name'];
4694 if (is_array($media['name'])) {
4695 $filename = basename($media['name'][0]);
4697 $filename = basename($media['name']);
4699 if (is_array($media['size'])) {
4700 $filesize = intval($media['size'][0]);
4702 $filesize = intval($media['size']);
4704 if (is_array($media['type'])) {
4705 $filetype = $media['type'][0];
4707 $filetype = $media['type'];
4711 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4714 "File upload src: " . $src . " - filename: " . $filename .
4715 " - size: " . $filesize . " - type: " . $filetype,
4719 // check if there was a php upload error
4720 if ($filesize == 0 && $media['error'] == 1) {
4721 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4723 // check against max upload size within Friendica instance
4724 $maximagesize = DI::config()->get('system', 'maximagesize');
4725 if ($maximagesize && ($filesize > $maximagesize)) {
4726 $formattedBytes = Strings::formatBytes($maximagesize);
4727 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4730 // create Photo instance with the data of the image
4731 $imagedata = @file_get_contents($src);
4732 $Image = new Image($imagedata, $filetype);
4733 if (!$Image->isValid()) {
4734 throw new InternalServerErrorException("unable to process image data");
4737 // check orientation of image
4738 $Image->orient($src);
4741 // check max length of images on server
4742 $max_length = DI::config()->get('system', 'max_image_length');
4744 $max_length = MAX_IMAGE_LENGTH;
4746 if ($max_length > 0) {
4747 $Image->scaleDown($max_length);
4748 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4750 $width = $Image->getWidth();
4751 $height = $Image->getHeight();
4753 // create a new resource-id if not already provided
4754 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4756 if ($mediatype == "photo") {
4757 // upload normal image (scales 0, 1, 2)
4758 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4760 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4762 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4764 if ($width > 640 || $height > 640) {
4765 $Image->scaleDown(640);
4766 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4768 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4772 if ($width > 320 || $height > 320) {
4773 $Image->scaleDown(320);
4774 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4776 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4779 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4780 } elseif ($mediatype == "profileimage") {
4781 // upload profile image (scales 4, 5, 6)
4782 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4784 if ($width > 300 || $height > 300) {
4785 $Image->scaleDown(300);
4786 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4788 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4792 if ($width > 80 || $height > 80) {
4793 $Image->scaleDown(80);
4794 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4796 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4800 if ($width > 48 || $height > 48) {
4801 $Image->scaleDown(48);
4802 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4804 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4807 $Image->__destruct();
4808 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4812 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4813 if ($photo_id == null && $mediatype == "photo") {
4814 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4816 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4817 return prepare_photo_data($type, false, $resource_id);
4819 throw new InternalServerErrorException("image upload failed");
4825 * @param string $hash
4826 * @param string $allow_cid
4827 * @param string $deny_cid
4828 * @param string $allow_gid
4829 * @param string $deny_gid
4830 * @param string $filetype
4831 * @param boolean $visibility
4832 * @throws InternalServerErrorException
4834 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4836 // get data about the api authenticated user
4837 $uri = Item::newURI(intval(api_user()));
4838 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4841 $arr['guid'] = System::createUUID();
4842 $arr['uid'] = intval(api_user());
4844 $arr['type'] = 'photo';
4846 $arr['resource-id'] = $hash;
4847 $arr['contact-id'] = $owner_record['id'];
4848 $arr['owner-name'] = $owner_record['name'];
4849 $arr['owner-link'] = $owner_record['url'];
4850 $arr['owner-avatar'] = $owner_record['thumb'];
4851 $arr['author-name'] = $owner_record['name'];
4852 $arr['author-link'] = $owner_record['url'];
4853 $arr['author-avatar'] = $owner_record['thumb'];
4855 $arr['allow_cid'] = $allow_cid;
4856 $arr['allow_gid'] = $allow_gid;
4857 $arr['deny_cid'] = $deny_cid;
4858 $arr['deny_gid'] = $deny_gid;
4859 $arr['visible'] = $visibility;
4863 'image/jpeg' => 'jpg',
4864 'image/png' => 'png',
4865 'image/gif' => 'gif'
4868 // adds link to the thumbnail scale photo
4869 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4870 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4873 // do the magic for storing the item in the database and trigger the federation to other contacts
4879 * @param string $type
4881 * @param string $photo_id
4884 * @throws BadRequestException
4885 * @throws ForbiddenException
4886 * @throws ImagickException
4887 * @throws InternalServerErrorException
4888 * @throws NotFoundException
4889 * @throws UnauthorizedException
4891 function prepare_photo_data($type, $scale, $photo_id)
4894 $user_info = api_get_user($a);
4896 if ($user_info === false) {
4897 throw new ForbiddenException();
4900 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4901 $data_sql = ($scale === false ? "" : "data, ");
4903 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4904 // clients needs to convert this in their way for further processing
4906 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4907 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4908 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4909 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4910 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4911 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4913 intval(local_user()),
4914 DBA::escape($photo_id),
4919 'image/jpeg' => 'jpg',
4920 'image/png' => 'png',
4921 'image/gif' => 'gif'
4924 // prepare output data for photo
4925 if (DBA::isResult($r)) {
4926 $data = ['photo' => $r[0]];
4927 $data['photo']['id'] = $data['photo']['resource-id'];
4928 if ($scale !== false) {
4929 $data['photo']['data'] = base64_encode($data['photo']['data']);
4931 unset($data['photo']['datasize']); //needed only with scale param
4933 if ($type == "xml") {
4934 $data['photo']['links'] = [];
4935 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4936 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4938 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4941 $data['photo']['link'] = [];
4942 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4944 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4945 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4949 unset($data['photo']['resource-id']);
4950 unset($data['photo']['minscale']);
4951 unset($data['photo']['maxscale']);
4953 throw new NotFoundException();
4956 // retrieve item element for getting activities (like, dislike etc.) related to photo
4957 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4958 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4959 if (!DBA::isResult($item)) {
4960 throw new NotFoundException('Photo-related item not found.');
4963 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4965 // retrieve comments on photo
4966 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4967 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4969 $statuses = Post::selectForUser(api_user(), [], $condition);
4971 // prepare output of comments
4972 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4974 if ($type == "xml") {
4976 foreach ($commentData as $comment) {
4977 $comments[$k++ . ":comment"] = $comment;
4980 foreach ($commentData as $comment) {
4981 $comments[] = $comment;
4984 $data['photo']['friendica_comments'] = $comments;
4986 // include info if rights on photo and rights on item are mismatching
4987 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4988 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4989 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4990 $data['photo']['deny_gid'] != $item['deny_gid'];
4991 $data['photo']['rights_mismatch'] = $rights_mismatch;
4998 * Similar as /mod/redir.php
4999 * redirect to 'url' after dfrn auth
5001 * Why this when there is mod/redir.php already?
5002 * This use api_user() and api_login()
5005 * c_url: url of remote contact to auth to
5006 * url: string, url to redirect after auth
5008 function api_friendica_remoteauth()
5010 $url = $_GET['url'] ?? '';
5011 $c_url = $_GET['c_url'] ?? '';
5013 if ($url === '' || $c_url === '') {
5014 throw new BadRequestException("Wrong parameters.");
5017 $c_url = Strings::normaliseLink($c_url);
5021 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5022 if (!DBA::isResult($contact)) {
5023 throw new BadRequestException("Unknown contact");
5026 $cid = $contact['id'];
5028 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5030 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5031 System::externalRedirect($url ?: $c_url);
5034 if ($contact['duplex'] && $contact['issued-id']) {
5035 $orig_id = $contact['issued-id'];
5036 $dfrn_id = '1:' . $orig_id;
5038 if ($contact['duplex'] && $contact['dfrn-id']) {
5039 $orig_id = $contact['dfrn-id'];
5040 $dfrn_id = '0:' . $orig_id;
5043 $sec = Strings::getRandomHex();
5045 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5046 'sec' => $sec, 'expire' => time() + 45];
5047 DBA::insert('profile_check', $fields);
5049 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5050 $dest = ($url ? '&destination_url=' . $url : '');
5052 System::externalRedirect(
5053 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5054 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5055 . '&type=profile&sec=' . $sec . $dest
5058 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5061 * Return an item with announcer data if it had been announced
5063 * @param array $item Item array
5064 * @return array Item array with announce data
5066 function api_get_announce($item)
5068 // Quit if the item already has got a different owner and author
5069 if ($item['owner-id'] != $item['author-id']) {
5073 // Don't change original or Diaspora posts
5074 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5078 // Quit if we do now the original author and it had been a post from a native network
5079 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5083 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5084 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5085 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5086 if (!DBA::isResult($announce)) {
5090 return array_merge($item, $announce);
5094 * Return the item shared, if the item contains only the [share] tag
5096 * @param array $item Sharer item
5097 * @return array|false Shared item or false if not a reshare
5098 * @throws ImagickException
5099 * @throws InternalServerErrorException
5101 function api_share_as_retweet(&$item)
5103 $body = trim($item["body"]);
5105 if (Diaspora::isReshare($body, false) === false) {
5106 if ($item['author-id'] == $item['owner-id']) {
5109 // Reshares from OStatus, ActivityPub and Twitter
5110 $reshared_item = $item;
5111 $reshared_item['owner-id'] = $reshared_item['author-id'];
5112 $reshared_item['owner-link'] = $reshared_item['author-link'];
5113 $reshared_item['owner-name'] = $reshared_item['author-name'];
5114 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5115 return $reshared_item;
5119 $reshared = Item::getShareArray($item);
5120 if (empty($reshared)) {
5124 $reshared_item = $item;
5126 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5130 if (!empty($reshared['comment'])) {
5131 $item['body'] = $reshared['comment'];
5134 $reshared_item["share-pre-body"] = $reshared['comment'];
5135 $reshared_item["body"] = $reshared['shared'];
5136 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5137 $reshared_item["author-name"] = $reshared['author'];
5138 $reshared_item["author-link"] = $reshared['profile'];
5139 $reshared_item["author-avatar"] = $reshared['avatar'];
5140 $reshared_item["plink"] = $reshared['link'] ?? '';
5141 $reshared_item["created"] = $reshared['posted'];
5142 $reshared_item["edited"] = $reshared['posted'];
5144 // Try to fetch the original item
5145 if (!empty($reshared['guid'])) {
5146 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5147 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5148 $condition = ['id' => $original_id];
5153 if (!empty($condition)) {
5154 $original_item = Post::selectFirst([], $condition);
5155 if (DBA::isResult($original_item)) {
5156 $reshared_item = array_merge($reshared_item, $original_item);
5160 return $reshared_item;
5165 * @param array $item
5170 function api_in_reply_to($item)
5174 $in_reply_to['status_id'] = null;
5175 $in_reply_to['user_id'] = null;
5176 $in_reply_to['status_id_str'] = null;
5177 $in_reply_to['user_id_str'] = null;
5178 $in_reply_to['screen_name'] = null;
5180 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5181 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5182 if (DBA::isResult($parent)) {
5183 $in_reply_to['status_id'] = intval($parent['id']);
5185 $in_reply_to['status_id'] = intval($item['parent']);
5188 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5190 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5191 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5193 if (DBA::isResult($parent)) {
5194 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5195 $in_reply_to['user_id'] = intval($parent['author-id']);
5196 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5199 // There seems to be situation, where both fields are identical:
5200 // https://github.com/friendica/friendica/issues/1010
5201 // This is a bugfix for that.
5202 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5203 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']]);
5204 $in_reply_to['status_id'] = null;
5205 $in_reply_to['user_id'] = null;
5206 $in_reply_to['status_id_str'] = null;
5207 $in_reply_to['user_id_str'] = null;
5208 $in_reply_to['screen_name'] = null;
5212 return $in_reply_to;
5217 * @param string $text
5220 * @throws InternalServerErrorException
5222 function api_clean_plain_items($text)
5224 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5226 $text = BBCode::cleanPictureLinks($text);
5227 $URLSearchString = "^\[\]";
5229 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5231 if ($include_entities == "true") {
5232 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5235 // Simplify "attachment" element
5236 $text = BBCode::removeAttachment($text);
5243 * @param array $contacts
5247 function api_best_nickname(&$contacts)
5251 if (count($contacts) == 0) {
5255 foreach ($contacts as $contact) {
5256 if ($contact["network"] == "") {
5257 $contact["network"] = "dfrn";
5258 $best_contact = [$contact];
5262 if (sizeof($best_contact) == 0) {
5263 foreach ($contacts as $contact) {
5264 if ($contact["network"] == "dfrn") {
5265 $best_contact = [$contact];
5270 if (sizeof($best_contact) == 0) {
5271 foreach ($contacts as $contact) {
5272 if ($contact["network"] == "dspr") {
5273 $best_contact = [$contact];
5278 if (sizeof($best_contact) == 0) {
5279 foreach ($contacts as $contact) {
5280 if ($contact["network"] == "stat") {
5281 $best_contact = [$contact];
5286 if (sizeof($best_contact) == 0) {
5287 foreach ($contacts as $contact) {
5288 if ($contact["network"] == "pump") {
5289 $best_contact = [$contact];
5294 if (sizeof($best_contact) == 0) {
5295 foreach ($contacts as $contact) {
5296 if ($contact["network"] == "twit") {
5297 $best_contact = [$contact];
5302 if (sizeof($best_contact) == 1) {
5303 $contacts = $best_contact;
5305 $contacts = [$contacts[0]];
5310 * Return all or a specified group of the user with the containing contacts.
5312 * @param string $type Return type (atom, rss, xml, json)
5314 * @return array|string
5315 * @throws BadRequestException
5316 * @throws ForbiddenException
5317 * @throws ImagickException
5318 * @throws InternalServerErrorException
5319 * @throws UnauthorizedException
5321 function api_friendica_group_show($type)
5325 if (api_user() === false) {
5326 throw new ForbiddenException();
5330 $user_info = api_get_user($a);
5331 $gid = $_REQUEST['gid'] ?? 0;
5332 $uid = $user_info['uid'];
5334 // get data of the specified group id or all groups if not specified
5337 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5341 // error message if specified gid is not in database
5342 if (!DBA::isResult($r)) {
5343 throw new BadRequestException("gid not available");
5347 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5352 // loop through all groups and retrieve all members for adding data in the user array
5354 foreach ($r as $rr) {
5355 $members = Contact\Group::getById($rr['id']);
5358 if ($type == "xml") {
5359 $user_element = "users";
5361 foreach ($members as $member) {
5362 $user = api_get_user($a, $member['nurl']);
5363 $users[$k++.":user"] = $user;
5366 $user_element = "user";
5367 foreach ($members as $member) {
5368 $user = api_get_user($a, $member['nurl']);
5372 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5374 return api_format_data("groups", $type, ['group' => $grps]);
5376 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5380 * Delete the specified group of the user.
5382 * @param string $type Return type (atom, rss, xml, json)
5384 * @return array|string
5385 * @throws BadRequestException
5386 * @throws ForbiddenException
5387 * @throws ImagickException
5388 * @throws InternalServerErrorException
5389 * @throws UnauthorizedException
5391 function api_friendica_group_delete($type)
5395 if (api_user() === false) {
5396 throw new ForbiddenException();
5400 $user_info = api_get_user($a);
5401 $gid = $_REQUEST['gid'] ?? 0;
5402 $name = $_REQUEST['name'] ?? '';
5403 $uid = $user_info['uid'];
5405 // error if no gid specified
5406 if ($gid == 0 || $name == "") {
5407 throw new BadRequestException('gid or name not specified');
5410 // get data of the specified group id
5412 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5416 // error message if specified gid is not in database
5417 if (!DBA::isResult($r)) {
5418 throw new BadRequestException('gid not available');
5421 // get data of the specified group id and group name
5423 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5428 // error message if specified gid is not in database
5429 if (!DBA::isResult($rname)) {
5430 throw new BadRequestException('wrong group name');
5434 $ret = Group::removeByName($uid, $name);
5437 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5438 return api_format_data("group_delete", $type, ['result' => $success]);
5440 throw new BadRequestException('other API error');
5443 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5448 * @param string $type Return type (atom, rss, xml, json)
5450 * @return array|string
5451 * @throws BadRequestException
5452 * @throws ForbiddenException
5453 * @throws ImagickException
5454 * @throws InternalServerErrorException
5455 * @throws UnauthorizedException
5456 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5458 function api_lists_destroy($type)
5462 if (api_user() === false) {
5463 throw new ForbiddenException();
5467 $user_info = api_get_user($a);
5468 $gid = $_REQUEST['list_id'] ?? 0;
5469 $uid = $user_info['uid'];
5471 // error if no gid specified
5473 throw new BadRequestException('gid not specified');
5476 // get data of the specified group id
5477 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5478 // error message if specified gid is not in database
5480 throw new BadRequestException('gid not available');
5483 if (Group::remove($gid)) {
5485 'name' => $group['name'],
5486 'id' => intval($gid),
5487 'id_str' => (string) $gid,
5488 'user' => $user_info
5491 return api_format_data("lists", $type, ['lists' => $list]);
5494 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5497 * Add a new group to the database.
5499 * @param string $name Group name
5500 * @param int $uid User ID
5501 * @param array $users List of users to add to the group
5504 * @throws BadRequestException
5506 function group_create($name, $uid, $users = [])
5508 // error if no name specified
5510 throw new BadRequestException('group name not specified');
5513 // get data of the specified group name
5515 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5519 // error message if specified group name already exists
5520 if (DBA::isResult($rname)) {
5521 throw new BadRequestException('group name already exists');
5524 // check if specified group name is a deleted group
5526 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5530 // error message if specified group name already exists
5531 if (DBA::isResult($rname)) {
5532 $reactivate_group = true;
5536 $ret = Group::create($uid, $name);
5538 $gid = Group::getIdByName($uid, $name);
5540 throw new BadRequestException('other API error');
5544 $erroraddinguser = false;
5546 foreach ($users as $user) {
5547 $cid = $user['cid'];
5548 // check if user really exists as contact
5550 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5554 if (count($contact)) {
5555 Group::addMember($gid, $cid);
5557 $erroraddinguser = true;
5558 $errorusers[] = $cid;
5562 // return success message incl. missing users in array
5563 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5565 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5569 * Create the specified group with the posted array of contacts.
5571 * @param string $type Return type (atom, rss, xml, json)
5573 * @return array|string
5574 * @throws BadRequestException
5575 * @throws ForbiddenException
5576 * @throws ImagickException
5577 * @throws InternalServerErrorException
5578 * @throws UnauthorizedException
5580 function api_friendica_group_create($type)
5584 if (api_user() === false) {
5585 throw new ForbiddenException();
5589 $user_info = api_get_user($a);
5590 $name = $_REQUEST['name'] ?? '';
5591 $uid = $user_info['uid'];
5592 $json = json_decode($_POST['json'], true);
5593 $users = $json['user'];
5595 $success = group_create($name, $uid, $users);
5597 return api_format_data("group_create", $type, ['result' => $success]);
5599 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5602 * Create a new group.
5604 * @param string $type Return type (atom, rss, xml, json)
5606 * @return array|string
5607 * @throws BadRequestException
5608 * @throws ForbiddenException
5609 * @throws ImagickException
5610 * @throws InternalServerErrorException
5611 * @throws UnauthorizedException
5612 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5614 function api_lists_create($type)
5618 if (api_user() === false) {
5619 throw new ForbiddenException();
5623 $user_info = api_get_user($a);
5624 $name = $_REQUEST['name'] ?? '';
5625 $uid = $user_info['uid'];
5627 $success = group_create($name, $uid);
5628 if ($success['success']) {
5630 'name' => $success['name'],
5631 'id' => intval($success['gid']),
5632 'id_str' => (string) $success['gid'],
5633 'user' => $user_info
5636 return api_format_data("lists", $type, ['lists'=>$grp]);
5639 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5642 * Update the specified group with the posted array of contacts.
5644 * @param string $type Return type (atom, rss, xml, json)
5646 * @return array|string
5647 * @throws BadRequestException
5648 * @throws ForbiddenException
5649 * @throws ImagickException
5650 * @throws InternalServerErrorException
5651 * @throws UnauthorizedException
5653 function api_friendica_group_update($type)
5657 if (api_user() === false) {
5658 throw new ForbiddenException();
5662 $user_info = api_get_user($a);
5663 $uid = $user_info['uid'];
5664 $gid = $_REQUEST['gid'] ?? 0;
5665 $name = $_REQUEST['name'] ?? '';
5666 $json = json_decode($_POST['json'], true);
5667 $users = $json['user'];
5669 // error if no name specified
5671 throw new BadRequestException('group name not specified');
5674 // error if no gid specified
5676 throw new BadRequestException('gid not specified');
5680 $members = Contact\Group::getById($gid);
5681 foreach ($members as $member) {
5682 $cid = $member['id'];
5683 foreach ($users as $user) {
5684 $found = ($user['cid'] == $cid ? true : false);
5686 if (!isset($found) || !$found) {
5687 Group::removeMemberByName($uid, $name, $cid);
5692 $erroraddinguser = false;
5694 foreach ($users as $user) {
5695 $cid = $user['cid'];
5696 // check if user really exists as contact
5698 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5703 if (count($contact)) {
5704 Group::addMember($gid, $cid);
5706 $erroraddinguser = true;
5707 $errorusers[] = $cid;
5711 // return success message incl. missing users in array
5712 $status = ($erroraddinguser ? "missing user" : "ok");
5713 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5714 return api_format_data("group_update", $type, ['result' => $success]);
5717 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5720 * Update information about a group.
5722 * @param string $type Return type (atom, rss, xml, json)
5724 * @return array|string
5725 * @throws BadRequestException
5726 * @throws ForbiddenException
5727 * @throws ImagickException
5728 * @throws InternalServerErrorException
5729 * @throws UnauthorizedException
5730 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5732 function api_lists_update($type)
5736 if (api_user() === false) {
5737 throw new ForbiddenException();
5741 $user_info = api_get_user($a);
5742 $gid = $_REQUEST['list_id'] ?? 0;
5743 $name = $_REQUEST['name'] ?? '';
5744 $uid = $user_info['uid'];
5746 // error if no gid specified
5748 throw new BadRequestException('gid not specified');
5751 // get data of the specified group id
5752 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5753 // error message if specified gid is not in database
5755 throw new BadRequestException('gid not available');
5758 if (Group::update($gid, $name)) {
5761 'id' => intval($gid),
5762 'id_str' => (string) $gid,
5763 'user' => $user_info
5766 return api_format_data("lists", $type, ['lists' => $list]);
5770 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5774 * @param string $type Return type (atom, rss, xml, json)
5776 * @return array|string
5777 * @throws BadRequestException
5778 * @throws ForbiddenException
5779 * @throws ImagickException
5780 * @throws InternalServerErrorException
5782 function api_friendica_activity($type)
5786 if (api_user() === false) {
5787 throw new ForbiddenException();
5789 $verb = strtolower($a->argv[3]);
5790 $verb = preg_replace("|\..*$|", "", $verb);
5792 $id = $_REQUEST['id'] ?? 0;
5794 $res = Item::performActivity($id, $verb, api_user());
5797 if ($type == "xml") {
5802 return api_format_data('ok', $type, ['ok' => $ok]);
5804 throw new BadRequestException('Error adding activity');
5808 /// @TODO move to top of file or somewhere better
5809 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5810 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5811 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5812 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5813 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5814 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5815 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5816 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5817 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5818 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5821 * Returns notifications
5823 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5825 * @return string|array
5826 * @throws ForbiddenException
5827 * @throws BadRequestException
5830 function api_friendica_notification($type)
5834 if (api_user() === false) {
5835 throw new ForbiddenException();
5838 throw new BadRequestException("Invalid argument count");
5841 $notifications = DI::notification()->getApiList(local_user());
5843 if ($type == "xml") {
5845 if (!empty($notifications)) {
5846 foreach ($notifications as $notification) {
5847 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5851 $result = $xmlnotes;
5852 } elseif (count($notifications) > 0) {
5853 $result = $notifications->getArrayCopy();
5858 return api_format_data("notes", $type, ['note' => $result]);
5862 * Set notification as seen and returns associated item (if possible)
5864 * POST request with 'id' param as notification id
5866 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5867 * @return string|array
5868 * @throws BadRequestException
5869 * @throws ForbiddenException
5870 * @throws ImagickException
5871 * @throws InternalServerErrorException
5872 * @throws UnauthorizedException
5874 function api_friendica_notification_seen($type)
5877 $user_info = api_get_user($a);
5879 if (api_user() === false || $user_info === false) {
5880 throw new ForbiddenException();
5882 if ($a->argc !== 4) {
5883 throw new BadRequestException("Invalid argument count");
5886 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5889 $notify = DI::notify()->getByID($id, api_user());
5890 DI::notify()->setSeen(true, $notify);
5892 if ($notify->otype === Notification\ObjectType::ITEM) {
5893 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5894 if (DBA::isResult($item)) {
5895 // we found the item, return it to the user
5896 $ret = api_format_items([$item], $user_info, false, $type);
5897 $data = ['status' => $ret];
5898 return api_format_data("status", $type, $data);
5900 // the item can't be found, but we set the notification as seen, so we count this as a success
5902 return api_format_data('result', $type, ['result' => "success"]);
5903 } catch (NotFoundException $e) {
5904 throw new BadRequestException('Invalid argument', $e);
5905 } catch (Exception $e) {
5906 throw new InternalServerErrorException('Internal Server exception', $e);
5910 /// @TODO move to top of file or somewhere better
5911 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5912 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5915 * update a direct_message to seen state
5917 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5918 * @return string|array (success result=ok, error result=error with error message)
5919 * @throws BadRequestException
5920 * @throws ForbiddenException
5921 * @throws ImagickException
5922 * @throws InternalServerErrorException
5923 * @throws UnauthorizedException
5925 function api_friendica_direct_messages_setseen($type)
5928 if (api_user() === false) {
5929 throw new ForbiddenException();
5933 $user_info = api_get_user($a);
5934 $uid = $user_info['uid'];
5935 $id = $_REQUEST['id'] ?? 0;
5937 // return error if id is zero
5939 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5940 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5943 // error message if specified id is not in database
5944 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5945 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5946 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5949 // update seen indicator
5950 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5954 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5955 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5957 $answer = ['result' => 'error', 'message' => 'unknown error'];
5958 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5962 /// @TODO move to top of file or somewhere better
5963 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5966 * search for direct_messages containing a searchstring through api
5968 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5969 * @param string $box
5970 * @return string|array (success: success=true if found and search_result contains found messages,
5971 * success=false if nothing was found, search_result='nothing found',
5972 * error: result=error with error message)
5973 * @throws BadRequestException
5974 * @throws ForbiddenException
5975 * @throws ImagickException
5976 * @throws InternalServerErrorException
5977 * @throws UnauthorizedException
5979 function api_friendica_direct_messages_search($type, $box = "")
5983 if (api_user() === false) {
5984 throw new ForbiddenException();
5988 $user_info = api_get_user($a);
5989 $searchstring = $_REQUEST['searchstring'] ?? '';
5990 $uid = $user_info['uid'];
5992 // error if no searchstring specified
5993 if ($searchstring == "") {
5994 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5995 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5998 // get data for the specified searchstring
6000 "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",
6002 DBA::escape('%'.$searchstring.'%')
6005 $profile_url = $user_info["url"];
6007 // message if nothing was found
6008 if (!DBA::isResult($r)) {
6009 $success = ['success' => false, 'search_results' => 'problem with query'];
6010 } elseif (count($r) == 0) {
6011 $success = ['success' => false, 'search_results' => 'nothing found'];
6014 foreach ($r as $item) {
6015 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6016 $recipient = $user_info;
6017 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6018 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6019 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6020 $sender = $user_info;
6023 if (isset($recipient) && isset($sender)) {
6024 $ret[] = api_format_messages($item, $recipient, $sender);
6027 $success = ['success' => true, 'search_results' => $ret];
6030 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6033 /// @TODO move to top of file or somewhere better
6034 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6037 * Returns a list of saved searches.
6039 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6041 * @param string $type Return format: json or xml
6043 * @return string|array
6046 function api_saved_searches_list($type)
6048 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6051 while ($term = DBA::fetch($terms)) {
6053 'created_at' => api_date(time()),
6054 'id' => intval($term['id']),
6055 'id_str' => $term['id'],
6056 'name' => $term['term'],
6058 'query' => $term['term']
6064 return api_format_data("terms", $type, ['terms' => $result]);
6067 /// @TODO move to top of file or somewhere better
6068 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6071 * Number of comments
6073 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6075 * @param object $data [Status, Status]
6079 function bindComments(&$data)
6081 if (count($data) == 0) {
6087 foreach ($data as $item) {
6088 $ids[] = $item['id'];
6091 $idStr = DBA::escape(implode(', ', $ids));
6092 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6093 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6094 $itemsData = DBA::toArray($items);
6096 foreach ($itemsData as $item) {
6097 $comments[$item['parent']] = $item['comments'];
6100 foreach ($data as $idx => $item) {
6102 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6107 @TODO Maybe open to implement?
6109 [pagename] => api/1.1/statuses/lookup.json
6110 [id] => 605138389168451584
6111 [include_cards] => true
6112 [cards_platform] => Android-12
6113 [include_entities] => true
6114 [include_my_retweet] => 1
6116 [include_reply_count] => true
6117 [include_descendent_reply_count] => true
6121 Not implemented by now:
6122 statuses/retweets_of_me
6127 account/update_location
6128 account/update_profile_background_image
6131 friendica/profile/update
6132 friendica/profile/create
6133 friendica/profile/delete
6135 Not implemented in status.net:
6136 statuses/retweeted_to_me
6137 statuses/retweeted_by_me
6138 direct_messages/destroy
6140 account/update_delivery_device
6141 notifications/follow