3 * @copyright Copyright (C) 2020, Friendica
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\Notify;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\UserItem;
47 use Friendica\Model\Verb;
48 use Friendica\Security\FKOAuth1;
49 use Friendica\Network\HTTPException;
50 use Friendica\Network\HTTPException\BadRequestException;
51 use Friendica\Network\HTTPException\ExpectationFailedException;
52 use Friendica\Network\HTTPException\ForbiddenException;
53 use Friendica\Network\HTTPException\InternalServerErrorException;
54 use Friendica\Network\HTTPException\MethodNotAllowedException;
55 use Friendica\Network\HTTPException\NotFoundException;
56 use Friendica\Network\HTTPException\NotImplementedException;
57 use Friendica\Network\HTTPException\TooManyRequestsException;
58 use Friendica\Network\HTTPException\UnauthorizedException;
59 use Friendica\Object\Image;
60 use Friendica\Protocol\Activity;
61 use Friendica\Protocol\Diaspora;
62 use Friendica\Security\OAuth1\OAuthRequest;
63 use Friendica\Security\OAuth1\OAuthUtil;
64 use Friendica\Util\DateTimeFormat;
65 use Friendica\Util\Images;
66 use Friendica\Util\Network;
67 use Friendica\Util\Proxy as ProxyUtils;
68 use Friendica\Util\Strings;
69 use Friendica\Util\XML;
71 require_once __DIR__ . '/../mod/item.php';
72 require_once __DIR__ . '/../mod/wall_upload.php';
74 define('API_METHOD_ANY', '*');
75 define('API_METHOD_GET', 'GET');
76 define('API_METHOD_POST', 'POST,PUT');
77 define('API_METHOD_DELETE', 'POST,DELETE');
79 define('API_LOG_PREFIX', 'API {action} - ');
87 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
88 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
89 * into a page, and visitors will post something without noticing it).
93 if (!empty($_SESSION['allow_api'])) {
101 * Get source name from API client
103 * Clients can send 'source' parameter to be show in post metadata
104 * as "sent via <source>".
105 * Some clients doesn't send a source param, we support ones we know
106 * (only Twidere, atm)
109 * Client source name, default to "api" if unset/unknown
112 function api_source()
114 if (requestdata('source')) {
115 return requestdata('source');
118 // Support for known clients that doesn't send a source name
119 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
120 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
124 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
126 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
133 * Format date for API
135 * @param string $str Source date, as UTC
136 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
139 function api_date($str)
141 // Wed May 23 06:01:13 +0000 2007
142 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
146 * Register a function to be the endpoint for defined API path.
148 * @param string $path API URL path, relative to DI::baseUrl()
149 * @param string $func Function name to call on path request
150 * @param bool $auth API need logged user
151 * @param string $method HTTP method reqiured to call this endpoint.
152 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
153 * Default to API_METHOD_ANY
155 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
165 // Workaround for hotot
166 $path = str_replace("api/", "api/1.1/", $path);
176 * Log in user via OAuth1 or Simple HTTP Auth.
177 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
180 * @throws ForbiddenException
181 * @throws InternalServerErrorException
182 * @throws UnauthorizedException
183 * @hook 'authenticate'
185 * 'username' => username from login form
186 * 'password' => password from login form
187 * 'authenticated' => return status,
188 * 'user_record' => return authenticated user record
190 function api_login(App $a)
192 // workaround for HTTP-auth in CGI mode
193 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
194 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
195 if (strlen($userpass)) {
196 list($name, $password) = explode(':', $userpass);
197 $_SERVER['PHP_AUTH_USER'] = $name;
198 $_SERVER['PHP_AUTH_PW'] = $password;
202 if (empty($_SERVER['PHP_AUTH_USER'])) {
203 // Try OAuth when no user is provided
204 $oauth1 = new FKOAuth1();
207 $request = OAuthRequest::from_request();
208 list($consumer, $token) = $oauth1->verify_request($request);
209 if (!is_null($token)) {
210 $oauth1->loginUser($token->uid);
211 Session::set('allow_api', true);
214 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
215 var_dump($consumer, $token);
217 } catch (Exception $e) {
218 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
221 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
222 header('WWW-Authenticate: Basic realm="Friendica"');
223 throw new UnauthorizedException("This API requires login");
226 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
227 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
229 // allow "user@server" login (but ignore 'server' part)
230 $at = strstr($user, "@", true);
235 // next code from mod/auth.php. needs better solution
239 'username' => trim($user),
240 'password' => trim($password),
241 'authenticated' => 0,
242 'user_record' => null,
246 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
247 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
248 * and later addons should not interfere with an earlier one that succeeded.
250 Hook::callAll('authenticate', $addon_auth);
252 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
253 $record = $addon_auth['user_record'];
255 $user_id = User::authenticate(trim($user), trim($password), true);
256 if ($user_id !== false) {
257 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
261 if (!DBA::isResult($record)) {
262 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
263 header('WWW-Authenticate: Basic realm="Friendica"');
264 //header('HTTP/1.0 401 Unauthorized');
265 //die('This api requires login');
266 throw new UnauthorizedException("This API requires login");
269 // Don't refresh the login date more often than twice a day to spare database writes
270 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
272 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
274 $_SESSION["allow_api"] = true;
276 Hook::callAll('logged_in', $a->user);
280 * Check HTTP method of called API
282 * API endpoints can define which HTTP method to accept when called.
283 * This function check the current HTTP method agains endpoint
286 * @param string $method Required methods, uppercase, separated by comma
289 function api_check_method($method)
291 if ($method == "*") {
294 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
298 * Main API entry point
300 * Authenticate user, call registered API function, set HTTP headers
303 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
304 * @return string|array API call result
307 function api_call(App $a, App\Arguments $args = null)
309 global $API, $called_api;
316 if (strpos($args->getCommand(), ".xml") > 0) {
319 if (strpos($args->getCommand(), ".json") > 0) {
322 if (strpos($args->getCommand(), ".rss") > 0) {
325 if (strpos($args->getCommand(), ".atom") > 0) {
330 foreach ($API as $p => $info) {
331 if (strpos($args->getCommand(), $p) === 0) {
332 if (!api_check_method($info['method'])) {
333 throw new MethodNotAllowedException();
336 $called_api = explode("/", $p);
338 if (!empty($info['auth']) && api_user() === false) {
340 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
343 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
345 $stamp = microtime(true);
346 $return = call_user_func($info['func'], $type);
347 $duration = floatval(microtime(true) - $stamp);
349 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
351 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
353 if (false === $return) {
355 * api function returned false withour throw an
356 * exception. This should not happend, throw a 500
358 throw new InternalServerErrorException();
363 header("Content-Type: text/xml");
366 header("Content-Type: application/json");
367 if (!empty($return)) {
368 $json = json_encode(end($return));
369 if (!empty($_GET['callback'])) {
370 $json = $_GET['callback'] . "(" . $json . ")";
376 header("Content-Type: application/rss+xml");
377 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
380 header("Content-Type: application/atom+xml");
381 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
388 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
389 throw new NotFoundException();
390 } catch (HTTPException $e) {
391 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
392 return api_error($type, $e, $args);
397 * Format API error string
399 * @param string $type Return type (xml, json, rss, as)
400 * @param object $e HTTPException Error object
401 * @param App\Arguments $args The App arguments
402 * @return string|array error message formatted as $type
404 function api_error($type, $e, App\Arguments $args)
406 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
407 /// @TODO: https://dev.twitter.com/overview/api/response-codes
409 $error = ["error" => $error,
410 "code" => $e->getCode() . " " . $e->httpdesc,
411 "request" => $args->getQueryString()];
413 $return = api_format_data('status', $type, ['status' => $error]);
417 header("Content-Type: text/xml");
420 header("Content-Type: application/json");
421 $return = json_encode($return);
424 header("Content-Type: application/rss+xml");
427 header("Content-Type: application/atom+xml");
435 * Set values for RSS template
438 * @param array $arr Array to be passed to template
439 * @param array $user_info User info
441 * @throws BadRequestException
442 * @throws ImagickException
443 * @throws InternalServerErrorException
444 * @throws UnauthorizedException
445 * @todo find proper type-hints
447 function api_rss_extra(App $a, $arr, $user_info)
449 if (is_null($user_info)) {
450 $user_info = api_get_user($a);
453 $arr['$user'] = $user_info;
455 'alternate' => $user_info['url'],
456 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
457 'base' => DI::baseUrl(),
458 'updated' => api_date(null),
459 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
460 'language' => $user_info['lang'],
461 'logo' => DI::baseUrl() . "/images/friendica-32.png",
469 * Unique contact to contact url.
471 * @param int $id Contact id
472 * @return bool|string
473 * Contact url or False if contact id is unknown
476 function api_unique_id_to_nurl($id)
478 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
480 if (DBA::isResult($r)) {
488 * Get user info array.
491 * @param int|string $contact_id Contact ID or URL
493 * @throws BadRequestException
494 * @throws ImagickException
495 * @throws InternalServerErrorException
496 * @throws UnauthorizedException
498 function api_get_user(App $a, $contact_id = null)
506 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
508 // Searching for contact URL
509 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
510 $user = DBA::escape(Strings::normaliseLink($contact_id));
512 $extra_query = "AND `contact`.`nurl` = '%s' ";
513 if (api_user() !== false) {
514 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
518 // Searching for contact id with uid = 0
519 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
520 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
523 throw new BadRequestException("User ID ".$contact_id." not found.");
527 $extra_query = "AND `contact`.`nurl` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
533 if (is_null($user) && !empty($_GET['user_id'])) {
534 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
537 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
546 if (is_null($user) && !empty($_GET['screen_name'])) {
547 $user = DBA::escape($_GET['screen_name']);
548 $extra_query = "AND `contact`.`nick` = '%s' ";
549 if (api_user() !== false) {
550 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
554 if (is_null($user) && !empty($_GET['profileurl'])) {
555 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
556 $extra_query = "AND `contact`.`nurl` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
562 // $called_api is the API path exploded on / and is expected to have at least 2 elements
563 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
564 $argid = count($called_api);
565 if (!empty($a->argv[$argid])) {
566 $data = explode(".", $a->argv[$argid]);
567 if (count($data) > 1) {
568 list($user, $null) = $data;
571 if (is_numeric($user)) {
572 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
576 $extra_query = "AND `contact`.`nurl` = '%s' ";
577 if (api_user() !== false) {
578 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
582 $user = DBA::escape($user);
583 $extra_query = "AND `contact`.`nick` = '%s' ";
584 if (api_user() !== false) {
585 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
590 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
593 if (api_user() === false) {
597 $user = $_SESSION['uid'];
598 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
602 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
606 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
612 // Selecting the id by priority, friendica first
613 if (is_array($uinfo)) {
614 api_best_nickname($uinfo);
617 // if the contact wasn't found, fetch it from the contacts with uid = 0
618 if (!DBA::isResult($uinfo)) {
620 throw new BadRequestException("User not found.");
623 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
625 if (DBA::isResult($contact)) {
627 'id' => $contact["id"],
628 'id_str' => (string) $contact["id"],
629 'name' => $contact["name"],
630 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
631 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
632 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
633 'profile_image_url' => $contact["micro"],
634 'profile_image_url_https' => $contact["micro"],
635 'profile_image_url_profile_size' => $contact["thumb"],
636 'profile_image_url_large' => $contact["photo"],
637 'url' => $contact["url"],
638 'protected' => false,
639 'followers_count' => 0,
640 'friends_count' => 0,
642 'created_at' => api_date($contact["created"]),
643 'favourites_count' => 0,
645 'time_zone' => 'UTC',
646 'geo_enabled' => false,
648 'statuses_count' => 0,
650 'contributors_enabled' => false,
651 'is_translator' => false,
652 'is_translation_enabled' => false,
653 'following' => false,
654 'follow_request_sent' => false,
655 'statusnet_blocking' => false,
656 'notifications' => false,
657 'statusnet_profile_url' => $contact["url"],
659 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
660 'pid' => Contact::getIdForURL($contact["url"], 0, false),
662 'network' => $contact["network"],
667 throw new BadRequestException("User ".$url." not found.");
671 if ($uinfo[0]['self']) {
672 if ($uinfo[0]['network'] == "") {
673 $uinfo[0]['network'] = Protocol::DFRN;
676 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
677 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
684 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
686 if (!empty($profile['about'])) {
687 $description = $profile['about'];
689 $description = $uinfo[0]["about"];
692 if (!empty($usr['default-location'])) {
693 $location = $usr['default-location'];
694 } elseif (!empty($uinfo[0]["location"])) {
695 $location = $uinfo[0]["location"];
697 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
701 'id' => intval($pcontact_id),
702 'id_str' => (string) intval($pcontact_id),
703 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
704 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
705 'location' => $location,
706 'description' => BBCode::toPlaintext($description ?? ''),
707 'profile_image_url' => $uinfo[0]['micro'],
708 'profile_image_url_https' => $uinfo[0]['micro'],
709 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
710 'profile_image_url_large' => $uinfo[0]["photo"],
711 'url' => $uinfo[0]['url'],
712 'protected' => false,
713 'followers_count' => intval($countfollowers),
714 'friends_count' => intval($countfriends),
716 'created_at' => api_date($uinfo[0]['created']),
717 'favourites_count' => intval($starred),
719 'time_zone' => 'UTC',
720 'geo_enabled' => false,
722 'statuses_count' => intval($countitems),
724 'contributors_enabled' => false,
725 'is_translator' => false,
726 'is_translation_enabled' => false,
727 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
728 'follow_request_sent' => false,
729 'statusnet_blocking' => false,
730 'notifications' => false,
732 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
733 'statusnet_profile_url' => $uinfo[0]['url'],
734 'uid' => intval($uinfo[0]['uid']),
735 'cid' => intval($uinfo[0]['cid']),
736 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
737 'self' => $uinfo[0]['self'],
738 'network' => $uinfo[0]['network'],
741 // If this is a local user and it uses Frio, we can get its color preferences.
743 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
744 if ($theme_info['theme'] === 'frio') {
745 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
747 if ($schema && ($schema != '---')) {
748 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
749 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
750 require_once $schemefile;
753 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
754 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
755 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
757 if (empty($nav_bg)) {
760 if (empty($link_color)) {
761 $link_color = "#6fdbe8";
763 if (empty($bgcolor)) {
764 $bgcolor = "#ededed";
767 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
768 $ret['profile_link_color'] = str_replace('#', '', $link_color);
769 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
777 * return api-formatted array for item's author and owner
780 * @param array $item item from db
781 * @return array(array:author, array:owner)
782 * @throws BadRequestException
783 * @throws ImagickException
784 * @throws InternalServerErrorException
785 * @throws UnauthorizedException
787 function api_item_get_user(App $a, $item)
789 $status_user = api_get_user($a, $item['author-id'] ?? null);
791 $author_user = $status_user;
793 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
795 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
796 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
798 $owner_user = $author_user;
801 return ([$status_user, $author_user, $owner_user]);
805 * walks recursively through an array with the possibility to change value and key
807 * @param array $array The array to walk through
808 * @param callable $callback The callback function
810 * @return array the transformed array
812 function api_walk_recursive(array &$array, callable $callback)
816 foreach ($array as $k => $v) {
818 if ($callback($v, $k)) {
819 $new_array[$k] = api_walk_recursive($v, $callback);
822 if ($callback($v, $k)) {
833 * Callback function to transform the array in an array that can be transformed in a XML file
835 * @param mixed $item Array item value
836 * @param string $key Array key
838 * @return boolean Should the array item be deleted?
840 function api_reformat_xml(&$item, &$key)
842 if (is_bool($item)) {
843 $item = ($item ? "true" : "false");
846 if (substr($key, 0, 10) == "statusnet_") {
847 $key = "statusnet:".substr($key, 10);
848 } elseif (substr($key, 0, 10) == "friendica_") {
849 $key = "friendica:".substr($key, 10);
851 /// @TODO old-lost code?
853 // $key = "default:".$key;
859 * Creates the XML from a JSON style array
861 * @param array $data JSON style array
862 * @param string $root_element Name of the root element
864 * @return string The XML data
866 function api_create_xml(array $data, $root_element)
868 $childname = key($data);
869 $data2 = array_pop($data);
871 $namespaces = ["" => "http://api.twitter.com",
872 "statusnet" => "http://status.net/schema/api/1/",
873 "friendica" => "http://friendi.ca/schema/api/1/",
874 "georss" => "http://www.georss.org/georss"];
876 /// @todo Auto detection of needed namespaces
877 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
881 if (is_array($data2)) {
883 api_walk_recursive($data2, "api_reformat_xml");
889 foreach ($data2 as $item) {
890 $data4[$i++ . ":" . $childname] = $item;
897 $data3 = [$root_element => $data2];
899 $ret = XML::fromArray($data3, $xml, false, $namespaces);
904 * Formats the data according to the data type
906 * @param string $root_element Name of the root element
907 * @param string $type Return type (atom, rss, xml, json)
908 * @param array $data JSON style array
910 * @return array|string (string|array) XML data or JSON data
912 function api_format_data($root_element, $type, $data)
918 $ret = api_create_xml($data, $root_element);
933 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
934 * returns a 401 status code and an error message if not.
936 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
938 * @param string $type Return type (atom, rss, xml, json)
939 * @return array|string
940 * @throws BadRequestException
941 * @throws ForbiddenException
942 * @throws ImagickException
943 * @throws InternalServerErrorException
944 * @throws UnauthorizedException
946 function api_account_verify_credentials($type)
950 if (api_user() === false) {
951 throw new ForbiddenException();
954 unset($_REQUEST["user_id"]);
955 unset($_GET["user_id"]);
957 unset($_REQUEST["screen_name"]);
958 unset($_GET["screen_name"]);
960 $skip_status = $_REQUEST['skip_status'] ?? false;
962 $user_info = api_get_user($a);
964 // "verified" isn't used here in the standard
965 unset($user_info["verified"]);
967 // - Adding last status
969 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
971 $user_info['status'] = api_format_item($item, $type);
975 // "uid" and "self" are only needed for some internal stuff, so remove it from here
976 unset($user_info["uid"]);
977 unset($user_info["self"]);
979 return api_format_data("user", $type, ['user' => $user_info]);
982 /// @TODO move to top of file or somewhere better
983 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
986 * Get data from $_POST or $_GET
991 function requestdata($k)
993 if (!empty($_POST[$k])) {
996 if (!empty($_GET[$k])) {
1003 * Deprecated function to upload media.
1005 * @param string $type Return type (atom, rss, xml, json)
1007 * @return array|string
1008 * @throws BadRequestException
1009 * @throws ForbiddenException
1010 * @throws ImagickException
1011 * @throws InternalServerErrorException
1012 * @throws UnauthorizedException
1014 function api_statuses_mediap($type)
1018 if (api_user() === false) {
1019 Logger::log('api_statuses_update: no user');
1020 throw new ForbiddenException();
1022 $user_info = api_get_user($a);
1024 $_REQUEST['profile_uid'] = api_user();
1025 $_REQUEST['api_source'] = true;
1026 $txt = requestdata('status');
1027 /// @TODO old-lost code?
1028 //$txt = urldecode(requestdata('status'));
1030 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1031 $txt = HTML::toBBCodeVideo($txt);
1032 $config = HTMLPurifier_Config::createDefault();
1033 $config->set('Cache.DefinitionImpl', null);
1034 $purifier = new HTMLPurifier($config);
1035 $txt = $purifier->purify($txt);
1037 $txt = HTML::toBBCode($txt);
1039 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1041 $picture = wall_upload_post($a, false);
1043 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1044 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1045 $item_id = item_post($a);
1047 // output the post that we just posted.
1048 return api_status_show($type, $item_id);
1051 /// @TODO move this to top of file or somewhere better!
1052 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1055 * Updates the user’s current status.
1057 * @param string $type Return type (atom, rss, xml, json)
1059 * @return array|string
1060 * @throws BadRequestException
1061 * @throws ForbiddenException
1062 * @throws ImagickException
1063 * @throws InternalServerErrorException
1064 * @throws TooManyRequestsException
1065 * @throws UnauthorizedException
1066 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1068 function api_statuses_update($type)
1072 if (api_user() === false) {
1073 Logger::log('api_statuses_update: no user');
1074 throw new ForbiddenException();
1079 // convert $_POST array items to the form we use for web posts.
1080 if (requestdata('htmlstatus')) {
1081 $txt = requestdata('htmlstatus');
1082 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1083 $txt = HTML::toBBCodeVideo($txt);
1085 $config = HTMLPurifier_Config::createDefault();
1086 $config->set('Cache.DefinitionImpl', null);
1088 $purifier = new HTMLPurifier($config);
1089 $txt = $purifier->purify($txt);
1091 $_REQUEST['body'] = HTML::toBBCode($txt);
1094 $_REQUEST['body'] = requestdata('status');
1097 $_REQUEST['title'] = requestdata('title');
1099 $parent = requestdata('in_reply_to_status_id');
1101 // Twidere sends "-1" if it is no reply ...
1102 if ($parent == -1) {
1106 if (ctype_digit($parent)) {
1107 $_REQUEST['parent'] = $parent;
1109 $_REQUEST['parent_uri'] = $parent;
1112 if (requestdata('lat') && requestdata('long')) {
1113 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1115 $_REQUEST['profile_uid'] = api_user();
1118 // Check for throttling (maximum posts per day, week and month)
1119 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1120 if ($throttle_day > 0) {
1121 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1123 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1124 $posts_day = DBA::count('thread', $condition);
1126 if ($posts_day > $throttle_day) {
1127 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1128 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1129 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));
1133 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1134 if ($throttle_week > 0) {
1135 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1137 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1138 $posts_week = DBA::count('thread', $condition);
1140 if ($posts_week > $throttle_week) {
1141 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1142 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1143 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));
1147 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1148 if ($throttle_month > 0) {
1149 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1151 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1152 $posts_month = DBA::count('thread', $condition);
1154 if ($posts_month > $throttle_month) {
1155 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1156 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1157 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));
1162 if (!empty($_FILES['media'])) {
1163 // upload the image if we have one
1164 $picture = wall_upload_post($a, false);
1165 if (is_array($picture)) {
1166 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1170 if (requestdata('media_ids')) {
1171 $ids = explode(',', requestdata('media_ids'));
1172 foreach ($ids as $id) {
1174 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1178 if (DBA::isResult($r)) {
1179 $phototypes = Images::supportedTypes();
1180 $ext = $phototypes[$r[0]['type']];
1181 $description = $r[0]['desc'] ?? '';
1182 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1183 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1188 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1190 $_REQUEST['api_source'] = true;
1192 if (empty($_REQUEST['source'])) {
1193 $_REQUEST["source"] = api_source();
1196 // call out normal post function
1197 $item_id = item_post($a);
1199 // output the post that we just posted.
1200 return api_status_show($type, $item_id);
1203 /// @TODO move to top of file or somewhere better
1204 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1205 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1208 * Uploads an image to Friendica.
1211 * @throws BadRequestException
1212 * @throws ForbiddenException
1213 * @throws ImagickException
1214 * @throws InternalServerErrorException
1215 * @throws UnauthorizedException
1216 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1218 function api_media_upload()
1222 if (api_user() === false) {
1223 Logger::log('no user');
1224 throw new ForbiddenException();
1229 if (empty($_FILES['media'])) {
1231 throw new BadRequestException("No media.");
1234 $media = wall_upload_post($a, false);
1237 throw new InternalServerErrorException();
1241 $returndata["media_id"] = $media["id"];
1242 $returndata["media_id_string"] = (string)$media["id"];
1243 $returndata["size"] = $media["size"];
1244 $returndata["image"] = ["w" => $media["width"],
1245 "h" => $media["height"],
1246 "image_type" => $media["type"],
1247 "friendica_preview_url" => $media["preview"]];
1249 Logger::info('Media uploaded', ['return' => $returndata]);
1251 return ["media" => $returndata];
1254 /// @TODO move to top of file or somewhere better
1255 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1258 * Updates media meta data (picture descriptions)
1260 * @param string $type Return type (atom, rss, xml, json)
1262 * @return array|string
1263 * @throws BadRequestException
1264 * @throws ForbiddenException
1265 * @throws ImagickException
1266 * @throws InternalServerErrorException
1267 * @throws TooManyRequestsException
1268 * @throws UnauthorizedException
1269 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1271 * @todo Compare the corresponding Twitter function for correct return values
1273 function api_media_metadata_create($type)
1277 if (api_user() === false) {
1278 Logger::info('no user');
1279 throw new ForbiddenException();
1284 $postdata = Network::postdata();
1286 if (empty($postdata)) {
1287 throw new BadRequestException("No post data");
1290 $data = json_decode($postdata, true);
1292 throw new BadRequestException("Invalid post data");
1295 if (empty($data['media_id']) || empty($data['alt_text'])) {
1296 throw new BadRequestException("Missing post data values");
1299 if (empty($data['alt_text']['text'])) {
1300 throw new BadRequestException("No alt text.");
1303 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1305 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1306 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1307 if (!DBA::isResult($photo)) {
1308 throw new BadRequestException("Metadata not found.");
1311 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1314 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1317 * @param string $type Return format (atom, rss, xml, json)
1318 * @param int $item_id
1319 * @return array|string
1322 function api_status_show($type, $item_id)
1324 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1328 $item = api_get_item(['id' => $item_id]);
1329 if (!empty($item)) {
1330 $status_info = api_format_item($item, $type);
1333 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1335 return api_format_data('statuses', $type, ['status' => $status_info]);
1339 * Retrieves the last public status of the provided user info
1341 * @param int $ownerId Public contact Id
1342 * @param int $uid User Id
1346 function api_get_last_status($ownerId, $uid)
1349 'author-id'=> $ownerId,
1351 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1352 'private' => [Item::PUBLIC, Item::UNLISTED]
1355 $item = api_get_item($condition);
1361 * Retrieves a single item record based on the provided condition and converts it for API use.
1363 * @param array $condition Item table condition array
1367 function api_get_item(array $condition)
1369 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1375 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1376 * The author's most recent status will be returned inline.
1378 * @param string $type Return type (atom, rss, xml, json)
1379 * @return array|string
1380 * @throws BadRequestException
1381 * @throws ImagickException
1382 * @throws InternalServerErrorException
1383 * @throws UnauthorizedException
1384 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1386 function api_users_show($type)
1388 $a = Friendica\DI::app();
1390 $user_info = api_get_user($a);
1392 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1393 if (!empty($item)) {
1394 $user_info['status'] = api_format_item($item, $type);
1397 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1398 unset($user_info['uid']);
1399 unset($user_info['self']);
1401 return api_format_data('user', $type, ['user' => $user_info]);
1404 /// @TODO move to top of file or somewhere better
1405 api_register_func('api/users/show', 'api_users_show');
1406 api_register_func('api/externalprofile/show', 'api_users_show');
1409 * Search a public user account.
1411 * @param string $type Return type (atom, rss, xml, json)
1413 * @return array|string
1414 * @throws BadRequestException
1415 * @throws ImagickException
1416 * @throws InternalServerErrorException
1417 * @throws UnauthorizedException
1418 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1420 function api_users_search($type)
1426 if (!empty($_GET['q'])) {
1427 $contacts = Contact::selectToArray(
1430 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1438 if (DBA::isResult($contacts)) {
1440 foreach ($contacts as $contact) {
1441 $user_info = api_get_user($a, $contact['id']);
1443 if ($type == 'xml') {
1444 $userlist[$k++ . ':user'] = $user_info;
1446 $userlist[] = $user_info;
1449 $userlist = ['users' => $userlist];
1451 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1454 throw new BadRequestException('No search term specified.');
1457 return api_format_data('users', $type, $userlist);
1460 /// @TODO move to top of file or somewhere better
1461 api_register_func('api/users/search', 'api_users_search');
1464 * Return user objects
1466 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1468 * @param string $type Return format: json or xml
1470 * @return array|string
1471 * @throws BadRequestException
1472 * @throws ImagickException
1473 * @throws InternalServerErrorException
1474 * @throws NotFoundException if the results are empty.
1475 * @throws UnauthorizedException
1477 function api_users_lookup($type)
1481 if (!empty($_REQUEST['user_id'])) {
1482 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1484 $users[] = api_get_user(DI::app(), $id);
1489 if (empty($users)) {
1490 throw new NotFoundException;
1493 return api_format_data("users", $type, ['users' => $users]);
1496 /// @TODO move to top of file or somewhere better
1497 api_register_func('api/users/lookup', 'api_users_lookup', true);
1500 * Returns statuses that match a specified query.
1502 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1504 * @param string $type Return format: json, xml, atom, rss
1506 * @return array|string
1507 * @throws BadRequestException if the "q" parameter is missing.
1508 * @throws ForbiddenException
1509 * @throws ImagickException
1510 * @throws InternalServerErrorException
1511 * @throws UnauthorizedException
1513 function api_search($type)
1516 $user_info = api_get_user($a);
1518 if (api_user() === false || $user_info === false) {
1519 throw new ForbiddenException();
1522 if (empty($_REQUEST['q'])) {
1523 throw new BadRequestException('q parameter is required.');
1526 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1529 $data['status'] = [];
1531 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1532 if (!empty($_REQUEST['rpp'])) {
1533 $count = $_REQUEST['rpp'];
1534 } elseif (!empty($_REQUEST['count'])) {
1535 $count = $_REQUEST['count'];
1538 $since_id = $_REQUEST['since_id'] ?? 0;
1539 $max_id = $_REQUEST['max_id'] ?? 0;
1540 $page = $_REQUEST['page'] ?? 1;
1542 $start = max(0, ($page - 1) * $count);
1544 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1545 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1546 $searchTerm = $matches[1];
1547 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1548 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1550 while ($tag = DBA::fetch($tags)) {
1551 $uriids[] = $tag['uri-id'];
1555 if (empty($uriids)) {
1556 return api_format_data('statuses', $type, $data);
1559 $condition = ['uri-id' => $uriids];
1560 if ($exclude_replies) {
1561 $condition['gravity'] = GRAVITY_PARENT;
1564 $params['group_by'] = ['uri-id'];
1566 $condition = ["`id` > ?
1567 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1568 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1569 AND `body` LIKE CONCAT('%',?,'%')",
1570 $since_id, api_user(), $_REQUEST['q']];
1572 $condition[0] .= ' AND `id` <= ?';
1573 $condition[] = $max_id;
1579 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1580 $id = Item::fetchByLink($searchTerm, api_user());
1583 $id = Item::fetchByLink($searchTerm);
1587 $statuses = Post::select([], ['id' => $id]);
1591 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1593 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1595 bindComments($data['status']);
1597 return api_format_data('statuses', $type, $data);
1600 /// @TODO move to top of file or somewhere better
1601 api_register_func('api/search/tweets', 'api_search', true);
1602 api_register_func('api/search', 'api_search', true);
1605 * Returns the most recent statuses posted by the user and the users they follow.
1607 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1609 * @param string $type Return type (atom, rss, xml, json)
1611 * @return array|string
1612 * @throws BadRequestException
1613 * @throws ForbiddenException
1614 * @throws ImagickException
1615 * @throws InternalServerErrorException
1616 * @throws UnauthorizedException
1617 * @todo Optional parameters
1618 * @todo Add reply info
1620 function api_statuses_home_timeline($type)
1623 $user_info = api_get_user($a);
1625 if (api_user() === false || $user_info === false) {
1626 throw new ForbiddenException();
1629 unset($_REQUEST["user_id"]);
1630 unset($_GET["user_id"]);
1632 unset($_REQUEST["screen_name"]);
1633 unset($_GET["screen_name"]);
1635 // get last network messages
1638 $count = $_REQUEST['count'] ?? 20;
1639 $page = $_REQUEST['page']?? 0;
1640 $since_id = $_REQUEST['since_id'] ?? 0;
1641 $max_id = $_REQUEST['max_id'] ?? 0;
1642 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1643 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1645 $start = max(0, ($page - 1) * $count);
1647 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1648 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1651 $condition[0] .= " AND `id` <= ?";
1652 $condition[] = $max_id;
1654 if ($exclude_replies) {
1655 $condition[0] .= ' AND `gravity` = ?';
1656 $condition[] = GRAVITY_PARENT;
1658 if ($conversation_id > 0) {
1659 $condition[0] .= " AND `parent` = ?";
1660 $condition[] = $conversation_id;
1663 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1664 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1666 $items = Post::toArray($statuses);
1668 $ret = api_format_items($items, $user_info, false, $type);
1670 // Set all posts from the query above to seen
1672 foreach ($items as $item) {
1673 $idarray[] = intval($item["id"]);
1676 if (!empty($idarray)) {
1677 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1679 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1685 $data = ['status' => $ret];
1690 $data = api_rss_extra($a, $data, $user_info);
1694 return api_format_data("statuses", $type, $data);
1698 /// @TODO move to top of file or somewhere better
1699 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1700 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1703 * Returns the most recent statuses from public users.
1705 * @param string $type Return type (atom, rss, xml, json)
1707 * @return array|string
1708 * @throws BadRequestException
1709 * @throws ForbiddenException
1710 * @throws ImagickException
1711 * @throws InternalServerErrorException
1712 * @throws UnauthorizedException
1714 function api_statuses_public_timeline($type)
1717 $user_info = api_get_user($a);
1719 if (api_user() === false || $user_info === false) {
1720 throw new ForbiddenException();
1723 // get last network messages
1726 $count = $_REQUEST['count'] ?? 20;
1727 $page = $_REQUEST['page'] ?? 1;
1728 $since_id = $_REQUEST['since_id'] ?? 0;
1729 $max_id = $_REQUEST['max_id'] ?? 0;
1730 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1731 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1733 $start = max(0, ($page - 1) * $count);
1735 if ($exclude_replies && !$conversation_id) {
1736 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
1737 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1740 $condition[0] .= " AND `thread`.`iid` <= ?";
1741 $condition[] = $max_id;
1744 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1745 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1747 $r = Item::toArray($statuses);
1749 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1750 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1753 $condition[0] .= " AND `id` <= ?";
1754 $condition[] = $max_id;
1756 if ($conversation_id > 0) {
1757 $condition[0] .= " AND `parent` = ?";
1758 $condition[] = $conversation_id;
1761 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1762 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1764 $r = Post::toArray($statuses);
1767 $ret = api_format_items($r, $user_info, false, $type);
1771 $data = ['status' => $ret];
1776 $data = api_rss_extra($a, $data, $user_info);
1780 return api_format_data("statuses", $type, $data);
1783 /// @TODO move to top of file or somewhere better
1784 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1787 * Returns the most recent statuses posted by users this node knows about.
1789 * @param string $type Return format: json, xml, atom, rss
1790 * @return array|string
1791 * @throws BadRequestException
1792 * @throws ForbiddenException
1793 * @throws ImagickException
1794 * @throws InternalServerErrorException
1795 * @throws UnauthorizedException
1797 function api_statuses_networkpublic_timeline($type)
1800 $user_info = api_get_user($a);
1802 if (api_user() === false || $user_info === false) {
1803 throw new ForbiddenException();
1806 $since_id = $_REQUEST['since_id'] ?? 0;
1807 $max_id = $_REQUEST['max_id'] ?? 0;
1810 $count = $_REQUEST['count'] ?? 20;
1811 $page = $_REQUEST['page'] ?? 1;
1813 $start = max(0, ($page - 1) * $count);
1815 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
1816 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1819 $condition[0] .= " AND `thread`.`iid` <= ?";
1820 $condition[] = $max_id;
1823 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1824 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1826 $ret = api_format_items(Item::toArray($statuses), $user_info, false, $type);
1830 $data = ['status' => $ret];
1835 $data = api_rss_extra($a, $data, $user_info);
1839 return api_format_data("statuses", $type, $data);
1842 /// @TODO move to top of file or somewhere better
1843 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1846 * Returns a single status.
1848 * @param string $type Return type (atom, rss, xml, json)
1850 * @return array|string
1851 * @throws BadRequestException
1852 * @throws ForbiddenException
1853 * @throws ImagickException
1854 * @throws InternalServerErrorException
1855 * @throws UnauthorizedException
1856 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1858 function api_statuses_show($type)
1861 $user_info = api_get_user($a);
1863 if (api_user() === false || $user_info === false) {
1864 throw new ForbiddenException();
1868 $id = intval($a->argv[3] ?? 0);
1871 $id = intval($_REQUEST['id'] ?? 0);
1876 $id = intval($a->argv[4] ?? 0);
1879 Logger::log('API: api_statuses_show: ' . $id);
1881 $conversation = !empty($_REQUEST['conversation']);
1883 // try to fetch the item for the local user - or the public item, if there is no local one
1884 $uri_item = Post::selectFirst(['uri'], ['id' => $id]);
1885 if (!DBA::isResult($uri_item)) {
1886 throw new BadRequestException("There is no status with this id.");
1889 $item = Post::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1890 if (!DBA::isResult($item)) {
1891 throw new BadRequestException("There is no status with this id.");
1896 if ($conversation) {
1897 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1898 $params = ['order' => ['id' => true]];
1900 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1904 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1906 /// @TODO How about copying this to above methods which don't check $r ?
1907 if (!DBA::isResult($statuses)) {
1908 throw new BadRequestException("There is no status with this id.");
1911 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1913 if ($conversation) {
1914 $data = ['status' => $ret];
1915 return api_format_data("statuses", $type, $data);
1917 $data = ['status' => $ret[0]];
1918 return api_format_data("status", $type, $data);
1922 /// @TODO move to top of file or somewhere better
1923 api_register_func('api/statuses/show', 'api_statuses_show', true);
1927 * @param string $type Return type (atom, rss, xml, json)
1929 * @return array|string
1930 * @throws BadRequestException
1931 * @throws ForbiddenException
1932 * @throws ImagickException
1933 * @throws InternalServerErrorException
1934 * @throws UnauthorizedException
1935 * @todo nothing to say?
1937 function api_conversation_show($type)
1940 $user_info = api_get_user($a);
1942 if (api_user() === false || $user_info === false) {
1943 throw new ForbiddenException();
1947 $id = intval($a->argv[3] ?? 0);
1948 $since_id = intval($_REQUEST['since_id'] ?? 0);
1949 $max_id = intval($_REQUEST['max_id'] ?? 0);
1950 $count = intval($_REQUEST['count'] ?? 20);
1951 $page = intval($_REQUEST['page'] ?? 1);
1953 $start = max(0, ($page - 1) * $count);
1956 $id = intval($_REQUEST['id'] ?? 0);
1961 $id = intval($a->argv[4] ?? 0);
1964 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1966 // try to fetch the item for the local user - or the public item, if there is no local one
1967 $item = Post::selectFirst(['parent-uri'], ['id' => $id]);
1968 if (!DBA::isResult($item)) {
1969 throw new BadRequestException("There is no status with this id.");
1972 $parent = Post::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1973 if (!DBA::isResult($parent)) {
1974 throw new BadRequestException("There is no status with this id.");
1977 $id = $parent['id'];
1979 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1980 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1983 $condition[0] .= " AND `id` <= ?";
1984 $condition[] = $max_id;
1987 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1988 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1990 if (!DBA::isResult($statuses)) {
1991 throw new BadRequestException("There is no status with id $id.");
1994 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1996 $data = ['status' => $ret];
1997 return api_format_data("statuses", $type, $data);
2000 /// @TODO move to top of file or somewhere better
2001 api_register_func('api/conversation/show', 'api_conversation_show', true);
2002 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2007 * @param string $type Return type (atom, rss, xml, json)
2009 * @return array|string
2010 * @throws BadRequestException
2011 * @throws ForbiddenException
2012 * @throws ImagickException
2013 * @throws InternalServerErrorException
2014 * @throws UnauthorizedException
2015 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2017 function api_statuses_repeat($type)
2023 if (api_user() === false) {
2024 throw new ForbiddenException();
2030 $id = intval($a->argv[3] ?? 0);
2033 $id = intval($_REQUEST['id'] ?? 0);
2038 $id = intval($a->argv[4] ?? 0);
2041 Logger::log('API: api_statuses_repeat: '.$id);
2043 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2044 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2046 if (DBA::isResult($item) && $item['body'] != "") {
2047 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2048 if (!Item::performActivity($id, 'announce', local_user())) {
2049 throw new InternalServerErrorException();
2054 if (strpos($item['body'], "[/share]") !== false) {
2055 $pos = strpos($item['body'], "[share");
2056 $post = substr($item['body'], $pos);
2058 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2060 if (!empty($item['title'])) {
2061 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2064 $post .= $item['body'];
2065 $post .= "[/share]";
2067 $_REQUEST['body'] = $post;
2068 $_REQUEST['profile_uid'] = api_user();
2069 $_REQUEST['api_source'] = true;
2071 if (empty($_REQUEST['source'])) {
2072 $_REQUEST["source"] = api_source();
2075 $item_id = item_post($a);
2078 throw new ForbiddenException();
2081 // output the post that we just posted.
2083 return api_status_show($type, $item_id);
2086 /// @TODO move to top of file or somewhere better
2087 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2090 * Destroys a specific status.
2092 * @param string $type Return type (atom, rss, xml, json)
2094 * @return array|string
2095 * @throws BadRequestException
2096 * @throws ForbiddenException
2097 * @throws ImagickException
2098 * @throws InternalServerErrorException
2099 * @throws UnauthorizedException
2100 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2102 function api_statuses_destroy($type)
2106 if (api_user() === false) {
2107 throw new ForbiddenException();
2113 $id = intval($a->argv[3] ?? 0);
2116 $id = intval($_REQUEST['id'] ?? 0);
2121 $id = intval($a->argv[4] ?? 0);
2124 Logger::log('API: api_statuses_destroy: '.$id);
2126 $ret = api_statuses_show($type);
2128 Item::deleteForUser(['id' => $id], api_user());
2133 /// @TODO move to top of file or somewhere better
2134 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2137 * Returns the most recent mentions.
2139 * @param string $type Return type (atom, rss, xml, json)
2141 * @return array|string
2142 * @throws BadRequestException
2143 * @throws ForbiddenException
2144 * @throws ImagickException
2145 * @throws InternalServerErrorException
2146 * @throws UnauthorizedException
2147 * @see http://developer.twitter.com/doc/get/statuses/mentions
2149 function api_statuses_mentions($type)
2152 $user_info = api_get_user($a);
2154 if (api_user() === false || $user_info === false) {
2155 throw new ForbiddenException();
2158 unset($_REQUEST["user_id"]);
2159 unset($_GET["user_id"]);
2161 unset($_REQUEST["screen_name"]);
2162 unset($_GET["screen_name"]);
2164 // get last network messages
2167 $since_id = intval($_REQUEST['since_id'] ?? 0);
2168 $max_id = intval($_REQUEST['max_id'] ?? 0);
2169 $count = intval($_REQUEST['count'] ?? 20);
2170 $page = intval($_REQUEST['page'] ?? 1);
2172 $start = max(0, ($page - 1) * $count);
2174 $query = "SELECT `item`.`id` FROM `user-item`
2175 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2176 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2177 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2178 AND `user-item`.`iid` > ?";
2179 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2180 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2181 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2182 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2186 $query .= " AND `item`.`id` <= ?";
2187 $condition[] = $max_id;
2190 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2191 $condition[] = $start;
2192 $condition[] = $count;
2194 $useritems = DBA::p($query, $condition);
2196 while ($useritem = DBA::fetch($useritems)) {
2197 $itemids[] = $useritem['id'];
2199 DBA::close($useritems);
2201 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2202 $statuses = Post::selectForUser(api_user(), [], ['id' => $itemids], $params);
2204 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2206 $data = ['status' => $ret];
2211 $data = api_rss_extra($a, $data, $user_info);
2215 return api_format_data("statuses", $type, $data);
2218 /// @TODO move to top of file or somewhere better
2219 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2220 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2223 * Returns the most recent statuses posted by the user.
2225 * @param string $type Either "json" or "xml"
2226 * @return string|array
2227 * @throws BadRequestException
2228 * @throws ForbiddenException
2229 * @throws ImagickException
2230 * @throws InternalServerErrorException
2231 * @throws UnauthorizedException
2232 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2234 function api_statuses_user_timeline($type)
2237 $user_info = api_get_user($a);
2239 if (api_user() === false || $user_info === false) {
2240 throw new ForbiddenException();
2243 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2245 $since_id = $_REQUEST['since_id'] ?? 0;
2246 $max_id = $_REQUEST['max_id'] ?? 0;
2247 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2248 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2251 $count = $_REQUEST['count'] ?? 20;
2252 $page = $_REQUEST['page'] ?? 1;
2254 $start = max(0, ($page - 1) * $count);
2256 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2257 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2259 if ($user_info['self'] == 1) {
2260 $condition[0] .= ' AND `wall` ';
2263 if ($exclude_replies) {
2264 $condition[0] .= ' AND `gravity` = ?';
2265 $condition[] = GRAVITY_PARENT;
2268 if ($conversation_id > 0) {
2269 $condition[0] .= " AND `parent` = ?";
2270 $condition[] = $conversation_id;
2274 $condition[0] .= " AND `id` <= ?";
2275 $condition[] = $max_id;
2278 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2279 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2281 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2285 $data = ['status' => $ret];
2290 $data = api_rss_extra($a, $data, $user_info);
2294 return api_format_data("statuses", $type, $data);
2297 /// @TODO move to top of file or somewhere better
2298 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2301 * Star/unstar an item.
2302 * param: id : id of the item
2304 * @param string $type Return type (atom, rss, xml, json)
2306 * @return array|string
2307 * @throws BadRequestException
2308 * @throws ForbiddenException
2309 * @throws ImagickException
2310 * @throws InternalServerErrorException
2311 * @throws UnauthorizedException
2312 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2314 function api_favorites_create_destroy($type)
2318 if (api_user() === false) {
2319 throw new ForbiddenException();
2322 // for versioned api.
2323 /// @TODO We need a better global soluton
2324 $action_argv_id = 2;
2325 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2326 $action_argv_id = 3;
2329 if ($a->argc <= $action_argv_id) {
2330 throw new BadRequestException("Invalid request.");
2332 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2333 if ($a->argc == $action_argv_id + 2) {
2334 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2336 $itemid = intval($_REQUEST['id'] ?? 0);
2339 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2341 if (!DBA::isResult($item)) {
2342 throw new BadRequestException("Invalid item.");
2347 $item['starred'] = 1;
2350 $item['starred'] = 0;
2353 throw new BadRequestException("Invalid action ".$action);
2356 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2359 throw new InternalServerErrorException("DB error");
2363 $user_info = api_get_user($a);
2364 $rets = api_format_items([$item], $user_info, false, $type);
2367 $data = ['status' => $ret];
2372 $data = api_rss_extra($a, $data, $user_info);
2376 return api_format_data("status", $type, $data);
2379 /// @TODO move to top of file or somewhere better
2380 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2381 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2384 * Returns the most recent favorite statuses.
2386 * @param string $type Return type (atom, rss, xml, json)
2388 * @return string|array
2389 * @throws BadRequestException
2390 * @throws ForbiddenException
2391 * @throws ImagickException
2392 * @throws InternalServerErrorException
2393 * @throws UnauthorizedException
2395 function api_favorites($type)
2400 $user_info = api_get_user($a);
2402 if (api_user() === false || $user_info === false) {
2403 throw new ForbiddenException();
2408 // in friendica starred item are private
2409 // return favorites only for self
2410 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2412 if ($user_info['self'] == 0) {
2416 $since_id = $_REQUEST['since_id'] ?? 0;
2417 $max_id = $_REQUEST['max_id'] ?? 0;
2418 $count = $_GET['count'] ?? 20;
2419 $page = $_REQUEST['page'] ?? 1;
2421 $start = max(0, ($page - 1) * $count);
2423 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2424 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2426 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2429 $condition[0] .= " AND `id` <= ?";
2430 $condition[] = $max_id;
2433 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2435 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2440 $data = ['status' => $ret];
2445 $data = api_rss_extra($a, $data, $user_info);
2449 return api_format_data("statuses", $type, $data);
2452 /// @TODO move to top of file or somewhere better
2453 api_register_func('api/favorites', 'api_favorites', true);
2457 * @param array $item
2458 * @param array $recipient
2459 * @param array $sender
2462 * @throws InternalServerErrorException
2464 function api_format_messages($item, $recipient, $sender)
2466 // standard meta information
2468 'id' => $item['id'],
2469 'sender_id' => $sender['id'],
2471 'recipient_id' => $recipient['id'],
2472 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2473 'sender_screen_name' => $sender['screen_name'],
2474 'recipient_screen_name' => $recipient['screen_name'],
2475 'sender' => $sender,
2476 'recipient' => $recipient,
2478 'friendica_seen' => $item['seen'] ?? 0,
2479 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2482 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2483 if (isset($ret['sender']['uid'])) {
2484 unset($ret['sender']['uid']);
2486 if (isset($ret['sender']['self'])) {
2487 unset($ret['sender']['self']);
2489 if (isset($ret['recipient']['uid'])) {
2490 unset($ret['recipient']['uid']);
2492 if (isset($ret['recipient']['self'])) {
2493 unset($ret['recipient']['self']);
2496 //don't send title to regular StatusNET requests to avoid confusing these apps
2497 if (!empty($_GET['getText'])) {
2498 $ret['title'] = $item['title'];
2499 if ($_GET['getText'] == 'html') {
2500 $ret['text'] = BBCode::convert($item['body'], false);
2501 } elseif ($_GET['getText'] == 'plain') {
2502 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2505 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2507 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2508 unset($ret['sender']);
2509 unset($ret['recipient']);
2517 * @param array $item
2520 * @throws InternalServerErrorException
2522 function api_convert_item($item)
2524 $body = $item['body'];
2525 $entities = api_get_entitities($statustext, $body);
2527 // Add pictures to the attachment array and remove them from the body
2528 $attachments = api_get_attachments($body);
2530 // Workaround for ostatus messages where the title is identically to the body
2531 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2532 $statusbody = trim(HTML::toPlaintext($html, 0));
2534 // handle data: images
2535 $statusbody = api_format_items_embeded_images($item, $statusbody);
2537 $statustitle = trim($item['title']);
2539 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2540 $statustext = trim($statusbody);
2542 $statustext = trim($statustitle."\n\n".$statusbody);
2545 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2546 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2549 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2551 // Workaround for clients with limited HTML parser functionality
2552 $search = ["<br>", "<blockquote>", "</blockquote>",
2553 "<h1>", "</h1>", "<h2>", "</h2>",
2554 "<h3>", "</h3>", "<h4>", "</h4>",
2555 "<h5>", "</h5>", "<h6>", "</h6>"];
2556 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2557 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2558 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2559 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2560 $statushtml = str_replace($search, $replace, $statushtml);
2562 if ($item['title'] != "") {
2563 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2567 $oldtext = $statushtml;
2568 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2569 } while ($oldtext != $statushtml);
2571 if (substr($statushtml, 0, 4) == '<br>') {
2572 $statushtml = substr($statushtml, 4);
2575 if (substr($statushtml, 0, -4) == '<br>') {
2576 $statushtml = substr($statushtml, -4);
2579 // feeds without body should contain the link
2580 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2581 $statushtml .= BBCode::convert($item['plink']);
2585 "text" => $statustext,
2586 "html" => $statushtml,
2587 "attachments" => $attachments,
2588 "entities" => $entities
2594 * @param string $body
2597 * @throws InternalServerErrorException
2599 function api_get_attachments(&$body)
2601 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2602 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2604 $URLSearchString = "^\[\]";
2605 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2609 // Remove all embedded pictures, since they are added as attachments
2610 foreach ($images[0] as $orig) {
2611 $body = str_replace($orig, '', $body);
2616 foreach ($images[1] as $image) {
2617 $imagedata = Images::getInfoFromURLCached($image);
2620 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2624 return $attachments;
2629 * @param string $text
2630 * @param string $bbcode
2633 * @throws InternalServerErrorException
2634 * @todo Links at the first character of the post
2636 function api_get_entitities(&$text, $bbcode)
2638 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2640 if ($include_entities != "true") {
2641 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2643 foreach ($images[1] as $image) {
2644 $replace = ProxyUtils::proxifyUrl($image);
2645 $text = str_replace($image, $replace, $text);
2650 $bbcode = BBCode::cleanPictureLinks($bbcode);
2652 // Change pure links in text to bbcode uris
2653 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2656 $entities["hashtags"] = [];
2657 $entities["symbols"] = [];
2658 $entities["urls"] = [];
2659 $entities["user_mentions"] = [];
2661 $URLSearchString = "^\[\]";
2663 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2665 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2666 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2668 $bbcode = preg_replace(
2669 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2670 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2673 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2675 $bbcode = preg_replace(
2676 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2677 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2680 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2682 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2684 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2687 foreach ($urls[1] as $id => $url) {
2688 $start = iconv_strpos($text, $url, 0, "UTF-8");
2689 if (!($start === false)) {
2690 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2694 ksort($ordered_urls);
2698 foreach ($ordered_urls as $url) {
2699 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2700 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2702 $display_url = $url["title"];
2704 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2705 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2707 if (strlen($display_url) > 26) {
2708 $display_url = substr($display_url, 0, 25)."…";
2712 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2713 if (!($start === false)) {
2714 $entities["urls"][] = ["url" => $url["url"],
2715 "expanded_url" => $url["url"],
2716 "display_url" => $display_url,
2717 "indices" => [$start, $start+strlen($url["url"])]];
2718 $offset = $start + 1;
2722 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2723 $ordered_images = [];
2724 foreach ($images as $image) {
2725 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2726 if (!($start === false)) {
2727 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2731 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2732 foreach ($images[1] as $image) {
2733 $start = iconv_strpos($text, $image, 0, "UTF-8");
2734 if (!($start === false)) {
2735 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2741 foreach ($ordered_images as $image) {
2742 $url = $image['url'];
2743 $ext_alt_text = $image['alt'];
2745 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2746 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2748 if (strlen($display_url) > 26) {
2749 $display_url = substr($display_url, 0, 25)."…";
2752 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2753 if (!($start === false)) {
2754 $image = Images::getInfoFromURLCached($url);
2756 // If image cache is activated, then use the following sizes:
2757 // thumb (150), small (340), medium (600) and large (1024)
2758 if (!DI::config()->get("system", "proxy_disabled")) {
2759 $media_url = ProxyUtils::proxifyUrl($url);
2762 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2763 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2765 if (($image[0] > 150) || ($image[1] > 150)) {
2766 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2767 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2770 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2771 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2773 if (($image[0] > 600) || ($image[1] > 600)) {
2774 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2775 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2779 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2782 $entities["media"][] = [
2784 "id_str" => (string) ($start + 1),
2785 "indices" => [$start, $start+strlen($url)],
2786 "media_url" => Strings::normaliseLink($media_url),
2787 "media_url_https" => $media_url,
2789 "display_url" => $display_url,
2790 "expanded_url" => $url,
2791 "ext_alt_text" => $ext_alt_text,
2795 $offset = $start + 1;
2804 * @param array $item
2805 * @param string $text
2809 function api_format_items_embeded_images($item, $text)
2811 $text = preg_replace_callback(
2812 '|data:image/([^;]+)[^=]+=*|m',
2813 function () use ($item) {
2814 return DI::baseUrl() . '/display/' . $item['guid'];
2822 * return <a href='url'>name</a> as array
2824 * @param string $txt text
2829 function api_contactlink_to_array($txt)
2832 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2833 if ($r && count($match)==3) {
2835 'name' => $match[2],
2849 * return likes, dislikes and attend status for item
2851 * @param array $item array
2852 * @param string $type Return type (atom, rss, xml, json)
2855 * likes => int count,
2856 * dislikes => int count
2857 * @throws BadRequestException
2858 * @throws ImagickException
2859 * @throws InternalServerErrorException
2860 * @throws UnauthorizedException
2862 function api_format_items_activities($item, $type = "json")
2871 'attendmaybe' => [],
2875 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2876 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2878 while ($parent_item = Post::fetch($ret)) {
2879 // not used as result should be structured like other user data
2880 //builtin_activity_puller($i, $activities);
2882 // get user data and add it to the array of the activity
2883 $user = api_get_user($a, $parent_item['author-id']);
2884 switch ($parent_item['verb']) {
2885 case Activity::LIKE:
2886 $activities['like'][] = $user;
2888 case Activity::DISLIKE:
2889 $activities['dislike'][] = $user;
2891 case Activity::ATTEND:
2892 $activities['attendyes'][] = $user;
2894 case Activity::ATTENDNO:
2895 $activities['attendno'][] = $user;
2897 case Activity::ATTENDMAYBE:
2898 $activities['attendmaybe'][] = $user;
2900 case Activity::ANNOUNCE:
2901 $activities['announce'][] = $user;
2910 if ($type == "xml") {
2911 $xml_activities = [];
2912 foreach ($activities as $k => $v) {
2913 // change xml element from "like" to "friendica:like"
2914 $xml_activities["friendica:".$k] = $v;
2915 // add user data into xml output
2917 foreach ($v as $user) {
2918 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2921 $activities = $xml_activities;
2928 * format items to be returned by api
2930 * @param array $items array of items
2931 * @param array $user_info
2932 * @param bool $filter_user filter items by $user_info
2933 * @param string $type Return type (atom, rss, xml, json)
2935 * @throws BadRequestException
2936 * @throws ImagickException
2937 * @throws InternalServerErrorException
2938 * @throws UnauthorizedException
2940 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2942 $a = Friendica\DI::app();
2946 foreach ((array)$items as $item) {
2947 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2949 // Look if the posts are matching if they should be filtered by user id
2950 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2954 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2963 * @param array $item Item record
2964 * @param string $type Return format (atom, rss, xml, json)
2965 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2966 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2967 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2968 * @return array API-formatted status
2969 * @throws BadRequestException
2970 * @throws ImagickException
2971 * @throws InternalServerErrorException
2972 * @throws UnauthorizedException
2974 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2976 $a = Friendica\DI::app();
2978 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2979 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2982 localize_item($item);
2984 $in_reply_to = api_in_reply_to($item);
2986 $converted = api_convert_item($item);
2988 if ($type == "xml") {
2989 $geo = "georss:point";
2995 'text' => $converted["text"],
2996 'truncated' => false,
2997 'created_at'=> api_date($item['created']),
2998 'in_reply_to_status_id' => $in_reply_to['status_id'],
2999 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3000 'source' => (($item['app']) ? $item['app'] : 'web'),
3001 'id' => intval($item['id']),
3002 'id_str' => (string) intval($item['id']),
3003 'in_reply_to_user_id' => $in_reply_to['user_id'],
3004 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3005 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3007 'favorited' => $item['starred'] ? true : false,
3008 'user' => $status_user,
3009 'friendica_author' => $author_user,
3010 'friendica_owner' => $owner_user,
3011 'friendica_private' => $item['private'] == Item::PRIVATE,
3012 //'entities' => NULL,
3013 'statusnet_html' => $converted["html"],
3014 'statusnet_conversation_id' => $item['parent'],
3015 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3016 'friendica_activities' => api_format_items_activities($item, $type),
3017 'friendica_title' => $item['title'],
3018 'friendica_html' => BBCode::convert($item['body'], false)
3021 if (count($converted["attachments"]) > 0) {
3022 $status["attachments"] = $converted["attachments"];
3025 if (count($converted["entities"]) > 0) {
3026 $status["entities"] = $converted["entities"];
3029 if ($status["source"] == 'web') {
3030 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3031 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3032 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3035 $retweeted_item = [];
3038 if ($item['gravity'] == GRAVITY_PARENT) {
3039 $body = $item['body'];
3040 $retweeted_item = api_share_as_retweet($item);
3041 if ($body != $item['body']) {
3042 $quoted_item = $retweeted_item;
3043 $retweeted_item = [];
3047 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3048 $announce = api_get_announce($item);
3049 if (!empty($announce)) {
3050 $retweeted_item = $item;
3052 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3056 if (!empty($quoted_item)) {
3057 if ($quoted_item['id'] != $item['id']) {
3058 $quoted_status = api_format_item($quoted_item);
3059 /// @todo Only remove the attachments that are also contained in the quotes status
3060 unset($status['attachments']);
3061 unset($status['entities']);
3063 $conv_quoted = api_convert_item($quoted_item);
3064 $quoted_status = $status;
3065 unset($quoted_status['attachments']);
3066 unset($quoted_status['entities']);
3067 unset($quoted_status['statusnet_conversation_id']);
3068 $quoted_status['text'] = $conv_quoted['text'];
3069 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3071 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3072 } catch (BadRequestException $e) {
3073 // user not found. should be found?
3074 /// @todo check if the user should be always found
3075 $quoted_status["user"] = [];
3078 unset($quoted_status['friendica_author']);
3079 unset($quoted_status['friendica_owner']);
3080 unset($quoted_status['friendica_activities']);
3081 unset($quoted_status['friendica_private']);
3084 if (!empty($retweeted_item)) {
3085 $retweeted_status = $status;
3086 unset($retweeted_status['friendica_author']);
3087 unset($retweeted_status['friendica_owner']);
3088 unset($retweeted_status['friendica_activities']);
3089 unset($retweeted_status['friendica_private']);
3090 unset($retweeted_status['statusnet_conversation_id']);
3091 $status['user'] = $status['friendica_owner'];
3093 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3094 } catch (BadRequestException $e) {
3095 // user not found. should be found?
3096 /// @todo check if the user should be always found
3097 $retweeted_status["user"] = [];
3100 $rt_converted = api_convert_item($retweeted_item);
3102 $retweeted_status['text'] = $rt_converted["text"];
3103 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3104 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3106 if (!empty($quoted_status)) {
3107 $retweeted_status['quoted_status'] = $quoted_status;
3110 $status['friendica_author'] = $retweeted_status['user'];
3111 $status['retweeted_status'] = $retweeted_status;
3112 } elseif (!empty($quoted_status)) {
3113 $root_status = api_convert_item($item);
3115 $status['text'] = $root_status["text"];
3116 $status['statusnet_html'] = $root_status["html"];
3117 $status['quoted_status'] = $quoted_status;
3120 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3121 unset($status["user"]["uid"]);
3122 unset($status["user"]["self"]);
3124 if ($item["coord"] != "") {
3125 $coords = explode(' ', $item["coord"]);
3126 if (count($coords) == 2) {
3127 if ($type == "json") {
3128 $status["geo"] = ['type' => 'Point',
3129 'coordinates' => [(float) $coords[0],
3130 (float) $coords[1]]];
3131 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3132 $status["georss:point"] = $item["coord"];
3141 * Returns the remaining number of API requests available to the user before the API limit is reached.
3143 * @param string $type Return type (atom, rss, xml, json)
3145 * @return array|string
3148 function api_account_rate_limit_status($type)
3150 if ($type == "xml") {
3152 'remaining-hits' => '150',
3153 '@attributes' => ["type" => "integer"],
3154 'hourly-limit' => '150',
3155 '@attributes2' => ["type" => "integer"],
3156 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3157 '@attributes3' => ["type" => "datetime"],
3158 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3159 '@attributes4' => ["type" => "integer"],
3163 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3164 'remaining_hits' => '150',
3165 'hourly_limit' => '150',
3166 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3170 return api_format_data('hash', $type, ['hash' => $hash]);
3173 /// @TODO move to top of file or somewhere better
3174 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3177 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3179 * @param string $type Return type (atom, rss, xml, json)
3181 * @return array|string
3183 function api_help_test($type)
3185 if ($type == 'xml') {
3191 return api_format_data('ok', $type, ["ok" => $ok]);
3194 /// @TODO move to top of file or somewhere better
3195 api_register_func('api/help/test', 'api_help_test', false);
3198 * Returns all lists the user subscribes to.
3200 * @param string $type Return type (atom, rss, xml, json)
3202 * @return array|string
3203 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3205 function api_lists_list($type)
3208 /// @TODO $ret is not filled here?
3209 return api_format_data('lists', $type, ["lists_list" => $ret]);
3212 /// @TODO move to top of file or somewhere better
3213 api_register_func('api/lists/list', 'api_lists_list', true);
3214 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3217 * Returns all groups the user owns.
3219 * @param string $type Return type (atom, rss, xml, json)
3221 * @return array|string
3222 * @throws BadRequestException
3223 * @throws ForbiddenException
3224 * @throws ImagickException
3225 * @throws InternalServerErrorException
3226 * @throws UnauthorizedException
3227 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3229 function api_lists_ownerships($type)
3233 if (api_user() === false) {
3234 throw new ForbiddenException();
3238 $user_info = api_get_user($a);
3239 $uid = $user_info['uid'];
3241 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3243 // loop through all groups
3245 foreach ($groups as $group) {
3246 if ($group['visible']) {
3252 'name' => $group['name'],
3253 'id' => intval($group['id']),
3254 'id_str' => (string) $group['id'],
3255 'user' => $user_info,
3259 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3262 /// @TODO move to top of file or somewhere better
3263 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3266 * Returns recent statuses from users in the specified group.
3268 * @param string $type Return type (atom, rss, xml, json)
3270 * @return array|string
3271 * @throws BadRequestException
3272 * @throws ForbiddenException
3273 * @throws ImagickException
3274 * @throws InternalServerErrorException
3275 * @throws UnauthorizedException
3276 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3278 function api_lists_statuses($type)
3282 $user_info = api_get_user($a);
3283 if (api_user() === false || $user_info === false) {
3284 throw new ForbiddenException();
3287 unset($_REQUEST["user_id"]);
3288 unset($_GET["user_id"]);
3290 unset($_REQUEST["screen_name"]);
3291 unset($_GET["screen_name"]);
3293 if (empty($_REQUEST['list_id'])) {
3294 throw new BadRequestException('list_id not specified');
3298 $count = $_REQUEST['count'] ?? 20;
3299 $page = $_REQUEST['page'] ?? 1;
3300 $since_id = $_REQUEST['since_id'] ?? 0;
3301 $max_id = $_REQUEST['max_id'] ?? 0;
3302 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3303 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3305 $start = max(0, ($page - 1) * $count);
3307 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group-id` = ?",
3308 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3311 $condition[0] .= " AND `id` <= ?";
3312 $condition[] = $max_id;
3314 if ($exclude_replies > 0) {
3315 $condition[0] .= ' AND `gravity` = ?';
3316 $condition[] = GRAVITY_PARENT;
3318 if ($conversation_id > 0) {
3319 $condition[0] .= " AND `parent` = ?";
3320 $condition[] = $conversation_id;
3323 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3324 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3326 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3328 $data = ['status' => $items];
3333 $data = api_rss_extra($a, $data, $user_info);
3337 return api_format_data("statuses", $type, $data);
3340 /// @TODO move to top of file or somewhere better
3341 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3344 * Returns either the friends of the follower list
3346 * Considers friends and followers lists to be private and won't return
3347 * anything if any user_id parameter is passed.
3349 * @param string $qtype Either "friends" or "followers"
3350 * @return boolean|array
3351 * @throws BadRequestException
3352 * @throws ForbiddenException
3353 * @throws ImagickException
3354 * @throws InternalServerErrorException
3355 * @throws UnauthorizedException
3357 function api_statuses_f($qtype)
3361 if (api_user() === false) {
3362 throw new ForbiddenException();
3366 $count = $_GET['count'] ?? 20;
3367 $page = $_GET['page'] ?? 1;
3369 $start = max(0, ($page - 1) * $count);
3371 $user_info = api_get_user($a);
3373 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3374 /* this is to stop Hotot to load friends multiple times
3375 * I'm not sure if I'm missing return something or
3376 * is a bug in hotot. Workaround, meantime
3380 return array('$users' => $ret);*/
3385 if ($qtype == 'friends') {
3386 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3387 } elseif ($qtype == 'followers') {
3388 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3391 // friends and followers only for self
3392 if ($user_info['self'] == 0) {
3393 $sql_extra = " AND false ";
3396 if ($qtype == 'blocks') {
3397 $sql_filter = 'AND `blocked` AND NOT `pending`';
3398 } elseif ($qtype == 'incoming') {
3399 $sql_filter = 'AND `pending`';
3401 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3419 foreach ($r as $cid) {
3420 $user = api_get_user($a, $cid['nurl']);
3421 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3422 unset($user["uid"]);
3423 unset($user["self"]);
3430 return ['user' => $ret];
3435 * Returns the list of friends of the provided user
3437 * @deprecated By Twitter API in favor of friends/list
3439 * @param string $type Either "json" or "xml"
3440 * @return boolean|string|array
3441 * @throws BadRequestException
3442 * @throws ForbiddenException
3444 function api_statuses_friends($type)
3446 $data = api_statuses_f("friends");
3447 if ($data === false) {
3450 return api_format_data("users", $type, $data);
3454 * Returns the list of followers of the provided user
3456 * @deprecated By Twitter API in favor of friends/list
3458 * @param string $type Either "json" or "xml"
3459 * @return boolean|string|array
3460 * @throws BadRequestException
3461 * @throws ForbiddenException
3463 function api_statuses_followers($type)
3465 $data = api_statuses_f("followers");
3466 if ($data === false) {
3469 return api_format_data("users", $type, $data);
3472 /// @TODO move to top of file or somewhere better
3473 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3474 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3477 * Returns the list of blocked users
3479 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3481 * @param string $type Either "json" or "xml"
3483 * @return boolean|string|array
3484 * @throws BadRequestException
3485 * @throws ForbiddenException
3487 function api_blocks_list($type)
3489 $data = api_statuses_f('blocks');
3490 if ($data === false) {
3493 return api_format_data("users", $type, $data);
3496 /// @TODO move to top of file or somewhere better
3497 api_register_func('api/blocks/list', 'api_blocks_list', true);
3500 * Returns the list of pending users IDs
3502 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3504 * @param string $type Either "json" or "xml"
3506 * @return boolean|string|array
3507 * @throws BadRequestException
3508 * @throws ForbiddenException
3510 function api_friendships_incoming($type)
3512 $data = api_statuses_f('incoming');
3513 if ($data === false) {
3518 foreach ($data['user'] as $user) {
3519 $ids[] = $user['id'];
3522 return api_format_data("ids", $type, ['id' => $ids]);
3525 /// @TODO move to top of file or somewhere better
3526 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3529 * Returns the instance's configuration information.
3531 * @param string $type Return type (atom, rss, xml, json)
3533 * @return array|string
3534 * @throws InternalServerErrorException
3536 function api_statusnet_config($type)
3538 $name = DI::config()->get('config', 'sitename');
3539 $server = DI::baseUrl()->getHostname();
3540 $logo = DI::baseUrl() . '/images/friendica-64.png';
3541 $email = DI::config()->get('config', 'admin_email');
3542 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3543 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3544 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3545 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3546 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3549 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3550 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3551 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3552 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3553 'shorturllength' => '30',
3555 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3556 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3557 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3558 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3563 return api_format_data('config', $type, ['config' => $config]);
3566 /// @TODO move to top of file or somewhere better
3567 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3568 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3572 * @param string $type Return type (atom, rss, xml, json)
3574 * @return array|string
3576 function api_statusnet_version($type)
3579 $fake_statusnet_version = "0.9.7";
3581 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3584 /// @TODO move to top of file or somewhere better
3585 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3586 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3589 * Sends a new direct message.
3591 * @param string $type Return type (atom, rss, xml, json)
3593 * @return array|string
3594 * @throws BadRequestException
3595 * @throws ForbiddenException
3596 * @throws ImagickException
3597 * @throws InternalServerErrorException
3598 * @throws NotFoundException
3599 * @throws UnauthorizedException
3600 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3602 function api_direct_messages_new($type)
3606 if (api_user() === false) {
3607 throw new ForbiddenException();
3610 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3614 $sender = api_get_user($a);
3617 if (!empty($_POST['screen_name'])) {
3619 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3621 DBA::escape($_POST['screen_name'])
3624 if (DBA::isResult($r)) {
3625 // Selecting the id by priority, friendica first
3626 api_best_nickname($r);
3628 $recipient = api_get_user($a, $r[0]['nurl']);
3631 $recipient = api_get_user($a, $_POST['user_id']);
3634 if (empty($recipient)) {
3635 throw new NotFoundException('Recipient not found');
3639 if (!empty($_REQUEST['replyto'])) {
3641 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3643 intval($_REQUEST['replyto'])
3645 $replyto = $r[0]['parent-uri'];
3646 $sub = $r[0]['title'];
3648 if (!empty($_REQUEST['title'])) {
3649 $sub = $_REQUEST['title'];
3651 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3655 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3658 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3659 $ret = api_format_messages($r[0], $recipient, $sender);
3661 $ret = ["error"=>$id];
3664 $data = ['direct_message'=>$ret];
3670 $data = api_rss_extra($a, $data, $sender);
3674 return api_format_data("direct-messages", $type, $data);
3677 /// @TODO move to top of file or somewhere better
3678 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3681 * delete a direct_message from mail table through api
3683 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3684 * @return string|array
3685 * @throws BadRequestException
3686 * @throws ForbiddenException
3687 * @throws ImagickException
3688 * @throws InternalServerErrorException
3689 * @throws UnauthorizedException
3690 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3692 function api_direct_messages_destroy($type)
3696 if (api_user() === false) {
3697 throw new ForbiddenException();
3701 $user_info = api_get_user($a);
3703 $id = $_REQUEST['id'] ?? 0;
3705 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3706 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3707 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3709 $uid = $user_info['uid'];
3710 // error if no id or parenturi specified (for clients posting parent-uri as well)
3711 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3712 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3713 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3716 // BadRequestException if no id specified (for clients using Twitter API)
3718 throw new BadRequestException('Message id not specified');
3721 // add parent-uri to sql command if specified by calling app
3722 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3724 // get data of the specified message id
3726 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3731 // error message if specified id is not in database
3732 if (!DBA::isResult($r)) {
3733 if ($verbose == "true") {
3734 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3735 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3737 /// @todo BadRequestException ok for Twitter API clients?
3738 throw new BadRequestException('message id not in database');
3743 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3748 if ($verbose == "true") {
3751 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3752 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3754 $answer = ['result' => 'error', 'message' => 'unknown error'];
3755 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3758 /// @todo return JSON data like Twitter API not yet implemented
3761 /// @TODO move to top of file or somewhere better
3762 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3767 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3768 * @return string|array
3769 * @throws BadRequestException
3770 * @throws ForbiddenException
3771 * @throws ImagickException
3772 * @throws InternalServerErrorException
3773 * @throws NotFoundException
3774 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3776 function api_friendships_destroy($type)
3780 if ($uid === false) {
3781 throw new ForbiddenException();
3784 $contact_id = $_REQUEST['user_id'] ?? 0;
3786 if (empty($contact_id)) {
3787 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3788 throw new BadRequestException("no user_id specified");
3791 // Get Contact by given id
3792 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3794 if(!DBA::isResult($contact)) {
3795 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3796 throw new NotFoundException("no contact found to given ID");
3799 $url = $contact["url"];
3801 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3802 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3803 Strings::normaliseLink($url), $url];
3804 $contact = DBA::selectFirst('contact', [], $condition);
3806 if (!DBA::isResult($contact)) {
3807 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3808 throw new NotFoundException("Not following Contact");
3811 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3812 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3813 throw new ExpectationFailedException("Not supported");
3816 $dissolve = ($contact['rel'] == Contact::SHARING);
3818 $owner = User::getOwnerDataById($uid);
3820 Contact::terminateFriendship($owner, $contact, $dissolve);
3823 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3824 throw new NotFoundException("Error Processing Request");
3827 // Sharing-only contacts get deleted as there no relationship any more
3829 Contact::remove($contact['id']);
3831 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3834 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3835 unset($contact["uid"]);
3836 unset($contact["self"]);
3838 // Set screen_name since Twidere requests it
3839 $contact["screen_name"] = $contact["nick"];
3841 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3843 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3847 * @param string $type Return type (atom, rss, xml, json)
3848 * @param string $box
3849 * @param string $verbose
3851 * @return array|string
3852 * @throws BadRequestException
3853 * @throws ForbiddenException
3854 * @throws ImagickException
3855 * @throws InternalServerErrorException
3856 * @throws UnauthorizedException
3858 function api_direct_messages_box($type, $box, $verbose)
3861 if (api_user() === false) {
3862 throw new ForbiddenException();
3865 $count = $_GET['count'] ?? 20;
3866 $page = $_REQUEST['page'] ?? 1;
3868 $since_id = $_REQUEST['since_id'] ?? 0;
3869 $max_id = $_REQUEST['max_id'] ?? 0;
3871 $user_id = $_REQUEST['user_id'] ?? '';
3872 $screen_name = $_REQUEST['screen_name'] ?? '';
3875 unset($_REQUEST["user_id"]);
3876 unset($_GET["user_id"]);
3878 unset($_REQUEST["screen_name"]);
3879 unset($_GET["screen_name"]);
3881 $user_info = api_get_user($a);
3882 if ($user_info === false) {
3883 throw new ForbiddenException();
3885 $profile_url = $user_info["url"];
3888 $start = max(0, ($page - 1) * $count);
3893 if ($box=="sentbox") {
3894 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3895 } elseif ($box == "conversation") {
3896 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3897 } elseif ($box == "all") {
3898 $sql_extra = "true";
3899 } elseif ($box == "inbox") {
3900 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3904 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3907 if ($user_id != "") {
3908 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3909 } elseif ($screen_name !="") {
3910 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3914 "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",
3920 if ($verbose == "true" && !DBA::isResult($r)) {
3921 $answer = ['result' => 'error', 'message' => 'no mails available'];
3922 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3926 foreach ($r as $item) {
3927 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3928 $recipient = $user_info;
3929 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3930 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3931 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3932 $sender = $user_info;
3935 if (isset($recipient) && isset($sender)) {
3936 $ret[] = api_format_messages($item, $recipient, $sender);
3941 $data = ['direct_message' => $ret];
3946 $data = api_rss_extra($a, $data, $user_info);
3950 return api_format_data("direct-messages", $type, $data);
3954 * Returns the most recent direct messages sent by the user.
3956 * @param string $type Return type (atom, rss, xml, json)
3958 * @return array|string
3959 * @throws BadRequestException
3960 * @throws ForbiddenException
3961 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3963 function api_direct_messages_sentbox($type)
3965 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3966 return api_direct_messages_box($type, "sentbox", $verbose);
3970 * Returns the most recent direct messages sent to the user.
3972 * @param string $type Return type (atom, rss, xml, json)
3974 * @return array|string
3975 * @throws BadRequestException
3976 * @throws ForbiddenException
3977 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3979 function api_direct_messages_inbox($type)
3981 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3982 return api_direct_messages_box($type, "inbox", $verbose);
3987 * @param string $type Return type (atom, rss, xml, json)
3989 * @return array|string
3990 * @throws BadRequestException
3991 * @throws ForbiddenException
3993 function api_direct_messages_all($type)
3995 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3996 return api_direct_messages_box($type, "all", $verbose);
4001 * @param string $type Return type (atom, rss, xml, json)
4003 * @return array|string
4004 * @throws BadRequestException
4005 * @throws ForbiddenException
4007 function api_direct_messages_conversation($type)
4009 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4010 return api_direct_messages_box($type, "conversation", $verbose);
4013 /// @TODO move to top of file or somewhere better
4014 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4015 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4016 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4017 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4020 * Returns an OAuth Request Token.
4022 * @see https://oauth.net/core/1.0/#auth_step1
4024 function api_oauth_request_token()
4026 $oauth1 = new FKOAuth1();
4028 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4029 } catch (Exception $e) {
4030 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4038 * Returns an OAuth Access Token.
4040 * @return array|string
4041 * @see https://oauth.net/core/1.0/#auth_step3
4043 function api_oauth_access_token()
4045 $oauth1 = new FKOAuth1();
4047 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4048 } catch (Exception $e) {
4049 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4056 /// @TODO move to top of file or somewhere better
4057 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4058 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4062 * delete a complete photoalbum with all containing photos from database through api
4064 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4065 * @return string|array
4066 * @throws BadRequestException
4067 * @throws ForbiddenException
4068 * @throws InternalServerErrorException
4070 function api_fr_photoalbum_delete($type)
4072 if (api_user() === false) {
4073 throw new ForbiddenException();
4076 $album = $_REQUEST['album'] ?? '';
4078 // we do not allow calls without album string
4080 throw new BadRequestException("no albumname specified");
4082 // check if album is existing
4084 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4085 if (!DBA::isResult($photos)) {
4086 throw new BadRequestException("album not available");
4089 $resourceIds = array_column($photos, 'resource-id');
4091 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4092 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4093 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4094 Item::deleteForUser($condition, api_user());
4096 // now let's delete all photos from the album
4097 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4099 // return success of deletion or error message
4101 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4102 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4104 throw new InternalServerErrorException("unknown error - deleting from database failed");
4109 * update the name of the album for all photos of an album
4111 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4112 * @return string|array
4113 * @throws BadRequestException
4114 * @throws ForbiddenException
4115 * @throws InternalServerErrorException
4117 function api_fr_photoalbum_update($type)
4119 if (api_user() === false) {
4120 throw new ForbiddenException();
4123 $album = $_REQUEST['album'] ?? '';
4124 $album_new = $_REQUEST['album_new'] ?? '';
4126 // we do not allow calls without album string
4128 throw new BadRequestException("no albumname specified");
4130 if ($album_new == "") {
4131 throw new BadRequestException("no new albumname specified");
4133 // check if album is existing
4134 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4135 throw new BadRequestException("album not available");
4137 // now let's update all photos to the albumname
4138 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4140 // return success of updating or error message
4142 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4143 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4145 throw new InternalServerErrorException("unknown error - updating in database failed");
4151 * list all photos of the authenticated user
4153 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4154 * @return string|array
4155 * @throws ForbiddenException
4156 * @throws InternalServerErrorException
4158 function api_fr_photos_list($type)
4160 if (api_user() === false) {
4161 throw new ForbiddenException();
4164 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4165 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4166 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4167 intval(local_user())
4170 'image/jpeg' => 'jpg',
4171 'image/png' => 'png',
4172 'image/gif' => 'gif'
4174 $data = ['photo'=>[]];
4175 if (DBA::isResult($r)) {
4176 foreach ($r as $rr) {
4178 $photo['id'] = $rr['resource-id'];
4179 $photo['album'] = $rr['album'];
4180 $photo['filename'] = $rr['filename'];
4181 $photo['type'] = $rr['type'];
4182 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4183 $photo['created'] = $rr['created'];
4184 $photo['edited'] = $rr['edited'];
4185 $photo['desc'] = $rr['desc'];
4187 if ($type == "xml") {
4188 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4190 $photo['thumb'] = $thumb;
4191 $data['photo'][] = $photo;
4195 return api_format_data("photos", $type, $data);
4199 * upload a new photo or change an existing photo
4201 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4202 * @return string|array
4203 * @throws BadRequestException
4204 * @throws ForbiddenException
4205 * @throws ImagickException
4206 * @throws InternalServerErrorException
4207 * @throws NotFoundException
4209 function api_fr_photo_create_update($type)
4211 if (api_user() === false) {
4212 throw new ForbiddenException();
4215 $photo_id = $_REQUEST['photo_id'] ?? null;
4216 $desc = $_REQUEST['desc'] ?? null;
4217 $album = $_REQUEST['album'] ?? null;
4218 $album_new = $_REQUEST['album_new'] ?? null;
4219 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4220 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4221 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4222 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4223 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4225 // do several checks on input parameters
4226 // we do not allow calls without album string
4227 if ($album == null) {
4228 throw new BadRequestException("no albumname specified");
4230 // if photo_id == null --> we are uploading a new photo
4231 if ($photo_id == null) {
4234 // error if no media posted in create-mode
4235 if (empty($_FILES['media'])) {
4237 throw new BadRequestException("no media data submitted");
4240 // album_new will be ignored in create-mode
4245 // check if photo is existing in databasei
4246 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4247 throw new BadRequestException("photo not available");
4251 // checks on acl strings provided by clients
4252 $acl_input_error = false;
4253 $acl_input_error |= check_acl_input($allow_cid);
4254 $acl_input_error |= check_acl_input($deny_cid);
4255 $acl_input_error |= check_acl_input($allow_gid);
4256 $acl_input_error |= check_acl_input($deny_gid);
4257 if ($acl_input_error) {
4258 throw new BadRequestException("acl data invalid");
4260 // now let's upload the new media in create-mode
4261 if ($mode == "create") {
4262 $media = $_FILES['media'];
4263 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4265 // return success of updating or error message
4266 if (!is_null($data)) {
4267 return api_format_data("photo_create", $type, $data);
4269 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4273 // now let's do the changes in update-mode
4274 if ($mode == "update") {
4275 $updated_fields = [];
4277 if (!is_null($desc)) {
4278 $updated_fields['desc'] = $desc;
4281 if (!is_null($album_new)) {
4282 $updated_fields['album'] = $album_new;
4285 if (!is_null($allow_cid)) {
4286 $allow_cid = trim($allow_cid);
4287 $updated_fields['allow_cid'] = $allow_cid;
4290 if (!is_null($deny_cid)) {
4291 $deny_cid = trim($deny_cid);
4292 $updated_fields['deny_cid'] = $deny_cid;
4295 if (!is_null($allow_gid)) {
4296 $allow_gid = trim($allow_gid);
4297 $updated_fields['allow_gid'] = $allow_gid;
4300 if (!is_null($deny_gid)) {
4301 $deny_gid = trim($deny_gid);
4302 $updated_fields['deny_gid'] = $deny_gid;
4306 if (count($updated_fields) > 0) {
4307 $nothingtodo = false;
4308 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4310 $nothingtodo = true;
4313 if (!empty($_FILES['media'])) {
4314 $nothingtodo = false;
4315 $media = $_FILES['media'];
4316 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4317 if (!is_null($data)) {
4318 return api_format_data("photo_update", $type, $data);
4322 // return success of updating or error message
4324 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4325 return api_format_data("photo_update", $type, ['$result' => $answer]);
4328 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4329 return api_format_data("photo_update", $type, ['$result' => $answer]);
4331 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4334 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4338 * delete a single photo from the database through api
4340 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4341 * @return string|array
4342 * @throws BadRequestException
4343 * @throws ForbiddenException
4344 * @throws InternalServerErrorException
4346 function api_fr_photo_delete($type)
4348 if (api_user() === false) {
4349 throw new ForbiddenException();
4353 $photo_id = $_REQUEST['photo_id'] ?? null;
4355 // do several checks on input parameters
4356 // we do not allow calls without photo id
4357 if ($photo_id == null) {
4358 throw new BadRequestException("no photo_id specified");
4361 // check if photo is existing in database
4362 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4363 throw new BadRequestException("photo not available");
4366 // now we can perform on the deletion of the photo
4367 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4369 // return success of deletion or error message
4371 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4372 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4373 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4374 Item::deleteForUser($condition, api_user());
4376 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4377 return api_format_data("photo_delete", $type, ['$result' => $result]);
4379 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4385 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4387 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4388 * @return string|array
4389 * @throws BadRequestException
4390 * @throws ForbiddenException
4391 * @throws InternalServerErrorException
4392 * @throws NotFoundException
4394 function api_fr_photo_detail($type)
4396 if (api_user() === false) {
4397 throw new ForbiddenException();
4399 if (empty($_REQUEST['photo_id'])) {
4400 throw new BadRequestException("No photo id.");
4403 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4404 $photo_id = $_REQUEST['photo_id'];
4406 // prepare json/xml output with data from database for the requested photo
4407 $data = prepare_photo_data($type, $scale, $photo_id);
4409 return api_format_data("photo_detail", $type, $data);
4414 * updates the profile image for the user (either a specified profile or the default profile)
4416 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4418 * @return string|array
4419 * @throws BadRequestException
4420 * @throws ForbiddenException
4421 * @throws ImagickException
4422 * @throws InternalServerErrorException
4423 * @throws NotFoundException
4424 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4426 function api_account_update_profile_image($type)
4428 if (api_user() === false) {
4429 throw new ForbiddenException();
4432 $profile_id = $_REQUEST['profile_id'] ?? 0;
4434 // error if image data is missing
4435 if (empty($_FILES['image'])) {
4436 throw new BadRequestException("no media data submitted");
4439 // check if specified profile id is valid
4440 if ($profile_id != 0) {
4441 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4442 // error message if specified profile id is not in database
4443 if (!DBA::isResult($profile)) {
4444 throw new BadRequestException("profile_id not available");
4446 $is_default_profile = $profile['is-default'];
4448 $is_default_profile = 1;
4451 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4453 if (!empty($_FILES['image'])) {
4454 $media = $_FILES['image'];
4455 } elseif (!empty($_FILES['media'])) {
4456 $media = $_FILES['media'];
4458 // save new profile image
4459 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4462 if (is_array($media['type'])) {
4463 $filetype = $media['type'][0];
4465 $filetype = $media['type'];
4467 if ($filetype == "image/jpeg") {
4469 } elseif ($filetype == "image/png") {
4472 throw new InternalServerErrorException('Unsupported filetype');
4475 // change specified profile or all profiles to the new resource-id
4476 if ($is_default_profile) {
4477 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4478 Photo::update(['profile' => false], $condition);
4480 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4481 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4482 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4485 Contact::updateSelfFromUserID(api_user(), true);
4487 // Update global directory in background
4488 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4489 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4490 Worker::add(PRIORITY_LOW, "Directory", $url);
4493 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4495 // output for client
4497 return api_account_verify_credentials($type);
4499 // SaveMediaToDatabase failed for some reason
4500 throw new InternalServerErrorException("image upload failed");
4504 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4505 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4506 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4507 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4508 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4509 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4510 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4511 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4512 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4515 * Update user profile
4517 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4519 * @return array|string
4520 * @throws BadRequestException
4521 * @throws ForbiddenException
4522 * @throws ImagickException
4523 * @throws InternalServerErrorException
4524 * @throws UnauthorizedException
4526 function api_account_update_profile($type)
4528 $local_user = api_user();
4529 $api_user = api_get_user(DI::app());
4531 if (!empty($_POST['name'])) {
4532 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4533 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4534 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4535 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4538 if (isset($_POST['description'])) {
4539 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4540 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4541 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4544 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4545 // Update global directory in background
4546 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4547 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4550 return api_account_verify_credentials($type);
4553 /// @TODO move to top of file or somewhere better
4554 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4558 * @param string $acl_string
4562 function check_acl_input($acl_string)
4564 if (empty($acl_string)) {
4568 $contact_not_found = false;
4570 // split <x><y><z> into array of cid's
4571 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4573 // check for each cid if it is available on server
4574 $cid_array = $array[0];
4575 foreach ($cid_array as $cid) {
4576 $cid = str_replace("<", "", $cid);
4577 $cid = str_replace(">", "", $cid);
4578 $condition = ['id' => $cid, 'uid' => api_user()];
4579 $contact_not_found |= !DBA::exists('contact', $condition);
4581 return $contact_not_found;
4585 * @param string $mediatype
4586 * @param array $media
4587 * @param string $type
4588 * @param string $album
4589 * @param string $allow_cid
4590 * @param string $deny_cid
4591 * @param string $allow_gid
4592 * @param string $deny_gid
4593 * @param string $desc
4594 * @param integer $profile
4595 * @param boolean $visibility
4596 * @param string $photo_id
4598 * @throws BadRequestException
4599 * @throws ForbiddenException
4600 * @throws ImagickException
4601 * @throws InternalServerErrorException
4602 * @throws NotFoundException
4603 * @throws UnauthorizedException
4605 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)
4613 if (is_array($media)) {
4614 if (is_array($media['tmp_name'])) {
4615 $src = $media['tmp_name'][0];
4617 $src = $media['tmp_name'];
4619 if (is_array($media['name'])) {
4620 $filename = basename($media['name'][0]);
4622 $filename = basename($media['name']);
4624 if (is_array($media['size'])) {
4625 $filesize = intval($media['size'][0]);
4627 $filesize = intval($media['size']);
4629 if (is_array($media['type'])) {
4630 $filetype = $media['type'][0];
4632 $filetype = $media['type'];
4636 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4639 "File upload src: " . $src . " - filename: " . $filename .
4640 " - size: " . $filesize . " - type: " . $filetype,
4644 // check if there was a php upload error
4645 if ($filesize == 0 && $media['error'] == 1) {
4646 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4648 // check against max upload size within Friendica instance
4649 $maximagesize = DI::config()->get('system', 'maximagesize');
4650 if ($maximagesize && ($filesize > $maximagesize)) {
4651 $formattedBytes = Strings::formatBytes($maximagesize);
4652 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4655 // create Photo instance with the data of the image
4656 $imagedata = @file_get_contents($src);
4657 $Image = new Image($imagedata, $filetype);
4658 if (!$Image->isValid()) {
4659 throw new InternalServerErrorException("unable to process image data");
4662 // check orientation of image
4663 $Image->orient($src);
4666 // check max length of images on server
4667 $max_length = DI::config()->get('system', 'max_image_length');
4669 $max_length = MAX_IMAGE_LENGTH;
4671 if ($max_length > 0) {
4672 $Image->scaleDown($max_length);
4673 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4675 $width = $Image->getWidth();
4676 $height = $Image->getHeight();
4678 // create a new resource-id if not already provided
4679 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4681 if ($mediatype == "photo") {
4682 // upload normal image (scales 0, 1, 2)
4683 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4685 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4687 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4689 if ($width > 640 || $height > 640) {
4690 $Image->scaleDown(640);
4691 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4693 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4697 if ($width > 320 || $height > 320) {
4698 $Image->scaleDown(320);
4699 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4701 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4704 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4705 } elseif ($mediatype == "profileimage") {
4706 // upload profile image (scales 4, 5, 6)
4707 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4709 if ($width > 300 || $height > 300) {
4710 $Image->scaleDown(300);
4711 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4713 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4717 if ($width > 80 || $height > 80) {
4718 $Image->scaleDown(80);
4719 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4721 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4725 if ($width > 48 || $height > 48) {
4726 $Image->scaleDown(48);
4727 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4729 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4732 $Image->__destruct();
4733 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4737 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4738 if ($photo_id == null && $mediatype == "photo") {
4739 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4741 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4742 return prepare_photo_data($type, false, $resource_id);
4744 throw new InternalServerErrorException("image upload failed");
4750 * @param string $hash
4751 * @param string $allow_cid
4752 * @param string $deny_cid
4753 * @param string $allow_gid
4754 * @param string $deny_gid
4755 * @param string $filetype
4756 * @param boolean $visibility
4757 * @throws InternalServerErrorException
4759 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4761 // get data about the api authenticated user
4762 $uri = Item::newURI(intval(api_user()));
4763 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4766 $arr['guid'] = System::createUUID();
4767 $arr['uid'] = intval(api_user());
4769 $arr['type'] = 'photo';
4771 $arr['resource-id'] = $hash;
4772 $arr['contact-id'] = $owner_record['id'];
4773 $arr['owner-name'] = $owner_record['name'];
4774 $arr['owner-link'] = $owner_record['url'];
4775 $arr['owner-avatar'] = $owner_record['thumb'];
4776 $arr['author-name'] = $owner_record['name'];
4777 $arr['author-link'] = $owner_record['url'];
4778 $arr['author-avatar'] = $owner_record['thumb'];
4780 $arr['allow_cid'] = $allow_cid;
4781 $arr['allow_gid'] = $allow_gid;
4782 $arr['deny_cid'] = $deny_cid;
4783 $arr['deny_gid'] = $deny_gid;
4784 $arr['visible'] = $visibility;
4788 'image/jpeg' => 'jpg',
4789 'image/png' => 'png',
4790 'image/gif' => 'gif'
4793 // adds link to the thumbnail scale photo
4794 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4795 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4798 // do the magic for storing the item in the database and trigger the federation to other contacts
4804 * @param string $type
4806 * @param string $photo_id
4809 * @throws BadRequestException
4810 * @throws ForbiddenException
4811 * @throws ImagickException
4812 * @throws InternalServerErrorException
4813 * @throws NotFoundException
4814 * @throws UnauthorizedException
4816 function prepare_photo_data($type, $scale, $photo_id)
4819 $user_info = api_get_user($a);
4821 if ($user_info === false) {
4822 throw new ForbiddenException();
4825 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4826 $data_sql = ($scale === false ? "" : "data, ");
4828 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4829 // clients needs to convert this in their way for further processing
4831 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4832 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4833 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4834 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4835 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4836 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4838 intval(local_user()),
4839 DBA::escape($photo_id),
4844 'image/jpeg' => 'jpg',
4845 'image/png' => 'png',
4846 'image/gif' => 'gif'
4849 // prepare output data for photo
4850 if (DBA::isResult($r)) {
4851 $data = ['photo' => $r[0]];
4852 $data['photo']['id'] = $data['photo']['resource-id'];
4853 if ($scale !== false) {
4854 $data['photo']['data'] = base64_encode($data['photo']['data']);
4856 unset($data['photo']['datasize']); //needed only with scale param
4858 if ($type == "xml") {
4859 $data['photo']['links'] = [];
4860 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4861 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4863 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4866 $data['photo']['link'] = [];
4867 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4869 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4870 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4874 unset($data['photo']['resource-id']);
4875 unset($data['photo']['minscale']);
4876 unset($data['photo']['maxscale']);
4878 throw new NotFoundException();
4881 // retrieve item element for getting activities (like, dislike etc.) related to photo
4882 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4883 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4884 if (!DBA::isResult($item)) {
4885 throw new NotFoundException('Photo-related item not found.');
4888 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4890 // retrieve comments on photo
4891 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4892 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4894 $statuses = Post::selectForUser(api_user(), [], $condition);
4896 // prepare output of comments
4897 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4899 if ($type == "xml") {
4901 foreach ($commentData as $comment) {
4902 $comments[$k++ . ":comment"] = $comment;
4905 foreach ($commentData as $comment) {
4906 $comments[] = $comment;
4909 $data['photo']['friendica_comments'] = $comments;
4911 // include info if rights on photo and rights on item are mismatching
4912 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4913 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4914 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4915 $data['photo']['deny_gid'] != $item['deny_gid'];
4916 $data['photo']['rights_mismatch'] = $rights_mismatch;
4923 * Similar as /mod/redir.php
4924 * redirect to 'url' after dfrn auth
4926 * Why this when there is mod/redir.php already?
4927 * This use api_user() and api_login()
4930 * c_url: url of remote contact to auth to
4931 * url: string, url to redirect after auth
4933 function api_friendica_remoteauth()
4935 $url = $_GET['url'] ?? '';
4936 $c_url = $_GET['c_url'] ?? '';
4938 if ($url === '' || $c_url === '') {
4939 throw new BadRequestException("Wrong parameters.");
4942 $c_url = Strings::normaliseLink($c_url);
4946 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4947 if (!DBA::isResult($contact)) {
4948 throw new BadRequestException("Unknown contact");
4951 $cid = $contact['id'];
4953 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
4955 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
4956 System::externalRedirect($url ?: $c_url);
4959 if ($contact['duplex'] && $contact['issued-id']) {
4960 $orig_id = $contact['issued-id'];
4961 $dfrn_id = '1:' . $orig_id;
4963 if ($contact['duplex'] && $contact['dfrn-id']) {
4964 $orig_id = $contact['dfrn-id'];
4965 $dfrn_id = '0:' . $orig_id;
4968 $sec = Strings::getRandomHex();
4970 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4971 'sec' => $sec, 'expire' => time() + 45];
4972 DBA::insert('profile_check', $fields);
4974 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4975 $dest = ($url ? '&destination_url=' . $url : '');
4977 System::externalRedirect(
4978 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4979 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4980 . '&type=profile&sec=' . $sec . $dest
4983 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4986 * Return an item with announcer data if it had been announced
4988 * @param array $item Item array
4989 * @return array Item array with announce data
4991 function api_get_announce($item)
4993 // Quit if the item already has got a different owner and author
4994 if ($item['owner-id'] != $item['author-id']) {
4998 // Don't change original or Diaspora posts
4999 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5003 // Quit if we do now the original author and it had been a post from a native network
5004 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5008 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5009 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5010 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5011 if (!DBA::isResult($announce)) {
5015 return array_merge($item, $announce);
5019 * Return the item shared, if the item contains only the [share] tag
5021 * @param array $item Sharer item
5022 * @return array|false Shared item or false if not a reshare
5023 * @throws ImagickException
5024 * @throws InternalServerErrorException
5026 function api_share_as_retweet(&$item)
5028 $body = trim($item["body"]);
5030 if (Diaspora::isReshare($body, false) === false) {
5031 if ($item['author-id'] == $item['owner-id']) {
5034 // Reshares from OStatus, ActivityPub and Twitter
5035 $reshared_item = $item;
5036 $reshared_item['owner-id'] = $reshared_item['author-id'];
5037 $reshared_item['owner-link'] = $reshared_item['author-link'];
5038 $reshared_item['owner-name'] = $reshared_item['author-name'];
5039 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5040 return $reshared_item;
5044 $reshared = Item::getShareArray($item);
5045 if (empty($reshared)) {
5049 $reshared_item = $item;
5051 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5055 if (!empty($reshared['comment'])) {
5056 $item['body'] = $reshared['comment'];
5059 $reshared_item["share-pre-body"] = $reshared['comment'];
5060 $reshared_item["body"] = $reshared['shared'];
5061 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5062 $reshared_item["author-name"] = $reshared['author'];
5063 $reshared_item["author-link"] = $reshared['profile'];
5064 $reshared_item["author-avatar"] = $reshared['avatar'];
5065 $reshared_item["plink"] = $reshared['link'] ?? '';
5066 $reshared_item["created"] = $reshared['posted'];
5067 $reshared_item["edited"] = $reshared['posted'];
5069 // Try to fetch the original item
5070 if (!empty($reshared['guid'])) {
5071 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5072 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5073 $condition = ['id' => $original_id];
5078 if (!empty($condition)) {
5079 $original_item = Post::selectFirst([], $condition);
5080 if (DBA::isResult($original_item)) {
5081 $reshared_item = array_merge($reshared_item, $original_item);
5085 return $reshared_item;
5090 * @param array $item
5095 function api_in_reply_to($item)
5099 $in_reply_to['status_id'] = null;
5100 $in_reply_to['user_id'] = null;
5101 $in_reply_to['status_id_str'] = null;
5102 $in_reply_to['user_id_str'] = null;
5103 $in_reply_to['screen_name'] = null;
5105 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5106 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5107 if (DBA::isResult($parent)) {
5108 $in_reply_to['status_id'] = intval($parent['id']);
5110 $in_reply_to['status_id'] = intval($item['parent']);
5113 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5115 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5116 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5118 if (DBA::isResult($parent)) {
5119 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5120 $in_reply_to['user_id'] = intval($parent['author-id']);
5121 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5124 // There seems to be situation, where both fields are identical:
5125 // https://github.com/friendica/friendica/issues/1010
5126 // This is a bugfix for that.
5127 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5128 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']]);
5129 $in_reply_to['status_id'] = null;
5130 $in_reply_to['user_id'] = null;
5131 $in_reply_to['status_id_str'] = null;
5132 $in_reply_to['user_id_str'] = null;
5133 $in_reply_to['screen_name'] = null;
5137 return $in_reply_to;
5142 * @param string $text
5145 * @throws InternalServerErrorException
5147 function api_clean_plain_items($text)
5149 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5151 $text = BBCode::cleanPictureLinks($text);
5152 $URLSearchString = "^\[\]";
5154 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5156 if ($include_entities == "true") {
5157 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5160 // Simplify "attachment" element
5161 $text = BBCode::removeAttachment($text);
5168 * @param array $contacts
5172 function api_best_nickname(&$contacts)
5176 if (count($contacts) == 0) {
5180 foreach ($contacts as $contact) {
5181 if ($contact["network"] == "") {
5182 $contact["network"] = "dfrn";
5183 $best_contact = [$contact];
5187 if (sizeof($best_contact) == 0) {
5188 foreach ($contacts as $contact) {
5189 if ($contact["network"] == "dfrn") {
5190 $best_contact = [$contact];
5195 if (sizeof($best_contact) == 0) {
5196 foreach ($contacts as $contact) {
5197 if ($contact["network"] == "dspr") {
5198 $best_contact = [$contact];
5203 if (sizeof($best_contact) == 0) {
5204 foreach ($contacts as $contact) {
5205 if ($contact["network"] == "stat") {
5206 $best_contact = [$contact];
5211 if (sizeof($best_contact) == 0) {
5212 foreach ($contacts as $contact) {
5213 if ($contact["network"] == "pump") {
5214 $best_contact = [$contact];
5219 if (sizeof($best_contact) == 0) {
5220 foreach ($contacts as $contact) {
5221 if ($contact["network"] == "twit") {
5222 $best_contact = [$contact];
5227 if (sizeof($best_contact) == 1) {
5228 $contacts = $best_contact;
5230 $contacts = [$contacts[0]];
5235 * Return all or a specified group of the user with the containing contacts.
5237 * @param string $type Return type (atom, rss, xml, json)
5239 * @return array|string
5240 * @throws BadRequestException
5241 * @throws ForbiddenException
5242 * @throws ImagickException
5243 * @throws InternalServerErrorException
5244 * @throws UnauthorizedException
5246 function api_friendica_group_show($type)
5250 if (api_user() === false) {
5251 throw new ForbiddenException();
5255 $user_info = api_get_user($a);
5256 $gid = $_REQUEST['gid'] ?? 0;
5257 $uid = $user_info['uid'];
5259 // get data of the specified group id or all groups if not specified
5262 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5266 // error message if specified gid is not in database
5267 if (!DBA::isResult($r)) {
5268 throw new BadRequestException("gid not available");
5272 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5277 // loop through all groups and retrieve all members for adding data in the user array
5279 foreach ($r as $rr) {
5280 $members = Contact\Group::getById($rr['id']);
5283 if ($type == "xml") {
5284 $user_element = "users";
5286 foreach ($members as $member) {
5287 $user = api_get_user($a, $member['nurl']);
5288 $users[$k++.":user"] = $user;
5291 $user_element = "user";
5292 foreach ($members as $member) {
5293 $user = api_get_user($a, $member['nurl']);
5297 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5299 return api_format_data("groups", $type, ['group' => $grps]);
5301 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5305 * Delete the specified group of the user.
5307 * @param string $type Return type (atom, rss, xml, json)
5309 * @return array|string
5310 * @throws BadRequestException
5311 * @throws ForbiddenException
5312 * @throws ImagickException
5313 * @throws InternalServerErrorException
5314 * @throws UnauthorizedException
5316 function api_friendica_group_delete($type)
5320 if (api_user() === false) {
5321 throw new ForbiddenException();
5325 $user_info = api_get_user($a);
5326 $gid = $_REQUEST['gid'] ?? 0;
5327 $name = $_REQUEST['name'] ?? '';
5328 $uid = $user_info['uid'];
5330 // error if no gid specified
5331 if ($gid == 0 || $name == "") {
5332 throw new BadRequestException('gid or name not specified');
5335 // get data of the specified group id
5337 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5341 // error message if specified gid is not in database
5342 if (!DBA::isResult($r)) {
5343 throw new BadRequestException('gid not available');
5346 // get data of the specified group id and group name
5348 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5353 // error message if specified gid is not in database
5354 if (!DBA::isResult($rname)) {
5355 throw new BadRequestException('wrong group name');
5359 $ret = Group::removeByName($uid, $name);
5362 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5363 return api_format_data("group_delete", $type, ['result' => $success]);
5365 throw new BadRequestException('other API error');
5368 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5373 * @param string $type Return type (atom, rss, xml, json)
5375 * @return array|string
5376 * @throws BadRequestException
5377 * @throws ForbiddenException
5378 * @throws ImagickException
5379 * @throws InternalServerErrorException
5380 * @throws UnauthorizedException
5381 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5383 function api_lists_destroy($type)
5387 if (api_user() === false) {
5388 throw new ForbiddenException();
5392 $user_info = api_get_user($a);
5393 $gid = $_REQUEST['list_id'] ?? 0;
5394 $uid = $user_info['uid'];
5396 // error if no gid specified
5398 throw new BadRequestException('gid not specified');
5401 // get data of the specified group id
5402 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5403 // error message if specified gid is not in database
5405 throw new BadRequestException('gid not available');
5408 if (Group::remove($gid)) {
5410 'name' => $group['name'],
5411 'id' => intval($gid),
5412 'id_str' => (string) $gid,
5413 'user' => $user_info
5416 return api_format_data("lists", $type, ['lists' => $list]);
5419 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5422 * Add a new group to the database.
5424 * @param string $name Group name
5425 * @param int $uid User ID
5426 * @param array $users List of users to add to the group
5429 * @throws BadRequestException
5431 function group_create($name, $uid, $users = [])
5433 // error if no name specified
5435 throw new BadRequestException('group name not specified');
5438 // get data of the specified group name
5440 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5444 // error message if specified group name already exists
5445 if (DBA::isResult($rname)) {
5446 throw new BadRequestException('group name already exists');
5449 // check if specified group name is a deleted group
5451 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5455 // error message if specified group name already exists
5456 if (DBA::isResult($rname)) {
5457 $reactivate_group = true;
5461 $ret = Group::create($uid, $name);
5463 $gid = Group::getIdByName($uid, $name);
5465 throw new BadRequestException('other API error');
5469 $erroraddinguser = false;
5471 foreach ($users as $user) {
5472 $cid = $user['cid'];
5473 // check if user really exists as contact
5475 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5479 if (count($contact)) {
5480 Group::addMember($gid, $cid);
5482 $erroraddinguser = true;
5483 $errorusers[] = $cid;
5487 // return success message incl. missing users in array
5488 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5490 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5494 * Create the specified group with the posted array of contacts.
5496 * @param string $type Return type (atom, rss, xml, json)
5498 * @return array|string
5499 * @throws BadRequestException
5500 * @throws ForbiddenException
5501 * @throws ImagickException
5502 * @throws InternalServerErrorException
5503 * @throws UnauthorizedException
5505 function api_friendica_group_create($type)
5509 if (api_user() === false) {
5510 throw new ForbiddenException();
5514 $user_info = api_get_user($a);
5515 $name = $_REQUEST['name'] ?? '';
5516 $uid = $user_info['uid'];
5517 $json = json_decode($_POST['json'], true);
5518 $users = $json['user'];
5520 $success = group_create($name, $uid, $users);
5522 return api_format_data("group_create", $type, ['result' => $success]);
5524 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5527 * Create a new group.
5529 * @param string $type Return type (atom, rss, xml, json)
5531 * @return array|string
5532 * @throws BadRequestException
5533 * @throws ForbiddenException
5534 * @throws ImagickException
5535 * @throws InternalServerErrorException
5536 * @throws UnauthorizedException
5537 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5539 function api_lists_create($type)
5543 if (api_user() === false) {
5544 throw new ForbiddenException();
5548 $user_info = api_get_user($a);
5549 $name = $_REQUEST['name'] ?? '';
5550 $uid = $user_info['uid'];
5552 $success = group_create($name, $uid);
5553 if ($success['success']) {
5555 'name' => $success['name'],
5556 'id' => intval($success['gid']),
5557 'id_str' => (string) $success['gid'],
5558 'user' => $user_info
5561 return api_format_data("lists", $type, ['lists'=>$grp]);
5564 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5567 * Update the specified group with the posted array of contacts.
5569 * @param string $type Return type (atom, rss, xml, json)
5571 * @return array|string
5572 * @throws BadRequestException
5573 * @throws ForbiddenException
5574 * @throws ImagickException
5575 * @throws InternalServerErrorException
5576 * @throws UnauthorizedException
5578 function api_friendica_group_update($type)
5582 if (api_user() === false) {
5583 throw new ForbiddenException();
5587 $user_info = api_get_user($a);
5588 $uid = $user_info['uid'];
5589 $gid = $_REQUEST['gid'] ?? 0;
5590 $name = $_REQUEST['name'] ?? '';
5591 $json = json_decode($_POST['json'], true);
5592 $users = $json['user'];
5594 // error if no name specified
5596 throw new BadRequestException('group name not specified');
5599 // error if no gid specified
5601 throw new BadRequestException('gid not specified');
5605 $members = Contact\Group::getById($gid);
5606 foreach ($members as $member) {
5607 $cid = $member['id'];
5608 foreach ($users as $user) {
5609 $found = ($user['cid'] == $cid ? true : false);
5611 if (!isset($found) || !$found) {
5612 Group::removeMemberByName($uid, $name, $cid);
5617 $erroraddinguser = false;
5619 foreach ($users as $user) {
5620 $cid = $user['cid'];
5621 // check if user really exists as contact
5623 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5628 if (count($contact)) {
5629 Group::addMember($gid, $cid);
5631 $erroraddinguser = true;
5632 $errorusers[] = $cid;
5636 // return success message incl. missing users in array
5637 $status = ($erroraddinguser ? "missing user" : "ok");
5638 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5639 return api_format_data("group_update", $type, ['result' => $success]);
5642 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5645 * Update information about a group.
5647 * @param string $type Return type (atom, rss, xml, json)
5649 * @return array|string
5650 * @throws BadRequestException
5651 * @throws ForbiddenException
5652 * @throws ImagickException
5653 * @throws InternalServerErrorException
5654 * @throws UnauthorizedException
5655 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5657 function api_lists_update($type)
5661 if (api_user() === false) {
5662 throw new ForbiddenException();
5666 $user_info = api_get_user($a);
5667 $gid = $_REQUEST['list_id'] ?? 0;
5668 $name = $_REQUEST['name'] ?? '';
5669 $uid = $user_info['uid'];
5671 // error if no gid specified
5673 throw new BadRequestException('gid not specified');
5676 // get data of the specified group id
5677 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5678 // error message if specified gid is not in database
5680 throw new BadRequestException('gid not available');
5683 if (Group::update($gid, $name)) {
5686 'id' => intval($gid),
5687 'id_str' => (string) $gid,
5688 'user' => $user_info
5691 return api_format_data("lists", $type, ['lists' => $list]);
5695 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5699 * @param string $type Return type (atom, rss, xml, json)
5701 * @return array|string
5702 * @throws BadRequestException
5703 * @throws ForbiddenException
5704 * @throws ImagickException
5705 * @throws InternalServerErrorException
5707 function api_friendica_activity($type)
5711 if (api_user() === false) {
5712 throw new ForbiddenException();
5714 $verb = strtolower($a->argv[3]);
5715 $verb = preg_replace("|\..*$|", "", $verb);
5717 $id = $_REQUEST['id'] ?? 0;
5719 $res = Item::performActivity($id, $verb, api_user());
5722 if ($type == "xml") {
5727 return api_format_data('ok', $type, ['ok' => $ok]);
5729 throw new BadRequestException('Error adding activity');
5733 /// @TODO move to top of file or somewhere better
5734 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5735 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5736 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5737 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5738 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5739 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5740 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5741 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5742 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5743 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5746 * Returns notifications
5748 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5750 * @return string|array
5751 * @throws ForbiddenException
5752 * @throws BadRequestException
5755 function api_friendica_notification($type)
5759 if (api_user() === false) {
5760 throw new ForbiddenException();
5763 throw new BadRequestException("Invalid argument count");
5766 $notifications = DI::notification()->getApiList(local_user());
5768 if ($type == "xml") {
5770 if (!empty($notifications)) {
5771 foreach ($notifications as $notification) {
5772 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5776 $result = $xmlnotes;
5777 } elseif (count($notifications) > 0) {
5778 $result = $notifications->getArrayCopy();
5783 return api_format_data("notes", $type, ['note' => $result]);
5787 * Set notification as seen and returns associated item (if possible)
5789 * POST request with 'id' param as notification id
5791 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5792 * @return string|array
5793 * @throws BadRequestException
5794 * @throws ForbiddenException
5795 * @throws ImagickException
5796 * @throws InternalServerErrorException
5797 * @throws UnauthorizedException
5799 function api_friendica_notification_seen($type)
5802 $user_info = api_get_user($a);
5804 if (api_user() === false || $user_info === false) {
5805 throw new ForbiddenException();
5807 if ($a->argc !== 4) {
5808 throw new BadRequestException("Invalid argument count");
5811 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5814 $notify = DI::notify()->getByID($id, api_user());
5815 DI::notify()->setSeen(true, $notify);
5817 if ($notify->otype === Notify\ObjectType::ITEM) {
5818 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5819 if (DBA::isResult($item)) {
5820 // we found the item, return it to the user
5821 $ret = api_format_items([$item], $user_info, false, $type);
5822 $data = ['status' => $ret];
5823 return api_format_data("status", $type, $data);
5825 // the item can't be found, but we set the notification as seen, so we count this as a success
5827 return api_format_data('result', $type, ['result' => "success"]);
5828 } catch (NotFoundException $e) {
5829 throw new BadRequestException('Invalid argument', $e);
5830 } catch (Exception $e) {
5831 throw new InternalServerErrorException('Internal Server exception', $e);
5835 /// @TODO move to top of file or somewhere better
5836 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5837 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5840 * update a direct_message to seen state
5842 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5843 * @return string|array (success result=ok, error result=error with error message)
5844 * @throws BadRequestException
5845 * @throws ForbiddenException
5846 * @throws ImagickException
5847 * @throws InternalServerErrorException
5848 * @throws UnauthorizedException
5850 function api_friendica_direct_messages_setseen($type)
5853 if (api_user() === false) {
5854 throw new ForbiddenException();
5858 $user_info = api_get_user($a);
5859 $uid = $user_info['uid'];
5860 $id = $_REQUEST['id'] ?? 0;
5862 // return error if id is zero
5864 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5865 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5868 // error message if specified id is not in database
5869 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5870 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5871 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5874 // update seen indicator
5875 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5879 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5880 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5882 $answer = ['result' => 'error', 'message' => 'unknown error'];
5883 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5887 /// @TODO move to top of file or somewhere better
5888 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5891 * search for direct_messages containing a searchstring through api
5893 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5894 * @param string $box
5895 * @return string|array (success: success=true if found and search_result contains found messages,
5896 * success=false if nothing was found, search_result='nothing found',
5897 * error: result=error with error message)
5898 * @throws BadRequestException
5899 * @throws ForbiddenException
5900 * @throws ImagickException
5901 * @throws InternalServerErrorException
5902 * @throws UnauthorizedException
5904 function api_friendica_direct_messages_search($type, $box = "")
5908 if (api_user() === false) {
5909 throw new ForbiddenException();
5913 $user_info = api_get_user($a);
5914 $searchstring = $_REQUEST['searchstring'] ?? '';
5915 $uid = $user_info['uid'];
5917 // error if no searchstring specified
5918 if ($searchstring == "") {
5919 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5920 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5923 // get data for the specified searchstring
5925 "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",
5927 DBA::escape('%'.$searchstring.'%')
5930 $profile_url = $user_info["url"];
5932 // message if nothing was found
5933 if (!DBA::isResult($r)) {
5934 $success = ['success' => false, 'search_results' => 'problem with query'];
5935 } elseif (count($r) == 0) {
5936 $success = ['success' => false, 'search_results' => 'nothing found'];
5939 foreach ($r as $item) {
5940 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5941 $recipient = $user_info;
5942 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5943 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5944 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5945 $sender = $user_info;
5948 if (isset($recipient) && isset($sender)) {
5949 $ret[] = api_format_messages($item, $recipient, $sender);
5952 $success = ['success' => true, 'search_results' => $ret];
5955 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5958 /// @TODO move to top of file or somewhere better
5959 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5962 * Returns a list of saved searches.
5964 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5966 * @param string $type Return format: json or xml
5968 * @return string|array
5971 function api_saved_searches_list($type)
5973 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5976 while ($term = DBA::fetch($terms)) {
5978 'created_at' => api_date(time()),
5979 'id' => intval($term['id']),
5980 'id_str' => $term['id'],
5981 'name' => $term['term'],
5983 'query' => $term['term']
5989 return api_format_data("terms", $type, ['terms' => $result]);
5992 /// @TODO move to top of file or somewhere better
5993 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5996 * Number of comments
5998 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6000 * @param object $data [Status, Status]
6004 function bindComments(&$data)
6006 if (count($data) == 0) {
6012 foreach ($data as $item) {
6013 $ids[] = $item['id'];
6016 $idStr = DBA::escape(implode(', ', $ids));
6017 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6018 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6019 $itemsData = DBA::toArray($items);
6021 foreach ($itemsData as $item) {
6022 $comments[$item['parent']] = $item['comments'];
6025 foreach ($data as $idx => $item) {
6027 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6032 @TODO Maybe open to implement?
6034 [pagename] => api/1.1/statuses/lookup.json
6035 [id] => 605138389168451584
6036 [include_cards] => true
6037 [cards_platform] => Android-12
6038 [include_entities] => true
6039 [include_my_retweet] => 1
6041 [include_reply_count] => true
6042 [include_descendent_reply_count] => true
6046 Not implemented by now:
6047 statuses/retweets_of_me
6052 account/update_location
6053 account/update_profile_background_image
6056 friendica/profile/update
6057 friendica/profile/create
6058 friendica/profile/delete
6060 Not implemented in status.net:
6061 statuses/retweeted_to_me
6062 statuses/retweeted_by_me
6063 direct_messages/destroy
6065 account/update_delivery_device
6066 notifications/follow