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\Profile;
46 use Friendica\Model\User;
47 use Friendica\Model\Verb;
48 use Friendica\Network\HTTPException;
49 use Friendica\Network\HTTPException\BadRequestException;
50 use Friendica\Network\HTTPException\ExpectationFailedException;
51 use Friendica\Network\HTTPException\ForbiddenException;
52 use Friendica\Network\HTTPException\InternalServerErrorException;
53 use Friendica\Network\HTTPException\MethodNotAllowedException;
54 use Friendica\Network\HTTPException\NotFoundException;
55 use Friendica\Network\HTTPException\TooManyRequestsException;
56 use Friendica\Network\HTTPException\UnauthorizedException;
57 use Friendica\Object\Image;
58 use Friendica\Protocol\Activity;
59 use Friendica\Protocol\Diaspora;
60 use Friendica\Security\FKOAuth1;
61 use Friendica\Security\OAuth;
62 use Friendica\Security\OAuth1\OAuthRequest;
63 use Friendica\Security\OAuth1\OAuthUtil;
64 use Friendica\Util\DateTimeFormat;
65 use Friendica\Util\Images;
66 use Friendica\Util\Network;
67 use Friendica\Util\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 * @throws ForbiddenException
185 * @throws InternalServerErrorException
186 * @throws UnauthorizedException
187 * @hook 'authenticate'
189 * 'username' => username from login form
190 * 'password' => password from login form
191 * 'authenticated' => return status,
192 * 'user_record' => return authenticated user record
194 function api_login(App $a)
196 $_SESSION["allow_api"] = false;
198 // workaround for HTTP-auth in CGI mode
199 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
200 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
201 if (strlen($userpass)) {
202 list($name, $password) = explode(':', $userpass);
203 $_SERVER['PHP_AUTH_USER'] = $name;
204 $_SERVER['PHP_AUTH_PW'] = $password;
208 if (empty($_SERVER['PHP_AUTH_USER'])) {
209 // Try OAuth when no user is provided
210 $oauth1 = new FKOAuth1();
213 $request = OAuthRequest::from_request();
214 list($consumer, $token) = $oauth1->verify_request($request);
215 if (!is_null($token)) {
216 $oauth1->loginUser($token->uid);
217 Session::set('allow_api', true);
220 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
221 var_dump($consumer, $token);
223 } catch (Exception $e) {
224 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
227 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
228 header('WWW-Authenticate: Basic realm="Friendica"');
229 throw new UnauthorizedException("This API requires login");
232 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
233 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
235 // allow "user@server" login (but ignore 'server' part)
236 $at = strstr($user, "@", true);
241 // next code from mod/auth.php. needs better solution
245 'username' => trim($user),
246 'password' => trim($password),
247 'authenticated' => 0,
248 'user_record' => null,
252 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
253 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
254 * and later addons should not interfere with an earlier one that succeeded.
256 Hook::callAll('authenticate', $addon_auth);
258 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
259 $record = $addon_auth['user_record'];
261 $user_id = User::authenticate(trim($user), trim($password), true);
262 if ($user_id !== false) {
263 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
267 if (!DBA::isResult($record)) {
268 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
269 header('WWW-Authenticate: Basic realm="Friendica"');
270 //header('HTTP/1.0 401 Unauthorized');
271 //die('This api requires login');
272 throw new UnauthorizedException("This API requires login");
275 // Don't refresh the login date more often than twice a day to spare database writes
276 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
278 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
280 $_SESSION["allow_api"] = true;
282 Hook::callAll('logged_in', $a->user);
286 * Check HTTP method of called API
288 * API endpoints can define which HTTP method to accept when called.
289 * This function check the current HTTP method agains endpoint
292 * @param string $method Required methods, uppercase, separated by comma
295 function api_check_method($method)
297 if ($method == "*") {
300 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
304 * Main API entry point
306 * Authenticate user, call registered API function, set HTTP headers
309 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
310 * @return string|array API call result
313 function api_call(App $a, App\Arguments $args = null)
315 global $API, $called_api;
322 if (strpos($args->getCommand(), ".xml") > 0) {
325 if (strpos($args->getCommand(), ".json") > 0) {
328 if (strpos($args->getCommand(), ".rss") > 0) {
331 if (strpos($args->getCommand(), ".atom") > 0) {
336 foreach ($API as $p => $info) {
337 if (strpos($args->getCommand(), $p) === 0) {
338 if (!api_check_method($info['method'])) {
339 throw new MethodNotAllowedException();
342 $called_api = explode("/", $p);
344 if (!empty($info['auth']) && api_user() === false) {
346 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
349 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
351 $stamp = microtime(true);
352 $return = call_user_func($info['func'], $type);
353 $duration = floatval(microtime(true) - $stamp);
355 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
357 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
359 if (false === $return) {
361 * api function returned false withour throw an
362 * exception. This should not happend, throw a 500
364 throw new InternalServerErrorException();
369 header("Content-Type: text/xml");
372 header("Content-Type: application/json");
373 if (!empty($return)) {
374 $json = json_encode(end($return));
375 if (!empty($_GET['callback'])) {
376 $json = $_GET['callback'] . "(" . $json . ")";
382 header("Content-Type: application/rss+xml");
383 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
386 header("Content-Type: application/atom+xml");
387 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
394 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
395 throw new NotFoundException();
396 } catch (HTTPException $e) {
397 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
398 return api_error($type, $e, $args);
403 * Format API error string
405 * @param string $type Return type (xml, json, rss, as)
406 * @param object $e HTTPException Error object
407 * @param App\Arguments $args The App arguments
408 * @return string|array error message formatted as $type
410 function api_error($type, $e, App\Arguments $args)
412 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
413 /// @TODO: https://dev.twitter.com/overview/api/response-codes
415 $error = ["error" => $error,
416 "code" => $e->getCode() . " " . $e->httpdesc,
417 "request" => $args->getQueryString()];
419 $return = api_format_data('status', $type, ['status' => $error]);
423 header("Content-Type: text/xml");
426 header("Content-Type: application/json");
427 $return = json_encode($return);
430 header("Content-Type: application/rss+xml");
433 header("Content-Type: application/atom+xml");
441 * Set values for RSS template
444 * @param array $arr Array to be passed to template
445 * @param array $user_info User info
447 * @throws BadRequestException
448 * @throws ImagickException
449 * @throws InternalServerErrorException
450 * @throws UnauthorizedException
451 * @todo find proper type-hints
453 function api_rss_extra(App $a, $arr, $user_info)
455 if (is_null($user_info)) {
456 $user_info = api_get_user($a);
459 $arr['$user'] = $user_info;
461 'alternate' => $user_info['url'],
462 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
463 'base' => DI::baseUrl(),
464 'updated' => api_date(null),
465 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
466 'language' => $user_info['lang'],
467 'logo' => DI::baseUrl() . "/images/friendica-32.png",
475 * Unique contact to contact url.
477 * @param int $id Contact id
478 * @return bool|string
479 * Contact url or False if contact id is unknown
482 function api_unique_id_to_nurl($id)
484 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
486 if (DBA::isResult($r)) {
494 * Get user info array.
497 * @param int|string $contact_id Contact ID or URL
499 * @throws BadRequestException
500 * @throws ImagickException
501 * @throws InternalServerErrorException
502 * @throws UnauthorizedException
504 function api_get_user(App $a, $contact_id = null)
512 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
514 // Searching for contact URL
515 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
516 $user = DBA::escape(Strings::normaliseLink($contact_id));
518 $extra_query = "AND `contact`.`nurl` = '%s' ";
519 if (api_user() !== false) {
520 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
524 // Searching for contact id with uid = 0
525 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
526 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
529 throw new BadRequestException("User ID ".$contact_id." not found.");
533 $extra_query = "AND `contact`.`nurl` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
539 if (is_null($user) && !empty($_GET['user_id'])) {
540 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
543 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
547 $extra_query = "AND `contact`.`nurl` = '%s' ";
548 if (api_user() !== false) {
549 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
552 if (is_null($user) && !empty($_GET['screen_name'])) {
553 $user = DBA::escape($_GET['screen_name']);
554 $extra_query = "AND `contact`.`nick` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
560 if (is_null($user) && !empty($_GET['profileurl'])) {
561 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
562 $extra_query = "AND `contact`.`nurl` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
568 // $called_api is the API path exploded on / and is expected to have at least 2 elements
569 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
570 $argid = count($called_api);
571 if (!empty($a->argv[$argid])) {
572 $data = explode(".", $a->argv[$argid]);
573 if (count($data) > 1) {
574 list($user, $null) = $data;
577 if (is_numeric($user)) {
578 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
582 $extra_query = "AND `contact`.`nurl` = '%s' ";
583 if (api_user() !== false) {
584 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
588 $user = DBA::escape($user);
589 $extra_query = "AND `contact`.`nick` = '%s' ";
590 if (api_user() !== false) {
591 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
596 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
599 if (api_user() === false) {
604 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
608 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
612 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
618 // Selecting the id by priority, friendica first
619 if (is_array($uinfo)) {
620 api_best_nickname($uinfo);
623 // if the contact wasn't found, fetch it from the contacts with uid = 0
624 if (!DBA::isResult($uinfo)) {
626 throw new BadRequestException("User not found.");
629 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
631 if (DBA::isResult($contact)) {
633 'id' => $contact["id"],
634 'id_str' => (string) $contact["id"],
635 'name' => $contact["name"],
636 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
637 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
638 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
639 'profile_image_url' => $contact["micro"],
640 'profile_image_url_https' => $contact["micro"],
641 'profile_image_url_profile_size' => $contact["thumb"],
642 'profile_image_url_large' => $contact["photo"],
643 'url' => $contact["url"],
644 'protected' => false,
645 'followers_count' => 0,
646 'friends_count' => 0,
648 'created_at' => api_date($contact["created"]),
649 'favourites_count' => 0,
651 'time_zone' => 'UTC',
652 'geo_enabled' => false,
654 'statuses_count' => 0,
656 'contributors_enabled' => false,
657 'is_translator' => false,
658 'is_translation_enabled' => false,
659 'following' => false,
660 'follow_request_sent' => false,
661 'statusnet_blocking' => false,
662 'notifications' => false,
663 'statusnet_profile_url' => $contact["url"],
665 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
666 'pid' => Contact::getIdForURL($contact["url"], 0, false),
668 'network' => $contact["network"],
673 throw new BadRequestException("User ".$url." not found.");
677 if ($uinfo[0]['self']) {
678 if ($uinfo[0]['network'] == "") {
679 $uinfo[0]['network'] = Protocol::DFRN;
682 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
683 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
690 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
692 if (!empty($profile['about'])) {
693 $description = $profile['about'];
695 $description = $uinfo[0]["about"];
698 if (!empty($usr['default-location'])) {
699 $location = $usr['default-location'];
700 } elseif (!empty($uinfo[0]["location"])) {
701 $location = $uinfo[0]["location"];
703 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
707 'id' => intval($pcontact_id),
708 'id_str' => (string) intval($pcontact_id),
709 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
710 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
711 'location' => $location,
712 'description' => BBCode::toPlaintext($description ?? ''),
713 'profile_image_url' => $uinfo[0]['micro'],
714 'profile_image_url_https' => $uinfo[0]['micro'],
715 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
716 'profile_image_url_large' => $uinfo[0]["photo"],
717 'url' => $uinfo[0]['url'],
718 'protected' => false,
719 'followers_count' => intval($countfollowers),
720 'friends_count' => intval($countfriends),
722 'created_at' => api_date($uinfo[0]['created']),
723 'favourites_count' => intval($starred),
725 'time_zone' => 'UTC',
726 'geo_enabled' => false,
728 'statuses_count' => intval($countitems),
730 'contributors_enabled' => false,
731 'is_translator' => false,
732 'is_translation_enabled' => false,
733 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
734 'follow_request_sent' => false,
735 'statusnet_blocking' => false,
736 'notifications' => false,
738 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
739 'statusnet_profile_url' => $uinfo[0]['url'],
740 'uid' => intval($uinfo[0]['uid']),
741 'cid' => intval($uinfo[0]['cid']),
742 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
743 'self' => $uinfo[0]['self'],
744 'network' => $uinfo[0]['network'],
747 // If this is a local user and it uses Frio, we can get its color preferences.
749 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
750 if ($theme_info['theme'] === 'frio') {
751 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
753 if ($schema && ($schema != '---')) {
754 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
755 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
756 require_once $schemefile;
759 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
760 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
761 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
763 if (empty($nav_bg)) {
766 if (empty($link_color)) {
767 $link_color = "#6fdbe8";
769 if (empty($bgcolor)) {
770 $bgcolor = "#ededed";
773 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
774 $ret['profile_link_color'] = str_replace('#', '', $link_color);
775 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
783 * return api-formatted array for item's author and owner
786 * @param array $item item from db
787 * @return array(array:author, array:owner)
788 * @throws BadRequestException
789 * @throws ImagickException
790 * @throws InternalServerErrorException
791 * @throws UnauthorizedException
793 function api_item_get_user(App $a, $item)
795 $status_user = api_get_user($a, $item['author-id'] ?? null);
797 $author_user = $status_user;
799 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
801 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
802 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
804 $owner_user = $author_user;
807 return ([$status_user, $author_user, $owner_user]);
811 * walks recursively through an array with the possibility to change value and key
813 * @param array $array The array to walk through
814 * @param callable $callback The callback function
816 * @return array the transformed array
818 function api_walk_recursive(array &$array, callable $callback)
822 foreach ($array as $k => $v) {
824 if ($callback($v, $k)) {
825 $new_array[$k] = api_walk_recursive($v, $callback);
828 if ($callback($v, $k)) {
839 * Callback function to transform the array in an array that can be transformed in a XML file
841 * @param mixed $item Array item value
842 * @param string $key Array key
844 * @return boolean Should the array item be deleted?
846 function api_reformat_xml(&$item, &$key)
848 if (is_bool($item)) {
849 $item = ($item ? "true" : "false");
852 if (substr($key, 0, 10) == "statusnet_") {
853 $key = "statusnet:".substr($key, 10);
854 } elseif (substr($key, 0, 10) == "friendica_") {
855 $key = "friendica:".substr($key, 10);
857 /// @TODO old-lost code?
859 // $key = "default:".$key;
865 * Creates the XML from a JSON style array
867 * @param array $data JSON style array
868 * @param string $root_element Name of the root element
870 * @return string The XML data
872 function api_create_xml(array $data, $root_element)
874 $childname = key($data);
875 $data2 = array_pop($data);
877 $namespaces = ["" => "http://api.twitter.com",
878 "statusnet" => "http://status.net/schema/api/1/",
879 "friendica" => "http://friendi.ca/schema/api/1/",
880 "georss" => "http://www.georss.org/georss"];
882 /// @todo Auto detection of needed namespaces
883 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
887 if (is_array($data2)) {
889 api_walk_recursive($data2, "api_reformat_xml");
895 foreach ($data2 as $item) {
896 $data4[$i++ . ":" . $childname] = $item;
903 $data3 = [$root_element => $data2];
905 $ret = XML::fromArray($data3, $xml, false, $namespaces);
910 * Formats the data according to the data type
912 * @param string $root_element Name of the root element
913 * @param string $type Return type (atom, rss, xml, json)
914 * @param array $data JSON style array
916 * @return array|string (string|array) XML data or JSON data
918 function api_format_data($root_element, $type, $data)
924 $ret = api_create_xml($data, $root_element);
939 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
940 * returns a 401 status code and an error message if not.
942 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
944 * @param string $type Return type (atom, rss, xml, json)
945 * @return array|string
946 * @throws BadRequestException
947 * @throws ForbiddenException
948 * @throws ImagickException
949 * @throws InternalServerErrorException
950 * @throws UnauthorizedException
952 function api_account_verify_credentials($type)
956 if (api_user() === false) {
957 throw new ForbiddenException();
960 unset($_REQUEST["user_id"]);
961 unset($_GET["user_id"]);
963 unset($_REQUEST["screen_name"]);
964 unset($_GET["screen_name"]);
966 $skip_status = $_REQUEST['skip_status'] ?? false;
968 $user_info = api_get_user($a);
970 // "verified" isn't used here in the standard
971 unset($user_info["verified"]);
973 // - Adding last status
975 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
977 $user_info['status'] = api_format_item($item, $type);
981 // "uid" and "self" are only needed for some internal stuff, so remove it from here
982 unset($user_info["uid"]);
983 unset($user_info["self"]);
985 return api_format_data("user", $type, ['user' => $user_info]);
988 /// @TODO move to top of file or somewhere better
989 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
992 * Get data from $_POST or $_GET
997 function requestdata($k)
999 if (!empty($_POST[$k])) {
1002 if (!empty($_GET[$k])) {
1009 * Deprecated function to upload media.
1011 * @param string $type Return type (atom, rss, xml, json)
1013 * @return array|string
1014 * @throws BadRequestException
1015 * @throws ForbiddenException
1016 * @throws ImagickException
1017 * @throws InternalServerErrorException
1018 * @throws UnauthorizedException
1020 function api_statuses_mediap($type)
1024 if (api_user() === false) {
1025 Logger::log('api_statuses_update: no user');
1026 throw new ForbiddenException();
1028 $user_info = api_get_user($a);
1030 $_REQUEST['profile_uid'] = api_user();
1031 $_REQUEST['api_source'] = true;
1032 $txt = requestdata('status') ?? '';
1033 /// @TODO old-lost code?
1034 //$txt = urldecode(requestdata('status'));
1036 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1037 $txt = HTML::toBBCodeVideo($txt);
1038 $config = HTMLPurifier_Config::createDefault();
1039 $config->set('Cache.DefinitionImpl', null);
1040 $purifier = new HTMLPurifier($config);
1041 $txt = $purifier->purify($txt);
1043 $txt = HTML::toBBCode($txt);
1045 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1047 $picture = wall_upload_post($a, false);
1049 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1050 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1051 $item_id = item_post($a);
1053 // output the post that we just posted.
1054 return api_status_show($type, $item_id);
1057 /// @TODO move this to top of file or somewhere better!
1058 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1061 * Updates the user’s current status.
1063 * @param string $type Return type (atom, rss, xml, json)
1065 * @return array|string
1066 * @throws BadRequestException
1067 * @throws ForbiddenException
1068 * @throws ImagickException
1069 * @throws InternalServerErrorException
1070 * @throws TooManyRequestsException
1071 * @throws UnauthorizedException
1072 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1074 function api_statuses_update($type)
1078 if (api_user() === false) {
1079 Logger::log('api_statuses_update: no user');
1080 throw new ForbiddenException();
1085 // convert $_POST array items to the form we use for web posts.
1086 if (requestdata('htmlstatus')) {
1087 $txt = requestdata('htmlstatus') ?? '';
1088 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1089 $txt = HTML::toBBCodeVideo($txt);
1091 $config = HTMLPurifier_Config::createDefault();
1092 $config->set('Cache.DefinitionImpl', null);
1094 $purifier = new HTMLPurifier($config);
1095 $txt = $purifier->purify($txt);
1097 $_REQUEST['body'] = HTML::toBBCode($txt);
1100 $_REQUEST['body'] = requestdata('status');
1103 $_REQUEST['title'] = requestdata('title');
1105 $parent = requestdata('in_reply_to_status_id');
1107 // Twidere sends "-1" if it is no reply ...
1108 if ($parent == -1) {
1112 if (ctype_digit($parent)) {
1113 $_REQUEST['parent'] = $parent;
1115 $_REQUEST['parent_uri'] = $parent;
1118 if (requestdata('lat') && requestdata('long')) {
1119 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1121 $_REQUEST['profile_uid'] = api_user();
1124 // Check for throttling (maximum posts per day, week and month)
1125 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1126 if ($throttle_day > 0) {
1127 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1129 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1130 $posts_day = Post::count($condition);
1132 if ($posts_day > $throttle_day) {
1133 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1134 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1135 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));
1139 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1140 if ($throttle_week > 0) {
1141 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1143 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1144 $posts_week = Post::count($condition);
1146 if ($posts_week > $throttle_week) {
1147 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1148 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1149 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));
1153 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1154 if ($throttle_month > 0) {
1155 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1157 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1158 $posts_month = Post::count($condition);
1160 if ($posts_month > $throttle_month) {
1161 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1162 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1163 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));
1168 if (requestdata('media_ids')) {
1169 $ids = explode(',', requestdata('media_ids') ?? '');
1170 } elseif (!empty($_FILES['media'])) {
1171 // upload the image if we have one
1172 $picture = wall_upload_post($a, false);
1173 if (is_array($picture)) {
1174 $ids[] = $picture['id'];
1182 foreach ($ids as $id) {
1183 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1184 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1185 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1186 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1188 if (!empty($media)) {
1189 $ressources[] = $media[0]['resource-id'];
1190 $phototypes = Images::supportedTypes();
1191 $ext = $phototypes[$media[0]['type']];
1193 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1194 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1195 'size' => $media[0]['datasize'],
1196 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1197 'description' => $media[0]['desc'] ?? '',
1198 'width' => $media[0]['width'],
1199 'height' => $media[0]['height']];
1201 if (count($media) > 1) {
1202 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1203 $attachment['preview-width'] = $media[1]['width'];
1204 $attachment['preview-height'] = $media[1]['height'];
1206 $attachments[] = $attachment;
1210 // We have to avoid that the post is rejected because of an empty body
1211 if (empty($_REQUEST['body'])) {
1212 $_REQUEST['body'] = '[hr]';
1216 if (!empty($attachments)) {
1217 $_REQUEST['attachments'] = $attachments;
1220 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1222 $_REQUEST['api_source'] = true;
1224 if (empty($_REQUEST['source'])) {
1225 $_REQUEST["source"] = api_source();
1228 // call out normal post function
1229 $item_id = item_post($a);
1231 if (!empty($ressources) && !empty($item_id)) {
1232 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1233 foreach ($ressources as $ressource) {
1234 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1238 // output the post that we just posted.
1239 return api_status_show($type, $item_id);
1242 /// @TODO move to top of file or somewhere better
1243 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1244 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1247 * Uploads an image to Friendica.
1250 * @throws BadRequestException
1251 * @throws ForbiddenException
1252 * @throws ImagickException
1253 * @throws InternalServerErrorException
1254 * @throws UnauthorizedException
1255 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1257 function api_media_upload()
1261 if (api_user() === false) {
1262 Logger::log('no user');
1263 throw new ForbiddenException();
1268 if (empty($_FILES['media'])) {
1270 throw new BadRequestException("No media.");
1273 $media = wall_upload_post($a, false);
1276 throw new InternalServerErrorException();
1280 $returndata["media_id"] = $media["id"];
1281 $returndata["media_id_string"] = (string)$media["id"];
1282 $returndata["size"] = $media["size"];
1283 $returndata["image"] = ["w" => $media["width"],
1284 "h" => $media["height"],
1285 "image_type" => $media["type"],
1286 "friendica_preview_url" => $media["preview"]];
1288 Logger::info('Media uploaded', ['return' => $returndata]);
1290 return ["media" => $returndata];
1293 /// @TODO move to top of file or somewhere better
1294 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1297 * Updates media meta data (picture descriptions)
1299 * @param string $type Return type (atom, rss, xml, json)
1301 * @return array|string
1302 * @throws BadRequestException
1303 * @throws ForbiddenException
1304 * @throws ImagickException
1305 * @throws InternalServerErrorException
1306 * @throws TooManyRequestsException
1307 * @throws UnauthorizedException
1308 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1310 * @todo Compare the corresponding Twitter function for correct return values
1312 function api_media_metadata_create($type)
1316 if (api_user() === false) {
1317 Logger::info('no user');
1318 throw new ForbiddenException();
1323 $postdata = Network::postdata();
1325 if (empty($postdata)) {
1326 throw new BadRequestException("No post data");
1329 $data = json_decode($postdata, true);
1331 throw new BadRequestException("Invalid post data");
1334 if (empty($data['media_id']) || empty($data['alt_text'])) {
1335 throw new BadRequestException("Missing post data values");
1338 if (empty($data['alt_text']['text'])) {
1339 throw new BadRequestException("No alt text.");
1342 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1344 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1345 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1346 if (!DBA::isResult($photo)) {
1347 throw new BadRequestException("Metadata not found.");
1350 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1353 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1356 * @param string $type Return format (atom, rss, xml, json)
1357 * @param int $item_id
1358 * @return array|string
1361 function api_status_show($type, $item_id)
1363 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1367 $item = api_get_item(['id' => $item_id]);
1368 if (!empty($item)) {
1369 $status_info = api_format_item($item, $type);
1372 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1374 return api_format_data('statuses', $type, ['status' => $status_info]);
1378 * Retrieves the last public status of the provided user info
1380 * @param int $ownerId Public contact Id
1381 * @param int $uid User Id
1385 function api_get_last_status($ownerId, $uid)
1388 'author-id'=> $ownerId,
1390 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1391 'private' => [Item::PUBLIC, Item::UNLISTED]
1394 $item = api_get_item($condition);
1400 * Retrieves a single item record based on the provided condition and converts it for API use.
1402 * @param array $condition Item table condition array
1406 function api_get_item(array $condition)
1408 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1414 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1415 * The author's most recent status will be returned inline.
1417 * @param string $type Return type (atom, rss, xml, json)
1418 * @return array|string
1419 * @throws BadRequestException
1420 * @throws ImagickException
1421 * @throws InternalServerErrorException
1422 * @throws UnauthorizedException
1423 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1425 function api_users_show($type)
1427 $a = Friendica\DI::app();
1429 $user_info = api_get_user($a);
1431 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1432 if (!empty($item)) {
1433 $user_info['status'] = api_format_item($item, $type);
1436 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1437 unset($user_info['uid']);
1438 unset($user_info['self']);
1440 return api_format_data('user', $type, ['user' => $user_info]);
1443 /// @TODO move to top of file or somewhere better
1444 api_register_func('api/users/show', 'api_users_show');
1445 api_register_func('api/externalprofile/show', 'api_users_show');
1448 * Search a public user account.
1450 * @param string $type Return type (atom, rss, xml, json)
1452 * @return array|string
1453 * @throws BadRequestException
1454 * @throws ImagickException
1455 * @throws InternalServerErrorException
1456 * @throws UnauthorizedException
1457 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1459 function api_users_search($type)
1465 if (!empty($_GET['q'])) {
1466 $contacts = Contact::selectToArray(
1469 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1477 if (DBA::isResult($contacts)) {
1479 foreach ($contacts as $contact) {
1480 $user_info = api_get_user($a, $contact['id']);
1482 if ($type == 'xml') {
1483 $userlist[$k++ . ':user'] = $user_info;
1485 $userlist[] = $user_info;
1488 $userlist = ['users' => $userlist];
1490 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1493 throw new BadRequestException('No search term specified.');
1496 return api_format_data('users', $type, $userlist);
1499 /// @TODO move to top of file or somewhere better
1500 api_register_func('api/users/search', 'api_users_search');
1503 * Return user objects
1505 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1507 * @param string $type Return format: json or xml
1509 * @return array|string
1510 * @throws BadRequestException
1511 * @throws ImagickException
1512 * @throws InternalServerErrorException
1513 * @throws NotFoundException if the results are empty.
1514 * @throws UnauthorizedException
1516 function api_users_lookup($type)
1520 if (!empty($_REQUEST['user_id'])) {
1521 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1523 $users[] = api_get_user(DI::app(), $id);
1528 if (empty($users)) {
1529 throw new NotFoundException;
1532 return api_format_data("users", $type, ['users' => $users]);
1535 /// @TODO move to top of file or somewhere better
1536 api_register_func('api/users/lookup', 'api_users_lookup', true);
1539 * Returns statuses that match a specified query.
1541 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1543 * @param string $type Return format: json, xml, atom, rss
1545 * @return array|string
1546 * @throws BadRequestException if the "q" parameter is missing.
1547 * @throws ForbiddenException
1548 * @throws ImagickException
1549 * @throws InternalServerErrorException
1550 * @throws UnauthorizedException
1552 function api_search($type)
1555 $user_info = api_get_user($a);
1557 if (api_user() === false || $user_info === false) {
1558 throw new ForbiddenException();
1561 if (empty($_REQUEST['q'])) {
1562 throw new BadRequestException('q parameter is required.');
1565 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1568 $data['status'] = [];
1570 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1571 if (!empty($_REQUEST['rpp'])) {
1572 $count = $_REQUEST['rpp'];
1573 } elseif (!empty($_REQUEST['count'])) {
1574 $count = $_REQUEST['count'];
1577 $since_id = $_REQUEST['since_id'] ?? 0;
1578 $max_id = $_REQUEST['max_id'] ?? 0;
1579 $page = $_REQUEST['page'] ?? 1;
1581 $start = max(0, ($page - 1) * $count);
1583 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1584 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1585 $searchTerm = $matches[1];
1586 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1587 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1589 while ($tag = DBA::fetch($tags)) {
1590 $uriids[] = $tag['uri-id'];
1594 if (empty($uriids)) {
1595 return api_format_data('statuses', $type, $data);
1598 $condition = ['uri-id' => $uriids];
1599 if ($exclude_replies) {
1600 $condition['gravity'] = GRAVITY_PARENT;
1603 $params['group_by'] = ['uri-id'];
1605 $condition = ["`id` > ?
1606 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1607 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1608 AND `body` LIKE CONCAT('%',?,'%')",
1609 $since_id, api_user(), $_REQUEST['q']];
1611 $condition[0] .= ' AND `id` <= ?';
1612 $condition[] = $max_id;
1618 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1619 $id = Item::fetchByLink($searchTerm, api_user());
1622 $id = Item::fetchByLink($searchTerm);
1626 $statuses = Post::select([], ['id' => $id]);
1630 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1632 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1634 bindComments($data['status']);
1636 return api_format_data('statuses', $type, $data);
1639 /// @TODO move to top of file or somewhere better
1640 api_register_func('api/search/tweets', 'api_search', true);
1641 api_register_func('api/search', 'api_search', true);
1644 * Returns the most recent statuses posted by the user and the users they follow.
1646 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1648 * @param string $type Return type (atom, rss, xml, json)
1650 * @return array|string
1651 * @throws BadRequestException
1652 * @throws ForbiddenException
1653 * @throws ImagickException
1654 * @throws InternalServerErrorException
1655 * @throws UnauthorizedException
1656 * @todo Optional parameters
1657 * @todo Add reply info
1659 function api_statuses_home_timeline($type)
1662 $user_info = api_get_user($a);
1664 if (api_user() === false || $user_info === false) {
1665 throw new ForbiddenException();
1668 unset($_REQUEST["user_id"]);
1669 unset($_GET["user_id"]);
1671 unset($_REQUEST["screen_name"]);
1672 unset($_GET["screen_name"]);
1674 // get last network messages
1677 $count = $_REQUEST['count'] ?? 20;
1678 $page = $_REQUEST['page']?? 0;
1679 $since_id = $_REQUEST['since_id'] ?? 0;
1680 $max_id = $_REQUEST['max_id'] ?? 0;
1681 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1682 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1684 $start = max(0, ($page - 1) * $count);
1686 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1687 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1690 $condition[0] .= " AND `id` <= ?";
1691 $condition[] = $max_id;
1693 if ($exclude_replies) {
1694 $condition[0] .= ' AND `gravity` = ?';
1695 $condition[] = GRAVITY_PARENT;
1697 if ($conversation_id > 0) {
1698 $condition[0] .= " AND `parent` = ?";
1699 $condition[] = $conversation_id;
1702 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1703 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1705 $items = Post::toArray($statuses);
1707 $ret = api_format_items($items, $user_info, false, $type);
1709 // Set all posts from the query above to seen
1711 foreach ($items as $item) {
1712 $idarray[] = intval($item["id"]);
1715 if (!empty($idarray)) {
1716 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1718 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1724 $data = ['status' => $ret];
1729 $data = api_rss_extra($a, $data, $user_info);
1733 return api_format_data("statuses", $type, $data);
1737 /// @TODO move to top of file or somewhere better
1738 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1739 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1742 * Returns the most recent statuses from public users.
1744 * @param string $type Return type (atom, rss, xml, json)
1746 * @return array|string
1747 * @throws BadRequestException
1748 * @throws ForbiddenException
1749 * @throws ImagickException
1750 * @throws InternalServerErrorException
1751 * @throws UnauthorizedException
1753 function api_statuses_public_timeline($type)
1756 $user_info = api_get_user($a);
1758 if (api_user() === false || $user_info === false) {
1759 throw new ForbiddenException();
1762 // get last network messages
1765 $count = $_REQUEST['count'] ?? 20;
1766 $page = $_REQUEST['page'] ?? 1;
1767 $since_id = $_REQUEST['since_id'] ?? 0;
1768 $max_id = $_REQUEST['max_id'] ?? 0;
1769 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1770 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1772 $start = max(0, ($page - 1) * $count);
1774 if ($exclude_replies && !$conversation_id) {
1775 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1776 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1779 $condition[0] .= " AND `id` <= ?";
1780 $condition[] = $max_id;
1783 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1784 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1786 $r = Post::toArray($statuses);
1788 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1789 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1792 $condition[0] .= " AND `id` <= ?";
1793 $condition[] = $max_id;
1795 if ($conversation_id > 0) {
1796 $condition[0] .= " AND `parent` = ?";
1797 $condition[] = $conversation_id;
1800 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1801 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1803 $r = Post::toArray($statuses);
1806 $ret = api_format_items($r, $user_info, false, $type);
1810 $data = ['status' => $ret];
1815 $data = api_rss_extra($a, $data, $user_info);
1819 return api_format_data("statuses", $type, $data);
1822 /// @TODO move to top of file or somewhere better
1823 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1826 * Returns the most recent statuses posted by users this node knows about.
1828 * @param string $type Return format: json, xml, atom, rss
1829 * @return array|string
1830 * @throws BadRequestException
1831 * @throws ForbiddenException
1832 * @throws ImagickException
1833 * @throws InternalServerErrorException
1834 * @throws UnauthorizedException
1836 function api_statuses_networkpublic_timeline($type)
1839 $user_info = api_get_user($a);
1841 if (api_user() === false || $user_info === false) {
1842 throw new ForbiddenException();
1845 $since_id = $_REQUEST['since_id'] ?? 0;
1846 $max_id = $_REQUEST['max_id'] ?? 0;
1849 $count = $_REQUEST['count'] ?? 20;
1850 $page = $_REQUEST['page'] ?? 1;
1852 $start = max(0, ($page - 1) * $count);
1854 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1855 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1858 $condition[0] .= " AND `id` <= ?";
1859 $condition[] = $max_id;
1862 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1863 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1865 $ret = api_format_items($statuses, $user_info, false, $type);
1869 $data = ['status' => $ret];
1874 $data = api_rss_extra($a, $data, $user_info);
1878 return api_format_data("statuses", $type, $data);
1881 /// @TODO move to top of file or somewhere better
1882 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1885 * Returns a single status.
1887 * @param string $type Return type (atom, rss, xml, json)
1889 * @return array|string
1890 * @throws BadRequestException
1891 * @throws ForbiddenException
1892 * @throws ImagickException
1893 * @throws InternalServerErrorException
1894 * @throws UnauthorizedException
1895 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1897 function api_statuses_show($type)
1900 $user_info = api_get_user($a);
1902 if (api_user() === false || $user_info === false) {
1903 throw new ForbiddenException();
1907 $id = intval($a->argv[3] ?? 0);
1910 $id = intval($_REQUEST['id'] ?? 0);
1915 $id = intval($a->argv[4] ?? 0);
1918 Logger::log('API: api_statuses_show: ' . $id);
1920 $conversation = !empty($_REQUEST['conversation']);
1922 // try to fetch the item for the local user - or the public item, if there is no local one
1923 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1924 if (!DBA::isResult($uri_item)) {
1925 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1928 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1929 if (!DBA::isResult($item)) {
1930 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1935 if ($conversation) {
1936 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1937 $params = ['order' => ['id' => true]];
1939 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1943 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1945 /// @TODO How about copying this to above methods which don't check $r ?
1946 if (!DBA::isResult($statuses)) {
1947 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1950 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1952 if ($conversation) {
1953 $data = ['status' => $ret];
1954 return api_format_data("statuses", $type, $data);
1956 $data = ['status' => $ret[0]];
1957 return api_format_data("status", $type, $data);
1961 /// @TODO move to top of file or somewhere better
1962 api_register_func('api/statuses/show', 'api_statuses_show', true);
1966 * @param string $type Return type (atom, rss, xml, json)
1968 * @return array|string
1969 * @throws BadRequestException
1970 * @throws ForbiddenException
1971 * @throws ImagickException
1972 * @throws InternalServerErrorException
1973 * @throws UnauthorizedException
1974 * @todo nothing to say?
1976 function api_conversation_show($type)
1979 $user_info = api_get_user($a);
1981 if (api_user() === false || $user_info === false) {
1982 throw new ForbiddenException();
1986 $id = intval($a->argv[3] ?? 0);
1987 $since_id = intval($_REQUEST['since_id'] ?? 0);
1988 $max_id = intval($_REQUEST['max_id'] ?? 0);
1989 $count = intval($_REQUEST['count'] ?? 20);
1990 $page = intval($_REQUEST['page'] ?? 1);
1992 $start = max(0, ($page - 1) * $count);
1995 $id = intval($_REQUEST['id'] ?? 0);
2000 $id = intval($a->argv[4] ?? 0);
2003 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2005 // try to fetch the item for the local user - or the public item, if there is no local one
2006 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
2007 if (!DBA::isResult($item)) {
2008 throw new BadRequestException("There is no status with this id.");
2011 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2012 if (!DBA::isResult($parent)) {
2013 throw new BadRequestException("There is no status with this id.");
2016 $id = $parent['id'];
2018 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2019 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2022 $condition[0] .= " AND `id` <= ?";
2023 $condition[] = $max_id;
2026 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2027 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2029 if (!DBA::isResult($statuses)) {
2030 throw new BadRequestException("There is no status with id $id.");
2033 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2035 $data = ['status' => $ret];
2036 return api_format_data("statuses", $type, $data);
2039 /// @TODO move to top of file or somewhere better
2040 api_register_func('api/conversation/show', 'api_conversation_show', true);
2041 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2046 * @param string $type Return type (atom, rss, xml, json)
2048 * @return array|string
2049 * @throws BadRequestException
2050 * @throws ForbiddenException
2051 * @throws ImagickException
2052 * @throws InternalServerErrorException
2053 * @throws UnauthorizedException
2054 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2056 function api_statuses_repeat($type)
2062 if (api_user() === false) {
2063 throw new ForbiddenException();
2069 $id = intval($a->argv[3] ?? 0);
2072 $id = intval($_REQUEST['id'] ?? 0);
2077 $id = intval($a->argv[4] ?? 0);
2080 Logger::log('API: api_statuses_repeat: '.$id);
2082 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2083 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2085 if (DBA::isResult($item) && !empty($item['body'])) {
2086 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2087 if (!Item::performActivity($id, 'announce', local_user())) {
2088 throw new InternalServerErrorException();
2093 if (strpos($item['body'], "[/share]") !== false) {
2094 $pos = strpos($item['body'], "[share");
2095 $post = substr($item['body'], $pos);
2097 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2099 if (!empty($item['title'])) {
2100 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2103 $post .= $item['body'];
2104 $post .= "[/share]";
2106 $_REQUEST['body'] = $post;
2107 $_REQUEST['profile_uid'] = api_user();
2108 $_REQUEST['api_source'] = true;
2110 if (empty($_REQUEST['source'])) {
2111 $_REQUEST["source"] = api_source();
2114 $item_id = item_post($a);
2117 throw new ForbiddenException();
2120 // output the post that we just posted.
2122 return api_status_show($type, $item_id);
2125 /// @TODO move to top of file or somewhere better
2126 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2129 * Destroys a specific status.
2131 * @param string $type Return type (atom, rss, xml, json)
2133 * @return array|string
2134 * @throws BadRequestException
2135 * @throws ForbiddenException
2136 * @throws ImagickException
2137 * @throws InternalServerErrorException
2138 * @throws UnauthorizedException
2139 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2141 function api_statuses_destroy($type)
2145 if (api_user() === false) {
2146 throw new ForbiddenException();
2152 $id = intval($a->argv[3] ?? 0);
2155 $id = intval($_REQUEST['id'] ?? 0);
2160 $id = intval($a->argv[4] ?? 0);
2163 Logger::log('API: api_statuses_destroy: '.$id);
2165 $ret = api_statuses_show($type);
2167 Item::deleteForUser(['id' => $id], api_user());
2172 /// @TODO move to top of file or somewhere better
2173 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2176 * Returns the most recent mentions.
2178 * @param string $type Return type (atom, rss, xml, json)
2180 * @return array|string
2181 * @throws BadRequestException
2182 * @throws ForbiddenException
2183 * @throws ImagickException
2184 * @throws InternalServerErrorException
2185 * @throws UnauthorizedException
2186 * @see http://developer.twitter.com/doc/get/statuses/mentions
2188 function api_statuses_mentions($type)
2191 $user_info = api_get_user($a);
2193 if (api_user() === false || $user_info === false) {
2194 throw new ForbiddenException();
2197 unset($_REQUEST["user_id"]);
2198 unset($_GET["user_id"]);
2200 unset($_REQUEST["screen_name"]);
2201 unset($_GET["screen_name"]);
2203 // get last network messages
2206 $since_id = intval($_REQUEST['since_id'] ?? 0);
2207 $max_id = intval($_REQUEST['max_id'] ?? 0);
2208 $count = intval($_REQUEST['count'] ?? 20);
2209 $page = intval($_REQUEST['page'] ?? 1);
2211 $start = max(0, ($page - 1) * $count);
2213 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2214 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2215 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2217 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2218 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2219 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2220 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2221 api_user(), $since_id];
2224 $query .= " AND `id` <= ?";
2225 $condition[] = $max_id;
2228 array_unshift($condition, $query);
2230 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2231 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2233 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2235 $data = ['status' => $ret];
2240 $data = api_rss_extra($a, $data, $user_info);
2244 return api_format_data("statuses", $type, $data);
2247 /// @TODO move to top of file or somewhere better
2248 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2249 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2252 * Returns the most recent statuses posted by the user.
2254 * @param string $type Either "json" or "xml"
2255 * @return string|array
2256 * @throws BadRequestException
2257 * @throws ForbiddenException
2258 * @throws ImagickException
2259 * @throws InternalServerErrorException
2260 * @throws UnauthorizedException
2261 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2263 function api_statuses_user_timeline($type)
2266 $user_info = api_get_user($a);
2268 if (api_user() === false || $user_info === false) {
2269 throw new ForbiddenException();
2272 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2274 $since_id = $_REQUEST['since_id'] ?? 0;
2275 $max_id = $_REQUEST['max_id'] ?? 0;
2276 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2277 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2280 $count = $_REQUEST['count'] ?? 20;
2281 $page = $_REQUEST['page'] ?? 1;
2283 $start = max(0, ($page - 1) * $count);
2285 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2286 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2288 if ($user_info['self'] == 1) {
2289 $condition[0] .= ' AND `wall` ';
2292 if ($exclude_replies) {
2293 $condition[0] .= ' AND `gravity` = ?';
2294 $condition[] = GRAVITY_PARENT;
2297 if ($conversation_id > 0) {
2298 $condition[0] .= " AND `parent` = ?";
2299 $condition[] = $conversation_id;
2303 $condition[0] .= " AND `id` <= ?";
2304 $condition[] = $max_id;
2306 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2307 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2309 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2313 $data = ['status' => $ret];
2318 $data = api_rss_extra($a, $data, $user_info);
2322 return api_format_data("statuses", $type, $data);
2325 /// @TODO move to top of file or somewhere better
2326 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2329 * Star/unstar an item.
2330 * param: id : id of the item
2332 * @param string $type Return type (atom, rss, xml, json)
2334 * @return array|string
2335 * @throws BadRequestException
2336 * @throws ForbiddenException
2337 * @throws ImagickException
2338 * @throws InternalServerErrorException
2339 * @throws UnauthorizedException
2340 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2342 function api_favorites_create_destroy($type)
2346 if (api_user() === false) {
2347 throw new ForbiddenException();
2350 // for versioned api.
2351 /// @TODO We need a better global soluton
2352 $action_argv_id = 2;
2353 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2354 $action_argv_id = 3;
2357 if ($a->argc <= $action_argv_id) {
2358 throw new BadRequestException("Invalid request.");
2360 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2361 if ($a->argc == $action_argv_id + 2) {
2362 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2364 $itemid = intval($_REQUEST['id'] ?? 0);
2367 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2369 if (!DBA::isResult($item)) {
2370 throw new BadRequestException("Invalid item.");
2375 $item['starred'] = 1;
2378 $item['starred'] = 0;
2381 throw new BadRequestException("Invalid action ".$action);
2384 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2387 throw new InternalServerErrorException("DB error");
2391 $user_info = api_get_user($a);
2392 $rets = api_format_items([$item], $user_info, false, $type);
2395 $data = ['status' => $ret];
2400 $data = api_rss_extra($a, $data, $user_info);
2404 return api_format_data("status", $type, $data);
2407 /// @TODO move to top of file or somewhere better
2408 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2409 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2412 * Returns the most recent favorite statuses.
2414 * @param string $type Return type (atom, rss, xml, json)
2416 * @return string|array
2417 * @throws BadRequestException
2418 * @throws ForbiddenException
2419 * @throws ImagickException
2420 * @throws InternalServerErrorException
2421 * @throws UnauthorizedException
2423 function api_favorites($type)
2428 $user_info = api_get_user($a);
2430 if (api_user() === false || $user_info === false) {
2431 throw new ForbiddenException();
2436 // in friendica starred item are private
2437 // return favorites only for self
2438 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2440 if ($user_info['self'] == 0) {
2444 $since_id = $_REQUEST['since_id'] ?? 0;
2445 $max_id = $_REQUEST['max_id'] ?? 0;
2446 $count = $_GET['count'] ?? 20;
2447 $page = $_REQUEST['page'] ?? 1;
2449 $start = max(0, ($page - 1) * $count);
2451 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2452 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2454 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2457 $condition[0] .= " AND `id` <= ?";
2458 $condition[] = $max_id;
2461 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2463 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2468 $data = ['status' => $ret];
2473 $data = api_rss_extra($a, $data, $user_info);
2477 return api_format_data("statuses", $type, $data);
2480 /// @TODO move to top of file or somewhere better
2481 api_register_func('api/favorites', 'api_favorites', true);
2485 * @param array $item
2486 * @param array $recipient
2487 * @param array $sender
2490 * @throws InternalServerErrorException
2492 function api_format_messages($item, $recipient, $sender)
2494 // standard meta information
2496 'id' => $item['id'],
2497 'sender_id' => $sender['id'],
2499 'recipient_id' => $recipient['id'],
2500 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2501 'sender_screen_name' => $sender['screen_name'],
2502 'recipient_screen_name' => $recipient['screen_name'],
2503 'sender' => $sender,
2504 'recipient' => $recipient,
2506 'friendica_seen' => $item['seen'] ?? 0,
2507 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2510 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2511 if (isset($ret['sender']['uid'])) {
2512 unset($ret['sender']['uid']);
2514 if (isset($ret['sender']['self'])) {
2515 unset($ret['sender']['self']);
2517 if (isset($ret['recipient']['uid'])) {
2518 unset($ret['recipient']['uid']);
2520 if (isset($ret['recipient']['self'])) {
2521 unset($ret['recipient']['self']);
2524 //don't send title to regular StatusNET requests to avoid confusing these apps
2525 if (!empty($_GET['getText'])) {
2526 $ret['title'] = $item['title'];
2527 if ($_GET['getText'] == 'html') {
2528 $ret['text'] = BBCode::convert($item['body'], false);
2529 } elseif ($_GET['getText'] == 'plain') {
2530 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2533 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2535 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2536 unset($ret['sender']);
2537 unset($ret['recipient']);
2545 * @param array $item
2548 * @throws InternalServerErrorException
2550 function api_convert_item($item)
2552 $body = api_add_attachments_to_body($item);
2554 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2556 // Add pictures to the attachment array and remove them from the body
2557 $attachments = api_get_attachments($body, $item['uri-id']);
2559 // Workaround for ostatus messages where the title is identically to the body
2560 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2561 $statusbody = trim(HTML::toPlaintext($html, 0));
2563 // handle data: images
2564 $statusbody = api_format_items_embeded_images($item, $statusbody);
2566 $statustitle = trim($item['title']);
2568 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2569 $statustext = trim($statusbody);
2571 $statustext = trim($statustitle."\n\n".$statusbody);
2574 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2575 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2578 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2580 // Workaround for clients with limited HTML parser functionality
2581 $search = ["<br>", "<blockquote>", "</blockquote>",
2582 "<h1>", "</h1>", "<h2>", "</h2>",
2583 "<h3>", "</h3>", "<h4>", "</h4>",
2584 "<h5>", "</h5>", "<h6>", "</h6>"];
2585 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2586 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2587 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2588 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2589 $statushtml = str_replace($search, $replace, $statushtml);
2591 if ($item['title'] != "") {
2592 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2596 $oldtext = $statushtml;
2597 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2598 } while ($oldtext != $statushtml);
2600 if (substr($statushtml, 0, 4) == '<br>') {
2601 $statushtml = substr($statushtml, 4);
2604 if (substr($statushtml, 0, -4) == '<br>') {
2605 $statushtml = substr($statushtml, -4);
2608 // feeds without body should contain the link
2609 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2610 $statushtml .= BBCode::convert($item['plink']);
2614 "text" => $statustext,
2615 "html" => $statushtml,
2616 "attachments" => $attachments,
2617 "entities" => $entities
2622 * Add media attachments to the body
2624 * @param array $item
2625 * @return string body with added media
2627 function api_add_attachments_to_body(array $item)
2629 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2631 if (strpos($body, '[/img]') !== false) {
2635 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2636 if (!empty($media['preview'])) {
2637 $description = $media['description'] ?: $media['name'];
2638 if (!empty($description)) {
2639 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2641 $body .= "\n[img]" . $media['preview'] .'[/img]';
2651 * @param string $body
2654 * @throws InternalServerErrorException
2656 function api_get_attachments(&$body, $uriid)
2658 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2659 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2661 $URLSearchString = "^\[\]";
2662 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2666 // Remove all embedded pictures, since they are added as attachments
2667 foreach ($images[0] as $orig) {
2668 $body = str_replace($orig, '', $body);
2673 foreach ($images[1] as $image) {
2674 $imagedata = Images::getInfoFromURLCached($image);
2677 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2681 return $attachments;
2686 * @param string $text
2687 * @param string $bbcode
2690 * @throws InternalServerErrorException
2691 * @todo Links at the first character of the post
2693 function api_get_entitities(&$text, $bbcode, $uriid)
2695 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2697 if ($include_entities != "true") {
2698 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2700 foreach ($images[1] as $image) {
2701 $replace = Post\Link::getByLink($uriid, $image);
2702 $text = str_replace($image, $replace, $text);
2707 $bbcode = BBCode::cleanPictureLinks($bbcode);
2709 // Change pure links in text to bbcode uris
2710 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2713 $entities["hashtags"] = [];
2714 $entities["symbols"] = [];
2715 $entities["urls"] = [];
2716 $entities["user_mentions"] = [];
2718 $URLSearchString = "^\[\]";
2720 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2722 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2723 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2725 $bbcode = preg_replace(
2726 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2727 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2730 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2732 $bbcode = preg_replace(
2733 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2734 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2737 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2739 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2741 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2744 foreach ($urls[1] as $id => $url) {
2745 $start = iconv_strpos($text, $url, 0, "UTF-8");
2746 if (!($start === false)) {
2747 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2751 ksort($ordered_urls);
2755 foreach ($ordered_urls as $url) {
2756 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2757 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2759 $display_url = $url["title"];
2761 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2762 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2764 if (strlen($display_url) > 26) {
2765 $display_url = substr($display_url, 0, 25)."…";
2769 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2770 if (!($start === false)) {
2771 $entities["urls"][] = ["url" => $url["url"],
2772 "expanded_url" => $url["url"],
2773 "display_url" => $display_url,
2774 "indices" => [$start, $start+strlen($url["url"])]];
2775 $offset = $start + 1;
2779 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2780 $ordered_images = [];
2781 foreach ($images as $image) {
2782 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2783 if (!($start === false)) {
2784 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2788 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2789 foreach ($images[1] as $image) {
2790 $start = iconv_strpos($text, $image, 0, "UTF-8");
2791 if (!($start === false)) {
2792 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2798 foreach ($ordered_images as $image) {
2799 $url = $image['url'];
2800 $ext_alt_text = $image['alt'];
2802 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2803 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2805 if (strlen($display_url) > 26) {
2806 $display_url = substr($display_url, 0, 25)."…";
2809 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2810 if (!($start === false)) {
2811 $image = Images::getInfoFromURLCached($url);
2813 $media_url = Post\Link::getByLink($uriid, $url);
2814 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2816 $entities["media"][] = [
2818 "id_str" => (string) ($start + 1),
2819 "indices" => [$start, $start+strlen($url)],
2820 "media_url" => Strings::normaliseLink($media_url),
2821 "media_url_https" => $media_url,
2823 "display_url" => $display_url,
2824 "expanded_url" => $url,
2825 "ext_alt_text" => $ext_alt_text,
2829 $offset = $start + 1;
2838 * @param array $item
2839 * @param string $text
2843 function api_format_items_embeded_images($item, $text)
2845 $text = preg_replace_callback(
2846 '|data:image/([^;]+)[^=]+=*|m',
2847 function () use ($item) {
2848 return DI::baseUrl() . '/display/' . $item['guid'];
2856 * return <a href='url'>name</a> as array
2858 * @param string $txt text
2863 function api_contactlink_to_array($txt)
2866 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2867 if ($r && count($match)==3) {
2869 'name' => $match[2],
2883 * return likes, dislikes and attend status for item
2885 * @param array $item array
2886 * @param string $type Return type (atom, rss, xml, json)
2889 * likes => int count,
2890 * dislikes => int count
2891 * @throws BadRequestException
2892 * @throws ImagickException
2893 * @throws InternalServerErrorException
2894 * @throws UnauthorizedException
2896 function api_format_items_activities($item, $type = "json")
2905 'attendmaybe' => [],
2909 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2910 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2912 while ($parent_item = Post::fetch($ret)) {
2913 // not used as result should be structured like other user data
2914 //builtin_activity_puller($i, $activities);
2916 // get user data and add it to the array of the activity
2917 $user = api_get_user($a, $parent_item['author-id']);
2918 switch ($parent_item['verb']) {
2919 case Activity::LIKE:
2920 $activities['like'][] = $user;
2922 case Activity::DISLIKE:
2923 $activities['dislike'][] = $user;
2925 case Activity::ATTEND:
2926 $activities['attendyes'][] = $user;
2928 case Activity::ATTENDNO:
2929 $activities['attendno'][] = $user;
2931 case Activity::ATTENDMAYBE:
2932 $activities['attendmaybe'][] = $user;
2934 case Activity::ANNOUNCE:
2935 $activities['announce'][] = $user;
2944 if ($type == "xml") {
2945 $xml_activities = [];
2946 foreach ($activities as $k => $v) {
2947 // change xml element from "like" to "friendica:like"
2948 $xml_activities["friendica:".$k] = $v;
2949 // add user data into xml output
2951 foreach ($v as $user) {
2952 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2955 $activities = $xml_activities;
2962 * format items to be returned by api
2964 * @param array $items array of items
2965 * @param array $user_info
2966 * @param bool $filter_user filter items by $user_info
2967 * @param string $type Return type (atom, rss, xml, json)
2969 * @throws BadRequestException
2970 * @throws ImagickException
2971 * @throws InternalServerErrorException
2972 * @throws UnauthorizedException
2974 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2976 $a = Friendica\DI::app();
2980 if (empty($items)) {
2984 foreach ((array)$items as $item) {
2985 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2987 // Look if the posts are matching if they should be filtered by user id
2988 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2992 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3001 * @param array $item Item record
3002 * @param string $type Return format (atom, rss, xml, json)
3003 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3004 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3005 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3006 * @return array API-formatted status
3007 * @throws BadRequestException
3008 * @throws ImagickException
3009 * @throws InternalServerErrorException
3010 * @throws UnauthorizedException
3012 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3014 $a = Friendica\DI::app();
3016 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3017 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3020 localize_item($item);
3022 $in_reply_to = api_in_reply_to($item);
3024 $converted = api_convert_item($item);
3026 if ($type == "xml") {
3027 $geo = "georss:point";
3033 'text' => $converted["text"],
3034 'truncated' => false,
3035 'created_at'=> api_date($item['created']),
3036 'in_reply_to_status_id' => $in_reply_to['status_id'],
3037 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3038 'source' => (($item['app']) ? $item['app'] : 'web'),
3039 'id' => intval($item['id']),
3040 'id_str' => (string) intval($item['id']),
3041 'in_reply_to_user_id' => $in_reply_to['user_id'],
3042 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3043 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3045 'favorited' => $item['starred'] ? true : false,
3046 'user' => $status_user,
3047 'friendica_author' => $author_user,
3048 'friendica_owner' => $owner_user,
3049 'friendica_private' => $item['private'] == Item::PRIVATE,
3050 //'entities' => NULL,
3051 'statusnet_html' => $converted["html"],
3052 'statusnet_conversation_id' => $item['parent'],
3053 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3054 'friendica_activities' => api_format_items_activities($item, $type),
3055 'friendica_title' => $item['title'],
3056 'friendica_html' => BBCode::convert($item['body'], false)
3059 if (count($converted["attachments"]) > 0) {
3060 $status["attachments"] = $converted["attachments"];
3063 if (count($converted["entities"]) > 0) {
3064 $status["entities"] = $converted["entities"];
3067 if ($status["source"] == 'web') {
3068 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3069 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3070 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3073 $retweeted_item = [];
3076 if ($item['gravity'] == GRAVITY_PARENT) {
3077 $body = $item['body'];
3078 $retweeted_item = api_share_as_retweet($item);
3079 if ($body != $item['body']) {
3080 $quoted_item = $retweeted_item;
3081 $retweeted_item = [];
3085 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3086 $announce = api_get_announce($item);
3087 if (!empty($announce)) {
3088 $retweeted_item = $item;
3090 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3094 if (!empty($quoted_item)) {
3095 if ($quoted_item['id'] != $item['id']) {
3096 $quoted_status = api_format_item($quoted_item);
3097 /// @todo Only remove the attachments that are also contained in the quotes status
3098 unset($status['attachments']);
3099 unset($status['entities']);
3101 $conv_quoted = api_convert_item($quoted_item);
3102 $quoted_status = $status;
3103 unset($quoted_status['attachments']);
3104 unset($quoted_status['entities']);
3105 unset($quoted_status['statusnet_conversation_id']);
3106 $quoted_status['text'] = $conv_quoted['text'];
3107 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3109 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3110 } catch (BadRequestException $e) {
3111 // user not found. should be found?
3112 /// @todo check if the user should be always found
3113 $quoted_status["user"] = [];
3116 unset($quoted_status['friendica_author']);
3117 unset($quoted_status['friendica_owner']);
3118 unset($quoted_status['friendica_activities']);
3119 unset($quoted_status['friendica_private']);
3122 if (!empty($retweeted_item)) {
3123 $retweeted_status = $status;
3124 unset($retweeted_status['friendica_author']);
3125 unset($retweeted_status['friendica_owner']);
3126 unset($retweeted_status['friendica_activities']);
3127 unset($retweeted_status['friendica_private']);
3128 unset($retweeted_status['statusnet_conversation_id']);
3129 $status['user'] = $status['friendica_owner'];
3131 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3132 } catch (BadRequestException $e) {
3133 // user not found. should be found?
3134 /// @todo check if the user should be always found
3135 $retweeted_status["user"] = [];
3138 $rt_converted = api_convert_item($retweeted_item);
3140 $retweeted_status['text'] = $rt_converted["text"];
3141 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3142 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3144 if (!empty($quoted_status)) {
3145 $retweeted_status['quoted_status'] = $quoted_status;
3148 $status['friendica_author'] = $retweeted_status['user'];
3149 $status['retweeted_status'] = $retweeted_status;
3150 } elseif (!empty($quoted_status)) {
3151 $root_status = api_convert_item($item);
3153 $status['text'] = $root_status["text"];
3154 $status['statusnet_html'] = $root_status["html"];
3155 $status['quoted_status'] = $quoted_status;
3158 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3159 unset($status["user"]["uid"]);
3160 unset($status["user"]["self"]);
3162 if ($item["coord"] != "") {
3163 $coords = explode(' ', $item["coord"]);
3164 if (count($coords) == 2) {
3165 if ($type == "json") {
3166 $status["geo"] = ['type' => 'Point',
3167 'coordinates' => [(float) $coords[0],
3168 (float) $coords[1]]];
3169 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3170 $status["georss:point"] = $item["coord"];
3179 * Returns the remaining number of API requests available to the user before the API limit is reached.
3181 * @param string $type Return type (atom, rss, xml, json)
3183 * @return array|string
3186 function api_account_rate_limit_status($type)
3188 if ($type == "xml") {
3190 'remaining-hits' => '150',
3191 '@attributes' => ["type" => "integer"],
3192 'hourly-limit' => '150',
3193 '@attributes2' => ["type" => "integer"],
3194 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3195 '@attributes3' => ["type" => "datetime"],
3196 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3197 '@attributes4' => ["type" => "integer"],
3201 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3202 'remaining_hits' => '150',
3203 'hourly_limit' => '150',
3204 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3208 return api_format_data('hash', $type, ['hash' => $hash]);
3211 /// @TODO move to top of file or somewhere better
3212 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3215 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3217 * @param string $type Return type (atom, rss, xml, json)
3219 * @return array|string
3221 function api_help_test($type)
3223 if ($type == 'xml') {
3229 return api_format_data('ok', $type, ["ok" => $ok]);
3232 /// @TODO move to top of file or somewhere better
3233 api_register_func('api/help/test', 'api_help_test', false);
3236 * Returns all lists the user subscribes to.
3238 * @param string $type Return type (atom, rss, xml, json)
3240 * @return array|string
3241 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3243 function api_lists_list($type)
3246 /// @TODO $ret is not filled here?
3247 return api_format_data('lists', $type, ["lists_list" => $ret]);
3250 /// @TODO move to top of file or somewhere better
3251 api_register_func('api/lists/list', 'api_lists_list', true);
3252 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3255 * Returns all groups the user owns.
3257 * @param string $type Return type (atom, rss, xml, json)
3259 * @return array|string
3260 * @throws BadRequestException
3261 * @throws ForbiddenException
3262 * @throws ImagickException
3263 * @throws InternalServerErrorException
3264 * @throws UnauthorizedException
3265 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3267 function api_lists_ownerships($type)
3271 if (api_user() === false) {
3272 throw new ForbiddenException();
3276 $user_info = api_get_user($a);
3277 $uid = $user_info['uid'];
3279 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3281 // loop through all groups
3283 foreach ($groups as $group) {
3284 if ($group['visible']) {
3290 'name' => $group['name'],
3291 'id' => intval($group['id']),
3292 'id_str' => (string) $group['id'],
3293 'user' => $user_info,
3297 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3300 /// @TODO move to top of file or somewhere better
3301 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3304 * Returns recent statuses from users in the specified group.
3306 * @param string $type Return type (atom, rss, xml, json)
3308 * @return array|string
3309 * @throws BadRequestException
3310 * @throws ForbiddenException
3311 * @throws ImagickException
3312 * @throws InternalServerErrorException
3313 * @throws UnauthorizedException
3314 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3316 function api_lists_statuses($type)
3320 $user_info = api_get_user($a);
3321 if (api_user() === false || $user_info === false) {
3322 throw new ForbiddenException();
3325 unset($_REQUEST["user_id"]);
3326 unset($_GET["user_id"]);
3328 unset($_REQUEST["screen_name"]);
3329 unset($_GET["screen_name"]);
3331 if (empty($_REQUEST['list_id'])) {
3332 throw new BadRequestException('list_id not specified');
3336 $count = $_REQUEST['count'] ?? 20;
3337 $page = $_REQUEST['page'] ?? 1;
3338 $since_id = $_REQUEST['since_id'] ?? 0;
3339 $max_id = $_REQUEST['max_id'] ?? 0;
3340 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3341 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3343 $start = max(0, ($page - 1) * $count);
3345 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3346 $gids = array_column($groups, 'contact-id');
3347 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3348 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3351 $condition[0] .= " AND `id` <= ?";
3352 $condition[] = $max_id;
3354 if ($exclude_replies > 0) {
3355 $condition[0] .= ' AND `gravity` = ?';
3356 $condition[] = GRAVITY_PARENT;
3358 if ($conversation_id > 0) {
3359 $condition[0] .= " AND `parent` = ?";
3360 $condition[] = $conversation_id;
3363 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3364 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3366 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3368 $data = ['status' => $items];
3373 $data = api_rss_extra($a, $data, $user_info);
3377 return api_format_data("statuses", $type, $data);
3380 /// @TODO move to top of file or somewhere better
3381 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3384 * Returns either the friends of the follower list
3386 * Considers friends and followers lists to be private and won't return
3387 * anything if any user_id parameter is passed.
3389 * @param string $qtype Either "friends" or "followers"
3390 * @return boolean|array
3391 * @throws BadRequestException
3392 * @throws ForbiddenException
3393 * @throws ImagickException
3394 * @throws InternalServerErrorException
3395 * @throws UnauthorizedException
3397 function api_statuses_f($qtype)
3401 if (api_user() === false) {
3402 throw new ForbiddenException();
3406 $count = $_GET['count'] ?? 20;
3407 $page = $_GET['page'] ?? 1;
3409 $start = max(0, ($page - 1) * $count);
3411 $user_info = api_get_user($a);
3413 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3414 /* this is to stop Hotot to load friends multiple times
3415 * I'm not sure if I'm missing return something or
3416 * is a bug in hotot. Workaround, meantime
3420 return array('$users' => $ret);*/
3425 if ($qtype == 'friends') {
3426 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3427 } elseif ($qtype == 'followers') {
3428 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3431 // friends and followers only for self
3432 if ($user_info['self'] == 0) {
3433 $sql_extra = " AND false ";
3436 if ($qtype == 'blocks') {
3437 $sql_filter = 'AND `blocked` AND NOT `pending`';
3438 } elseif ($qtype == 'incoming') {
3439 $sql_filter = 'AND `pending`';
3441 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3459 foreach ($r as $cid) {
3460 $user = api_get_user($a, $cid['nurl']);
3461 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3462 unset($user["uid"]);
3463 unset($user["self"]);
3470 return ['user' => $ret];
3475 * Returns the list of friends of the provided user
3477 * @deprecated By Twitter API in favor of friends/list
3479 * @param string $type Either "json" or "xml"
3480 * @return boolean|string|array
3481 * @throws BadRequestException
3482 * @throws ForbiddenException
3484 function api_statuses_friends($type)
3486 $data = api_statuses_f("friends");
3487 if ($data === false) {
3490 return api_format_data("users", $type, $data);
3494 * Returns the list of followers of the provided user
3496 * @deprecated By Twitter API in favor of friends/list
3498 * @param string $type Either "json" or "xml"
3499 * @return boolean|string|array
3500 * @throws BadRequestException
3501 * @throws ForbiddenException
3503 function api_statuses_followers($type)
3505 $data = api_statuses_f("followers");
3506 if ($data === false) {
3509 return api_format_data("users", $type, $data);
3512 /// @TODO move to top of file or somewhere better
3513 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3514 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3517 * Returns the list of blocked users
3519 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3521 * @param string $type Either "json" or "xml"
3523 * @return boolean|string|array
3524 * @throws BadRequestException
3525 * @throws ForbiddenException
3527 function api_blocks_list($type)
3529 $data = api_statuses_f('blocks');
3530 if ($data === false) {
3533 return api_format_data("users", $type, $data);
3536 /// @TODO move to top of file or somewhere better
3537 api_register_func('api/blocks/list', 'api_blocks_list', true);
3540 * Returns the list of pending users IDs
3542 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3544 * @param string $type Either "json" or "xml"
3546 * @return boolean|string|array
3547 * @throws BadRequestException
3548 * @throws ForbiddenException
3550 function api_friendships_incoming($type)
3552 $data = api_statuses_f('incoming');
3553 if ($data === false) {
3558 foreach ($data['user'] as $user) {
3559 $ids[] = $user['id'];
3562 return api_format_data("ids", $type, ['id' => $ids]);
3565 /// @TODO move to top of file or somewhere better
3566 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3569 * Returns the instance's configuration information.
3571 * @param string $type Return type (atom, rss, xml, json)
3573 * @return array|string
3574 * @throws InternalServerErrorException
3576 function api_statusnet_config($type)
3578 $name = DI::config()->get('config', 'sitename');
3579 $server = DI::baseUrl()->getHostname();
3580 $logo = DI::baseUrl() . '/images/friendica-64.png';
3581 $email = DI::config()->get('config', 'admin_email');
3582 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3583 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3584 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3585 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3586 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3589 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3590 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3591 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3592 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3593 'shorturllength' => '30',
3595 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3596 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3597 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3598 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3603 return api_format_data('config', $type, ['config' => $config]);
3606 /// @TODO move to top of file or somewhere better
3607 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3608 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3612 * @param string $type Return type (atom, rss, xml, json)
3614 * @return array|string
3616 function api_statusnet_version($type)
3619 $fake_statusnet_version = "0.9.7";
3621 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3624 /// @TODO move to top of file or somewhere better
3625 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3626 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3629 * Sends a new direct message.
3631 * @param string $type Return type (atom, rss, xml, json)
3633 * @return array|string
3634 * @throws BadRequestException
3635 * @throws ForbiddenException
3636 * @throws ImagickException
3637 * @throws InternalServerErrorException
3638 * @throws NotFoundException
3639 * @throws UnauthorizedException
3640 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3642 function api_direct_messages_new($type)
3646 if (api_user() === false) {
3647 throw new ForbiddenException();
3650 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3654 $sender = api_get_user($a);
3657 if (!empty($_POST['screen_name'])) {
3659 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3661 DBA::escape($_POST['screen_name'])
3664 if (DBA::isResult($r)) {
3665 // Selecting the id by priority, friendica first
3666 api_best_nickname($r);
3668 $recipient = api_get_user($a, $r[0]['nurl']);
3671 $recipient = api_get_user($a, $_POST['user_id']);
3674 if (empty($recipient)) {
3675 throw new NotFoundException('Recipient not found');
3679 if (!empty($_REQUEST['replyto'])) {
3681 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3683 intval($_REQUEST['replyto'])
3685 $replyto = $r[0]['parent-uri'];
3686 $sub = $r[0]['title'];
3688 if (!empty($_REQUEST['title'])) {
3689 $sub = $_REQUEST['title'];
3691 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3695 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3698 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3699 $ret = api_format_messages($r[0], $recipient, $sender);
3701 $ret = ["error"=>$id];
3704 $data = ['direct_message'=>$ret];
3710 $data = api_rss_extra($a, $data, $sender);
3714 return api_format_data("direct-messages", $type, $data);
3717 /// @TODO move to top of file or somewhere better
3718 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3721 * delete a direct_message from mail table through api
3723 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3724 * @return string|array
3725 * @throws BadRequestException
3726 * @throws ForbiddenException
3727 * @throws ImagickException
3728 * @throws InternalServerErrorException
3729 * @throws UnauthorizedException
3730 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3732 function api_direct_messages_destroy($type)
3736 if (api_user() === false) {
3737 throw new ForbiddenException();
3741 $user_info = api_get_user($a);
3743 $id = $_REQUEST['id'] ?? 0;
3745 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3746 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3747 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3749 $uid = $user_info['uid'];
3750 // error if no id or parenturi specified (for clients posting parent-uri as well)
3751 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3752 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3753 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3756 // BadRequestException if no id specified (for clients using Twitter API)
3758 throw new BadRequestException('Message id not specified');
3761 // add parent-uri to sql command if specified by calling app
3762 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3764 // get data of the specified message id
3766 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3771 // error message if specified id is not in database
3772 if (!DBA::isResult($r)) {
3773 if ($verbose == "true") {
3774 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3775 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3777 /// @todo BadRequestException ok for Twitter API clients?
3778 throw new BadRequestException('message id not in database');
3783 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3788 if ($verbose == "true") {
3791 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3792 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3794 $answer = ['result' => 'error', 'message' => 'unknown error'];
3795 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3798 /// @todo return JSON data like Twitter API not yet implemented
3801 /// @TODO move to top of file or somewhere better
3802 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3807 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3808 * @return string|array
3809 * @throws BadRequestException
3810 * @throws ForbiddenException
3811 * @throws ImagickException
3812 * @throws InternalServerErrorException
3813 * @throws NotFoundException
3814 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3816 function api_friendships_destroy($type)
3820 if ($uid === false) {
3821 throw new ForbiddenException();
3824 $contact_id = $_REQUEST['user_id'] ?? 0;
3826 if (empty($contact_id)) {
3827 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3828 throw new BadRequestException("no user_id specified");
3831 // Get Contact by given id
3832 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3834 if(!DBA::isResult($contact)) {
3835 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3836 throw new NotFoundException("no contact found to given ID");
3839 $url = $contact["url"];
3841 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3842 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3843 Strings::normaliseLink($url), $url];
3844 $contact = DBA::selectFirst('contact', [], $condition);
3846 if (!DBA::isResult($contact)) {
3847 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3848 throw new NotFoundException("Not following Contact");
3851 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3852 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3853 throw new ExpectationFailedException("Not supported");
3856 $dissolve = ($contact['rel'] == Contact::SHARING);
3858 $owner = User::getOwnerDataById($uid);
3860 Contact::terminateFriendship($owner, $contact, $dissolve);
3863 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3864 throw new NotFoundException("Error Processing Request");
3867 // Sharing-only contacts get deleted as there no relationship any more
3869 Contact::remove($contact['id']);
3871 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3874 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3875 unset($contact["uid"]);
3876 unset($contact["self"]);
3878 // Set screen_name since Twidere requests it
3879 $contact["screen_name"] = $contact["nick"];
3881 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3883 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3887 * @param string $type Return type (atom, rss, xml, json)
3888 * @param string $box
3889 * @param string $verbose
3891 * @return array|string
3892 * @throws BadRequestException
3893 * @throws ForbiddenException
3894 * @throws ImagickException
3895 * @throws InternalServerErrorException
3896 * @throws UnauthorizedException
3898 function api_direct_messages_box($type, $box, $verbose)
3901 if (api_user() === false) {
3902 throw new ForbiddenException();
3905 $count = $_GET['count'] ?? 20;
3906 $page = $_REQUEST['page'] ?? 1;
3908 $since_id = $_REQUEST['since_id'] ?? 0;
3909 $max_id = $_REQUEST['max_id'] ?? 0;
3911 $user_id = $_REQUEST['user_id'] ?? '';
3912 $screen_name = $_REQUEST['screen_name'] ?? '';
3915 unset($_REQUEST["user_id"]);
3916 unset($_GET["user_id"]);
3918 unset($_REQUEST["screen_name"]);
3919 unset($_GET["screen_name"]);
3921 $user_info = api_get_user($a);
3922 if ($user_info === false) {
3923 throw new ForbiddenException();
3925 $profile_url = $user_info["url"];
3928 $start = max(0, ($page - 1) * $count);
3933 if ($box=="sentbox") {
3934 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3935 } elseif ($box == "conversation") {
3936 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3937 } elseif ($box == "all") {
3938 $sql_extra = "true";
3939 } elseif ($box == "inbox") {
3940 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3944 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3947 if ($user_id != "") {
3948 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3949 } elseif ($screen_name !="") {
3950 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3954 "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",
3960 if ($verbose == "true" && !DBA::isResult($r)) {
3961 $answer = ['result' => 'error', 'message' => 'no mails available'];
3962 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3966 foreach ($r as $item) {
3967 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3968 $recipient = $user_info;
3969 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3970 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3971 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3972 $sender = $user_info;
3975 if (isset($recipient) && isset($sender)) {
3976 $ret[] = api_format_messages($item, $recipient, $sender);
3981 $data = ['direct_message' => $ret];
3986 $data = api_rss_extra($a, $data, $user_info);
3990 return api_format_data("direct-messages", $type, $data);
3994 * Returns the most recent direct messages sent by the user.
3996 * @param string $type Return type (atom, rss, xml, json)
3998 * @return array|string
3999 * @throws BadRequestException
4000 * @throws ForbiddenException
4001 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4003 function api_direct_messages_sentbox($type)
4005 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4006 return api_direct_messages_box($type, "sentbox", $verbose);
4010 * Returns the most recent direct messages sent to the user.
4012 * @param string $type Return type (atom, rss, xml, json)
4014 * @return array|string
4015 * @throws BadRequestException
4016 * @throws ForbiddenException
4017 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4019 function api_direct_messages_inbox($type)
4021 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4022 return api_direct_messages_box($type, "inbox", $verbose);
4027 * @param string $type Return type (atom, rss, xml, json)
4029 * @return array|string
4030 * @throws BadRequestException
4031 * @throws ForbiddenException
4033 function api_direct_messages_all($type)
4035 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4036 return api_direct_messages_box($type, "all", $verbose);
4041 * @param string $type Return type (atom, rss, xml, json)
4043 * @return array|string
4044 * @throws BadRequestException
4045 * @throws ForbiddenException
4047 function api_direct_messages_conversation($type)
4049 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4050 return api_direct_messages_box($type, "conversation", $verbose);
4053 /// @TODO move to top of file or somewhere better
4054 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4055 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4056 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4057 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4060 * Returns an OAuth Request Token.
4062 * @see https://oauth.net/core/1.0/#auth_step1
4064 function api_oauth_request_token()
4066 $oauth1 = new FKOAuth1();
4068 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4069 } catch (Exception $e) {
4070 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4078 * Returns an OAuth Access Token.
4080 * @return array|string
4081 * @see https://oauth.net/core/1.0/#auth_step3
4083 function api_oauth_access_token()
4085 $oauth1 = new FKOAuth1();
4087 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4088 } catch (Exception $e) {
4089 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4096 /// @TODO move to top of file or somewhere better
4097 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4098 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4102 * delete a complete photoalbum with all containing photos from database through api
4104 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4105 * @return string|array
4106 * @throws BadRequestException
4107 * @throws ForbiddenException
4108 * @throws InternalServerErrorException
4110 function api_fr_photoalbum_delete($type)
4112 if (api_user() === false) {
4113 throw new ForbiddenException();
4116 $album = $_REQUEST['album'] ?? '';
4118 // we do not allow calls without album string
4120 throw new BadRequestException("no albumname specified");
4122 // check if album is existing
4124 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4125 if (!DBA::isResult($photos)) {
4126 throw new BadRequestException("album not available");
4129 $resourceIds = array_column($photos, 'resource-id');
4131 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4132 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4133 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4134 Item::deleteForUser($condition, api_user());
4136 // now let's delete all photos from the album
4137 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4139 // return success of deletion or error message
4141 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4142 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4144 throw new InternalServerErrorException("unknown error - deleting from database failed");
4149 * update the name of the album for all photos of an album
4151 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4152 * @return string|array
4153 * @throws BadRequestException
4154 * @throws ForbiddenException
4155 * @throws InternalServerErrorException
4157 function api_fr_photoalbum_update($type)
4159 if (api_user() === false) {
4160 throw new ForbiddenException();
4163 $album = $_REQUEST['album'] ?? '';
4164 $album_new = $_REQUEST['album_new'] ?? '';
4166 // we do not allow calls without album string
4168 throw new BadRequestException("no albumname specified");
4170 if ($album_new == "") {
4171 throw new BadRequestException("no new albumname specified");
4173 // check if album is existing
4174 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4175 throw new BadRequestException("album not available");
4177 // now let's update all photos to the albumname
4178 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4180 // return success of updating or error message
4182 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4183 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4185 throw new InternalServerErrorException("unknown error - updating in database failed");
4191 * list all photos of the authenticated user
4193 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4194 * @return string|array
4195 * @throws ForbiddenException
4196 * @throws InternalServerErrorException
4198 function api_fr_photos_list($type)
4200 if (api_user() === false) {
4201 throw new ForbiddenException();
4204 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4205 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4206 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4207 intval(local_user())
4210 'image/jpeg' => 'jpg',
4211 'image/png' => 'png',
4212 'image/gif' => 'gif'
4214 $data = ['photo'=>[]];
4215 if (DBA::isResult($r)) {
4216 foreach ($r as $rr) {
4218 $photo['id'] = $rr['resource-id'];
4219 $photo['album'] = $rr['album'];
4220 $photo['filename'] = $rr['filename'];
4221 $photo['type'] = $rr['type'];
4222 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4223 $photo['created'] = $rr['created'];
4224 $photo['edited'] = $rr['edited'];
4225 $photo['desc'] = $rr['desc'];
4227 if ($type == "xml") {
4228 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4230 $photo['thumb'] = $thumb;
4231 $data['photo'][] = $photo;
4235 return api_format_data("photos", $type, $data);
4239 * upload a new photo or change an existing photo
4241 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4242 * @return string|array
4243 * @throws BadRequestException
4244 * @throws ForbiddenException
4245 * @throws ImagickException
4246 * @throws InternalServerErrorException
4247 * @throws NotFoundException
4249 function api_fr_photo_create_update($type)
4251 if (api_user() === false) {
4252 throw new ForbiddenException();
4255 $photo_id = $_REQUEST['photo_id'] ?? null;
4256 $desc = $_REQUEST['desc'] ?? null;
4257 $album = $_REQUEST['album'] ?? null;
4258 $album_new = $_REQUEST['album_new'] ?? null;
4259 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4260 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4261 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4262 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4263 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4265 // do several checks on input parameters
4266 // we do not allow calls without album string
4267 if ($album == null) {
4268 throw new BadRequestException("no albumname specified");
4270 // if photo_id == null --> we are uploading a new photo
4271 if ($photo_id == null) {
4274 // error if no media posted in create-mode
4275 if (empty($_FILES['media'])) {
4277 throw new BadRequestException("no media data submitted");
4280 // album_new will be ignored in create-mode
4285 // check if photo is existing in databasei
4286 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4287 throw new BadRequestException("photo not available");
4291 // checks on acl strings provided by clients
4292 $acl_input_error = false;
4293 $acl_input_error |= check_acl_input($allow_cid);
4294 $acl_input_error |= check_acl_input($deny_cid);
4295 $acl_input_error |= check_acl_input($allow_gid);
4296 $acl_input_error |= check_acl_input($deny_gid);
4297 if ($acl_input_error) {
4298 throw new BadRequestException("acl data invalid");
4300 // now let's upload the new media in create-mode
4301 if ($mode == "create") {
4302 $media = $_FILES['media'];
4303 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4305 // return success of updating or error message
4306 if (!is_null($data)) {
4307 return api_format_data("photo_create", $type, $data);
4309 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4313 // now let's do the changes in update-mode
4314 if ($mode == "update") {
4315 $updated_fields = [];
4317 if (!is_null($desc)) {
4318 $updated_fields['desc'] = $desc;
4321 if (!is_null($album_new)) {
4322 $updated_fields['album'] = $album_new;
4325 if (!is_null($allow_cid)) {
4326 $allow_cid = trim($allow_cid);
4327 $updated_fields['allow_cid'] = $allow_cid;
4330 if (!is_null($deny_cid)) {
4331 $deny_cid = trim($deny_cid);
4332 $updated_fields['deny_cid'] = $deny_cid;
4335 if (!is_null($allow_gid)) {
4336 $allow_gid = trim($allow_gid);
4337 $updated_fields['allow_gid'] = $allow_gid;
4340 if (!is_null($deny_gid)) {
4341 $deny_gid = trim($deny_gid);
4342 $updated_fields['deny_gid'] = $deny_gid;
4346 if (count($updated_fields) > 0) {
4347 $nothingtodo = false;
4348 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4350 $nothingtodo = true;
4353 if (!empty($_FILES['media'])) {
4354 $nothingtodo = false;
4355 $media = $_FILES['media'];
4356 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4357 if (!is_null($data)) {
4358 return api_format_data("photo_update", $type, $data);
4362 // return success of updating or error message
4364 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4365 return api_format_data("photo_update", $type, ['$result' => $answer]);
4368 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4369 return api_format_data("photo_update", $type, ['$result' => $answer]);
4371 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4374 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4378 * delete a single photo from the database through api
4380 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4381 * @return string|array
4382 * @throws BadRequestException
4383 * @throws ForbiddenException
4384 * @throws InternalServerErrorException
4386 function api_fr_photo_delete($type)
4388 if (api_user() === false) {
4389 throw new ForbiddenException();
4393 $photo_id = $_REQUEST['photo_id'] ?? null;
4395 // do several checks on input parameters
4396 // we do not allow calls without photo id
4397 if ($photo_id == null) {
4398 throw new BadRequestException("no photo_id specified");
4401 // check if photo is existing in database
4402 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4403 throw new BadRequestException("photo not available");
4406 // now we can perform on the deletion of the photo
4407 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4409 // return success of deletion or error message
4411 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4412 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4413 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4414 Item::deleteForUser($condition, api_user());
4416 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4417 return api_format_data("photo_delete", $type, ['$result' => $result]);
4419 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4425 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4427 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4428 * @return string|array
4429 * @throws BadRequestException
4430 * @throws ForbiddenException
4431 * @throws InternalServerErrorException
4432 * @throws NotFoundException
4434 function api_fr_photo_detail($type)
4436 if (api_user() === false) {
4437 throw new ForbiddenException();
4439 if (empty($_REQUEST['photo_id'])) {
4440 throw new BadRequestException("No photo id.");
4443 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4444 $photo_id = $_REQUEST['photo_id'];
4446 // prepare json/xml output with data from database for the requested photo
4447 $data = prepare_photo_data($type, $scale, $photo_id);
4449 return api_format_data("photo_detail", $type, $data);
4454 * updates the profile image for the user (either a specified profile or the default profile)
4456 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4458 * @return string|array
4459 * @throws BadRequestException
4460 * @throws ForbiddenException
4461 * @throws ImagickException
4462 * @throws InternalServerErrorException
4463 * @throws NotFoundException
4464 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4466 function api_account_update_profile_image($type)
4468 if (api_user() === false) {
4469 throw new ForbiddenException();
4472 $profile_id = $_REQUEST['profile_id'] ?? 0;
4474 // error if image data is missing
4475 if (empty($_FILES['image'])) {
4476 throw new BadRequestException("no media data submitted");
4479 // check if specified profile id is valid
4480 if ($profile_id != 0) {
4481 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4482 // error message if specified profile id is not in database
4483 if (!DBA::isResult($profile)) {
4484 throw new BadRequestException("profile_id not available");
4486 $is_default_profile = $profile['is-default'];
4488 $is_default_profile = 1;
4491 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4493 if (!empty($_FILES['image'])) {
4494 $media = $_FILES['image'];
4495 } elseif (!empty($_FILES['media'])) {
4496 $media = $_FILES['media'];
4498 // save new profile image
4499 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4502 if (is_array($media['type'])) {
4503 $filetype = $media['type'][0];
4505 $filetype = $media['type'];
4507 if ($filetype == "image/jpeg") {
4509 } elseif ($filetype == "image/png") {
4512 throw new InternalServerErrorException('Unsupported filetype');
4515 // change specified profile or all profiles to the new resource-id
4516 if ($is_default_profile) {
4517 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4518 Photo::update(['profile' => false], $condition);
4520 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4521 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4522 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4525 Contact::updateSelfFromUserID(api_user(), true);
4527 // Update global directory in background
4528 Profile::publishUpdate(api_user());
4530 // output for client
4532 return api_account_verify_credentials($type);
4534 // SaveMediaToDatabase failed for some reason
4535 throw new InternalServerErrorException("image upload failed");
4539 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4540 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4541 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4542 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4543 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4544 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4545 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4546 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4547 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4550 * Update user profile
4552 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4554 * @return array|string
4555 * @throws BadRequestException
4556 * @throws ForbiddenException
4557 * @throws ImagickException
4558 * @throws InternalServerErrorException
4559 * @throws UnauthorizedException
4561 function api_account_update_profile($type)
4563 $local_user = api_user();
4564 $api_user = api_get_user(DI::app());
4566 if (!empty($_POST['name'])) {
4567 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4568 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4569 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4570 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4573 if (isset($_POST['description'])) {
4574 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4575 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4576 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4579 Profile::publishUpdate($local_user);
4581 return api_account_verify_credentials($type);
4584 /// @TODO move to top of file or somewhere better
4585 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4589 * @param string $acl_string
4593 function check_acl_input($acl_string)
4595 if (empty($acl_string)) {
4599 $contact_not_found = false;
4601 // split <x><y><z> into array of cid's
4602 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4604 // check for each cid if it is available on server
4605 $cid_array = $array[0];
4606 foreach ($cid_array as $cid) {
4607 $cid = str_replace("<", "", $cid);
4608 $cid = str_replace(">", "", $cid);
4609 $condition = ['id' => $cid, 'uid' => api_user()];
4610 $contact_not_found |= !DBA::exists('contact', $condition);
4612 return $contact_not_found;
4616 * @param string $mediatype
4617 * @param array $media
4618 * @param string $type
4619 * @param string $album
4620 * @param string $allow_cid
4621 * @param string $deny_cid
4622 * @param string $allow_gid
4623 * @param string $deny_gid
4624 * @param string $desc
4625 * @param integer $profile
4626 * @param boolean $visibility
4627 * @param string $photo_id
4629 * @throws BadRequestException
4630 * @throws ForbiddenException
4631 * @throws ImagickException
4632 * @throws InternalServerErrorException
4633 * @throws NotFoundException
4634 * @throws UnauthorizedException
4636 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)
4644 if (is_array($media)) {
4645 if (is_array($media['tmp_name'])) {
4646 $src = $media['tmp_name'][0];
4648 $src = $media['tmp_name'];
4650 if (is_array($media['name'])) {
4651 $filename = basename($media['name'][0]);
4653 $filename = basename($media['name']);
4655 if (is_array($media['size'])) {
4656 $filesize = intval($media['size'][0]);
4658 $filesize = intval($media['size']);
4660 if (is_array($media['type'])) {
4661 $filetype = $media['type'][0];
4663 $filetype = $media['type'];
4667 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4670 "File upload src: " . $src . " - filename: " . $filename .
4671 " - size: " . $filesize . " - type: " . $filetype,
4675 // check if there was a php upload error
4676 if ($filesize == 0 && $media['error'] == 1) {
4677 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4679 // check against max upload size within Friendica instance
4680 $maximagesize = DI::config()->get('system', 'maximagesize');
4681 if ($maximagesize && ($filesize > $maximagesize)) {
4682 $formattedBytes = Strings::formatBytes($maximagesize);
4683 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4686 // create Photo instance with the data of the image
4687 $imagedata = @file_get_contents($src);
4688 $Image = new Image($imagedata, $filetype);
4689 if (!$Image->isValid()) {
4690 throw new InternalServerErrorException("unable to process image data");
4693 // check orientation of image
4694 $Image->orient($src);
4697 // check max length of images on server
4698 $max_length = DI::config()->get('system', 'max_image_length');
4700 $max_length = MAX_IMAGE_LENGTH;
4702 if ($max_length > 0) {
4703 $Image->scaleDown($max_length);
4704 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4706 $width = $Image->getWidth();
4707 $height = $Image->getHeight();
4709 // create a new resource-id if not already provided
4710 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4712 if ($mediatype == "photo") {
4713 // upload normal image (scales 0, 1, 2)
4714 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4716 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4718 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4720 if ($width > 640 || $height > 640) {
4721 $Image->scaleDown(640);
4722 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4724 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4728 if ($width > 320 || $height > 320) {
4729 $Image->scaleDown(320);
4730 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4732 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4735 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4736 } elseif ($mediatype == "profileimage") {
4737 // upload profile image (scales 4, 5, 6)
4738 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4740 if ($width > 300 || $height > 300) {
4741 $Image->scaleDown(300);
4742 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4744 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4748 if ($width > 80 || $height > 80) {
4749 $Image->scaleDown(80);
4750 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4752 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4756 if ($width > 48 || $height > 48) {
4757 $Image->scaleDown(48);
4758 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4760 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4763 $Image->__destruct();
4764 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4768 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4769 if ($photo_id == null && $mediatype == "photo") {
4770 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4772 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4773 return prepare_photo_data($type, false, $resource_id);
4775 throw new InternalServerErrorException("image upload failed");
4781 * @param string $hash
4782 * @param string $allow_cid
4783 * @param string $deny_cid
4784 * @param string $allow_gid
4785 * @param string $deny_gid
4786 * @param string $filetype
4787 * @param boolean $visibility
4788 * @throws InternalServerErrorException
4790 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4792 // get data about the api authenticated user
4793 $uri = Item::newURI(intval(api_user()));
4794 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4797 $arr['guid'] = System::createUUID();
4798 $arr['uid'] = intval(api_user());
4800 $arr['type'] = 'photo';
4802 $arr['resource-id'] = $hash;
4803 $arr['contact-id'] = $owner_record['id'];
4804 $arr['owner-name'] = $owner_record['name'];
4805 $arr['owner-link'] = $owner_record['url'];
4806 $arr['owner-avatar'] = $owner_record['thumb'];
4807 $arr['author-name'] = $owner_record['name'];
4808 $arr['author-link'] = $owner_record['url'];
4809 $arr['author-avatar'] = $owner_record['thumb'];
4811 $arr['allow_cid'] = $allow_cid;
4812 $arr['allow_gid'] = $allow_gid;
4813 $arr['deny_cid'] = $deny_cid;
4814 $arr['deny_gid'] = $deny_gid;
4815 $arr['visible'] = $visibility;
4819 'image/jpeg' => 'jpg',
4820 'image/png' => 'png',
4821 'image/gif' => 'gif'
4824 // adds link to the thumbnail scale photo
4825 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4826 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4829 // do the magic for storing the item in the database and trigger the federation to other contacts
4835 * @param string $type
4837 * @param string $photo_id
4840 * @throws BadRequestException
4841 * @throws ForbiddenException
4842 * @throws ImagickException
4843 * @throws InternalServerErrorException
4844 * @throws NotFoundException
4845 * @throws UnauthorizedException
4847 function prepare_photo_data($type, $scale, $photo_id)
4850 $user_info = api_get_user($a);
4852 if ($user_info === false) {
4853 throw new ForbiddenException();
4856 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4857 $data_sql = ($scale === false ? "" : "data, ");
4859 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4860 // clients needs to convert this in their way for further processing
4862 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4863 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4864 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4865 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4866 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4867 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4869 intval(local_user()),
4870 DBA::escape($photo_id),
4875 'image/jpeg' => 'jpg',
4876 'image/png' => 'png',
4877 'image/gif' => 'gif'
4880 // prepare output data for photo
4881 if (DBA::isResult($r)) {
4882 $data = ['photo' => $r[0]];
4883 $data['photo']['id'] = $data['photo']['resource-id'];
4884 if ($scale !== false) {
4885 $data['photo']['data'] = base64_encode($data['photo']['data']);
4887 unset($data['photo']['datasize']); //needed only with scale param
4889 if ($type == "xml") {
4890 $data['photo']['links'] = [];
4891 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4892 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4894 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4897 $data['photo']['link'] = [];
4898 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4900 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4901 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4905 unset($data['photo']['resource-id']);
4906 unset($data['photo']['minscale']);
4907 unset($data['photo']['maxscale']);
4909 throw new NotFoundException();
4912 // retrieve item element for getting activities (like, dislike etc.) related to photo
4913 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4914 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4915 if (!DBA::isResult($item)) {
4916 throw new NotFoundException('Photo-related item not found.');
4919 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4921 // retrieve comments on photo
4922 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4923 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4925 $statuses = Post::selectForUser(api_user(), [], $condition);
4927 // prepare output of comments
4928 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4930 if ($type == "xml") {
4932 foreach ($commentData as $comment) {
4933 $comments[$k++ . ":comment"] = $comment;
4936 foreach ($commentData as $comment) {
4937 $comments[] = $comment;
4940 $data['photo']['friendica_comments'] = $comments;
4942 // include info if rights on photo and rights on item are mismatching
4943 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4944 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4945 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4946 $data['photo']['deny_gid'] != $item['deny_gid'];
4947 $data['photo']['rights_mismatch'] = $rights_mismatch;
4954 * Similar as /mod/redir.php
4955 * redirect to 'url' after dfrn auth
4957 * Why this when there is mod/redir.php already?
4958 * This use api_user() and api_login()
4961 * c_url: url of remote contact to auth to
4962 * url: string, url to redirect after auth
4964 function api_friendica_remoteauth()
4966 $url = $_GET['url'] ?? '';
4967 $c_url = $_GET['c_url'] ?? '';
4969 if ($url === '' || $c_url === '') {
4970 throw new BadRequestException("Wrong parameters.");
4973 $c_url = Strings::normaliseLink($c_url);
4977 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4978 if (!DBA::isResult($contact)) {
4979 throw new BadRequestException("Unknown contact");
4982 $cid = $contact['id'];
4984 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
4986 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
4987 System::externalRedirect($url ?: $c_url);
4990 if ($contact['duplex'] && $contact['issued-id']) {
4991 $orig_id = $contact['issued-id'];
4992 $dfrn_id = '1:' . $orig_id;
4994 if ($contact['duplex'] && $contact['dfrn-id']) {
4995 $orig_id = $contact['dfrn-id'];
4996 $dfrn_id = '0:' . $orig_id;
4999 $sec = Strings::getRandomHex();
5001 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5002 'sec' => $sec, 'expire' => time() + 45];
5003 DBA::insert('profile_check', $fields);
5005 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5006 $dest = ($url ? '&destination_url=' . $url : '');
5008 System::externalRedirect(
5009 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5010 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5011 . '&type=profile&sec=' . $sec . $dest
5014 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5017 * Return an item with announcer data if it had been announced
5019 * @param array $item Item array
5020 * @return array Item array with announce data
5022 function api_get_announce($item)
5024 // Quit if the item already has got a different owner and author
5025 if ($item['owner-id'] != $item['author-id']) {
5029 // Don't change original or Diaspora posts
5030 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5034 // Quit if we do now the original author and it had been a post from a native network
5035 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5039 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5040 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5041 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5042 if (!DBA::isResult($announce)) {
5046 return array_merge($item, $announce);
5050 * Return the item shared, if the item contains only the [share] tag
5052 * @param array $item Sharer item
5053 * @return array|false Shared item or false if not a reshare
5054 * @throws ImagickException
5055 * @throws InternalServerErrorException
5057 function api_share_as_retweet(&$item)
5059 $body = trim($item["body"]);
5061 if (Diaspora::isReshare($body, false) === false) {
5062 if ($item['author-id'] == $item['owner-id']) {
5065 // Reshares from OStatus, ActivityPub and Twitter
5066 $reshared_item = $item;
5067 $reshared_item['owner-id'] = $reshared_item['author-id'];
5068 $reshared_item['owner-link'] = $reshared_item['author-link'];
5069 $reshared_item['owner-name'] = $reshared_item['author-name'];
5070 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5071 return $reshared_item;
5075 $reshared = Item::getShareArray($item);
5076 if (empty($reshared)) {
5080 $reshared_item = $item;
5082 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5086 if (!empty($reshared['comment'])) {
5087 $item['body'] = $reshared['comment'];
5090 $reshared_item["share-pre-body"] = $reshared['comment'];
5091 $reshared_item["body"] = $reshared['shared'];
5092 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5093 $reshared_item["author-name"] = $reshared['author'];
5094 $reshared_item["author-link"] = $reshared['profile'];
5095 $reshared_item["author-avatar"] = $reshared['avatar'];
5096 $reshared_item["plink"] = $reshared['link'] ?? '';
5097 $reshared_item["created"] = $reshared['posted'];
5098 $reshared_item["edited"] = $reshared['posted'];
5100 // Try to fetch the original item
5101 if (!empty($reshared['guid'])) {
5102 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5103 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5104 $condition = ['id' => $original_id];
5109 if (!empty($condition)) {
5110 $original_item = Post::selectFirst([], $condition);
5111 if (DBA::isResult($original_item)) {
5112 $reshared_item = array_merge($reshared_item, $original_item);
5116 return $reshared_item;
5121 * @param array $item
5126 function api_in_reply_to($item)
5130 $in_reply_to['status_id'] = null;
5131 $in_reply_to['user_id'] = null;
5132 $in_reply_to['status_id_str'] = null;
5133 $in_reply_to['user_id_str'] = null;
5134 $in_reply_to['screen_name'] = null;
5136 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5137 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5138 if (DBA::isResult($parent)) {
5139 $in_reply_to['status_id'] = intval($parent['id']);
5141 $in_reply_to['status_id'] = intval($item['parent']);
5144 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5146 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5147 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5149 if (DBA::isResult($parent)) {
5150 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5151 $in_reply_to['user_id'] = intval($parent['author-id']);
5152 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5155 // There seems to be situation, where both fields are identical:
5156 // https://github.com/friendica/friendica/issues/1010
5157 // This is a bugfix for that.
5158 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5159 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']]);
5160 $in_reply_to['status_id'] = null;
5161 $in_reply_to['user_id'] = null;
5162 $in_reply_to['status_id_str'] = null;
5163 $in_reply_to['user_id_str'] = null;
5164 $in_reply_to['screen_name'] = null;
5168 return $in_reply_to;
5173 * @param string $text
5176 * @throws InternalServerErrorException
5178 function api_clean_plain_items($text)
5180 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5182 $text = BBCode::cleanPictureLinks($text);
5183 $URLSearchString = "^\[\]";
5185 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5187 if ($include_entities == "true") {
5188 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5191 // Simplify "attachment" element
5192 $text = BBCode::removeAttachment($text);
5199 * @param array $contacts
5203 function api_best_nickname(&$contacts)
5207 if (count($contacts) == 0) {
5211 foreach ($contacts as $contact) {
5212 if ($contact["network"] == "") {
5213 $contact["network"] = "dfrn";
5214 $best_contact = [$contact];
5218 if (sizeof($best_contact) == 0) {
5219 foreach ($contacts as $contact) {
5220 if ($contact["network"] == "dfrn") {
5221 $best_contact = [$contact];
5226 if (sizeof($best_contact) == 0) {
5227 foreach ($contacts as $contact) {
5228 if ($contact["network"] == "dspr") {
5229 $best_contact = [$contact];
5234 if (sizeof($best_contact) == 0) {
5235 foreach ($contacts as $contact) {
5236 if ($contact["network"] == "stat") {
5237 $best_contact = [$contact];
5242 if (sizeof($best_contact) == 0) {
5243 foreach ($contacts as $contact) {
5244 if ($contact["network"] == "pump") {
5245 $best_contact = [$contact];
5250 if (sizeof($best_contact) == 0) {
5251 foreach ($contacts as $contact) {
5252 if ($contact["network"] == "twit") {
5253 $best_contact = [$contact];
5258 if (sizeof($best_contact) == 1) {
5259 $contacts = $best_contact;
5261 $contacts = [$contacts[0]];
5266 * Return all or a specified group of the user with the containing contacts.
5268 * @param string $type Return type (atom, rss, xml, json)
5270 * @return array|string
5271 * @throws BadRequestException
5272 * @throws ForbiddenException
5273 * @throws ImagickException
5274 * @throws InternalServerErrorException
5275 * @throws UnauthorizedException
5277 function api_friendica_group_show($type)
5281 if (api_user() === false) {
5282 throw new ForbiddenException();
5286 $user_info = api_get_user($a);
5287 $gid = $_REQUEST['gid'] ?? 0;
5288 $uid = $user_info['uid'];
5290 // get data of the specified group id or all groups if not specified
5293 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5297 // error message if specified gid is not in database
5298 if (!DBA::isResult($r)) {
5299 throw new BadRequestException("gid not available");
5303 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5308 // loop through all groups and retrieve all members for adding data in the user array
5310 foreach ($r as $rr) {
5311 $members = Contact\Group::getById($rr['id']);
5314 if ($type == "xml") {
5315 $user_element = "users";
5317 foreach ($members as $member) {
5318 $user = api_get_user($a, $member['nurl']);
5319 $users[$k++.":user"] = $user;
5322 $user_element = "user";
5323 foreach ($members as $member) {
5324 $user = api_get_user($a, $member['nurl']);
5328 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5330 return api_format_data("groups", $type, ['group' => $grps]);
5332 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5336 * Delete the specified group of the user.
5338 * @param string $type Return type (atom, rss, xml, json)
5340 * @return array|string
5341 * @throws BadRequestException
5342 * @throws ForbiddenException
5343 * @throws ImagickException
5344 * @throws InternalServerErrorException
5345 * @throws UnauthorizedException
5347 function api_friendica_group_delete($type)
5351 if (api_user() === false) {
5352 throw new ForbiddenException();
5356 $user_info = api_get_user($a);
5357 $gid = $_REQUEST['gid'] ?? 0;
5358 $name = $_REQUEST['name'] ?? '';
5359 $uid = $user_info['uid'];
5361 // error if no gid specified
5362 if ($gid == 0 || $name == "") {
5363 throw new BadRequestException('gid or name not specified');
5366 // get data of the specified group id
5368 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5372 // error message if specified gid is not in database
5373 if (!DBA::isResult($r)) {
5374 throw new BadRequestException('gid not available');
5377 // get data of the specified group id and group name
5379 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5384 // error message if specified gid is not in database
5385 if (!DBA::isResult($rname)) {
5386 throw new BadRequestException('wrong group name');
5390 $ret = Group::removeByName($uid, $name);
5393 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5394 return api_format_data("group_delete", $type, ['result' => $success]);
5396 throw new BadRequestException('other API error');
5399 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5404 * @param string $type Return type (atom, rss, xml, json)
5406 * @return array|string
5407 * @throws BadRequestException
5408 * @throws ForbiddenException
5409 * @throws ImagickException
5410 * @throws InternalServerErrorException
5411 * @throws UnauthorizedException
5412 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5414 function api_lists_destroy($type)
5418 if (api_user() === false) {
5419 throw new ForbiddenException();
5423 $user_info = api_get_user($a);
5424 $gid = $_REQUEST['list_id'] ?? 0;
5425 $uid = $user_info['uid'];
5427 // error if no gid specified
5429 throw new BadRequestException('gid not specified');
5432 // get data of the specified group id
5433 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5434 // error message if specified gid is not in database
5436 throw new BadRequestException('gid not available');
5439 if (Group::remove($gid)) {
5441 'name' => $group['name'],
5442 'id' => intval($gid),
5443 'id_str' => (string) $gid,
5444 'user' => $user_info
5447 return api_format_data("lists", $type, ['lists' => $list]);
5450 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5453 * Add a new group to the database.
5455 * @param string $name Group name
5456 * @param int $uid User ID
5457 * @param array $users List of users to add to the group
5460 * @throws BadRequestException
5462 function group_create($name, $uid, $users = [])
5464 // error if no name specified
5466 throw new BadRequestException('group name not specified');
5469 // get data of the specified group name
5471 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5475 // error message if specified group name already exists
5476 if (DBA::isResult($rname)) {
5477 throw new BadRequestException('group name already exists');
5480 // check if specified group name is a deleted group
5482 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5486 // error message if specified group name already exists
5487 if (DBA::isResult($rname)) {
5488 $reactivate_group = true;
5492 $ret = Group::create($uid, $name);
5494 $gid = Group::getIdByName($uid, $name);
5496 throw new BadRequestException('other API error');
5500 $erroraddinguser = false;
5502 foreach ($users as $user) {
5503 $cid = $user['cid'];
5504 // check if user really exists as contact
5506 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5510 if (count($contact)) {
5511 Group::addMember($gid, $cid);
5513 $erroraddinguser = true;
5514 $errorusers[] = $cid;
5518 // return success message incl. missing users in array
5519 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5521 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5525 * Create the specified group with the posted array of contacts.
5527 * @param string $type Return type (atom, rss, xml, json)
5529 * @return array|string
5530 * @throws BadRequestException
5531 * @throws ForbiddenException
5532 * @throws ImagickException
5533 * @throws InternalServerErrorException
5534 * @throws UnauthorizedException
5536 function api_friendica_group_create($type)
5540 if (api_user() === false) {
5541 throw new ForbiddenException();
5545 $user_info = api_get_user($a);
5546 $name = $_REQUEST['name'] ?? '';
5547 $uid = $user_info['uid'];
5548 $json = json_decode($_POST['json'], true);
5549 $users = $json['user'];
5551 $success = group_create($name, $uid, $users);
5553 return api_format_data("group_create", $type, ['result' => $success]);
5555 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5558 * Create a new group.
5560 * @param string $type Return type (atom, rss, xml, json)
5562 * @return array|string
5563 * @throws BadRequestException
5564 * @throws ForbiddenException
5565 * @throws ImagickException
5566 * @throws InternalServerErrorException
5567 * @throws UnauthorizedException
5568 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5570 function api_lists_create($type)
5574 if (api_user() === false) {
5575 throw new ForbiddenException();
5579 $user_info = api_get_user($a);
5580 $name = $_REQUEST['name'] ?? '';
5581 $uid = $user_info['uid'];
5583 $success = group_create($name, $uid);
5584 if ($success['success']) {
5586 'name' => $success['name'],
5587 'id' => intval($success['gid']),
5588 'id_str' => (string) $success['gid'],
5589 'user' => $user_info
5592 return api_format_data("lists", $type, ['lists'=>$grp]);
5595 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5598 * Update the specified group with the posted array of contacts.
5600 * @param string $type Return type (atom, rss, xml, json)
5602 * @return array|string
5603 * @throws BadRequestException
5604 * @throws ForbiddenException
5605 * @throws ImagickException
5606 * @throws InternalServerErrorException
5607 * @throws UnauthorizedException
5609 function api_friendica_group_update($type)
5613 if (api_user() === false) {
5614 throw new ForbiddenException();
5618 $user_info = api_get_user($a);
5619 $uid = $user_info['uid'];
5620 $gid = $_REQUEST['gid'] ?? 0;
5621 $name = $_REQUEST['name'] ?? '';
5622 $json = json_decode($_POST['json'], true);
5623 $users = $json['user'];
5625 // error if no name specified
5627 throw new BadRequestException('group name not specified');
5630 // error if no gid specified
5632 throw new BadRequestException('gid not specified');
5636 $members = Contact\Group::getById($gid);
5637 foreach ($members as $member) {
5638 $cid = $member['id'];
5639 foreach ($users as $user) {
5640 $found = ($user['cid'] == $cid ? true : false);
5642 if (!isset($found) || !$found) {
5643 Group::removeMemberByName($uid, $name, $cid);
5648 $erroraddinguser = false;
5650 foreach ($users as $user) {
5651 $cid = $user['cid'];
5652 // check if user really exists as contact
5654 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5659 if (count($contact)) {
5660 Group::addMember($gid, $cid);
5662 $erroraddinguser = true;
5663 $errorusers[] = $cid;
5667 // return success message incl. missing users in array
5668 $status = ($erroraddinguser ? "missing user" : "ok");
5669 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5670 return api_format_data("group_update", $type, ['result' => $success]);
5673 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5676 * Update information about a group.
5678 * @param string $type Return type (atom, rss, xml, json)
5680 * @return array|string
5681 * @throws BadRequestException
5682 * @throws ForbiddenException
5683 * @throws ImagickException
5684 * @throws InternalServerErrorException
5685 * @throws UnauthorizedException
5686 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5688 function api_lists_update($type)
5692 if (api_user() === false) {
5693 throw new ForbiddenException();
5697 $user_info = api_get_user($a);
5698 $gid = $_REQUEST['list_id'] ?? 0;
5699 $name = $_REQUEST['name'] ?? '';
5700 $uid = $user_info['uid'];
5702 // error if no gid specified
5704 throw new BadRequestException('gid not specified');
5707 // get data of the specified group id
5708 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5709 // error message if specified gid is not in database
5711 throw new BadRequestException('gid not available');
5714 if (Group::update($gid, $name)) {
5717 'id' => intval($gid),
5718 'id_str' => (string) $gid,
5719 'user' => $user_info
5722 return api_format_data("lists", $type, ['lists' => $list]);
5726 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5730 * @param string $type Return type (atom, rss, xml, json)
5732 * @return array|string
5733 * @throws BadRequestException
5734 * @throws ForbiddenException
5735 * @throws ImagickException
5736 * @throws InternalServerErrorException
5738 function api_friendica_activity($type)
5742 if (api_user() === false) {
5743 throw new ForbiddenException();
5745 $verb = strtolower($a->argv[3]);
5746 $verb = preg_replace("|\..*$|", "", $verb);
5748 $id = $_REQUEST['id'] ?? 0;
5750 $res = Item::performActivity($id, $verb, api_user());
5753 if ($type == "xml") {
5758 return api_format_data('ok', $type, ['ok' => $ok]);
5760 throw new BadRequestException('Error adding activity');
5764 /// @TODO move to top of file or somewhere better
5765 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5766 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5767 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5768 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5769 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5770 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5771 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5772 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5773 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5774 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5777 * Returns notifications
5779 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5781 * @return string|array
5782 * @throws ForbiddenException
5783 * @throws BadRequestException
5786 function api_friendica_notification($type)
5790 if (api_user() === false) {
5791 throw new ForbiddenException();
5794 throw new BadRequestException("Invalid argument count");
5797 $notifications = DI::notification()->getApiList(local_user());
5799 if ($type == "xml") {
5801 if (!empty($notifications)) {
5802 foreach ($notifications as $notification) {
5803 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5807 $result = $xmlnotes;
5808 } elseif (count($notifications) > 0) {
5809 $result = $notifications->getArrayCopy();
5814 return api_format_data("notes", $type, ['note' => $result]);
5818 * Set notification as seen and returns associated item (if possible)
5820 * POST request with 'id' param as notification id
5822 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5823 * @return string|array
5824 * @throws BadRequestException
5825 * @throws ForbiddenException
5826 * @throws ImagickException
5827 * @throws InternalServerErrorException
5828 * @throws UnauthorizedException
5830 function api_friendica_notification_seen($type)
5833 $user_info = api_get_user($a);
5835 if (api_user() === false || $user_info === false) {
5836 throw new ForbiddenException();
5838 if ($a->argc !== 4) {
5839 throw new BadRequestException("Invalid argument count");
5842 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5845 $notify = DI::notify()->getByID($id, api_user());
5846 DI::notify()->setSeen(true, $notify);
5848 if ($notify->otype === Notification\ObjectType::ITEM) {
5849 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5850 if (DBA::isResult($item)) {
5851 // we found the item, return it to the user
5852 $ret = api_format_items([$item], $user_info, false, $type);
5853 $data = ['status' => $ret];
5854 return api_format_data("status", $type, $data);
5856 // the item can't be found, but we set the notification as seen, so we count this as a success
5858 return api_format_data('result', $type, ['result' => "success"]);
5859 } catch (NotFoundException $e) {
5860 throw new BadRequestException('Invalid argument', $e);
5861 } catch (Exception $e) {
5862 throw new InternalServerErrorException('Internal Server exception', $e);
5866 /// @TODO move to top of file or somewhere better
5867 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5868 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5871 * update a direct_message to seen state
5873 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5874 * @return string|array (success result=ok, error result=error with error message)
5875 * @throws BadRequestException
5876 * @throws ForbiddenException
5877 * @throws ImagickException
5878 * @throws InternalServerErrorException
5879 * @throws UnauthorizedException
5881 function api_friendica_direct_messages_setseen($type)
5884 if (api_user() === false) {
5885 throw new ForbiddenException();
5889 $user_info = api_get_user($a);
5890 $uid = $user_info['uid'];
5891 $id = $_REQUEST['id'] ?? 0;
5893 // return error if id is zero
5895 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5896 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5899 // error message if specified id is not in database
5900 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5901 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5902 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5905 // update seen indicator
5906 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5910 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5911 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5913 $answer = ['result' => 'error', 'message' => 'unknown error'];
5914 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5918 /// @TODO move to top of file or somewhere better
5919 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5922 * search for direct_messages containing a searchstring through api
5924 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5925 * @param string $box
5926 * @return string|array (success: success=true if found and search_result contains found messages,
5927 * success=false if nothing was found, search_result='nothing found',
5928 * error: result=error with error message)
5929 * @throws BadRequestException
5930 * @throws ForbiddenException
5931 * @throws ImagickException
5932 * @throws InternalServerErrorException
5933 * @throws UnauthorizedException
5935 function api_friendica_direct_messages_search($type, $box = "")
5939 if (api_user() === false) {
5940 throw new ForbiddenException();
5944 $user_info = api_get_user($a);
5945 $searchstring = $_REQUEST['searchstring'] ?? '';
5946 $uid = $user_info['uid'];
5948 // error if no searchstring specified
5949 if ($searchstring == "") {
5950 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5951 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5954 // get data for the specified searchstring
5956 "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",
5958 DBA::escape('%'.$searchstring.'%')
5961 $profile_url = $user_info["url"];
5963 // message if nothing was found
5964 if (!DBA::isResult($r)) {
5965 $success = ['success' => false, 'search_results' => 'problem with query'];
5966 } elseif (count($r) == 0) {
5967 $success = ['success' => false, 'search_results' => 'nothing found'];
5970 foreach ($r as $item) {
5971 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5972 $recipient = $user_info;
5973 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5974 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5975 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5976 $sender = $user_info;
5979 if (isset($recipient) && isset($sender)) {
5980 $ret[] = api_format_messages($item, $recipient, $sender);
5983 $success = ['success' => true, 'search_results' => $ret];
5986 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5989 /// @TODO move to top of file or somewhere better
5990 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5993 * Returns a list of saved searches.
5995 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5997 * @param string $type Return format: json or xml
5999 * @return string|array
6002 function api_saved_searches_list($type)
6004 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6007 while ($term = DBA::fetch($terms)) {
6009 'created_at' => api_date(time()),
6010 'id' => intval($term['id']),
6011 'id_str' => $term['id'],
6012 'name' => $term['term'],
6014 'query' => $term['term']
6020 return api_format_data("terms", $type, ['terms' => $result]);
6023 /// @TODO move to top of file or somewhere better
6024 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6027 * Number of comments
6029 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6031 * @param object $data [Status, Status]
6035 function bindComments(&$data)
6037 if (count($data) == 0) {
6043 foreach ($data as $item) {
6044 $ids[] = $item['id'];
6047 $idStr = DBA::escape(implode(', ', $ids));
6048 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6049 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6050 $itemsData = DBA::toArray($items);
6052 foreach ($itemsData as $item) {
6053 $comments[$item['parent']] = $item['comments'];
6056 foreach ($data as $idx => $item) {
6058 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6063 @TODO Maybe open to implement?
6065 [pagename] => api/1.1/statuses/lookup.json
6066 [id] => 605138389168451584
6067 [include_cards] => true
6068 [cards_platform] => Android-12
6069 [include_entities] => true
6070 [include_my_retweet] => 1
6072 [include_reply_count] => true
6073 [include_descendent_reply_count] => true
6077 Not implemented by now:
6078 statuses/retweets_of_me
6083 account/update_location
6084 account/update_profile_background_image
6087 friendica/profile/update
6088 friendica/profile/create
6089 friendica/profile/delete
6091 Not implemented in status.net:
6092 statuses/retweeted_to_me
6093 statuses/retweeted_by_me
6094 direct_messages/destroy
6096 account/update_delivery_device
6097 notifications/follow