3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\Verb;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\TooManyRequestsException;
55 use Friendica\Network\HTTPException\UnauthorizedException;
56 use Friendica\Object\Image;
57 use Friendica\Protocol\Activity;
58 use Friendica\Protocol\Diaspora;
59 use Friendica\Security\FKOAuth1;
60 use Friendica\Security\OAuth1\OAuthRequest;
61 use Friendica\Security\OAuth1\OAuthUtil;
62 use Friendica\Util\DateTimeFormat;
63 use Friendica\Util\Images;
64 use Friendica\Util\Network;
65 use Friendica\Util\Proxy as ProxyUtils;
66 use Friendica\Util\Strings;
67 use Friendica\Util\XML;
69 require_once __DIR__ . '/../mod/item.php';
70 require_once __DIR__ . '/../mod/wall_upload.php';
72 define('API_METHOD_ANY', '*');
73 define('API_METHOD_GET', 'GET');
74 define('API_METHOD_POST', 'POST,PUT');
75 define('API_METHOD_DELETE', 'POST,DELETE');
77 define('API_LOG_PREFIX', 'API {action} - ');
85 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
86 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
87 * into a page, and visitors will post something without noticing it).
91 if (!empty($_SESSION['allow_api'])) {
99 * Get source name from API client
101 * Clients can send 'source' parameter to be show in post metadata
102 * as "sent via <source>".
103 * Some clients doesn't send a source param, we support ones we know
104 * (only Twidere, atm)
107 * Client source name, default to "api" if unset/unknown
110 function api_source()
112 if (requestdata('source')) {
113 return requestdata('source');
116 // Support for known clients that doesn't send a source name
117 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
118 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
122 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
124 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
131 * Format date for API
133 * @param string $str Source date, as UTC
134 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
137 function api_date($str)
139 // Wed May 23 06:01:13 +0000 2007
140 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
144 * Register a function to be the endpoint for defined API path.
146 * @param string $path API URL path, relative to DI::baseUrl()
147 * @param string $func Function name to call on path request
148 * @param bool $auth API need logged user
149 * @param string $method HTTP method reqiured to call this endpoint.
150 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
151 * Default to API_METHOD_ANY
153 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
163 // Workaround for hotot
164 $path = str_replace("api/", "api/1.1/", $path);
174 * Log in user via OAuth1 or Simple HTTP Auth.
175 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
178 * @param bool $do_login try to log in when not logged in, otherwise quit silently
179 * @throws ForbiddenException
180 * @throws InternalServerErrorException
181 * @throws UnauthorizedException
182 * @hook 'authenticate'
184 * 'username' => username from login form
185 * 'password' => password from login form
186 * 'authenticated' => return status,
187 * 'user_record' => return authenticated user record
189 function api_login(App $a, bool $do_login = true)
191 $_SESSION["allow_api"] = false;
193 // workaround for HTTP-auth in CGI mode
194 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
195 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
196 if (strlen($userpass)) {
197 list($name, $password) = explode(':', $userpass);
198 $_SERVER['PHP_AUTH_USER'] = $name;
199 $_SERVER['PHP_AUTH_PW'] = $password;
203 if (empty($_SERVER['PHP_AUTH_USER'])) {
204 // Try OAuth when no user is provided
205 $oauth1 = new FKOAuth1();
208 $request = OAuthRequest::from_request();
209 list($consumer, $token) = $oauth1->verify_request($request);
210 if (!is_null($token)) {
211 $oauth1->loginUser($token->uid);
212 Session::set('allow_api', true);
215 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
216 var_dump($consumer, $token);
218 } catch (Exception $e) {
219 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
226 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
227 header('WWW-Authenticate: Basic realm="Friendica"');
228 throw new UnauthorizedException("This API requires login");
231 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
232 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
234 // allow "user@server" login (but ignore 'server' part)
235 $at = strstr($user, "@", true);
240 // next code from mod/auth.php. needs better solution
244 'username' => trim($user),
245 'password' => trim($password),
246 'authenticated' => 0,
247 'user_record' => null,
251 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
252 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
253 * and later addons should not interfere with an earlier one that succeeded.
255 Hook::callAll('authenticate', $addon_auth);
257 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
258 $record = $addon_auth['user_record'];
260 $user_id = User::authenticate(trim($user), trim($password), true);
261 if ($user_id !== false) {
262 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
266 if (!DBA::isResult($record)) {
270 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
271 header('WWW-Authenticate: Basic realm="Friendica"');
272 //header('HTTP/1.0 401 Unauthorized');
273 //die('This api requires login');
274 throw new UnauthorizedException("This API requires login");
277 // Don't refresh the login date more often than twice a day to spare database writes
278 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
280 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
282 $_SESSION["allow_api"] = true;
284 Hook::callAll('logged_in', $a->user);
288 * Check HTTP method of called API
290 * API endpoints can define which HTTP method to accept when called.
291 * This function check the current HTTP method agains endpoint
294 * @param string $method Required methods, uppercase, separated by comma
297 function api_check_method($method)
299 if ($method == "*") {
302 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
306 * Main API entry point
308 * Authenticate user, call registered API function, set HTTP headers
311 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
312 * @return string|array API call result
315 function api_call(App $a, App\Arguments $args = null)
317 global $API, $called_api;
324 if (strpos($args->getCommand(), ".xml") > 0) {
327 if (strpos($args->getCommand(), ".json") > 0) {
330 if (strpos($args->getCommand(), ".rss") > 0) {
333 if (strpos($args->getCommand(), ".atom") > 0) {
338 foreach ($API as $p => $info) {
339 if (strpos($args->getCommand(), $p) === 0) {
340 if (!api_check_method($info['method'])) {
341 throw new MethodNotAllowedException();
344 $called_api = explode("/", $p);
346 if (!empty($info['auth']) && api_user() === false) {
348 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
351 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
353 $stamp = microtime(true);
354 $return = call_user_func($info['func'], $type);
355 $duration = floatval(microtime(true) - $stamp);
357 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
359 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
361 if (false === $return) {
363 * api function returned false withour throw an
364 * exception. This should not happend, throw a 500
366 throw new InternalServerErrorException();
371 header("Content-Type: text/xml");
374 header("Content-Type: application/json");
375 if (!empty($return)) {
376 $json = json_encode(end($return));
377 if (!empty($_GET['callback'])) {
378 $json = $_GET['callback'] . "(" . $json . ")";
384 header("Content-Type: application/rss+xml");
385 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
388 header("Content-Type: application/atom+xml");
389 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
396 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
397 throw new NotFoundException();
398 } catch (HTTPException $e) {
399 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
400 return api_error($type, $e, $args);
405 * Format API error string
407 * @param string $type Return type (xml, json, rss, as)
408 * @param object $e HTTPException Error object
409 * @param App\Arguments $args The App arguments
410 * @return string|array error message formatted as $type
412 function api_error($type, $e, App\Arguments $args)
414 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
415 /// @TODO: https://dev.twitter.com/overview/api/response-codes
417 $error = ["error" => $error,
418 "code" => $e->getCode() . " " . $e->httpdesc,
419 "request" => $args->getQueryString()];
421 $return = api_format_data('status', $type, ['status' => $error]);
425 header("Content-Type: text/xml");
428 header("Content-Type: application/json");
429 $return = json_encode($return);
432 header("Content-Type: application/rss+xml");
435 header("Content-Type: application/atom+xml");
443 * Set values for RSS template
446 * @param array $arr Array to be passed to template
447 * @param array $user_info User info
449 * @throws BadRequestException
450 * @throws ImagickException
451 * @throws InternalServerErrorException
452 * @throws UnauthorizedException
453 * @todo find proper type-hints
455 function api_rss_extra(App $a, $arr, $user_info)
457 if (is_null($user_info)) {
458 $user_info = api_get_user($a);
461 $arr['$user'] = $user_info;
463 'alternate' => $user_info['url'],
464 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
465 'base' => DI::baseUrl(),
466 'updated' => api_date(null),
467 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
468 'language' => $user_info['lang'],
469 'logo' => DI::baseUrl() . "/images/friendica-32.png",
477 * Unique contact to contact url.
479 * @param int $id Contact id
480 * @return bool|string
481 * Contact url or False if contact id is unknown
484 function api_unique_id_to_nurl($id)
486 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
488 if (DBA::isResult($r)) {
496 * Get user info array.
499 * @param int|string $contact_id Contact ID or URL
501 * @throws BadRequestException
502 * @throws ImagickException
503 * @throws InternalServerErrorException
504 * @throws UnauthorizedException
506 function api_get_user(App $a, $contact_id = null)
514 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
516 // Searching for contact URL
517 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
518 $user = DBA::escape(Strings::normaliseLink($contact_id));
520 $extra_query = "AND `contact`.`nurl` = '%s' ";
521 if (api_user() !== false) {
522 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
526 // Searching for contact id with uid = 0
527 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
528 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
531 throw new BadRequestException("User ID ".$contact_id." not found.");
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 if (is_null($user) && !empty($_GET['user_id'])) {
542 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
545 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
549 $extra_query = "AND `contact`.`nurl` = '%s' ";
550 if (api_user() !== false) {
551 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
554 if (is_null($user) && !empty($_GET['screen_name'])) {
555 $user = DBA::escape($_GET['screen_name']);
556 $extra_query = "AND `contact`.`nick` = '%s' ";
557 if (api_user() !== false) {
558 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
562 if (is_null($user) && !empty($_GET['profileurl'])) {
563 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
564 $extra_query = "AND `contact`.`nurl` = '%s' ";
565 if (api_user() !== false) {
566 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
570 // $called_api is the API path exploded on / and is expected to have at least 2 elements
571 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
572 $argid = count($called_api);
573 if (!empty($a->argv[$argid])) {
574 $data = explode(".", $a->argv[$argid]);
575 if (count($data) > 1) {
576 list($user, $null) = $data;
579 if (is_numeric($user)) {
580 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
584 $extra_query = "AND `contact`.`nurl` = '%s' ";
585 if (api_user() !== false) {
586 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
590 $user = DBA::escape($user);
591 $extra_query = "AND `contact`.`nick` = '%s' ";
592 if (api_user() !== false) {
593 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
598 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
601 if (api_user() === false) {
605 $user = $_SESSION['uid'];
606 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
610 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
614 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
620 // Selecting the id by priority, friendica first
621 if (is_array($uinfo)) {
622 api_best_nickname($uinfo);
625 // if the contact wasn't found, fetch it from the contacts with uid = 0
626 if (!DBA::isResult($uinfo)) {
628 throw new BadRequestException("User not found.");
631 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
633 if (DBA::isResult($contact)) {
635 'id' => $contact["id"],
636 'id_str' => (string) $contact["id"],
637 'name' => $contact["name"],
638 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
639 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
640 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
641 'profile_image_url' => $contact["micro"],
642 'profile_image_url_https' => $contact["micro"],
643 'profile_image_url_profile_size' => $contact["thumb"],
644 'profile_image_url_large' => $contact["photo"],
645 'url' => $contact["url"],
646 'protected' => false,
647 'followers_count' => 0,
648 'friends_count' => 0,
650 'created_at' => api_date($contact["created"]),
651 'favourites_count' => 0,
653 'time_zone' => 'UTC',
654 'geo_enabled' => false,
656 'statuses_count' => 0,
658 'contributors_enabled' => false,
659 'is_translator' => false,
660 'is_translation_enabled' => false,
661 'following' => false,
662 'follow_request_sent' => false,
663 'statusnet_blocking' => false,
664 'notifications' => false,
665 'statusnet_profile_url' => $contact["url"],
667 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
668 'pid' => Contact::getIdForURL($contact["url"], 0, false),
670 'network' => $contact["network"],
675 throw new BadRequestException("User ".$url." not found.");
679 if ($uinfo[0]['self']) {
680 if ($uinfo[0]['network'] == "") {
681 $uinfo[0]['network'] = Protocol::DFRN;
684 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
685 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
692 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
694 if (!empty($profile['about'])) {
695 $description = $profile['about'];
697 $description = $uinfo[0]["about"];
700 if (!empty($usr['default-location'])) {
701 $location = $usr['default-location'];
702 } elseif (!empty($uinfo[0]["location"])) {
703 $location = $uinfo[0]["location"];
705 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
709 'id' => intval($pcontact_id),
710 'id_str' => (string) intval($pcontact_id),
711 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
712 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
713 'location' => $location,
714 'description' => BBCode::toPlaintext($description ?? ''),
715 'profile_image_url' => $uinfo[0]['micro'],
716 'profile_image_url_https' => $uinfo[0]['micro'],
717 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
718 'profile_image_url_large' => $uinfo[0]["photo"],
719 'url' => $uinfo[0]['url'],
720 'protected' => false,
721 'followers_count' => intval($countfollowers),
722 'friends_count' => intval($countfriends),
724 'created_at' => api_date($uinfo[0]['created']),
725 'favourites_count' => intval($starred),
727 'time_zone' => 'UTC',
728 'geo_enabled' => false,
730 'statuses_count' => intval($countitems),
732 'contributors_enabled' => false,
733 'is_translator' => false,
734 'is_translation_enabled' => false,
735 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
736 'follow_request_sent' => false,
737 'statusnet_blocking' => false,
738 'notifications' => false,
740 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
741 'statusnet_profile_url' => $uinfo[0]['url'],
742 'uid' => intval($uinfo[0]['uid']),
743 'cid' => intval($uinfo[0]['cid']),
744 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
745 'self' => $uinfo[0]['self'],
746 'network' => $uinfo[0]['network'],
749 // If this is a local user and it uses Frio, we can get its color preferences.
751 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
752 if ($theme_info['theme'] === 'frio') {
753 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
755 if ($schema && ($schema != '---')) {
756 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
757 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
758 require_once $schemefile;
761 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
762 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
763 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
765 if (empty($nav_bg)) {
768 if (empty($link_color)) {
769 $link_color = "#6fdbe8";
771 if (empty($bgcolor)) {
772 $bgcolor = "#ededed";
775 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
776 $ret['profile_link_color'] = str_replace('#', '', $link_color);
777 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
785 * return api-formatted array for item's author and owner
788 * @param array $item item from db
789 * @return array(array:author, array:owner)
790 * @throws BadRequestException
791 * @throws ImagickException
792 * @throws InternalServerErrorException
793 * @throws UnauthorizedException
795 function api_item_get_user(App $a, $item)
797 $status_user = api_get_user($a, $item['author-id'] ?? null);
799 $author_user = $status_user;
801 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
803 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
804 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
806 $owner_user = $author_user;
809 return ([$status_user, $author_user, $owner_user]);
813 * walks recursively through an array with the possibility to change value and key
815 * @param array $array The array to walk through
816 * @param callable $callback The callback function
818 * @return array the transformed array
820 function api_walk_recursive(array &$array, callable $callback)
824 foreach ($array as $k => $v) {
826 if ($callback($v, $k)) {
827 $new_array[$k] = api_walk_recursive($v, $callback);
830 if ($callback($v, $k)) {
841 * Callback function to transform the array in an array that can be transformed in a XML file
843 * @param mixed $item Array item value
844 * @param string $key Array key
846 * @return boolean Should the array item be deleted?
848 function api_reformat_xml(&$item, &$key)
850 if (is_bool($item)) {
851 $item = ($item ? "true" : "false");
854 if (substr($key, 0, 10) == "statusnet_") {
855 $key = "statusnet:".substr($key, 10);
856 } elseif (substr($key, 0, 10) == "friendica_") {
857 $key = "friendica:".substr($key, 10);
859 /// @TODO old-lost code?
861 // $key = "default:".$key;
867 * Creates the XML from a JSON style array
869 * @param array $data JSON style array
870 * @param string $root_element Name of the root element
872 * @return string The XML data
874 function api_create_xml(array $data, $root_element)
876 $childname = key($data);
877 $data2 = array_pop($data);
879 $namespaces = ["" => "http://api.twitter.com",
880 "statusnet" => "http://status.net/schema/api/1/",
881 "friendica" => "http://friendi.ca/schema/api/1/",
882 "georss" => "http://www.georss.org/georss"];
884 /// @todo Auto detection of needed namespaces
885 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
889 if (is_array($data2)) {
891 api_walk_recursive($data2, "api_reformat_xml");
897 foreach ($data2 as $item) {
898 $data4[$i++ . ":" . $childname] = $item;
905 $data3 = [$root_element => $data2];
907 $ret = XML::fromArray($data3, $xml, false, $namespaces);
912 * Formats the data according to the data type
914 * @param string $root_element Name of the root element
915 * @param string $type Return type (atom, rss, xml, json)
916 * @param array $data JSON style array
918 * @return array|string (string|array) XML data or JSON data
920 function api_format_data($root_element, $type, $data)
926 $ret = api_create_xml($data, $root_element);
941 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
942 * returns a 401 status code and an error message if not.
944 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
946 * @param string $type Return type (atom, rss, xml, json)
947 * @return array|string
948 * @throws BadRequestException
949 * @throws ForbiddenException
950 * @throws ImagickException
951 * @throws InternalServerErrorException
952 * @throws UnauthorizedException
954 function api_account_verify_credentials($type)
958 if (api_user() === false) {
959 throw new ForbiddenException();
962 unset($_REQUEST["user_id"]);
963 unset($_GET["user_id"]);
965 unset($_REQUEST["screen_name"]);
966 unset($_GET["screen_name"]);
968 $skip_status = $_REQUEST['skip_status'] ?? false;
970 $user_info = api_get_user($a);
972 // "verified" isn't used here in the standard
973 unset($user_info["verified"]);
975 // - Adding last status
977 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
979 $user_info['status'] = api_format_item($item, $type);
983 // "uid" and "self" are only needed for some internal stuff, so remove it from here
984 unset($user_info["uid"]);
985 unset($user_info["self"]);
987 return api_format_data("user", $type, ['user' => $user_info]);
990 /// @TODO move to top of file or somewhere better
991 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
994 * Get data from $_POST or $_GET
999 function requestdata($k)
1001 if (!empty($_POST[$k])) {
1004 if (!empty($_GET[$k])) {
1011 * Deprecated function to upload media.
1013 * @param string $type Return type (atom, rss, xml, json)
1015 * @return array|string
1016 * @throws BadRequestException
1017 * @throws ForbiddenException
1018 * @throws ImagickException
1019 * @throws InternalServerErrorException
1020 * @throws UnauthorizedException
1022 function api_statuses_mediap($type)
1026 if (api_user() === false) {
1027 Logger::log('api_statuses_update: no user');
1028 throw new ForbiddenException();
1030 $user_info = api_get_user($a);
1032 $_REQUEST['profile_uid'] = api_user();
1033 $_REQUEST['api_source'] = true;
1034 $txt = requestdata('status') ?? '';
1035 /// @TODO old-lost code?
1036 //$txt = urldecode(requestdata('status'));
1038 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1039 $txt = HTML::toBBCodeVideo($txt);
1040 $config = HTMLPurifier_Config::createDefault();
1041 $config->set('Cache.DefinitionImpl', null);
1042 $purifier = new HTMLPurifier($config);
1043 $txt = $purifier->purify($txt);
1045 $txt = HTML::toBBCode($txt);
1047 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1049 $picture = wall_upload_post($a, false);
1051 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1052 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1053 $item_id = item_post($a);
1055 // output the post that we just posted.
1056 return api_status_show($type, $item_id);
1059 /// @TODO move this to top of file or somewhere better!
1060 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1063 * Updates the user’s current status.
1065 * @param string $type Return type (atom, rss, xml, json)
1067 * @return array|string
1068 * @throws BadRequestException
1069 * @throws ForbiddenException
1070 * @throws ImagickException
1071 * @throws InternalServerErrorException
1072 * @throws TooManyRequestsException
1073 * @throws UnauthorizedException
1074 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1076 function api_statuses_update($type)
1080 if (api_user() === false) {
1081 Logger::log('api_statuses_update: no user');
1082 throw new ForbiddenException();
1087 // convert $_POST array items to the form we use for web posts.
1088 if (requestdata('htmlstatus')) {
1089 $txt = requestdata('htmlstatus') ?? '';
1090 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1091 $txt = HTML::toBBCodeVideo($txt);
1093 $config = HTMLPurifier_Config::createDefault();
1094 $config->set('Cache.DefinitionImpl', null);
1096 $purifier = new HTMLPurifier($config);
1097 $txt = $purifier->purify($txt);
1099 $_REQUEST['body'] = HTML::toBBCode($txt);
1102 $_REQUEST['body'] = requestdata('status');
1105 $_REQUEST['title'] = requestdata('title');
1107 $parent = requestdata('in_reply_to_status_id');
1109 // Twidere sends "-1" if it is no reply ...
1110 if ($parent == -1) {
1114 if (ctype_digit($parent)) {
1115 $_REQUEST['parent'] = $parent;
1117 $_REQUEST['parent_uri'] = $parent;
1120 if (requestdata('lat') && requestdata('long')) {
1121 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1123 $_REQUEST['profile_uid'] = api_user();
1126 // Check for throttling (maximum posts per day, week and month)
1127 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1128 if ($throttle_day > 0) {
1129 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1131 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1132 $posts_day = Post::count($condition);
1134 if ($posts_day > $throttle_day) {
1135 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1136 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1137 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));
1141 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1142 if ($throttle_week > 0) {
1143 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1145 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1146 $posts_week = Post::count($condition);
1148 if ($posts_week > $throttle_week) {
1149 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1150 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1151 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));
1155 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1156 if ($throttle_month > 0) {
1157 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1159 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1160 $posts_month = Post::count($condition);
1162 if ($posts_month > $throttle_month) {
1163 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1164 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1165 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));
1170 if (requestdata('media_ids')) {
1171 $ids = explode(',', requestdata('media_ids') ?? '');
1172 } elseif (!empty($_FILES['media'])) {
1173 // upload the image if we have one
1174 $picture = wall_upload_post($a, false);
1175 if (is_array($picture)) {
1176 $ids[] = $picture['id'];
1184 foreach ($ids as $id) {
1185 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1186 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1187 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1188 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1190 if (!empty($media)) {
1191 $ressources[] = $media[0]['resource-id'];
1192 $phototypes = Images::supportedTypes();
1193 $ext = $phototypes[$media[0]['type']];
1195 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1196 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1197 'size' => $media[0]['datasize'],
1198 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1199 'description' => $media[0]['desc'] ?? '',
1200 'width' => $media[0]['width'],
1201 'height' => $media[0]['height']];
1203 if (count($media) > 1) {
1204 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1205 $attachment['preview-width'] = $media[1]['width'];
1206 $attachment['preview-height'] = $media[1]['height'];
1208 $attachments[] = $attachment;
1212 // We have to avoid that the post is rejected because of an empty body
1213 if (empty($_REQUEST['body'])) {
1214 $_REQUEST['body'] = '[hr]';
1218 if (!empty($attachments)) {
1219 $_REQUEST['attachments'] = $attachments;
1222 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1224 $_REQUEST['api_source'] = true;
1226 if (empty($_REQUEST['source'])) {
1227 $_REQUEST["source"] = api_source();
1230 // call out normal post function
1231 $item_id = item_post($a);
1233 if (!empty($ressources) && !empty($item_id)) {
1234 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1235 foreach ($ressources as $ressource) {
1236 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1240 // output the post that we just posted.
1241 return api_status_show($type, $item_id);
1244 /// @TODO move to top of file or somewhere better
1245 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1246 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1249 * Uploads an image to Friendica.
1252 * @throws BadRequestException
1253 * @throws ForbiddenException
1254 * @throws ImagickException
1255 * @throws InternalServerErrorException
1256 * @throws UnauthorizedException
1257 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1259 function api_media_upload()
1263 if (api_user() === false) {
1264 Logger::log('no user');
1265 throw new ForbiddenException();
1270 if (empty($_FILES['media'])) {
1272 throw new BadRequestException("No media.");
1275 $media = wall_upload_post($a, false);
1278 throw new InternalServerErrorException();
1282 $returndata["media_id"] = $media["id"];
1283 $returndata["media_id_string"] = (string)$media["id"];
1284 $returndata["size"] = $media["size"];
1285 $returndata["image"] = ["w" => $media["width"],
1286 "h" => $media["height"],
1287 "image_type" => $media["type"],
1288 "friendica_preview_url" => $media["preview"]];
1290 Logger::info('Media uploaded', ['return' => $returndata]);
1292 return ["media" => $returndata];
1295 /// @TODO move to top of file or somewhere better
1296 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1299 * Updates media meta data (picture descriptions)
1301 * @param string $type Return type (atom, rss, xml, json)
1303 * @return array|string
1304 * @throws BadRequestException
1305 * @throws ForbiddenException
1306 * @throws ImagickException
1307 * @throws InternalServerErrorException
1308 * @throws TooManyRequestsException
1309 * @throws UnauthorizedException
1310 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1312 * @todo Compare the corresponding Twitter function for correct return values
1314 function api_media_metadata_create($type)
1318 if (api_user() === false) {
1319 Logger::info('no user');
1320 throw new ForbiddenException();
1325 $postdata = Network::postdata();
1327 if (empty($postdata)) {
1328 throw new BadRequestException("No post data");
1331 $data = json_decode($postdata, true);
1333 throw new BadRequestException("Invalid post data");
1336 if (empty($data['media_id']) || empty($data['alt_text'])) {
1337 throw new BadRequestException("Missing post data values");
1340 if (empty($data['alt_text']['text'])) {
1341 throw new BadRequestException("No alt text.");
1344 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1346 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1347 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1348 if (!DBA::isResult($photo)) {
1349 throw new BadRequestException("Metadata not found.");
1352 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1355 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1358 * @param string $type Return format (atom, rss, xml, json)
1359 * @param int $item_id
1360 * @return array|string
1363 function api_status_show($type, $item_id)
1365 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1369 $item = api_get_item(['id' => $item_id]);
1370 if (!empty($item)) {
1371 $status_info = api_format_item($item, $type);
1374 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1376 return api_format_data('statuses', $type, ['status' => $status_info]);
1380 * Retrieves the last public status of the provided user info
1382 * @param int $ownerId Public contact Id
1383 * @param int $uid User Id
1387 function api_get_last_status($ownerId, $uid)
1390 'author-id'=> $ownerId,
1392 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1393 'private' => [Item::PUBLIC, Item::UNLISTED]
1396 $item = api_get_item($condition);
1402 * Retrieves a single item record based on the provided condition and converts it for API use.
1404 * @param array $condition Item table condition array
1408 function api_get_item(array $condition)
1410 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1416 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1417 * The author's most recent status will be returned inline.
1419 * @param string $type Return type (atom, rss, xml, json)
1420 * @return array|string
1421 * @throws BadRequestException
1422 * @throws ImagickException
1423 * @throws InternalServerErrorException
1424 * @throws UnauthorizedException
1425 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1427 function api_users_show($type)
1429 $a = Friendica\DI::app();
1431 $user_info = api_get_user($a);
1433 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1434 if (!empty($item)) {
1435 $user_info['status'] = api_format_item($item, $type);
1438 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1439 unset($user_info['uid']);
1440 unset($user_info['self']);
1442 return api_format_data('user', $type, ['user' => $user_info]);
1445 /// @TODO move to top of file or somewhere better
1446 api_register_func('api/users/show', 'api_users_show');
1447 api_register_func('api/externalprofile/show', 'api_users_show');
1450 * Search a public user account.
1452 * @param string $type Return type (atom, rss, xml, json)
1454 * @return array|string
1455 * @throws BadRequestException
1456 * @throws ImagickException
1457 * @throws InternalServerErrorException
1458 * @throws UnauthorizedException
1459 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1461 function api_users_search($type)
1467 if (!empty($_GET['q'])) {
1468 $contacts = Contact::selectToArray(
1471 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1479 if (DBA::isResult($contacts)) {
1481 foreach ($contacts as $contact) {
1482 $user_info = api_get_user($a, $contact['id']);
1484 if ($type == 'xml') {
1485 $userlist[$k++ . ':user'] = $user_info;
1487 $userlist[] = $user_info;
1490 $userlist = ['users' => $userlist];
1492 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1495 throw new BadRequestException('No search term specified.');
1498 return api_format_data('users', $type, $userlist);
1501 /// @TODO move to top of file or somewhere better
1502 api_register_func('api/users/search', 'api_users_search');
1505 * Return user objects
1507 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1509 * @param string $type Return format: json or xml
1511 * @return array|string
1512 * @throws BadRequestException
1513 * @throws ImagickException
1514 * @throws InternalServerErrorException
1515 * @throws NotFoundException if the results are empty.
1516 * @throws UnauthorizedException
1518 function api_users_lookup($type)
1522 if (!empty($_REQUEST['user_id'])) {
1523 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1525 $users[] = api_get_user(DI::app(), $id);
1530 if (empty($users)) {
1531 throw new NotFoundException;
1534 return api_format_data("users", $type, ['users' => $users]);
1537 /// @TODO move to top of file or somewhere better
1538 api_register_func('api/users/lookup', 'api_users_lookup', true);
1541 * Returns statuses that match a specified query.
1543 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1545 * @param string $type Return format: json, xml, atom, rss
1547 * @return array|string
1548 * @throws BadRequestException if the "q" parameter is missing.
1549 * @throws ForbiddenException
1550 * @throws ImagickException
1551 * @throws InternalServerErrorException
1552 * @throws UnauthorizedException
1554 function api_search($type)
1557 $user_info = api_get_user($a);
1559 if (api_user() === false || $user_info === false) {
1560 throw new ForbiddenException();
1563 if (empty($_REQUEST['q'])) {
1564 throw new BadRequestException('q parameter is required.');
1567 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1570 $data['status'] = [];
1572 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1573 if (!empty($_REQUEST['rpp'])) {
1574 $count = $_REQUEST['rpp'];
1575 } elseif (!empty($_REQUEST['count'])) {
1576 $count = $_REQUEST['count'];
1579 $since_id = $_REQUEST['since_id'] ?? 0;
1580 $max_id = $_REQUEST['max_id'] ?? 0;
1581 $page = $_REQUEST['page'] ?? 1;
1583 $start = max(0, ($page - 1) * $count);
1585 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1586 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1587 $searchTerm = $matches[1];
1588 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1589 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1591 while ($tag = DBA::fetch($tags)) {
1592 $uriids[] = $tag['uri-id'];
1596 if (empty($uriids)) {
1597 return api_format_data('statuses', $type, $data);
1600 $condition = ['uri-id' => $uriids];
1601 if ($exclude_replies) {
1602 $condition['gravity'] = GRAVITY_PARENT;
1605 $params['group_by'] = ['uri-id'];
1607 $condition = ["`id` > ?
1608 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1609 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1610 AND `body` LIKE CONCAT('%',?,'%')",
1611 $since_id, api_user(), $_REQUEST['q']];
1613 $condition[0] .= ' AND `id` <= ?';
1614 $condition[] = $max_id;
1620 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1621 $id = Item::fetchByLink($searchTerm, api_user());
1624 $id = Item::fetchByLink($searchTerm);
1628 $statuses = Post::select([], ['id' => $id]);
1632 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1634 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1636 bindComments($data['status']);
1638 return api_format_data('statuses', $type, $data);
1641 /// @TODO move to top of file or somewhere better
1642 api_register_func('api/search/tweets', 'api_search', true);
1643 api_register_func('api/search', 'api_search', true);
1646 * Returns the most recent statuses posted by the user and the users they follow.
1648 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1650 * @param string $type Return type (atom, rss, xml, json)
1652 * @return array|string
1653 * @throws BadRequestException
1654 * @throws ForbiddenException
1655 * @throws ImagickException
1656 * @throws InternalServerErrorException
1657 * @throws UnauthorizedException
1658 * @todo Optional parameters
1659 * @todo Add reply info
1661 function api_statuses_home_timeline($type)
1664 $user_info = api_get_user($a);
1666 if (api_user() === false || $user_info === false) {
1667 throw new ForbiddenException();
1670 unset($_REQUEST["user_id"]);
1671 unset($_GET["user_id"]);
1673 unset($_REQUEST["screen_name"]);
1674 unset($_GET["screen_name"]);
1676 // get last network messages
1679 $count = $_REQUEST['count'] ?? 20;
1680 $page = $_REQUEST['page']?? 0;
1681 $since_id = $_REQUEST['since_id'] ?? 0;
1682 $max_id = $_REQUEST['max_id'] ?? 0;
1683 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1684 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1686 $start = max(0, ($page - 1) * $count);
1688 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1689 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1692 $condition[0] .= " AND `id` <= ?";
1693 $condition[] = $max_id;
1695 if ($exclude_replies) {
1696 $condition[0] .= ' AND `gravity` = ?';
1697 $condition[] = GRAVITY_PARENT;
1699 if ($conversation_id > 0) {
1700 $condition[0] .= " AND `parent` = ?";
1701 $condition[] = $conversation_id;
1704 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1705 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1707 $items = Post::toArray($statuses);
1709 $ret = api_format_items($items, $user_info, false, $type);
1711 // Set all posts from the query above to seen
1713 foreach ($items as $item) {
1714 $idarray[] = intval($item["id"]);
1717 if (!empty($idarray)) {
1718 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1720 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1726 $data = ['status' => $ret];
1731 $data = api_rss_extra($a, $data, $user_info);
1735 return api_format_data("statuses", $type, $data);
1739 /// @TODO move to top of file or somewhere better
1740 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1741 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1744 * Returns the most recent statuses from public users.
1746 * @param string $type Return type (atom, rss, xml, json)
1748 * @return array|string
1749 * @throws BadRequestException
1750 * @throws ForbiddenException
1751 * @throws ImagickException
1752 * @throws InternalServerErrorException
1753 * @throws UnauthorizedException
1755 function api_statuses_public_timeline($type)
1758 $user_info = api_get_user($a);
1760 if (api_user() === false || $user_info === false) {
1761 throw new ForbiddenException();
1764 // get last network messages
1767 $count = $_REQUEST['count'] ?? 20;
1768 $page = $_REQUEST['page'] ?? 1;
1769 $since_id = $_REQUEST['since_id'] ?? 0;
1770 $max_id = $_REQUEST['max_id'] ?? 0;
1771 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1772 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1774 $start = max(0, ($page - 1) * $count);
1776 if ($exclude_replies && !$conversation_id) {
1777 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1778 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1781 $condition[0] .= " AND `id` <= ?";
1782 $condition[] = $max_id;
1785 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1786 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1788 $r = Post::toArray($statuses);
1790 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1791 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1794 $condition[0] .= " AND `id` <= ?";
1795 $condition[] = $max_id;
1797 if ($conversation_id > 0) {
1798 $condition[0] .= " AND `parent` = ?";
1799 $condition[] = $conversation_id;
1802 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1803 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1805 $r = Post::toArray($statuses);
1808 $ret = api_format_items($r, $user_info, false, $type);
1812 $data = ['status' => $ret];
1817 $data = api_rss_extra($a, $data, $user_info);
1821 return api_format_data("statuses", $type, $data);
1824 /// @TODO move to top of file or somewhere better
1825 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1828 * Returns the most recent statuses posted by users this node knows about.
1830 * @param string $type Return format: json, xml, atom, rss
1831 * @return array|string
1832 * @throws BadRequestException
1833 * @throws ForbiddenException
1834 * @throws ImagickException
1835 * @throws InternalServerErrorException
1836 * @throws UnauthorizedException
1838 function api_statuses_networkpublic_timeline($type)
1841 $user_info = api_get_user($a);
1843 if (api_user() === false || $user_info === false) {
1844 throw new ForbiddenException();
1847 $since_id = $_REQUEST['since_id'] ?? 0;
1848 $max_id = $_REQUEST['max_id'] ?? 0;
1851 $count = $_REQUEST['count'] ?? 20;
1852 $page = $_REQUEST['page'] ?? 1;
1854 $start = max(0, ($page - 1) * $count);
1856 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1857 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1860 $condition[0] .= " AND `id` <= ?";
1861 $condition[] = $max_id;
1864 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1865 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1867 $ret = api_format_items($statuses, $user_info, false, $type);
1871 $data = ['status' => $ret];
1876 $data = api_rss_extra($a, $data, $user_info);
1880 return api_format_data("statuses", $type, $data);
1883 /// @TODO move to top of file or somewhere better
1884 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1887 * Returns a single status.
1889 * @param string $type Return type (atom, rss, xml, json)
1891 * @return array|string
1892 * @throws BadRequestException
1893 * @throws ForbiddenException
1894 * @throws ImagickException
1895 * @throws InternalServerErrorException
1896 * @throws UnauthorizedException
1897 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1899 function api_statuses_show($type)
1902 $user_info = api_get_user($a);
1904 if (api_user() === false || $user_info === false) {
1905 throw new ForbiddenException();
1909 $id = intval($a->argv[3] ?? 0);
1912 $id = intval($_REQUEST['id'] ?? 0);
1917 $id = intval($a->argv[4] ?? 0);
1920 Logger::log('API: api_statuses_show: ' . $id);
1922 $conversation = !empty($_REQUEST['conversation']);
1924 // try to fetch the item for the local user - or the public item, if there is no local one
1925 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1926 if (!DBA::isResult($uri_item)) {
1927 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1930 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1931 if (!DBA::isResult($item)) {
1932 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1937 if ($conversation) {
1938 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1939 $params = ['order' => ['id' => true]];
1941 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1945 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1947 /// @TODO How about copying this to above methods which don't check $r ?
1948 if (!DBA::isResult($statuses)) {
1949 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1952 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1954 if ($conversation) {
1955 $data = ['status' => $ret];
1956 return api_format_data("statuses", $type, $data);
1958 $data = ['status' => $ret[0]];
1959 return api_format_data("status", $type, $data);
1963 /// @TODO move to top of file or somewhere better
1964 api_register_func('api/statuses/show', 'api_statuses_show', true);
1968 * @param string $type Return type (atom, rss, xml, json)
1970 * @return array|string
1971 * @throws BadRequestException
1972 * @throws ForbiddenException
1973 * @throws ImagickException
1974 * @throws InternalServerErrorException
1975 * @throws UnauthorizedException
1976 * @todo nothing to say?
1978 function api_conversation_show($type)
1981 $user_info = api_get_user($a);
1983 if (api_user() === false || $user_info === false) {
1984 throw new ForbiddenException();
1988 $id = intval($a->argv[3] ?? 0);
1989 $since_id = intval($_REQUEST['since_id'] ?? 0);
1990 $max_id = intval($_REQUEST['max_id'] ?? 0);
1991 $count = intval($_REQUEST['count'] ?? 20);
1992 $page = intval($_REQUEST['page'] ?? 1);
1994 $start = max(0, ($page - 1) * $count);
1997 $id = intval($_REQUEST['id'] ?? 0);
2002 $id = intval($a->argv[4] ?? 0);
2005 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2007 // try to fetch the item for the local user - or the public item, if there is no local one
2008 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
2009 if (!DBA::isResult($item)) {
2010 throw new BadRequestException("There is no status with this id.");
2013 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2014 if (!DBA::isResult($parent)) {
2015 throw new BadRequestException("There is no status with this id.");
2018 $id = $parent['id'];
2020 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2021 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2024 $condition[0] .= " AND `id` <= ?";
2025 $condition[] = $max_id;
2028 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2029 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2031 if (!DBA::isResult($statuses)) {
2032 throw new BadRequestException("There is no status with id $id.");
2035 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2037 $data = ['status' => $ret];
2038 return api_format_data("statuses", $type, $data);
2041 /// @TODO move to top of file or somewhere better
2042 api_register_func('api/conversation/show', 'api_conversation_show', true);
2043 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2048 * @param string $type Return type (atom, rss, xml, json)
2050 * @return array|string
2051 * @throws BadRequestException
2052 * @throws ForbiddenException
2053 * @throws ImagickException
2054 * @throws InternalServerErrorException
2055 * @throws UnauthorizedException
2056 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2058 function api_statuses_repeat($type)
2064 if (api_user() === false) {
2065 throw new ForbiddenException();
2071 $id = intval($a->argv[3] ?? 0);
2074 $id = intval($_REQUEST['id'] ?? 0);
2079 $id = intval($a->argv[4] ?? 0);
2082 Logger::log('API: api_statuses_repeat: '.$id);
2084 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2085 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2087 if (DBA::isResult($item) && !empty($item['body'])) {
2088 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2089 if (!Item::performActivity($id, 'announce', local_user())) {
2090 throw new InternalServerErrorException();
2095 if (strpos($item['body'], "[/share]") !== false) {
2096 $pos = strpos($item['body'], "[share");
2097 $post = substr($item['body'], $pos);
2099 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2101 if (!empty($item['title'])) {
2102 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2105 $post .= $item['body'];
2106 $post .= "[/share]";
2108 $_REQUEST['body'] = $post;
2109 $_REQUEST['profile_uid'] = api_user();
2110 $_REQUEST['api_source'] = true;
2112 if (empty($_REQUEST['source'])) {
2113 $_REQUEST["source"] = api_source();
2116 $item_id = item_post($a);
2119 throw new ForbiddenException();
2122 // output the post that we just posted.
2124 return api_status_show($type, $item_id);
2127 /// @TODO move to top of file or somewhere better
2128 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2131 * Destroys a specific status.
2133 * @param string $type Return type (atom, rss, xml, json)
2135 * @return array|string
2136 * @throws BadRequestException
2137 * @throws ForbiddenException
2138 * @throws ImagickException
2139 * @throws InternalServerErrorException
2140 * @throws UnauthorizedException
2141 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2143 function api_statuses_destroy($type)
2147 if (api_user() === false) {
2148 throw new ForbiddenException();
2154 $id = intval($a->argv[3] ?? 0);
2157 $id = intval($_REQUEST['id'] ?? 0);
2162 $id = intval($a->argv[4] ?? 0);
2165 Logger::log('API: api_statuses_destroy: '.$id);
2167 $ret = api_statuses_show($type);
2169 Item::deleteForUser(['id' => $id], api_user());
2174 /// @TODO move to top of file or somewhere better
2175 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2178 * Returns the most recent mentions.
2180 * @param string $type Return type (atom, rss, xml, json)
2182 * @return array|string
2183 * @throws BadRequestException
2184 * @throws ForbiddenException
2185 * @throws ImagickException
2186 * @throws InternalServerErrorException
2187 * @throws UnauthorizedException
2188 * @see http://developer.twitter.com/doc/get/statuses/mentions
2190 function api_statuses_mentions($type)
2193 $user_info = api_get_user($a);
2195 if (api_user() === false || $user_info === false) {
2196 throw new ForbiddenException();
2199 unset($_REQUEST["user_id"]);
2200 unset($_GET["user_id"]);
2202 unset($_REQUEST["screen_name"]);
2203 unset($_GET["screen_name"]);
2205 // get last network messages
2208 $since_id = intval($_REQUEST['since_id'] ?? 0);
2209 $max_id = intval($_REQUEST['max_id'] ?? 0);
2210 $count = intval($_REQUEST['count'] ?? 20);
2211 $page = intval($_REQUEST['page'] ?? 1);
2213 $start = max(0, ($page - 1) * $count);
2215 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2216 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2217 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2219 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2220 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2221 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2222 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2223 api_user(), $since_id];
2226 $query .= " AND `id` <= ?";
2227 $condition[] = $max_id;
2230 array_unshift($condition, $query);
2232 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2233 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2235 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2237 $data = ['status' => $ret];
2242 $data = api_rss_extra($a, $data, $user_info);
2246 return api_format_data("statuses", $type, $data);
2249 /// @TODO move to top of file or somewhere better
2250 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2251 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2254 * Returns the most recent statuses posted by the user.
2256 * @param string $type Either "json" or "xml"
2257 * @return string|array
2258 * @throws BadRequestException
2259 * @throws ForbiddenException
2260 * @throws ImagickException
2261 * @throws InternalServerErrorException
2262 * @throws UnauthorizedException
2263 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2265 function api_statuses_user_timeline($type)
2268 $user_info = api_get_user($a);
2270 if (api_user() === false || $user_info === false) {
2271 throw new ForbiddenException();
2274 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2276 $since_id = $_REQUEST['since_id'] ?? 0;
2277 $max_id = $_REQUEST['max_id'] ?? 0;
2278 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2279 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2282 $count = $_REQUEST['count'] ?? 20;
2283 $page = $_REQUEST['page'] ?? 1;
2285 $start = max(0, ($page - 1) * $count);
2287 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2288 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2290 if ($user_info['self'] == 1) {
2291 $condition[0] .= ' AND `wall` ';
2294 if ($exclude_replies) {
2295 $condition[0] .= ' AND `gravity` = ?';
2296 $condition[] = GRAVITY_PARENT;
2299 if ($conversation_id > 0) {
2300 $condition[0] .= " AND `parent` = ?";
2301 $condition[] = $conversation_id;
2305 $condition[0] .= " AND `id` <= ?";
2306 $condition[] = $max_id;
2308 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2309 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2311 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2315 $data = ['status' => $ret];
2320 $data = api_rss_extra($a, $data, $user_info);
2324 return api_format_data("statuses", $type, $data);
2327 /// @TODO move to top of file or somewhere better
2328 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2331 * Star/unstar an item.
2332 * param: id : id of the item
2334 * @param string $type Return type (atom, rss, xml, json)
2336 * @return array|string
2337 * @throws BadRequestException
2338 * @throws ForbiddenException
2339 * @throws ImagickException
2340 * @throws InternalServerErrorException
2341 * @throws UnauthorizedException
2342 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2344 function api_favorites_create_destroy($type)
2348 if (api_user() === false) {
2349 throw new ForbiddenException();
2352 // for versioned api.
2353 /// @TODO We need a better global soluton
2354 $action_argv_id = 2;
2355 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2356 $action_argv_id = 3;
2359 if ($a->argc <= $action_argv_id) {
2360 throw new BadRequestException("Invalid request.");
2362 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2363 if ($a->argc == $action_argv_id + 2) {
2364 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2366 $itemid = intval($_REQUEST['id'] ?? 0);
2369 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2371 if (!DBA::isResult($item)) {
2372 throw new BadRequestException("Invalid item.");
2377 $item['starred'] = 1;
2380 $item['starred'] = 0;
2383 throw new BadRequestException("Invalid action ".$action);
2386 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2389 throw new InternalServerErrorException("DB error");
2393 $user_info = api_get_user($a);
2394 $rets = api_format_items([$item], $user_info, false, $type);
2397 $data = ['status' => $ret];
2402 $data = api_rss_extra($a, $data, $user_info);
2406 return api_format_data("status", $type, $data);
2409 /// @TODO move to top of file or somewhere better
2410 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2411 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2414 * Returns the most recent favorite statuses.
2416 * @param string $type Return type (atom, rss, xml, json)
2418 * @return string|array
2419 * @throws BadRequestException
2420 * @throws ForbiddenException
2421 * @throws ImagickException
2422 * @throws InternalServerErrorException
2423 * @throws UnauthorizedException
2425 function api_favorites($type)
2430 $user_info = api_get_user($a);
2432 if (api_user() === false || $user_info === false) {
2433 throw new ForbiddenException();
2438 // in friendica starred item are private
2439 // return favorites only for self
2440 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2442 if ($user_info['self'] == 0) {
2446 $since_id = $_REQUEST['since_id'] ?? 0;
2447 $max_id = $_REQUEST['max_id'] ?? 0;
2448 $count = $_GET['count'] ?? 20;
2449 $page = $_REQUEST['page'] ?? 1;
2451 $start = max(0, ($page - 1) * $count);
2453 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2454 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2456 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2459 $condition[0] .= " AND `id` <= ?";
2460 $condition[] = $max_id;
2463 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2465 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2470 $data = ['status' => $ret];
2475 $data = api_rss_extra($a, $data, $user_info);
2479 return api_format_data("statuses", $type, $data);
2482 /// @TODO move to top of file or somewhere better
2483 api_register_func('api/favorites', 'api_favorites', true);
2487 * @param array $item
2488 * @param array $recipient
2489 * @param array $sender
2492 * @throws InternalServerErrorException
2494 function api_format_messages($item, $recipient, $sender)
2496 // standard meta information
2498 'id' => $item['id'],
2499 'sender_id' => $sender['id'],
2501 'recipient_id' => $recipient['id'],
2502 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2503 'sender_screen_name' => $sender['screen_name'],
2504 'recipient_screen_name' => $recipient['screen_name'],
2505 'sender' => $sender,
2506 'recipient' => $recipient,
2508 'friendica_seen' => $item['seen'] ?? 0,
2509 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2512 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2513 if (isset($ret['sender']['uid'])) {
2514 unset($ret['sender']['uid']);
2516 if (isset($ret['sender']['self'])) {
2517 unset($ret['sender']['self']);
2519 if (isset($ret['recipient']['uid'])) {
2520 unset($ret['recipient']['uid']);
2522 if (isset($ret['recipient']['self'])) {
2523 unset($ret['recipient']['self']);
2526 //don't send title to regular StatusNET requests to avoid confusing these apps
2527 if (!empty($_GET['getText'])) {
2528 $ret['title'] = $item['title'];
2529 if ($_GET['getText'] == 'html') {
2530 $ret['text'] = BBCode::convert($item['body'], false);
2531 } elseif ($_GET['getText'] == 'plain') {
2532 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2535 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2537 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2538 unset($ret['sender']);
2539 unset($ret['recipient']);
2547 * @param array $item
2550 * @throws InternalServerErrorException
2552 function api_convert_item($item)
2554 $body = api_add_attachments_to_body($item);
2556 $entities = api_get_entitities($statustext, $body);
2558 // Add pictures to the attachment array and remove them from the body
2559 $attachments = api_get_attachments($body);
2561 // Workaround for ostatus messages where the title is identically to the body
2562 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2563 $statusbody = trim(HTML::toPlaintext($html, 0));
2565 // handle data: images
2566 $statusbody = api_format_items_embeded_images($item, $statusbody);
2568 $statustitle = trim($item['title']);
2570 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2571 $statustext = trim($statusbody);
2573 $statustext = trim($statustitle."\n\n".$statusbody);
2576 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2577 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2580 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2582 // Workaround for clients with limited HTML parser functionality
2583 $search = ["<br>", "<blockquote>", "</blockquote>",
2584 "<h1>", "</h1>", "<h2>", "</h2>",
2585 "<h3>", "</h3>", "<h4>", "</h4>",
2586 "<h5>", "</h5>", "<h6>", "</h6>"];
2587 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2588 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2589 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2590 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2591 $statushtml = str_replace($search, $replace, $statushtml);
2593 if ($item['title'] != "") {
2594 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2598 $oldtext = $statushtml;
2599 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2600 } while ($oldtext != $statushtml);
2602 if (substr($statushtml, 0, 4) == '<br>') {
2603 $statushtml = substr($statushtml, 4);
2606 if (substr($statushtml, 0, -4) == '<br>') {
2607 $statushtml = substr($statushtml, -4);
2610 // feeds without body should contain the link
2611 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2612 $statushtml .= BBCode::convert($item['plink']);
2616 "text" => $statustext,
2617 "html" => $statushtml,
2618 "attachments" => $attachments,
2619 "entities" => $entities
2624 * Add media attachments to the body
2626 * @param array $item
2627 * @return string body with added media
2629 function api_add_attachments_to_body(array $item)
2631 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2633 if (strpos($body, '[/img]') !== false) {
2637 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2638 if (!empty($media['preview'])) {
2639 $description = $media['description'] ?: $media['name'];
2640 if (!empty($description)) {
2641 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2643 $body .= "\n[img]" . $media['preview'] .'[/img]';
2653 * @param string $body
2656 * @throws InternalServerErrorException
2658 function api_get_attachments(&$body)
2660 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2661 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2663 $URLSearchString = "^\[\]";
2664 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2668 // Remove all embedded pictures, since they are added as attachments
2669 foreach ($images[0] as $orig) {
2670 $body = str_replace($orig, '', $body);
2675 foreach ($images[1] as $image) {
2676 $imagedata = Images::getInfoFromURLCached($image);
2679 if (DI::config()->get("system", "proxy_disabled")) {
2680 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2682 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2687 return $attachments;
2692 * @param string $text
2693 * @param string $bbcode
2696 * @throws InternalServerErrorException
2697 * @todo Links at the first character of the post
2699 function api_get_entitities(&$text, $bbcode)
2701 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2703 if ($include_entities != "true") {
2704 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2706 foreach ($images[1] as $image) {
2707 $replace = ProxyUtils::proxifyUrl($image, false);
2708 $text = str_replace($image, $replace, $text);
2713 $bbcode = BBCode::cleanPictureLinks($bbcode);
2715 // Change pure links in text to bbcode uris
2716 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2719 $entities["hashtags"] = [];
2720 $entities["symbols"] = [];
2721 $entities["urls"] = [];
2722 $entities["user_mentions"] = [];
2724 $URLSearchString = "^\[\]";
2726 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2728 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2729 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2731 $bbcode = preg_replace(
2732 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2733 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2736 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2738 $bbcode = preg_replace(
2739 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2740 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2743 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2745 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2747 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2750 foreach ($urls[1] as $id => $url) {
2751 $start = iconv_strpos($text, $url, 0, "UTF-8");
2752 if (!($start === false)) {
2753 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2757 ksort($ordered_urls);
2761 foreach ($ordered_urls as $url) {
2762 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2763 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2765 $display_url = $url["title"];
2767 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2768 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2770 if (strlen($display_url) > 26) {
2771 $display_url = substr($display_url, 0, 25)."…";
2775 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2776 if (!($start === false)) {
2777 $entities["urls"][] = ["url" => $url["url"],
2778 "expanded_url" => $url["url"],
2779 "display_url" => $display_url,
2780 "indices" => [$start, $start+strlen($url["url"])]];
2781 $offset = $start + 1;
2785 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2786 $ordered_images = [];
2787 foreach ($images as $image) {
2788 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2789 if (!($start === false)) {
2790 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2794 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2795 foreach ($images[1] as $image) {
2796 $start = iconv_strpos($text, $image, 0, "UTF-8");
2797 if (!($start === false)) {
2798 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2804 foreach ($ordered_images as $image) {
2805 $url = $image['url'];
2806 $ext_alt_text = $image['alt'];
2808 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2809 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2811 if (strlen($display_url) > 26) {
2812 $display_url = substr($display_url, 0, 25)."…";
2815 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2816 if (!($start === false)) {
2817 $image = Images::getInfoFromURLCached($url);
2819 // If image cache is activated, then use the following sizes:
2820 // thumb (150), small (340), medium (600) and large (1024)
2821 if (!DI::config()->get("system", "proxy_disabled")) {
2822 $media_url = ProxyUtils::proxifyUrl($url, false);
2825 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2826 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2828 if (($image[0] > 150) || ($image[1] > 150)) {
2829 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2830 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2833 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2834 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2836 if (($image[0] > 600) || ($image[1] > 600)) {
2837 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2838 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2842 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2845 $entities["media"][] = [
2847 "id_str" => (string) ($start + 1),
2848 "indices" => [$start, $start+strlen($url)],
2849 "media_url" => Strings::normaliseLink($media_url),
2850 "media_url_https" => $media_url,
2852 "display_url" => $display_url,
2853 "expanded_url" => $url,
2854 "ext_alt_text" => $ext_alt_text,
2858 $offset = $start + 1;
2867 * @param array $item
2868 * @param string $text
2872 function api_format_items_embeded_images($item, $text)
2874 $text = preg_replace_callback(
2875 '|data:image/([^;]+)[^=]+=*|m',
2876 function () use ($item) {
2877 return DI::baseUrl() . '/display/' . $item['guid'];
2885 * return <a href='url'>name</a> as array
2887 * @param string $txt text
2892 function api_contactlink_to_array($txt)
2895 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2896 if ($r && count($match)==3) {
2898 'name' => $match[2],
2912 * return likes, dislikes and attend status for item
2914 * @param array $item array
2915 * @param string $type Return type (atom, rss, xml, json)
2918 * likes => int count,
2919 * dislikes => int count
2920 * @throws BadRequestException
2921 * @throws ImagickException
2922 * @throws InternalServerErrorException
2923 * @throws UnauthorizedException
2925 function api_format_items_activities($item, $type = "json")
2934 'attendmaybe' => [],
2938 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2939 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2941 while ($parent_item = Post::fetch($ret)) {
2942 // not used as result should be structured like other user data
2943 //builtin_activity_puller($i, $activities);
2945 // get user data and add it to the array of the activity
2946 $user = api_get_user($a, $parent_item['author-id']);
2947 switch ($parent_item['verb']) {
2948 case Activity::LIKE:
2949 $activities['like'][] = $user;
2951 case Activity::DISLIKE:
2952 $activities['dislike'][] = $user;
2954 case Activity::ATTEND:
2955 $activities['attendyes'][] = $user;
2957 case Activity::ATTENDNO:
2958 $activities['attendno'][] = $user;
2960 case Activity::ATTENDMAYBE:
2961 $activities['attendmaybe'][] = $user;
2963 case Activity::ANNOUNCE:
2964 $activities['announce'][] = $user;
2973 if ($type == "xml") {
2974 $xml_activities = [];
2975 foreach ($activities as $k => $v) {
2976 // change xml element from "like" to "friendica:like"
2977 $xml_activities["friendica:".$k] = $v;
2978 // add user data into xml output
2980 foreach ($v as $user) {
2981 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2984 $activities = $xml_activities;
2991 * format items to be returned by api
2993 * @param array $items array of items
2994 * @param array $user_info
2995 * @param bool $filter_user filter items by $user_info
2996 * @param string $type Return type (atom, rss, xml, json)
2998 * @throws BadRequestException
2999 * @throws ImagickException
3000 * @throws InternalServerErrorException
3001 * @throws UnauthorizedException
3003 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
3005 $a = Friendica\DI::app();
3009 if (empty($items)) {
3013 foreach ((array)$items as $item) {
3014 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3016 // Look if the posts are matching if they should be filtered by user id
3017 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3021 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3030 * @param array $item Item record
3031 * @param string $type Return format (atom, rss, xml, json)
3032 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3033 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3034 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3035 * @return array API-formatted status
3036 * @throws BadRequestException
3037 * @throws ImagickException
3038 * @throws InternalServerErrorException
3039 * @throws UnauthorizedException
3041 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3043 $a = Friendica\DI::app();
3045 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3046 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3049 localize_item($item);
3051 $in_reply_to = api_in_reply_to($item);
3053 $converted = api_convert_item($item);
3055 if ($type == "xml") {
3056 $geo = "georss:point";
3062 'text' => $converted["text"],
3063 'truncated' => false,
3064 'created_at'=> api_date($item['created']),
3065 'in_reply_to_status_id' => $in_reply_to['status_id'],
3066 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3067 'source' => (($item['app']) ? $item['app'] : 'web'),
3068 'id' => intval($item['id']),
3069 'id_str' => (string) intval($item['id']),
3070 'in_reply_to_user_id' => $in_reply_to['user_id'],
3071 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3072 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3074 'favorited' => $item['starred'] ? true : false,
3075 'user' => $status_user,
3076 'friendica_author' => $author_user,
3077 'friendica_owner' => $owner_user,
3078 'friendica_private' => $item['private'] == Item::PRIVATE,
3079 //'entities' => NULL,
3080 'statusnet_html' => $converted["html"],
3081 'statusnet_conversation_id' => $item['parent'],
3082 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3083 'friendica_activities' => api_format_items_activities($item, $type),
3084 'friendica_title' => $item['title'],
3085 'friendica_html' => BBCode::convert($item['body'], false)
3088 if (count($converted["attachments"]) > 0) {
3089 $status["attachments"] = $converted["attachments"];
3092 if (count($converted["entities"]) > 0) {
3093 $status["entities"] = $converted["entities"];
3096 if ($status["source"] == 'web') {
3097 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3098 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3099 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3102 $retweeted_item = [];
3105 if ($item['gravity'] == GRAVITY_PARENT) {
3106 $body = $item['body'];
3107 $retweeted_item = api_share_as_retweet($item);
3108 if ($body != $item['body']) {
3109 $quoted_item = $retweeted_item;
3110 $retweeted_item = [];
3114 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3115 $announce = api_get_announce($item);
3116 if (!empty($announce)) {
3117 $retweeted_item = $item;
3119 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3123 if (!empty($quoted_item)) {
3124 if ($quoted_item['id'] != $item['id']) {
3125 $quoted_status = api_format_item($quoted_item);
3126 /// @todo Only remove the attachments that are also contained in the quotes status
3127 unset($status['attachments']);
3128 unset($status['entities']);
3130 $conv_quoted = api_convert_item($quoted_item);
3131 $quoted_status = $status;
3132 unset($quoted_status['attachments']);
3133 unset($quoted_status['entities']);
3134 unset($quoted_status['statusnet_conversation_id']);
3135 $quoted_status['text'] = $conv_quoted['text'];
3136 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3138 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3139 } catch (BadRequestException $e) {
3140 // user not found. should be found?
3141 /// @todo check if the user should be always found
3142 $quoted_status["user"] = [];
3145 unset($quoted_status['friendica_author']);
3146 unset($quoted_status['friendica_owner']);
3147 unset($quoted_status['friendica_activities']);
3148 unset($quoted_status['friendica_private']);
3151 if (!empty($retweeted_item)) {
3152 $retweeted_status = $status;
3153 unset($retweeted_status['friendica_author']);
3154 unset($retweeted_status['friendica_owner']);
3155 unset($retweeted_status['friendica_activities']);
3156 unset($retweeted_status['friendica_private']);
3157 unset($retweeted_status['statusnet_conversation_id']);
3158 $status['user'] = $status['friendica_owner'];
3160 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3161 } catch (BadRequestException $e) {
3162 // user not found. should be found?
3163 /// @todo check if the user should be always found
3164 $retweeted_status["user"] = [];
3167 $rt_converted = api_convert_item($retweeted_item);
3169 $retweeted_status['text'] = $rt_converted["text"];
3170 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3171 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3173 if (!empty($quoted_status)) {
3174 $retweeted_status['quoted_status'] = $quoted_status;
3177 $status['friendica_author'] = $retweeted_status['user'];
3178 $status['retweeted_status'] = $retweeted_status;
3179 } elseif (!empty($quoted_status)) {
3180 $root_status = api_convert_item($item);
3182 $status['text'] = $root_status["text"];
3183 $status['statusnet_html'] = $root_status["html"];
3184 $status['quoted_status'] = $quoted_status;
3187 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3188 unset($status["user"]["uid"]);
3189 unset($status["user"]["self"]);
3191 if ($item["coord"] != "") {
3192 $coords = explode(' ', $item["coord"]);
3193 if (count($coords) == 2) {
3194 if ($type == "json") {
3195 $status["geo"] = ['type' => 'Point',
3196 'coordinates' => [(float) $coords[0],
3197 (float) $coords[1]]];
3198 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3199 $status["georss:point"] = $item["coord"];
3208 * Returns the remaining number of API requests available to the user before the API limit is reached.
3210 * @param string $type Return type (atom, rss, xml, json)
3212 * @return array|string
3215 function api_account_rate_limit_status($type)
3217 if ($type == "xml") {
3219 'remaining-hits' => '150',
3220 '@attributes' => ["type" => "integer"],
3221 'hourly-limit' => '150',
3222 '@attributes2' => ["type" => "integer"],
3223 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3224 '@attributes3' => ["type" => "datetime"],
3225 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3226 '@attributes4' => ["type" => "integer"],
3230 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3231 'remaining_hits' => '150',
3232 'hourly_limit' => '150',
3233 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3237 return api_format_data('hash', $type, ['hash' => $hash]);
3240 /// @TODO move to top of file or somewhere better
3241 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3244 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3246 * @param string $type Return type (atom, rss, xml, json)
3248 * @return array|string
3250 function api_help_test($type)
3252 if ($type == 'xml') {
3258 return api_format_data('ok', $type, ["ok" => $ok]);
3261 /// @TODO move to top of file or somewhere better
3262 api_register_func('api/help/test', 'api_help_test', false);
3265 * Returns all lists the user subscribes to.
3267 * @param string $type Return type (atom, rss, xml, json)
3269 * @return array|string
3270 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3272 function api_lists_list($type)
3275 /// @TODO $ret is not filled here?
3276 return api_format_data('lists', $type, ["lists_list" => $ret]);
3279 /// @TODO move to top of file or somewhere better
3280 api_register_func('api/lists/list', 'api_lists_list', true);
3281 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3284 * Returns all groups the user owns.
3286 * @param string $type Return type (atom, rss, xml, json)
3288 * @return array|string
3289 * @throws BadRequestException
3290 * @throws ForbiddenException
3291 * @throws ImagickException
3292 * @throws InternalServerErrorException
3293 * @throws UnauthorizedException
3294 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3296 function api_lists_ownerships($type)
3300 if (api_user() === false) {
3301 throw new ForbiddenException();
3305 $user_info = api_get_user($a);
3306 $uid = $user_info['uid'];
3308 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3310 // loop through all groups
3312 foreach ($groups as $group) {
3313 if ($group['visible']) {
3319 'name' => $group['name'],
3320 'id' => intval($group['id']),
3321 'id_str' => (string) $group['id'],
3322 'user' => $user_info,
3326 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3329 /// @TODO move to top of file or somewhere better
3330 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3333 * Returns recent statuses from users in the specified group.
3335 * @param string $type Return type (atom, rss, xml, json)
3337 * @return array|string
3338 * @throws BadRequestException
3339 * @throws ForbiddenException
3340 * @throws ImagickException
3341 * @throws InternalServerErrorException
3342 * @throws UnauthorizedException
3343 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3345 function api_lists_statuses($type)
3349 $user_info = api_get_user($a);
3350 if (api_user() === false || $user_info === false) {
3351 throw new ForbiddenException();
3354 unset($_REQUEST["user_id"]);
3355 unset($_GET["user_id"]);
3357 unset($_REQUEST["screen_name"]);
3358 unset($_GET["screen_name"]);
3360 if (empty($_REQUEST['list_id'])) {
3361 throw new BadRequestException('list_id not specified');
3365 $count = $_REQUEST['count'] ?? 20;
3366 $page = $_REQUEST['page'] ?? 1;
3367 $since_id = $_REQUEST['since_id'] ?? 0;
3368 $max_id = $_REQUEST['max_id'] ?? 0;
3369 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3370 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3372 $start = max(0, ($page - 1) * $count);
3374 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3375 $gids = array_column($groups, 'contact-id');
3376 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3377 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3380 $condition[0] .= " AND `id` <= ?";
3381 $condition[] = $max_id;
3383 if ($exclude_replies > 0) {
3384 $condition[0] .= ' AND `gravity` = ?';
3385 $condition[] = GRAVITY_PARENT;
3387 if ($conversation_id > 0) {
3388 $condition[0] .= " AND `parent` = ?";
3389 $condition[] = $conversation_id;
3392 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3393 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3395 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3397 $data = ['status' => $items];
3402 $data = api_rss_extra($a, $data, $user_info);
3406 return api_format_data("statuses", $type, $data);
3409 /// @TODO move to top of file or somewhere better
3410 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3413 * Returns either the friends of the follower list
3415 * Considers friends and followers lists to be private and won't return
3416 * anything if any user_id parameter is passed.
3418 * @param string $qtype Either "friends" or "followers"
3419 * @return boolean|array
3420 * @throws BadRequestException
3421 * @throws ForbiddenException
3422 * @throws ImagickException
3423 * @throws InternalServerErrorException
3424 * @throws UnauthorizedException
3426 function api_statuses_f($qtype)
3430 if (api_user() === false) {
3431 throw new ForbiddenException();
3435 $count = $_GET['count'] ?? 20;
3436 $page = $_GET['page'] ?? 1;
3438 $start = max(0, ($page - 1) * $count);
3440 $user_info = api_get_user($a);
3442 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3443 /* this is to stop Hotot to load friends multiple times
3444 * I'm not sure if I'm missing return something or
3445 * is a bug in hotot. Workaround, meantime
3449 return array('$users' => $ret);*/
3454 if ($qtype == 'friends') {
3455 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3456 } elseif ($qtype == 'followers') {
3457 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3460 // friends and followers only for self
3461 if ($user_info['self'] == 0) {
3462 $sql_extra = " AND false ";
3465 if ($qtype == 'blocks') {
3466 $sql_filter = 'AND `blocked` AND NOT `pending`';
3467 } elseif ($qtype == 'incoming') {
3468 $sql_filter = 'AND `pending`';
3470 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3488 foreach ($r as $cid) {
3489 $user = api_get_user($a, $cid['nurl']);
3490 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3491 unset($user["uid"]);
3492 unset($user["self"]);
3499 return ['user' => $ret];
3504 * Returns the list of friends of the provided user
3506 * @deprecated By Twitter API in favor of friends/list
3508 * @param string $type Either "json" or "xml"
3509 * @return boolean|string|array
3510 * @throws BadRequestException
3511 * @throws ForbiddenException
3513 function api_statuses_friends($type)
3515 $data = api_statuses_f("friends");
3516 if ($data === false) {
3519 return api_format_data("users", $type, $data);
3523 * Returns the list of followers of the provided user
3525 * @deprecated By Twitter API in favor of friends/list
3527 * @param string $type Either "json" or "xml"
3528 * @return boolean|string|array
3529 * @throws BadRequestException
3530 * @throws ForbiddenException
3532 function api_statuses_followers($type)
3534 $data = api_statuses_f("followers");
3535 if ($data === false) {
3538 return api_format_data("users", $type, $data);
3541 /// @TODO move to top of file or somewhere better
3542 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3543 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3546 * Returns the list of blocked users
3548 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3550 * @param string $type Either "json" or "xml"
3552 * @return boolean|string|array
3553 * @throws BadRequestException
3554 * @throws ForbiddenException
3556 function api_blocks_list($type)
3558 $data = api_statuses_f('blocks');
3559 if ($data === false) {
3562 return api_format_data("users", $type, $data);
3565 /// @TODO move to top of file or somewhere better
3566 api_register_func('api/blocks/list', 'api_blocks_list', true);
3569 * Returns the list of pending users IDs
3571 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3573 * @param string $type Either "json" or "xml"
3575 * @return boolean|string|array
3576 * @throws BadRequestException
3577 * @throws ForbiddenException
3579 function api_friendships_incoming($type)
3581 $data = api_statuses_f('incoming');
3582 if ($data === false) {
3587 foreach ($data['user'] as $user) {
3588 $ids[] = $user['id'];
3591 return api_format_data("ids", $type, ['id' => $ids]);
3594 /// @TODO move to top of file or somewhere better
3595 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3598 * Returns the instance's configuration information.
3600 * @param string $type Return type (atom, rss, xml, json)
3602 * @return array|string
3603 * @throws InternalServerErrorException
3605 function api_statusnet_config($type)
3607 $name = DI::config()->get('config', 'sitename');
3608 $server = DI::baseUrl()->getHostname();
3609 $logo = DI::baseUrl() . '/images/friendica-64.png';
3610 $email = DI::config()->get('config', 'admin_email');
3611 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3612 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3613 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3614 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3615 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3618 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3619 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3620 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3621 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3622 'shorturllength' => '30',
3624 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3625 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3626 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3627 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3632 return api_format_data('config', $type, ['config' => $config]);
3635 /// @TODO move to top of file or somewhere better
3636 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3637 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3641 * @param string $type Return type (atom, rss, xml, json)
3643 * @return array|string
3645 function api_statusnet_version($type)
3648 $fake_statusnet_version = "0.9.7";
3650 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3653 /// @TODO move to top of file or somewhere better
3654 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3655 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3658 * Sends a new direct message.
3660 * @param string $type Return type (atom, rss, xml, json)
3662 * @return array|string
3663 * @throws BadRequestException
3664 * @throws ForbiddenException
3665 * @throws ImagickException
3666 * @throws InternalServerErrorException
3667 * @throws NotFoundException
3668 * @throws UnauthorizedException
3669 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3671 function api_direct_messages_new($type)
3675 if (api_user() === false) {
3676 throw new ForbiddenException();
3679 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3683 $sender = api_get_user($a);
3686 if (!empty($_POST['screen_name'])) {
3688 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3690 DBA::escape($_POST['screen_name'])
3693 if (DBA::isResult($r)) {
3694 // Selecting the id by priority, friendica first
3695 api_best_nickname($r);
3697 $recipient = api_get_user($a, $r[0]['nurl']);
3700 $recipient = api_get_user($a, $_POST['user_id']);
3703 if (empty($recipient)) {
3704 throw new NotFoundException('Recipient not found');
3708 if (!empty($_REQUEST['replyto'])) {
3710 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3712 intval($_REQUEST['replyto'])
3714 $replyto = $r[0]['parent-uri'];
3715 $sub = $r[0]['title'];
3717 if (!empty($_REQUEST['title'])) {
3718 $sub = $_REQUEST['title'];
3720 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3724 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3727 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3728 $ret = api_format_messages($r[0], $recipient, $sender);
3730 $ret = ["error"=>$id];
3733 $data = ['direct_message'=>$ret];
3739 $data = api_rss_extra($a, $data, $sender);
3743 return api_format_data("direct-messages", $type, $data);
3746 /// @TODO move to top of file or somewhere better
3747 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3750 * delete a direct_message from mail table through api
3752 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3753 * @return string|array
3754 * @throws BadRequestException
3755 * @throws ForbiddenException
3756 * @throws ImagickException
3757 * @throws InternalServerErrorException
3758 * @throws UnauthorizedException
3759 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3761 function api_direct_messages_destroy($type)
3765 if (api_user() === false) {
3766 throw new ForbiddenException();
3770 $user_info = api_get_user($a);
3772 $id = $_REQUEST['id'] ?? 0;
3774 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3775 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3776 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3778 $uid = $user_info['uid'];
3779 // error if no id or parenturi specified (for clients posting parent-uri as well)
3780 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3781 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3782 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3785 // BadRequestException if no id specified (for clients using Twitter API)
3787 throw new BadRequestException('Message id not specified');
3790 // add parent-uri to sql command if specified by calling app
3791 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3793 // get data of the specified message id
3795 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3800 // error message if specified id is not in database
3801 if (!DBA::isResult($r)) {
3802 if ($verbose == "true") {
3803 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3804 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3806 /// @todo BadRequestException ok for Twitter API clients?
3807 throw new BadRequestException('message id not in database');
3812 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3817 if ($verbose == "true") {
3820 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3821 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3823 $answer = ['result' => 'error', 'message' => 'unknown error'];
3824 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3827 /// @todo return JSON data like Twitter API not yet implemented
3830 /// @TODO move to top of file or somewhere better
3831 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3836 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3837 * @return string|array
3838 * @throws BadRequestException
3839 * @throws ForbiddenException
3840 * @throws ImagickException
3841 * @throws InternalServerErrorException
3842 * @throws NotFoundException
3843 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3845 function api_friendships_destroy($type)
3849 if ($uid === false) {
3850 throw new ForbiddenException();
3853 $contact_id = $_REQUEST['user_id'] ?? 0;
3855 if (empty($contact_id)) {
3856 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3857 throw new BadRequestException("no user_id specified");
3860 // Get Contact by given id
3861 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3863 if(!DBA::isResult($contact)) {
3864 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3865 throw new NotFoundException("no contact found to given ID");
3868 $url = $contact["url"];
3870 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3871 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3872 Strings::normaliseLink($url), $url];
3873 $contact = DBA::selectFirst('contact', [], $condition);
3875 if (!DBA::isResult($contact)) {
3876 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3877 throw new NotFoundException("Not following Contact");
3880 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3881 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3882 throw new ExpectationFailedException("Not supported");
3885 $dissolve = ($contact['rel'] == Contact::SHARING);
3887 $owner = User::getOwnerDataById($uid);
3889 Contact::terminateFriendship($owner, $contact, $dissolve);
3892 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3893 throw new NotFoundException("Error Processing Request");
3896 // Sharing-only contacts get deleted as there no relationship any more
3898 Contact::remove($contact['id']);
3900 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3903 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3904 unset($contact["uid"]);
3905 unset($contact["self"]);
3907 // Set screen_name since Twidere requests it
3908 $contact["screen_name"] = $contact["nick"];
3910 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3912 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3916 * @param string $type Return type (atom, rss, xml, json)
3917 * @param string $box
3918 * @param string $verbose
3920 * @return array|string
3921 * @throws BadRequestException
3922 * @throws ForbiddenException
3923 * @throws ImagickException
3924 * @throws InternalServerErrorException
3925 * @throws UnauthorizedException
3927 function api_direct_messages_box($type, $box, $verbose)
3930 if (api_user() === false) {
3931 throw new ForbiddenException();
3934 $count = $_GET['count'] ?? 20;
3935 $page = $_REQUEST['page'] ?? 1;
3937 $since_id = $_REQUEST['since_id'] ?? 0;
3938 $max_id = $_REQUEST['max_id'] ?? 0;
3940 $user_id = $_REQUEST['user_id'] ?? '';
3941 $screen_name = $_REQUEST['screen_name'] ?? '';
3944 unset($_REQUEST["user_id"]);
3945 unset($_GET["user_id"]);
3947 unset($_REQUEST["screen_name"]);
3948 unset($_GET["screen_name"]);
3950 $user_info = api_get_user($a);
3951 if ($user_info === false) {
3952 throw new ForbiddenException();
3954 $profile_url = $user_info["url"];
3957 $start = max(0, ($page - 1) * $count);
3962 if ($box=="sentbox") {
3963 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3964 } elseif ($box == "conversation") {
3965 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3966 } elseif ($box == "all") {
3967 $sql_extra = "true";
3968 } elseif ($box == "inbox") {
3969 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3973 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3976 if ($user_id != "") {
3977 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3978 } elseif ($screen_name !="") {
3979 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3983 "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",
3989 if ($verbose == "true" && !DBA::isResult($r)) {
3990 $answer = ['result' => 'error', 'message' => 'no mails available'];
3991 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3995 foreach ($r as $item) {
3996 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3997 $recipient = $user_info;
3998 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3999 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4000 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4001 $sender = $user_info;
4004 if (isset($recipient) && isset($sender)) {
4005 $ret[] = api_format_messages($item, $recipient, $sender);
4010 $data = ['direct_message' => $ret];
4015 $data = api_rss_extra($a, $data, $user_info);
4019 return api_format_data("direct-messages", $type, $data);
4023 * Returns the most recent direct messages sent by the user.
4025 * @param string $type Return type (atom, rss, xml, json)
4027 * @return array|string
4028 * @throws BadRequestException
4029 * @throws ForbiddenException
4030 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4032 function api_direct_messages_sentbox($type)
4034 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4035 return api_direct_messages_box($type, "sentbox", $verbose);
4039 * Returns the most recent direct messages sent to the user.
4041 * @param string $type Return type (atom, rss, xml, json)
4043 * @return array|string
4044 * @throws BadRequestException
4045 * @throws ForbiddenException
4046 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4048 function api_direct_messages_inbox($type)
4050 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4051 return api_direct_messages_box($type, "inbox", $verbose);
4056 * @param string $type Return type (atom, rss, xml, json)
4058 * @return array|string
4059 * @throws BadRequestException
4060 * @throws ForbiddenException
4062 function api_direct_messages_all($type)
4064 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4065 return api_direct_messages_box($type, "all", $verbose);
4070 * @param string $type Return type (atom, rss, xml, json)
4072 * @return array|string
4073 * @throws BadRequestException
4074 * @throws ForbiddenException
4076 function api_direct_messages_conversation($type)
4078 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4079 return api_direct_messages_box($type, "conversation", $verbose);
4082 /// @TODO move to top of file or somewhere better
4083 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4084 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4085 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4086 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4089 * Returns an OAuth Request Token.
4091 * @see https://oauth.net/core/1.0/#auth_step1
4093 function api_oauth_request_token()
4095 $oauth1 = new FKOAuth1();
4097 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4098 } catch (Exception $e) {
4099 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4107 * Returns an OAuth Access Token.
4109 * @return array|string
4110 * @see https://oauth.net/core/1.0/#auth_step3
4112 function api_oauth_access_token()
4114 $oauth1 = new FKOAuth1();
4116 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4117 } catch (Exception $e) {
4118 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4125 /// @TODO move to top of file or somewhere better
4126 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4127 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4131 * delete a complete photoalbum with all containing photos from database through api
4133 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4134 * @return string|array
4135 * @throws BadRequestException
4136 * @throws ForbiddenException
4137 * @throws InternalServerErrorException
4139 function api_fr_photoalbum_delete($type)
4141 if (api_user() === false) {
4142 throw new ForbiddenException();
4145 $album = $_REQUEST['album'] ?? '';
4147 // we do not allow calls without album string
4149 throw new BadRequestException("no albumname specified");
4151 // check if album is existing
4153 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4154 if (!DBA::isResult($photos)) {
4155 throw new BadRequestException("album not available");
4158 $resourceIds = array_column($photos, 'resource-id');
4160 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4161 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4162 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4163 Item::deleteForUser($condition, api_user());
4165 // now let's delete all photos from the album
4166 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4168 // return success of deletion or error message
4170 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4171 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4173 throw new InternalServerErrorException("unknown error - deleting from database failed");
4178 * update the name of the album for all photos of an album
4180 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4181 * @return string|array
4182 * @throws BadRequestException
4183 * @throws ForbiddenException
4184 * @throws InternalServerErrorException
4186 function api_fr_photoalbum_update($type)
4188 if (api_user() === false) {
4189 throw new ForbiddenException();
4192 $album = $_REQUEST['album'] ?? '';
4193 $album_new = $_REQUEST['album_new'] ?? '';
4195 // we do not allow calls without album string
4197 throw new BadRequestException("no albumname specified");
4199 if ($album_new == "") {
4200 throw new BadRequestException("no new albumname specified");
4202 // check if album is existing
4203 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4204 throw new BadRequestException("album not available");
4206 // now let's update all photos to the albumname
4207 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4209 // return success of updating or error message
4211 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4212 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4214 throw new InternalServerErrorException("unknown error - updating in database failed");
4220 * list all photos of the authenticated user
4222 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4223 * @return string|array
4224 * @throws ForbiddenException
4225 * @throws InternalServerErrorException
4227 function api_fr_photos_list($type)
4229 if (api_user() === false) {
4230 throw new ForbiddenException();
4233 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4234 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4235 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4236 intval(local_user())
4239 'image/jpeg' => 'jpg',
4240 'image/png' => 'png',
4241 'image/gif' => 'gif'
4243 $data = ['photo'=>[]];
4244 if (DBA::isResult($r)) {
4245 foreach ($r as $rr) {
4247 $photo['id'] = $rr['resource-id'];
4248 $photo['album'] = $rr['album'];
4249 $photo['filename'] = $rr['filename'];
4250 $photo['type'] = $rr['type'];
4251 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4252 $photo['created'] = $rr['created'];
4253 $photo['edited'] = $rr['edited'];
4254 $photo['desc'] = $rr['desc'];
4256 if ($type == "xml") {
4257 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4259 $photo['thumb'] = $thumb;
4260 $data['photo'][] = $photo;
4264 return api_format_data("photos", $type, $data);
4268 * upload a new photo or change an existing photo
4270 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4271 * @return string|array
4272 * @throws BadRequestException
4273 * @throws ForbiddenException
4274 * @throws ImagickException
4275 * @throws InternalServerErrorException
4276 * @throws NotFoundException
4278 function api_fr_photo_create_update($type)
4280 if (api_user() === false) {
4281 throw new ForbiddenException();
4284 $photo_id = $_REQUEST['photo_id'] ?? null;
4285 $desc = $_REQUEST['desc'] ?? null;
4286 $album = $_REQUEST['album'] ?? null;
4287 $album_new = $_REQUEST['album_new'] ?? null;
4288 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4289 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4290 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4291 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4292 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4294 // do several checks on input parameters
4295 // we do not allow calls without album string
4296 if ($album == null) {
4297 throw new BadRequestException("no albumname specified");
4299 // if photo_id == null --> we are uploading a new photo
4300 if ($photo_id == null) {
4303 // error if no media posted in create-mode
4304 if (empty($_FILES['media'])) {
4306 throw new BadRequestException("no media data submitted");
4309 // album_new will be ignored in create-mode
4314 // check if photo is existing in databasei
4315 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4316 throw new BadRequestException("photo not available");
4320 // checks on acl strings provided by clients
4321 $acl_input_error = false;
4322 $acl_input_error |= check_acl_input($allow_cid);
4323 $acl_input_error |= check_acl_input($deny_cid);
4324 $acl_input_error |= check_acl_input($allow_gid);
4325 $acl_input_error |= check_acl_input($deny_gid);
4326 if ($acl_input_error) {
4327 throw new BadRequestException("acl data invalid");
4329 // now let's upload the new media in create-mode
4330 if ($mode == "create") {
4331 $media = $_FILES['media'];
4332 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4334 // return success of updating or error message
4335 if (!is_null($data)) {
4336 return api_format_data("photo_create", $type, $data);
4338 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4342 // now let's do the changes in update-mode
4343 if ($mode == "update") {
4344 $updated_fields = [];
4346 if (!is_null($desc)) {
4347 $updated_fields['desc'] = $desc;
4350 if (!is_null($album_new)) {
4351 $updated_fields['album'] = $album_new;
4354 if (!is_null($allow_cid)) {
4355 $allow_cid = trim($allow_cid);
4356 $updated_fields['allow_cid'] = $allow_cid;
4359 if (!is_null($deny_cid)) {
4360 $deny_cid = trim($deny_cid);
4361 $updated_fields['deny_cid'] = $deny_cid;
4364 if (!is_null($allow_gid)) {
4365 $allow_gid = trim($allow_gid);
4366 $updated_fields['allow_gid'] = $allow_gid;
4369 if (!is_null($deny_gid)) {
4370 $deny_gid = trim($deny_gid);
4371 $updated_fields['deny_gid'] = $deny_gid;
4375 if (count($updated_fields) > 0) {
4376 $nothingtodo = false;
4377 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4379 $nothingtodo = true;
4382 if (!empty($_FILES['media'])) {
4383 $nothingtodo = false;
4384 $media = $_FILES['media'];
4385 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4386 if (!is_null($data)) {
4387 return api_format_data("photo_update", $type, $data);
4391 // return success of updating or error message
4393 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4394 return api_format_data("photo_update", $type, ['$result' => $answer]);
4397 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4398 return api_format_data("photo_update", $type, ['$result' => $answer]);
4400 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4403 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4407 * delete a single photo from the database through api
4409 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4410 * @return string|array
4411 * @throws BadRequestException
4412 * @throws ForbiddenException
4413 * @throws InternalServerErrorException
4415 function api_fr_photo_delete($type)
4417 if (api_user() === false) {
4418 throw new ForbiddenException();
4422 $photo_id = $_REQUEST['photo_id'] ?? null;
4424 // do several checks on input parameters
4425 // we do not allow calls without photo id
4426 if ($photo_id == null) {
4427 throw new BadRequestException("no photo_id specified");
4430 // check if photo is existing in database
4431 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4432 throw new BadRequestException("photo not available");
4435 // now we can perform on the deletion of the photo
4436 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4438 // return success of deletion or error message
4440 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4441 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4442 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4443 Item::deleteForUser($condition, api_user());
4445 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4446 return api_format_data("photo_delete", $type, ['$result' => $result]);
4448 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4454 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4456 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4457 * @return string|array
4458 * @throws BadRequestException
4459 * @throws ForbiddenException
4460 * @throws InternalServerErrorException
4461 * @throws NotFoundException
4463 function api_fr_photo_detail($type)
4465 if (api_user() === false) {
4466 throw new ForbiddenException();
4468 if (empty($_REQUEST['photo_id'])) {
4469 throw new BadRequestException("No photo id.");
4472 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4473 $photo_id = $_REQUEST['photo_id'];
4475 // prepare json/xml output with data from database for the requested photo
4476 $data = prepare_photo_data($type, $scale, $photo_id);
4478 return api_format_data("photo_detail", $type, $data);
4483 * updates the profile image for the user (either a specified profile or the default profile)
4485 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4487 * @return string|array
4488 * @throws BadRequestException
4489 * @throws ForbiddenException
4490 * @throws ImagickException
4491 * @throws InternalServerErrorException
4492 * @throws NotFoundException
4493 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4495 function api_account_update_profile_image($type)
4497 if (api_user() === false) {
4498 throw new ForbiddenException();
4501 $profile_id = $_REQUEST['profile_id'] ?? 0;
4503 // error if image data is missing
4504 if (empty($_FILES['image'])) {
4505 throw new BadRequestException("no media data submitted");
4508 // check if specified profile id is valid
4509 if ($profile_id != 0) {
4510 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4511 // error message if specified profile id is not in database
4512 if (!DBA::isResult($profile)) {
4513 throw new BadRequestException("profile_id not available");
4515 $is_default_profile = $profile['is-default'];
4517 $is_default_profile = 1;
4520 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4522 if (!empty($_FILES['image'])) {
4523 $media = $_FILES['image'];
4524 } elseif (!empty($_FILES['media'])) {
4525 $media = $_FILES['media'];
4527 // save new profile image
4528 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4531 if (is_array($media['type'])) {
4532 $filetype = $media['type'][0];
4534 $filetype = $media['type'];
4536 if ($filetype == "image/jpeg") {
4538 } elseif ($filetype == "image/png") {
4541 throw new InternalServerErrorException('Unsupported filetype');
4544 // change specified profile or all profiles to the new resource-id
4545 if ($is_default_profile) {
4546 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4547 Photo::update(['profile' => false], $condition);
4549 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4550 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4551 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4554 Contact::updateSelfFromUserID(api_user(), true);
4556 // Update global directory in background
4557 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4558 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4559 Worker::add(PRIORITY_LOW, "Directory", $url);
4562 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4564 // output for client
4566 return api_account_verify_credentials($type);
4568 // SaveMediaToDatabase failed for some reason
4569 throw new InternalServerErrorException("image upload failed");
4573 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4574 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4575 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4576 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4577 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4578 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4579 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4580 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4581 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4584 * Update user profile
4586 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4588 * @return array|string
4589 * @throws BadRequestException
4590 * @throws ForbiddenException
4591 * @throws ImagickException
4592 * @throws InternalServerErrorException
4593 * @throws UnauthorizedException
4595 function api_account_update_profile($type)
4597 $local_user = api_user();
4598 $api_user = api_get_user(DI::app());
4600 if (!empty($_POST['name'])) {
4601 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4602 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4603 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4604 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4607 if (isset($_POST['description'])) {
4608 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4609 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4610 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4613 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4614 // Update global directory in background
4615 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4616 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4619 return api_account_verify_credentials($type);
4622 /// @TODO move to top of file or somewhere better
4623 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4627 * @param string $acl_string
4631 function check_acl_input($acl_string)
4633 if (empty($acl_string)) {
4637 $contact_not_found = false;
4639 // split <x><y><z> into array of cid's
4640 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4642 // check for each cid if it is available on server
4643 $cid_array = $array[0];
4644 foreach ($cid_array as $cid) {
4645 $cid = str_replace("<", "", $cid);
4646 $cid = str_replace(">", "", $cid);
4647 $condition = ['id' => $cid, 'uid' => api_user()];
4648 $contact_not_found |= !DBA::exists('contact', $condition);
4650 return $contact_not_found;
4654 * @param string $mediatype
4655 * @param array $media
4656 * @param string $type
4657 * @param string $album
4658 * @param string $allow_cid
4659 * @param string $deny_cid
4660 * @param string $allow_gid
4661 * @param string $deny_gid
4662 * @param string $desc
4663 * @param integer $profile
4664 * @param boolean $visibility
4665 * @param string $photo_id
4667 * @throws BadRequestException
4668 * @throws ForbiddenException
4669 * @throws ImagickException
4670 * @throws InternalServerErrorException
4671 * @throws NotFoundException
4672 * @throws UnauthorizedException
4674 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)
4682 if (is_array($media)) {
4683 if (is_array($media['tmp_name'])) {
4684 $src = $media['tmp_name'][0];
4686 $src = $media['tmp_name'];
4688 if (is_array($media['name'])) {
4689 $filename = basename($media['name'][0]);
4691 $filename = basename($media['name']);
4693 if (is_array($media['size'])) {
4694 $filesize = intval($media['size'][0]);
4696 $filesize = intval($media['size']);
4698 if (is_array($media['type'])) {
4699 $filetype = $media['type'][0];
4701 $filetype = $media['type'];
4705 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4708 "File upload src: " . $src . " - filename: " . $filename .
4709 " - size: " . $filesize . " - type: " . $filetype,
4713 // check if there was a php upload error
4714 if ($filesize == 0 && $media['error'] == 1) {
4715 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4717 // check against max upload size within Friendica instance
4718 $maximagesize = DI::config()->get('system', 'maximagesize');
4719 if ($maximagesize && ($filesize > $maximagesize)) {
4720 $formattedBytes = Strings::formatBytes($maximagesize);
4721 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4724 // create Photo instance with the data of the image
4725 $imagedata = @file_get_contents($src);
4726 $Image = new Image($imagedata, $filetype);
4727 if (!$Image->isValid()) {
4728 throw new InternalServerErrorException("unable to process image data");
4731 // check orientation of image
4732 $Image->orient($src);
4735 // check max length of images on server
4736 $max_length = DI::config()->get('system', 'max_image_length');
4738 $max_length = MAX_IMAGE_LENGTH;
4740 if ($max_length > 0) {
4741 $Image->scaleDown($max_length);
4742 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4744 $width = $Image->getWidth();
4745 $height = $Image->getHeight();
4747 // create a new resource-id if not already provided
4748 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4750 if ($mediatype == "photo") {
4751 // upload normal image (scales 0, 1, 2)
4752 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4754 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4756 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4758 if ($width > 640 || $height > 640) {
4759 $Image->scaleDown(640);
4760 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4762 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4766 if ($width > 320 || $height > 320) {
4767 $Image->scaleDown(320);
4768 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4770 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4773 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4774 } elseif ($mediatype == "profileimage") {
4775 // upload profile image (scales 4, 5, 6)
4776 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4778 if ($width > 300 || $height > 300) {
4779 $Image->scaleDown(300);
4780 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4782 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4786 if ($width > 80 || $height > 80) {
4787 $Image->scaleDown(80);
4788 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4790 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4794 if ($width > 48 || $height > 48) {
4795 $Image->scaleDown(48);
4796 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4798 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4801 $Image->__destruct();
4802 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4806 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4807 if ($photo_id == null && $mediatype == "photo") {
4808 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4810 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4811 return prepare_photo_data($type, false, $resource_id);
4813 throw new InternalServerErrorException("image upload failed");
4819 * @param string $hash
4820 * @param string $allow_cid
4821 * @param string $deny_cid
4822 * @param string $allow_gid
4823 * @param string $deny_gid
4824 * @param string $filetype
4825 * @param boolean $visibility
4826 * @throws InternalServerErrorException
4828 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4830 // get data about the api authenticated user
4831 $uri = Item::newURI(intval(api_user()));
4832 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4835 $arr['guid'] = System::createUUID();
4836 $arr['uid'] = intval(api_user());
4838 $arr['type'] = 'photo';
4840 $arr['resource-id'] = $hash;
4841 $arr['contact-id'] = $owner_record['id'];
4842 $arr['owner-name'] = $owner_record['name'];
4843 $arr['owner-link'] = $owner_record['url'];
4844 $arr['owner-avatar'] = $owner_record['thumb'];
4845 $arr['author-name'] = $owner_record['name'];
4846 $arr['author-link'] = $owner_record['url'];
4847 $arr['author-avatar'] = $owner_record['thumb'];
4849 $arr['allow_cid'] = $allow_cid;
4850 $arr['allow_gid'] = $allow_gid;
4851 $arr['deny_cid'] = $deny_cid;
4852 $arr['deny_gid'] = $deny_gid;
4853 $arr['visible'] = $visibility;
4857 'image/jpeg' => 'jpg',
4858 'image/png' => 'png',
4859 'image/gif' => 'gif'
4862 // adds link to the thumbnail scale photo
4863 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4864 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4867 // do the magic for storing the item in the database and trigger the federation to other contacts
4873 * @param string $type
4875 * @param string $photo_id
4878 * @throws BadRequestException
4879 * @throws ForbiddenException
4880 * @throws ImagickException
4881 * @throws InternalServerErrorException
4882 * @throws NotFoundException
4883 * @throws UnauthorizedException
4885 function prepare_photo_data($type, $scale, $photo_id)
4888 $user_info = api_get_user($a);
4890 if ($user_info === false) {
4891 throw new ForbiddenException();
4894 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4895 $data_sql = ($scale === false ? "" : "data, ");
4897 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4898 // clients needs to convert this in their way for further processing
4900 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4901 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4902 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4903 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4904 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4905 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4907 intval(local_user()),
4908 DBA::escape($photo_id),
4913 'image/jpeg' => 'jpg',
4914 'image/png' => 'png',
4915 'image/gif' => 'gif'
4918 // prepare output data for photo
4919 if (DBA::isResult($r)) {
4920 $data = ['photo' => $r[0]];
4921 $data['photo']['id'] = $data['photo']['resource-id'];
4922 if ($scale !== false) {
4923 $data['photo']['data'] = base64_encode($data['photo']['data']);
4925 unset($data['photo']['datasize']); //needed only with scale param
4927 if ($type == "xml") {
4928 $data['photo']['links'] = [];
4929 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4930 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4932 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4935 $data['photo']['link'] = [];
4936 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4938 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4939 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4943 unset($data['photo']['resource-id']);
4944 unset($data['photo']['minscale']);
4945 unset($data['photo']['maxscale']);
4947 throw new NotFoundException();
4950 // retrieve item element for getting activities (like, dislike etc.) related to photo
4951 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4952 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4953 if (!DBA::isResult($item)) {
4954 throw new NotFoundException('Photo-related item not found.');
4957 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4959 // retrieve comments on photo
4960 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4961 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4963 $statuses = Post::selectForUser(api_user(), [], $condition);
4965 // prepare output of comments
4966 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4968 if ($type == "xml") {
4970 foreach ($commentData as $comment) {
4971 $comments[$k++ . ":comment"] = $comment;
4974 foreach ($commentData as $comment) {
4975 $comments[] = $comment;
4978 $data['photo']['friendica_comments'] = $comments;
4980 // include info if rights on photo and rights on item are mismatching
4981 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4982 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4983 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4984 $data['photo']['deny_gid'] != $item['deny_gid'];
4985 $data['photo']['rights_mismatch'] = $rights_mismatch;
4992 * Similar as /mod/redir.php
4993 * redirect to 'url' after dfrn auth
4995 * Why this when there is mod/redir.php already?
4996 * This use api_user() and api_login()
4999 * c_url: url of remote contact to auth to
5000 * url: string, url to redirect after auth
5002 function api_friendica_remoteauth()
5004 $url = $_GET['url'] ?? '';
5005 $c_url = $_GET['c_url'] ?? '';
5007 if ($url === '' || $c_url === '') {
5008 throw new BadRequestException("Wrong parameters.");
5011 $c_url = Strings::normaliseLink($c_url);
5015 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5016 if (!DBA::isResult($contact)) {
5017 throw new BadRequestException("Unknown contact");
5020 $cid = $contact['id'];
5022 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5024 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5025 System::externalRedirect($url ?: $c_url);
5028 if ($contact['duplex'] && $contact['issued-id']) {
5029 $orig_id = $contact['issued-id'];
5030 $dfrn_id = '1:' . $orig_id;
5032 if ($contact['duplex'] && $contact['dfrn-id']) {
5033 $orig_id = $contact['dfrn-id'];
5034 $dfrn_id = '0:' . $orig_id;
5037 $sec = Strings::getRandomHex();
5039 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5040 'sec' => $sec, 'expire' => time() + 45];
5041 DBA::insert('profile_check', $fields);
5043 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5044 $dest = ($url ? '&destination_url=' . $url : '');
5046 System::externalRedirect(
5047 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5048 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5049 . '&type=profile&sec=' . $sec . $dest
5052 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5055 * Return an item with announcer data if it had been announced
5057 * @param array $item Item array
5058 * @return array Item array with announce data
5060 function api_get_announce($item)
5062 // Quit if the item already has got a different owner and author
5063 if ($item['owner-id'] != $item['author-id']) {
5067 // Don't change original or Diaspora posts
5068 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5072 // Quit if we do now the original author and it had been a post from a native network
5073 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5077 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5078 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5079 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5080 if (!DBA::isResult($announce)) {
5084 return array_merge($item, $announce);
5088 * Return the item shared, if the item contains only the [share] tag
5090 * @param array $item Sharer item
5091 * @return array|false Shared item or false if not a reshare
5092 * @throws ImagickException
5093 * @throws InternalServerErrorException
5095 function api_share_as_retweet(&$item)
5097 $body = trim($item["body"]);
5099 if (Diaspora::isReshare($body, false) === false) {
5100 if ($item['author-id'] == $item['owner-id']) {
5103 // Reshares from OStatus, ActivityPub and Twitter
5104 $reshared_item = $item;
5105 $reshared_item['owner-id'] = $reshared_item['author-id'];
5106 $reshared_item['owner-link'] = $reshared_item['author-link'];
5107 $reshared_item['owner-name'] = $reshared_item['author-name'];
5108 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5109 return $reshared_item;
5113 $reshared = Item::getShareArray($item);
5114 if (empty($reshared)) {
5118 $reshared_item = $item;
5120 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5124 if (!empty($reshared['comment'])) {
5125 $item['body'] = $reshared['comment'];
5128 $reshared_item["share-pre-body"] = $reshared['comment'];
5129 $reshared_item["body"] = $reshared['shared'];
5130 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5131 $reshared_item["author-name"] = $reshared['author'];
5132 $reshared_item["author-link"] = $reshared['profile'];
5133 $reshared_item["author-avatar"] = $reshared['avatar'];
5134 $reshared_item["plink"] = $reshared['link'] ?? '';
5135 $reshared_item["created"] = $reshared['posted'];
5136 $reshared_item["edited"] = $reshared['posted'];
5138 // Try to fetch the original item
5139 if (!empty($reshared['guid'])) {
5140 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5141 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5142 $condition = ['id' => $original_id];
5147 if (!empty($condition)) {
5148 $original_item = Post::selectFirst([], $condition);
5149 if (DBA::isResult($original_item)) {
5150 $reshared_item = array_merge($reshared_item, $original_item);
5154 return $reshared_item;
5159 * @param array $item
5164 function api_in_reply_to($item)
5168 $in_reply_to['status_id'] = null;
5169 $in_reply_to['user_id'] = null;
5170 $in_reply_to['status_id_str'] = null;
5171 $in_reply_to['user_id_str'] = null;
5172 $in_reply_to['screen_name'] = null;
5174 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5175 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5176 if (DBA::isResult($parent)) {
5177 $in_reply_to['status_id'] = intval($parent['id']);
5179 $in_reply_to['status_id'] = intval($item['parent']);
5182 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5184 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5185 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5187 if (DBA::isResult($parent)) {
5188 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5189 $in_reply_to['user_id'] = intval($parent['author-id']);
5190 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5193 // There seems to be situation, where both fields are identical:
5194 // https://github.com/friendica/friendica/issues/1010
5195 // This is a bugfix for that.
5196 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5197 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']]);
5198 $in_reply_to['status_id'] = null;
5199 $in_reply_to['user_id'] = null;
5200 $in_reply_to['status_id_str'] = null;
5201 $in_reply_to['user_id_str'] = null;
5202 $in_reply_to['screen_name'] = null;
5206 return $in_reply_to;
5211 * @param string $text
5214 * @throws InternalServerErrorException
5216 function api_clean_plain_items($text)
5218 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5220 $text = BBCode::cleanPictureLinks($text);
5221 $URLSearchString = "^\[\]";
5223 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5225 if ($include_entities == "true") {
5226 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5229 // Simplify "attachment" element
5230 $text = BBCode::removeAttachment($text);
5237 * @param array $contacts
5241 function api_best_nickname(&$contacts)
5245 if (count($contacts) == 0) {
5249 foreach ($contacts as $contact) {
5250 if ($contact["network"] == "") {
5251 $contact["network"] = "dfrn";
5252 $best_contact = [$contact];
5256 if (sizeof($best_contact) == 0) {
5257 foreach ($contacts as $contact) {
5258 if ($contact["network"] == "dfrn") {
5259 $best_contact = [$contact];
5264 if (sizeof($best_contact) == 0) {
5265 foreach ($contacts as $contact) {
5266 if ($contact["network"] == "dspr") {
5267 $best_contact = [$contact];
5272 if (sizeof($best_contact) == 0) {
5273 foreach ($contacts as $contact) {
5274 if ($contact["network"] == "stat") {
5275 $best_contact = [$contact];
5280 if (sizeof($best_contact) == 0) {
5281 foreach ($contacts as $contact) {
5282 if ($contact["network"] == "pump") {
5283 $best_contact = [$contact];
5288 if (sizeof($best_contact) == 0) {
5289 foreach ($contacts as $contact) {
5290 if ($contact["network"] == "twit") {
5291 $best_contact = [$contact];
5296 if (sizeof($best_contact) == 1) {
5297 $contacts = $best_contact;
5299 $contacts = [$contacts[0]];
5304 * Return all or a specified group of the user with the containing contacts.
5306 * @param string $type Return type (atom, rss, xml, json)
5308 * @return array|string
5309 * @throws BadRequestException
5310 * @throws ForbiddenException
5311 * @throws ImagickException
5312 * @throws InternalServerErrorException
5313 * @throws UnauthorizedException
5315 function api_friendica_group_show($type)
5319 if (api_user() === false) {
5320 throw new ForbiddenException();
5324 $user_info = api_get_user($a);
5325 $gid = $_REQUEST['gid'] ?? 0;
5326 $uid = $user_info['uid'];
5328 // get data of the specified group id or all groups if not specified
5331 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5335 // error message if specified gid is not in database
5336 if (!DBA::isResult($r)) {
5337 throw new BadRequestException("gid not available");
5341 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5346 // loop through all groups and retrieve all members for adding data in the user array
5348 foreach ($r as $rr) {
5349 $members = Contact\Group::getById($rr['id']);
5352 if ($type == "xml") {
5353 $user_element = "users";
5355 foreach ($members as $member) {
5356 $user = api_get_user($a, $member['nurl']);
5357 $users[$k++.":user"] = $user;
5360 $user_element = "user";
5361 foreach ($members as $member) {
5362 $user = api_get_user($a, $member['nurl']);
5366 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5368 return api_format_data("groups", $type, ['group' => $grps]);
5370 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5374 * Delete the specified group of the user.
5376 * @param string $type Return type (atom, rss, xml, json)
5378 * @return array|string
5379 * @throws BadRequestException
5380 * @throws ForbiddenException
5381 * @throws ImagickException
5382 * @throws InternalServerErrorException
5383 * @throws UnauthorizedException
5385 function api_friendica_group_delete($type)
5389 if (api_user() === false) {
5390 throw new ForbiddenException();
5394 $user_info = api_get_user($a);
5395 $gid = $_REQUEST['gid'] ?? 0;
5396 $name = $_REQUEST['name'] ?? '';
5397 $uid = $user_info['uid'];
5399 // error if no gid specified
5400 if ($gid == 0 || $name == "") {
5401 throw new BadRequestException('gid or name not specified');
5404 // get data of the specified group id
5406 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5410 // error message if specified gid is not in database
5411 if (!DBA::isResult($r)) {
5412 throw new BadRequestException('gid not available');
5415 // get data of the specified group id and group name
5417 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5422 // error message if specified gid is not in database
5423 if (!DBA::isResult($rname)) {
5424 throw new BadRequestException('wrong group name');
5428 $ret = Group::removeByName($uid, $name);
5431 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5432 return api_format_data("group_delete", $type, ['result' => $success]);
5434 throw new BadRequestException('other API error');
5437 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5442 * @param string $type Return type (atom, rss, xml, json)
5444 * @return array|string
5445 * @throws BadRequestException
5446 * @throws ForbiddenException
5447 * @throws ImagickException
5448 * @throws InternalServerErrorException
5449 * @throws UnauthorizedException
5450 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5452 function api_lists_destroy($type)
5456 if (api_user() === false) {
5457 throw new ForbiddenException();
5461 $user_info = api_get_user($a);
5462 $gid = $_REQUEST['list_id'] ?? 0;
5463 $uid = $user_info['uid'];
5465 // error if no gid specified
5467 throw new BadRequestException('gid not specified');
5470 // get data of the specified group id
5471 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5472 // error message if specified gid is not in database
5474 throw new BadRequestException('gid not available');
5477 if (Group::remove($gid)) {
5479 'name' => $group['name'],
5480 'id' => intval($gid),
5481 'id_str' => (string) $gid,
5482 'user' => $user_info
5485 return api_format_data("lists", $type, ['lists' => $list]);
5488 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5491 * Add a new group to the database.
5493 * @param string $name Group name
5494 * @param int $uid User ID
5495 * @param array $users List of users to add to the group
5498 * @throws BadRequestException
5500 function group_create($name, $uid, $users = [])
5502 // error if no name specified
5504 throw new BadRequestException('group name not specified');
5507 // get data of the specified group name
5509 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5513 // error message if specified group name already exists
5514 if (DBA::isResult($rname)) {
5515 throw new BadRequestException('group name already exists');
5518 // check if specified group name is a deleted group
5520 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5524 // error message if specified group name already exists
5525 if (DBA::isResult($rname)) {
5526 $reactivate_group = true;
5530 $ret = Group::create($uid, $name);
5532 $gid = Group::getIdByName($uid, $name);
5534 throw new BadRequestException('other API error');
5538 $erroraddinguser = false;
5540 foreach ($users as $user) {
5541 $cid = $user['cid'];
5542 // check if user really exists as contact
5544 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5548 if (count($contact)) {
5549 Group::addMember($gid, $cid);
5551 $erroraddinguser = true;
5552 $errorusers[] = $cid;
5556 // return success message incl. missing users in array
5557 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5559 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5563 * Create the specified group with the posted array of contacts.
5565 * @param string $type Return type (atom, rss, xml, json)
5567 * @return array|string
5568 * @throws BadRequestException
5569 * @throws ForbiddenException
5570 * @throws ImagickException
5571 * @throws InternalServerErrorException
5572 * @throws UnauthorizedException
5574 function api_friendica_group_create($type)
5578 if (api_user() === false) {
5579 throw new ForbiddenException();
5583 $user_info = api_get_user($a);
5584 $name = $_REQUEST['name'] ?? '';
5585 $uid = $user_info['uid'];
5586 $json = json_decode($_POST['json'], true);
5587 $users = $json['user'];
5589 $success = group_create($name, $uid, $users);
5591 return api_format_data("group_create", $type, ['result' => $success]);
5593 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5596 * Create a new group.
5598 * @param string $type Return type (atom, rss, xml, json)
5600 * @return array|string
5601 * @throws BadRequestException
5602 * @throws ForbiddenException
5603 * @throws ImagickException
5604 * @throws InternalServerErrorException
5605 * @throws UnauthorizedException
5606 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5608 function api_lists_create($type)
5612 if (api_user() === false) {
5613 throw new ForbiddenException();
5617 $user_info = api_get_user($a);
5618 $name = $_REQUEST['name'] ?? '';
5619 $uid = $user_info['uid'];
5621 $success = group_create($name, $uid);
5622 if ($success['success']) {
5624 'name' => $success['name'],
5625 'id' => intval($success['gid']),
5626 'id_str' => (string) $success['gid'],
5627 'user' => $user_info
5630 return api_format_data("lists", $type, ['lists'=>$grp]);
5633 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5636 * Update the specified group with the posted array of contacts.
5638 * @param string $type Return type (atom, rss, xml, json)
5640 * @return array|string
5641 * @throws BadRequestException
5642 * @throws ForbiddenException
5643 * @throws ImagickException
5644 * @throws InternalServerErrorException
5645 * @throws UnauthorizedException
5647 function api_friendica_group_update($type)
5651 if (api_user() === false) {
5652 throw new ForbiddenException();
5656 $user_info = api_get_user($a);
5657 $uid = $user_info['uid'];
5658 $gid = $_REQUEST['gid'] ?? 0;
5659 $name = $_REQUEST['name'] ?? '';
5660 $json = json_decode($_POST['json'], true);
5661 $users = $json['user'];
5663 // error if no name specified
5665 throw new BadRequestException('group name not specified');
5668 // error if no gid specified
5670 throw new BadRequestException('gid not specified');
5674 $members = Contact\Group::getById($gid);
5675 foreach ($members as $member) {
5676 $cid = $member['id'];
5677 foreach ($users as $user) {
5678 $found = ($user['cid'] == $cid ? true : false);
5680 if (!isset($found) || !$found) {
5681 Group::removeMemberByName($uid, $name, $cid);
5686 $erroraddinguser = false;
5688 foreach ($users as $user) {
5689 $cid = $user['cid'];
5690 // check if user really exists as contact
5692 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5697 if (count($contact)) {
5698 Group::addMember($gid, $cid);
5700 $erroraddinguser = true;
5701 $errorusers[] = $cid;
5705 // return success message incl. missing users in array
5706 $status = ($erroraddinguser ? "missing user" : "ok");
5707 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5708 return api_format_data("group_update", $type, ['result' => $success]);
5711 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5714 * Update information about a group.
5716 * @param string $type Return type (atom, rss, xml, json)
5718 * @return array|string
5719 * @throws BadRequestException
5720 * @throws ForbiddenException
5721 * @throws ImagickException
5722 * @throws InternalServerErrorException
5723 * @throws UnauthorizedException
5724 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5726 function api_lists_update($type)
5730 if (api_user() === false) {
5731 throw new ForbiddenException();
5735 $user_info = api_get_user($a);
5736 $gid = $_REQUEST['list_id'] ?? 0;
5737 $name = $_REQUEST['name'] ?? '';
5738 $uid = $user_info['uid'];
5740 // error if no gid specified
5742 throw new BadRequestException('gid not specified');
5745 // get data of the specified group id
5746 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5747 // error message if specified gid is not in database
5749 throw new BadRequestException('gid not available');
5752 if (Group::update($gid, $name)) {
5755 'id' => intval($gid),
5756 'id_str' => (string) $gid,
5757 'user' => $user_info
5760 return api_format_data("lists", $type, ['lists' => $list]);
5764 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5768 * @param string $type Return type (atom, rss, xml, json)
5770 * @return array|string
5771 * @throws BadRequestException
5772 * @throws ForbiddenException
5773 * @throws ImagickException
5774 * @throws InternalServerErrorException
5776 function api_friendica_activity($type)
5780 if (api_user() === false) {
5781 throw new ForbiddenException();
5783 $verb = strtolower($a->argv[3]);
5784 $verb = preg_replace("|\..*$|", "", $verb);
5786 $id = $_REQUEST['id'] ?? 0;
5788 $res = Item::performActivity($id, $verb, api_user());
5791 if ($type == "xml") {
5796 return api_format_data('ok', $type, ['ok' => $ok]);
5798 throw new BadRequestException('Error adding activity');
5802 /// @TODO move to top of file or somewhere better
5803 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5804 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5805 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5806 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5807 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5808 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5809 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5810 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5811 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5812 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5815 * Returns notifications
5817 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5819 * @return string|array
5820 * @throws ForbiddenException
5821 * @throws BadRequestException
5824 function api_friendica_notification($type)
5828 if (api_user() === false) {
5829 throw new ForbiddenException();
5832 throw new BadRequestException("Invalid argument count");
5835 $notifications = DI::notification()->getApiList(local_user());
5837 if ($type == "xml") {
5839 if (!empty($notifications)) {
5840 foreach ($notifications as $notification) {
5841 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5845 $result = $xmlnotes;
5846 } elseif (count($notifications) > 0) {
5847 $result = $notifications->getArrayCopy();
5852 return api_format_data("notes", $type, ['note' => $result]);
5856 * Set notification as seen and returns associated item (if possible)
5858 * POST request with 'id' param as notification id
5860 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5861 * @return string|array
5862 * @throws BadRequestException
5863 * @throws ForbiddenException
5864 * @throws ImagickException
5865 * @throws InternalServerErrorException
5866 * @throws UnauthorizedException
5868 function api_friendica_notification_seen($type)
5871 $user_info = api_get_user($a);
5873 if (api_user() === false || $user_info === false) {
5874 throw new ForbiddenException();
5876 if ($a->argc !== 4) {
5877 throw new BadRequestException("Invalid argument count");
5880 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5883 $notify = DI::notify()->getByID($id, api_user());
5884 DI::notify()->setSeen(true, $notify);
5886 if ($notify->otype === Notification\ObjectType::ITEM) {
5887 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5888 if (DBA::isResult($item)) {
5889 // we found the item, return it to the user
5890 $ret = api_format_items([$item], $user_info, false, $type);
5891 $data = ['status' => $ret];
5892 return api_format_data("status", $type, $data);
5894 // the item can't be found, but we set the notification as seen, so we count this as a success
5896 return api_format_data('result', $type, ['result' => "success"]);
5897 } catch (NotFoundException $e) {
5898 throw new BadRequestException('Invalid argument', $e);
5899 } catch (Exception $e) {
5900 throw new InternalServerErrorException('Internal Server exception', $e);
5904 /// @TODO move to top of file or somewhere better
5905 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5906 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5909 * update a direct_message to seen state
5911 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5912 * @return string|array (success result=ok, error result=error with error message)
5913 * @throws BadRequestException
5914 * @throws ForbiddenException
5915 * @throws ImagickException
5916 * @throws InternalServerErrorException
5917 * @throws UnauthorizedException
5919 function api_friendica_direct_messages_setseen($type)
5922 if (api_user() === false) {
5923 throw new ForbiddenException();
5927 $user_info = api_get_user($a);
5928 $uid = $user_info['uid'];
5929 $id = $_REQUEST['id'] ?? 0;
5931 // return error if id is zero
5933 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5934 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5937 // error message if specified id is not in database
5938 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5939 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5940 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5943 // update seen indicator
5944 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5948 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5949 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5951 $answer = ['result' => 'error', 'message' => 'unknown error'];
5952 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5956 /// @TODO move to top of file or somewhere better
5957 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5960 * search for direct_messages containing a searchstring through api
5962 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5963 * @param string $box
5964 * @return string|array (success: success=true if found and search_result contains found messages,
5965 * success=false if nothing was found, search_result='nothing found',
5966 * error: result=error with error message)
5967 * @throws BadRequestException
5968 * @throws ForbiddenException
5969 * @throws ImagickException
5970 * @throws InternalServerErrorException
5971 * @throws UnauthorizedException
5973 function api_friendica_direct_messages_search($type, $box = "")
5977 if (api_user() === false) {
5978 throw new ForbiddenException();
5982 $user_info = api_get_user($a);
5983 $searchstring = $_REQUEST['searchstring'] ?? '';
5984 $uid = $user_info['uid'];
5986 // error if no searchstring specified
5987 if ($searchstring == "") {
5988 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5989 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5992 // get data for the specified searchstring
5994 "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",
5996 DBA::escape('%'.$searchstring.'%')
5999 $profile_url = $user_info["url"];
6001 // message if nothing was found
6002 if (!DBA::isResult($r)) {
6003 $success = ['success' => false, 'search_results' => 'problem with query'];
6004 } elseif (count($r) == 0) {
6005 $success = ['success' => false, 'search_results' => 'nothing found'];
6008 foreach ($r as $item) {
6009 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6010 $recipient = $user_info;
6011 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6012 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6013 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6014 $sender = $user_info;
6017 if (isset($recipient) && isset($sender)) {
6018 $ret[] = api_format_messages($item, $recipient, $sender);
6021 $success = ['success' => true, 'search_results' => $ret];
6024 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6027 /// @TODO move to top of file or somewhere better
6028 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6031 * Returns a list of saved searches.
6033 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6035 * @param string $type Return format: json or xml
6037 * @return string|array
6040 function api_saved_searches_list($type)
6042 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6045 while ($term = DBA::fetch($terms)) {
6047 'created_at' => api_date(time()),
6048 'id' => intval($term['id']),
6049 'id_str' => $term['id'],
6050 'name' => $term['term'],
6052 'query' => $term['term']
6058 return api_format_data("terms", $type, ['terms' => $result]);
6061 /// @TODO move to top of file or somewhere better
6062 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6065 * Number of comments
6067 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6069 * @param object $data [Status, Status]
6073 function bindComments(&$data)
6075 if (count($data) == 0) {
6081 foreach ($data as $item) {
6082 $ids[] = $item['id'];
6085 $idStr = DBA::escape(implode(', ', $ids));
6086 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6087 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6088 $itemsData = DBA::toArray($items);
6090 foreach ($itemsData as $item) {
6091 $comments[$item['parent']] = $item['comments'];
6094 foreach ($data as $idx => $item) {
6096 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6101 @TODO Maybe open to implement?
6103 [pagename] => api/1.1/statuses/lookup.json
6104 [id] => 605138389168451584
6105 [include_cards] => true
6106 [cards_platform] => Android-12
6107 [include_entities] => true
6108 [include_my_retweet] => 1
6110 [include_reply_count] => true
6111 [include_descendent_reply_count] => true
6115 Not implemented by now:
6116 statuses/retweets_of_me
6121 account/update_location
6122 account/update_profile_background_image
6125 friendica/profile/update
6126 friendica/profile/create
6127 friendica/profile/delete
6129 Not implemented in status.net:
6130 statuses/retweeted_to_me
6131 statuses/retweeted_by_me
6132 direct_messages/destroy
6134 account/update_delivery_device
6135 notifications/follow