3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\Profile;
46 use Friendica\Model\User;
47 use Friendica\Model\Verb;
48 use Friendica\Network\HTTPException;
49 use Friendica\Network\HTTPException\BadRequestException;
50 use Friendica\Network\HTTPException\ExpectationFailedException;
51 use Friendica\Network\HTTPException\ForbiddenException;
52 use Friendica\Network\HTTPException\InternalServerErrorException;
53 use Friendica\Network\HTTPException\MethodNotAllowedException;
54 use Friendica\Network\HTTPException\NotFoundException;
55 use Friendica\Network\HTTPException\TooManyRequestsException;
56 use Friendica\Network\HTTPException\UnauthorizedException;
57 use Friendica\Object\Image;
58 use Friendica\Protocol\Activity;
59 use Friendica\Protocol\Diaspora;
60 use Friendica\Security\FKOAuth1;
61 use Friendica\Security\OAuth;
62 use Friendica\Security\OAuth1\OAuthRequest;
63 use Friendica\Security\OAuth1\OAuthUtil;
64 use Friendica\Util\DateTimeFormat;
65 use Friendica\Util\Images;
66 use Friendica\Util\Network;
67 use Friendica\Util\Proxy as ProxyUtils;
68 use Friendica\Util\Strings;
69 use Friendica\Util\XML;
71 require_once __DIR__ . '/../mod/item.php';
72 require_once __DIR__ . '/../mod/wall_upload.php';
74 define('API_METHOD_ANY', '*');
75 define('API_METHOD_GET', 'GET');
76 define('API_METHOD_POST', 'POST,PUT');
77 define('API_METHOD_DELETE', 'POST,DELETE');
79 define('API_LOG_PREFIX', 'API {action} - ');
87 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
88 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
89 * into a page, and visitors will post something without noticing it).
93 $user = OAuth::getCurrentUserID();
98 if (!empty($_SESSION['allow_api'])) {
106 * Get source name from API client
108 * Clients can send 'source' parameter to be show in post metadata
109 * as "sent via <source>".
110 * Some clients doesn't send a source param, we support ones we know
111 * (only Twidere, atm)
114 * Client source name, default to "api" if unset/unknown
117 function api_source()
119 if (requestdata('source')) {
120 return requestdata('source');
123 // Support for known clients that doesn't send a source name
124 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
125 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
129 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
131 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
138 * Format date for API
140 * @param string $str Source date, as UTC
141 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
144 function api_date($str)
146 // Wed May 23 06:01:13 +0000 2007
147 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
151 * Register a function to be the endpoint for defined API path.
153 * @param string $path API URL path, relative to DI::baseUrl()
154 * @param string $func Function name to call on path request
155 * @param bool $auth API need logged user
156 * @param string $method HTTP method reqiured to call this endpoint.
157 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
158 * Default to API_METHOD_ANY
160 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
170 // Workaround for hotot
171 $path = str_replace("api/", "api/1.1/", $path);
181 * Log in user via OAuth1 or Simple HTTP Auth.
182 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
185 * @throws ForbiddenException
186 * @throws InternalServerErrorException
187 * @throws UnauthorizedException
188 * @hook 'authenticate'
190 * 'username' => username from login form
191 * 'password' => password from login form
192 * 'authenticated' => return status,
193 * 'user_record' => return authenticated user record
195 function api_login(App $a)
197 $_SESSION["allow_api"] = false;
199 // workaround for HTTP-auth in CGI mode
200 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
201 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
202 if (strlen($userpass)) {
203 list($name, $password) = explode(':', $userpass);
204 $_SERVER['PHP_AUTH_USER'] = $name;
205 $_SERVER['PHP_AUTH_PW'] = $password;
209 if (empty($_SERVER['PHP_AUTH_USER'])) {
210 // Try OAuth when no user is provided
211 $oauth1 = new FKOAuth1();
214 $request = OAuthRequest::from_request();
215 list($consumer, $token) = $oauth1->verify_request($request);
216 if (!is_null($token)) {
217 $oauth1->loginUser($token->uid);
218 Session::set('allow_api', true);
221 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
222 var_dump($consumer, $token);
224 } catch (Exception $e) {
225 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
228 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
229 header('WWW-Authenticate: Basic realm="Friendica"');
230 throw new UnauthorizedException("This API requires login");
233 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
234 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
236 // allow "user@server" login (but ignore 'server' part)
237 $at = strstr($user, "@", true);
242 // next code from mod/auth.php. needs better solution
246 'username' => trim($user),
247 'password' => trim($password),
248 'authenticated' => 0,
249 'user_record' => null,
253 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
254 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
255 * and later addons should not interfere with an earlier one that succeeded.
257 Hook::callAll('authenticate', $addon_auth);
259 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
260 $record = $addon_auth['user_record'];
262 $user_id = User::authenticate(trim($user), trim($password), true);
263 if ($user_id !== false) {
264 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
268 if (!DBA::isResult($record)) {
269 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
270 header('WWW-Authenticate: Basic realm="Friendica"');
271 //header('HTTP/1.0 401 Unauthorized');
272 //die('This api requires login');
273 throw new UnauthorizedException("This API requires login");
276 // Don't refresh the login date more often than twice a day to spare database writes
277 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
279 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
281 $_SESSION["allow_api"] = true;
283 Hook::callAll('logged_in', $a->user);
287 * Check HTTP method of called API
289 * API endpoints can define which HTTP method to accept when called.
290 * This function check the current HTTP method agains endpoint
293 * @param string $method Required methods, uppercase, separated by comma
296 function api_check_method($method)
298 if ($method == "*") {
301 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
305 * Main API entry point
307 * Authenticate user, call registered API function, set HTTP headers
310 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
311 * @return string|array API call result
314 function api_call(App $a, App\Arguments $args = null)
316 global $API, $called_api;
323 if (strpos($args->getCommand(), ".xml") > 0) {
326 if (strpos($args->getCommand(), ".json") > 0) {
329 if (strpos($args->getCommand(), ".rss") > 0) {
332 if (strpos($args->getCommand(), ".atom") > 0) {
337 foreach ($API as $p => $info) {
338 if (strpos($args->getCommand(), $p) === 0) {
339 if (!api_check_method($info['method'])) {
340 throw new MethodNotAllowedException();
343 $called_api = explode("/", $p);
345 if (!empty($info['auth']) && api_user() === false) {
347 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
350 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
352 $stamp = microtime(true);
353 $return = call_user_func($info['func'], $type);
354 $duration = floatval(microtime(true) - $stamp);
356 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
358 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
360 if (false === $return) {
362 * api function returned false withour throw an
363 * exception. This should not happend, throw a 500
365 throw new InternalServerErrorException();
370 header("Content-Type: text/xml");
373 header("Content-Type: application/json");
374 if (!empty($return)) {
375 $json = json_encode(end($return));
376 if (!empty($_GET['callback'])) {
377 $json = $_GET['callback'] . "(" . $json . ")";
383 header("Content-Type: application/rss+xml");
384 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
387 header("Content-Type: application/atom+xml");
388 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
395 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
396 throw new NotFoundException();
397 } catch (HTTPException $e) {
398 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
399 return api_error($type, $e, $args);
404 * Format API error string
406 * @param string $type Return type (xml, json, rss, as)
407 * @param object $e HTTPException Error object
408 * @param App\Arguments $args The App arguments
409 * @return string|array error message formatted as $type
411 function api_error($type, $e, App\Arguments $args)
413 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
414 /// @TODO: https://dev.twitter.com/overview/api/response-codes
416 $error = ["error" => $error,
417 "code" => $e->getCode() . " " . $e->httpdesc,
418 "request" => $args->getQueryString()];
420 $return = api_format_data('status', $type, ['status' => $error]);
424 header("Content-Type: text/xml");
427 header("Content-Type: application/json");
428 $return = json_encode($return);
431 header("Content-Type: application/rss+xml");
434 header("Content-Type: application/atom+xml");
442 * Set values for RSS template
445 * @param array $arr Array to be passed to template
446 * @param array $user_info User info
448 * @throws BadRequestException
449 * @throws ImagickException
450 * @throws InternalServerErrorException
451 * @throws UnauthorizedException
452 * @todo find proper type-hints
454 function api_rss_extra(App $a, $arr, $user_info)
456 if (is_null($user_info)) {
457 $user_info = api_get_user($a);
460 $arr['$user'] = $user_info;
462 'alternate' => $user_info['url'],
463 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
464 'base' => DI::baseUrl(),
465 'updated' => api_date(null),
466 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
467 'language' => $user_info['lang'],
468 'logo' => DI::baseUrl() . "/images/friendica-32.png",
476 * Unique contact to contact url.
478 * @param int $id Contact id
479 * @return bool|string
480 * Contact url or False if contact id is unknown
483 function api_unique_id_to_nurl($id)
485 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
487 if (DBA::isResult($r)) {
495 * Get user info array.
498 * @param int|string $contact_id Contact ID or URL
500 * @throws BadRequestException
501 * @throws ImagickException
502 * @throws InternalServerErrorException
503 * @throws UnauthorizedException
505 function api_get_user(App $a, $contact_id = null)
513 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
515 // Searching for contact URL
516 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
517 $user = DBA::escape(Strings::normaliseLink($contact_id));
519 $extra_query = "AND `contact`.`nurl` = '%s' ";
520 if (api_user() !== false) {
521 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
525 // Searching for contact id with uid = 0
526 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
527 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
530 throw new BadRequestException("User ID ".$contact_id." not found.");
534 $extra_query = "AND `contact`.`nurl` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
540 if (is_null($user) && !empty($_GET['user_id'])) {
541 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
544 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
548 $extra_query = "AND `contact`.`nurl` = '%s' ";
549 if (api_user() !== false) {
550 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
553 if (is_null($user) && !empty($_GET['screen_name'])) {
554 $user = DBA::escape($_GET['screen_name']);
555 $extra_query = "AND `contact`.`nick` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
561 if (is_null($user) && !empty($_GET['profileurl'])) {
562 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
563 $extra_query = "AND `contact`.`nurl` = '%s' ";
564 if (api_user() !== false) {
565 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
569 // $called_api is the API path exploded on / and is expected to have at least 2 elements
570 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
571 $argid = count($called_api);
572 if (!empty($a->argv[$argid])) {
573 $data = explode(".", $a->argv[$argid]);
574 if (count($data) > 1) {
575 list($user, $null) = $data;
578 if (is_numeric($user)) {
579 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
583 $extra_query = "AND `contact`.`nurl` = '%s' ";
584 if (api_user() !== false) {
585 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
589 $user = DBA::escape($user);
590 $extra_query = "AND `contact`.`nick` = '%s' ";
591 if (api_user() !== false) {
592 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
597 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
600 if (api_user() === false) {
605 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
609 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
613 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
619 // Selecting the id by priority, friendica first
620 if (is_array($uinfo)) {
621 api_best_nickname($uinfo);
624 // if the contact wasn't found, fetch it from the contacts with uid = 0
625 if (!DBA::isResult($uinfo)) {
627 throw new BadRequestException("User not found.");
630 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
632 if (DBA::isResult($contact)) {
634 'id' => $contact["id"],
635 'id_str' => (string) $contact["id"],
636 'name' => $contact["name"],
637 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
638 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
639 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
640 'profile_image_url' => $contact["micro"],
641 'profile_image_url_https' => $contact["micro"],
642 'profile_image_url_profile_size' => $contact["thumb"],
643 'profile_image_url_large' => $contact["photo"],
644 'url' => $contact["url"],
645 'protected' => false,
646 'followers_count' => 0,
647 'friends_count' => 0,
649 'created_at' => api_date($contact["created"]),
650 'favourites_count' => 0,
652 'time_zone' => 'UTC',
653 'geo_enabled' => false,
655 'statuses_count' => 0,
657 'contributors_enabled' => false,
658 'is_translator' => false,
659 'is_translation_enabled' => false,
660 'following' => false,
661 'follow_request_sent' => false,
662 'statusnet_blocking' => false,
663 'notifications' => false,
664 'statusnet_profile_url' => $contact["url"],
666 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
667 'pid' => Contact::getIdForURL($contact["url"], 0, false),
669 'network' => $contact["network"],
674 throw new BadRequestException("User ".$url." not found.");
678 if ($uinfo[0]['self']) {
679 if ($uinfo[0]['network'] == "") {
680 $uinfo[0]['network'] = Protocol::DFRN;
683 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
684 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
691 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
693 if (!empty($profile['about'])) {
694 $description = $profile['about'];
696 $description = $uinfo[0]["about"];
699 if (!empty($usr['default-location'])) {
700 $location = $usr['default-location'];
701 } elseif (!empty($uinfo[0]["location"])) {
702 $location = $uinfo[0]["location"];
704 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
708 'id' => intval($pcontact_id),
709 'id_str' => (string) intval($pcontact_id),
710 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
711 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
712 'location' => $location,
713 'description' => BBCode::toPlaintext($description ?? ''),
714 'profile_image_url' => $uinfo[0]['micro'],
715 'profile_image_url_https' => $uinfo[0]['micro'],
716 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
717 'profile_image_url_large' => $uinfo[0]["photo"],
718 'url' => $uinfo[0]['url'],
719 'protected' => false,
720 'followers_count' => intval($countfollowers),
721 'friends_count' => intval($countfriends),
723 'created_at' => api_date($uinfo[0]['created']),
724 'favourites_count' => intval($starred),
726 'time_zone' => 'UTC',
727 'geo_enabled' => false,
729 'statuses_count' => intval($countitems),
731 'contributors_enabled' => false,
732 'is_translator' => false,
733 'is_translation_enabled' => false,
734 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
735 'follow_request_sent' => false,
736 'statusnet_blocking' => false,
737 'notifications' => false,
739 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
740 'statusnet_profile_url' => $uinfo[0]['url'],
741 'uid' => intval($uinfo[0]['uid']),
742 'cid' => intval($uinfo[0]['cid']),
743 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
744 'self' => $uinfo[0]['self'],
745 'network' => $uinfo[0]['network'],
748 // If this is a local user and it uses Frio, we can get its color preferences.
750 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
751 if ($theme_info['theme'] === 'frio') {
752 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
754 if ($schema && ($schema != '---')) {
755 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
756 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
757 require_once $schemefile;
760 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
761 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
762 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
764 if (empty($nav_bg)) {
767 if (empty($link_color)) {
768 $link_color = "#6fdbe8";
770 if (empty($bgcolor)) {
771 $bgcolor = "#ededed";
774 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
775 $ret['profile_link_color'] = str_replace('#', '', $link_color);
776 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
784 * return api-formatted array for item's author and owner
787 * @param array $item item from db
788 * @return array(array:author, array:owner)
789 * @throws BadRequestException
790 * @throws ImagickException
791 * @throws InternalServerErrorException
792 * @throws UnauthorizedException
794 function api_item_get_user(App $a, $item)
796 $status_user = api_get_user($a, $item['author-id'] ?? null);
798 $author_user = $status_user;
800 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
802 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
803 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
805 $owner_user = $author_user;
808 return ([$status_user, $author_user, $owner_user]);
812 * walks recursively through an array with the possibility to change value and key
814 * @param array $array The array to walk through
815 * @param callable $callback The callback function
817 * @return array the transformed array
819 function api_walk_recursive(array &$array, callable $callback)
823 foreach ($array as $k => $v) {
825 if ($callback($v, $k)) {
826 $new_array[$k] = api_walk_recursive($v, $callback);
829 if ($callback($v, $k)) {
840 * Callback function to transform the array in an array that can be transformed in a XML file
842 * @param mixed $item Array item value
843 * @param string $key Array key
845 * @return boolean Should the array item be deleted?
847 function api_reformat_xml(&$item, &$key)
849 if (is_bool($item)) {
850 $item = ($item ? "true" : "false");
853 if (substr($key, 0, 10) == "statusnet_") {
854 $key = "statusnet:".substr($key, 10);
855 } elseif (substr($key, 0, 10) == "friendica_") {
856 $key = "friendica:".substr($key, 10);
858 /// @TODO old-lost code?
860 // $key = "default:".$key;
866 * Creates the XML from a JSON style array
868 * @param array $data JSON style array
869 * @param string $root_element Name of the root element
871 * @return string The XML data
873 function api_create_xml(array $data, $root_element)
875 $childname = key($data);
876 $data2 = array_pop($data);
878 $namespaces = ["" => "http://api.twitter.com",
879 "statusnet" => "http://status.net/schema/api/1/",
880 "friendica" => "http://friendi.ca/schema/api/1/",
881 "georss" => "http://www.georss.org/georss"];
883 /// @todo Auto detection of needed namespaces
884 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
888 if (is_array($data2)) {
890 api_walk_recursive($data2, "api_reformat_xml");
896 foreach ($data2 as $item) {
897 $data4[$i++ . ":" . $childname] = $item;
904 $data3 = [$root_element => $data2];
906 $ret = XML::fromArray($data3, $xml, false, $namespaces);
911 * Formats the data according to the data type
913 * @param string $root_element Name of the root element
914 * @param string $type Return type (atom, rss, xml, json)
915 * @param array $data JSON style array
917 * @return array|string (string|array) XML data or JSON data
919 function api_format_data($root_element, $type, $data)
925 $ret = api_create_xml($data, $root_element);
940 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
941 * returns a 401 status code and an error message if not.
943 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
945 * @param string $type Return type (atom, rss, xml, json)
946 * @return array|string
947 * @throws BadRequestException
948 * @throws ForbiddenException
949 * @throws ImagickException
950 * @throws InternalServerErrorException
951 * @throws UnauthorizedException
953 function api_account_verify_credentials($type)
957 if (api_user() === false) {
958 throw new ForbiddenException();
961 unset($_REQUEST["user_id"]);
962 unset($_GET["user_id"]);
964 unset($_REQUEST["screen_name"]);
965 unset($_GET["screen_name"]);
967 $skip_status = $_REQUEST['skip_status'] ?? false;
969 $user_info = api_get_user($a);
971 // "verified" isn't used here in the standard
972 unset($user_info["verified"]);
974 // - Adding last status
976 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
978 $user_info['status'] = api_format_item($item, $type);
982 // "uid" and "self" are only needed for some internal stuff, so remove it from here
983 unset($user_info["uid"]);
984 unset($user_info["self"]);
986 return api_format_data("user", $type, ['user' => $user_info]);
989 /// @TODO move to top of file or somewhere better
990 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
993 * Get data from $_POST or $_GET
998 function requestdata($k)
1000 if (!empty($_POST[$k])) {
1003 if (!empty($_GET[$k])) {
1010 * Deprecated function to upload media.
1012 * @param string $type Return type (atom, rss, xml, json)
1014 * @return array|string
1015 * @throws BadRequestException
1016 * @throws ForbiddenException
1017 * @throws ImagickException
1018 * @throws InternalServerErrorException
1019 * @throws UnauthorizedException
1021 function api_statuses_mediap($type)
1025 if (api_user() === false) {
1026 Logger::log('api_statuses_update: no user');
1027 throw new ForbiddenException();
1029 $user_info = api_get_user($a);
1031 $_REQUEST['profile_uid'] = api_user();
1032 $_REQUEST['api_source'] = true;
1033 $txt = requestdata('status') ?? '';
1034 /// @TODO old-lost code?
1035 //$txt = urldecode(requestdata('status'));
1037 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1038 $txt = HTML::toBBCodeVideo($txt);
1039 $config = HTMLPurifier_Config::createDefault();
1040 $config->set('Cache.DefinitionImpl', null);
1041 $purifier = new HTMLPurifier($config);
1042 $txt = $purifier->purify($txt);
1044 $txt = HTML::toBBCode($txt);
1046 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1048 $picture = wall_upload_post($a, false);
1050 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1051 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1052 $item_id = item_post($a);
1054 // output the post that we just posted.
1055 return api_status_show($type, $item_id);
1058 /// @TODO move this to top of file or somewhere better!
1059 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1062 * Updates the user’s current status.
1064 * @param string $type Return type (atom, rss, xml, json)
1066 * @return array|string
1067 * @throws BadRequestException
1068 * @throws ForbiddenException
1069 * @throws ImagickException
1070 * @throws InternalServerErrorException
1071 * @throws TooManyRequestsException
1072 * @throws UnauthorizedException
1073 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1075 function api_statuses_update($type)
1079 if (api_user() === false) {
1080 Logger::log('api_statuses_update: no user');
1081 throw new ForbiddenException();
1086 // convert $_POST array items to the form we use for web posts.
1087 if (requestdata('htmlstatus')) {
1088 $txt = requestdata('htmlstatus') ?? '';
1089 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1090 $txt = HTML::toBBCodeVideo($txt);
1092 $config = HTMLPurifier_Config::createDefault();
1093 $config->set('Cache.DefinitionImpl', null);
1095 $purifier = new HTMLPurifier($config);
1096 $txt = $purifier->purify($txt);
1098 $_REQUEST['body'] = HTML::toBBCode($txt);
1101 $_REQUEST['body'] = requestdata('status');
1104 $_REQUEST['title'] = requestdata('title');
1106 $parent = requestdata('in_reply_to_status_id');
1108 // Twidere sends "-1" if it is no reply ...
1109 if ($parent == -1) {
1113 if (ctype_digit($parent)) {
1114 $_REQUEST['parent'] = $parent;
1116 $_REQUEST['parent_uri'] = $parent;
1119 if (requestdata('lat') && requestdata('long')) {
1120 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1122 $_REQUEST['profile_uid'] = api_user();
1125 // Check for throttling (maximum posts per day, week and month)
1126 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1127 if ($throttle_day > 0) {
1128 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1130 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1131 $posts_day = Post::count($condition);
1133 if ($posts_day > $throttle_day) {
1134 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1135 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1136 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));
1140 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1141 if ($throttle_week > 0) {
1142 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1144 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1145 $posts_week = Post::count($condition);
1147 if ($posts_week > $throttle_week) {
1148 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1149 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1150 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));
1154 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1155 if ($throttle_month > 0) {
1156 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1158 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1159 $posts_month = Post::count($condition);
1161 if ($posts_month > $throttle_month) {
1162 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1163 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1164 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));
1169 if (requestdata('media_ids')) {
1170 $ids = explode(',', requestdata('media_ids') ?? '');
1171 } elseif (!empty($_FILES['media'])) {
1172 // upload the image if we have one
1173 $picture = wall_upload_post($a, false);
1174 if (is_array($picture)) {
1175 $ids[] = $picture['id'];
1183 foreach ($ids as $id) {
1184 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1185 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1186 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1187 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1189 if (!empty($media)) {
1190 $ressources[] = $media[0]['resource-id'];
1191 $phototypes = Images::supportedTypes();
1192 $ext = $phototypes[$media[0]['type']];
1194 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1195 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1196 'size' => $media[0]['datasize'],
1197 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1198 'description' => $media[0]['desc'] ?? '',
1199 'width' => $media[0]['width'],
1200 'height' => $media[0]['height']];
1202 if (count($media) > 1) {
1203 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1204 $attachment['preview-width'] = $media[1]['width'];
1205 $attachment['preview-height'] = $media[1]['height'];
1207 $attachments[] = $attachment;
1211 // We have to avoid that the post is rejected because of an empty body
1212 if (empty($_REQUEST['body'])) {
1213 $_REQUEST['body'] = '[hr]';
1217 if (!empty($attachments)) {
1218 $_REQUEST['attachments'] = $attachments;
1221 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1223 $_REQUEST['api_source'] = true;
1225 if (empty($_REQUEST['source'])) {
1226 $_REQUEST["source"] = api_source();
1229 // call out normal post function
1230 $item_id = item_post($a);
1232 if (!empty($ressources) && !empty($item_id)) {
1233 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1234 foreach ($ressources as $ressource) {
1235 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1239 // output the post that we just posted.
1240 return api_status_show($type, $item_id);
1243 /// @TODO move to top of file or somewhere better
1244 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1245 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1248 * Uploads an image to Friendica.
1251 * @throws BadRequestException
1252 * @throws ForbiddenException
1253 * @throws ImagickException
1254 * @throws InternalServerErrorException
1255 * @throws UnauthorizedException
1256 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1258 function api_media_upload()
1262 if (api_user() === false) {
1263 Logger::log('no user');
1264 throw new ForbiddenException();
1269 if (empty($_FILES['media'])) {
1271 throw new BadRequestException("No media.");
1274 $media = wall_upload_post($a, false);
1277 throw new InternalServerErrorException();
1281 $returndata["media_id"] = $media["id"];
1282 $returndata["media_id_string"] = (string)$media["id"];
1283 $returndata["size"] = $media["size"];
1284 $returndata["image"] = ["w" => $media["width"],
1285 "h" => $media["height"],
1286 "image_type" => $media["type"],
1287 "friendica_preview_url" => $media["preview"]];
1289 Logger::info('Media uploaded', ['return' => $returndata]);
1291 return ["media" => $returndata];
1294 /// @TODO move to top of file or somewhere better
1295 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1298 * Updates media meta data (picture descriptions)
1300 * @param string $type Return type (atom, rss, xml, json)
1302 * @return array|string
1303 * @throws BadRequestException
1304 * @throws ForbiddenException
1305 * @throws ImagickException
1306 * @throws InternalServerErrorException
1307 * @throws TooManyRequestsException
1308 * @throws UnauthorizedException
1309 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1311 * @todo Compare the corresponding Twitter function for correct return values
1313 function api_media_metadata_create($type)
1317 if (api_user() === false) {
1318 Logger::info('no user');
1319 throw new ForbiddenException();
1324 $postdata = Network::postdata();
1326 if (empty($postdata)) {
1327 throw new BadRequestException("No post data");
1330 $data = json_decode($postdata, true);
1332 throw new BadRequestException("Invalid post data");
1335 if (empty($data['media_id']) || empty($data['alt_text'])) {
1336 throw new BadRequestException("Missing post data values");
1339 if (empty($data['alt_text']['text'])) {
1340 throw new BadRequestException("No alt text.");
1343 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1345 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1346 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1347 if (!DBA::isResult($photo)) {
1348 throw new BadRequestException("Metadata not found.");
1351 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1354 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1357 * @param string $type Return format (atom, rss, xml, json)
1358 * @param int $item_id
1359 * @return array|string
1362 function api_status_show($type, $item_id)
1364 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1368 $item = api_get_item(['id' => $item_id]);
1369 if (!empty($item)) {
1370 $status_info = api_format_item($item, $type);
1373 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1375 return api_format_data('statuses', $type, ['status' => $status_info]);
1379 * Retrieves the last public status of the provided user info
1381 * @param int $ownerId Public contact Id
1382 * @param int $uid User Id
1386 function api_get_last_status($ownerId, $uid)
1389 'author-id'=> $ownerId,
1391 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1392 'private' => [Item::PUBLIC, Item::UNLISTED]
1395 $item = api_get_item($condition);
1401 * Retrieves a single item record based on the provided condition and converts it for API use.
1403 * @param array $condition Item table condition array
1407 function api_get_item(array $condition)
1409 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1415 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1416 * The author's most recent status will be returned inline.
1418 * @param string $type Return type (atom, rss, xml, json)
1419 * @return array|string
1420 * @throws BadRequestException
1421 * @throws ImagickException
1422 * @throws InternalServerErrorException
1423 * @throws UnauthorizedException
1424 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1426 function api_users_show($type)
1428 $a = Friendica\DI::app();
1430 $user_info = api_get_user($a);
1432 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1433 if (!empty($item)) {
1434 $user_info['status'] = api_format_item($item, $type);
1437 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1438 unset($user_info['uid']);
1439 unset($user_info['self']);
1441 return api_format_data('user', $type, ['user' => $user_info]);
1444 /// @TODO move to top of file or somewhere better
1445 api_register_func('api/users/show', 'api_users_show');
1446 api_register_func('api/externalprofile/show', 'api_users_show');
1449 * Search a public user account.
1451 * @param string $type Return type (atom, rss, xml, json)
1453 * @return array|string
1454 * @throws BadRequestException
1455 * @throws ImagickException
1456 * @throws InternalServerErrorException
1457 * @throws UnauthorizedException
1458 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1460 function api_users_search($type)
1466 if (!empty($_GET['q'])) {
1467 $contacts = Contact::selectToArray(
1470 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1478 if (DBA::isResult($contacts)) {
1480 foreach ($contacts as $contact) {
1481 $user_info = api_get_user($a, $contact['id']);
1483 if ($type == 'xml') {
1484 $userlist[$k++ . ':user'] = $user_info;
1486 $userlist[] = $user_info;
1489 $userlist = ['users' => $userlist];
1491 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1494 throw new BadRequestException('No search term specified.');
1497 return api_format_data('users', $type, $userlist);
1500 /// @TODO move to top of file or somewhere better
1501 api_register_func('api/users/search', 'api_users_search');
1504 * Return user objects
1506 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1508 * @param string $type Return format: json or xml
1510 * @return array|string
1511 * @throws BadRequestException
1512 * @throws ImagickException
1513 * @throws InternalServerErrorException
1514 * @throws NotFoundException if the results are empty.
1515 * @throws UnauthorizedException
1517 function api_users_lookup($type)
1521 if (!empty($_REQUEST['user_id'])) {
1522 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1524 $users[] = api_get_user(DI::app(), $id);
1529 if (empty($users)) {
1530 throw new NotFoundException;
1533 return api_format_data("users", $type, ['users' => $users]);
1536 /// @TODO move to top of file or somewhere better
1537 api_register_func('api/users/lookup', 'api_users_lookup', true);
1540 * Returns statuses that match a specified query.
1542 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1544 * @param string $type Return format: json, xml, atom, rss
1546 * @return array|string
1547 * @throws BadRequestException if the "q" parameter is missing.
1548 * @throws ForbiddenException
1549 * @throws ImagickException
1550 * @throws InternalServerErrorException
1551 * @throws UnauthorizedException
1553 function api_search($type)
1556 $user_info = api_get_user($a);
1558 if (api_user() === false || $user_info === false) {
1559 throw new ForbiddenException();
1562 if (empty($_REQUEST['q'])) {
1563 throw new BadRequestException('q parameter is required.');
1566 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1569 $data['status'] = [];
1571 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1572 if (!empty($_REQUEST['rpp'])) {
1573 $count = $_REQUEST['rpp'];
1574 } elseif (!empty($_REQUEST['count'])) {
1575 $count = $_REQUEST['count'];
1578 $since_id = $_REQUEST['since_id'] ?? 0;
1579 $max_id = $_REQUEST['max_id'] ?? 0;
1580 $page = $_REQUEST['page'] ?? 1;
1582 $start = max(0, ($page - 1) * $count);
1584 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1585 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1586 $searchTerm = $matches[1];
1587 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1588 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1590 while ($tag = DBA::fetch($tags)) {
1591 $uriids[] = $tag['uri-id'];
1595 if (empty($uriids)) {
1596 return api_format_data('statuses', $type, $data);
1599 $condition = ['uri-id' => $uriids];
1600 if ($exclude_replies) {
1601 $condition['gravity'] = GRAVITY_PARENT;
1604 $params['group_by'] = ['uri-id'];
1606 $condition = ["`id` > ?
1607 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1608 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1609 AND `body` LIKE CONCAT('%',?,'%')",
1610 $since_id, api_user(), $_REQUEST['q']];
1612 $condition[0] .= ' AND `id` <= ?';
1613 $condition[] = $max_id;
1619 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1620 $id = Item::fetchByLink($searchTerm, api_user());
1623 $id = Item::fetchByLink($searchTerm);
1627 $statuses = Post::select([], ['id' => $id]);
1631 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1633 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1635 bindComments($data['status']);
1637 return api_format_data('statuses', $type, $data);
1640 /// @TODO move to top of file or somewhere better
1641 api_register_func('api/search/tweets', 'api_search', true);
1642 api_register_func('api/search', 'api_search', true);
1645 * Returns the most recent statuses posted by the user and the users they follow.
1647 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1649 * @param string $type Return type (atom, rss, xml, json)
1651 * @return array|string
1652 * @throws BadRequestException
1653 * @throws ForbiddenException
1654 * @throws ImagickException
1655 * @throws InternalServerErrorException
1656 * @throws UnauthorizedException
1657 * @todo Optional parameters
1658 * @todo Add reply info
1660 function api_statuses_home_timeline($type)
1663 $user_info = api_get_user($a);
1665 if (api_user() === false || $user_info === false) {
1666 throw new ForbiddenException();
1669 unset($_REQUEST["user_id"]);
1670 unset($_GET["user_id"]);
1672 unset($_REQUEST["screen_name"]);
1673 unset($_GET["screen_name"]);
1675 // get last network messages
1678 $count = $_REQUEST['count'] ?? 20;
1679 $page = $_REQUEST['page']?? 0;
1680 $since_id = $_REQUEST['since_id'] ?? 0;
1681 $max_id = $_REQUEST['max_id'] ?? 0;
1682 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1683 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1685 $start = max(0, ($page - 1) * $count);
1687 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1688 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1691 $condition[0] .= " AND `id` <= ?";
1692 $condition[] = $max_id;
1694 if ($exclude_replies) {
1695 $condition[0] .= ' AND `gravity` = ?';
1696 $condition[] = GRAVITY_PARENT;
1698 if ($conversation_id > 0) {
1699 $condition[0] .= " AND `parent` = ?";
1700 $condition[] = $conversation_id;
1703 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1704 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1706 $items = Post::toArray($statuses);
1708 $ret = api_format_items($items, $user_info, false, $type);
1710 // Set all posts from the query above to seen
1712 foreach ($items as $item) {
1713 $idarray[] = intval($item["id"]);
1716 if (!empty($idarray)) {
1717 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1719 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1725 $data = ['status' => $ret];
1730 $data = api_rss_extra($a, $data, $user_info);
1734 return api_format_data("statuses", $type, $data);
1738 /// @TODO move to top of file or somewhere better
1739 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1740 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1743 * Returns the most recent statuses from public users.
1745 * @param string $type Return type (atom, rss, xml, json)
1747 * @return array|string
1748 * @throws BadRequestException
1749 * @throws ForbiddenException
1750 * @throws ImagickException
1751 * @throws InternalServerErrorException
1752 * @throws UnauthorizedException
1754 function api_statuses_public_timeline($type)
1757 $user_info = api_get_user($a);
1759 if (api_user() === false || $user_info === false) {
1760 throw new ForbiddenException();
1763 // get last network messages
1766 $count = $_REQUEST['count'] ?? 20;
1767 $page = $_REQUEST['page'] ?? 1;
1768 $since_id = $_REQUEST['since_id'] ?? 0;
1769 $max_id = $_REQUEST['max_id'] ?? 0;
1770 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1771 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1773 $start = max(0, ($page - 1) * $count);
1775 if ($exclude_replies && !$conversation_id) {
1776 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1777 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1780 $condition[0] .= " AND `id` <= ?";
1781 $condition[] = $max_id;
1784 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1785 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1787 $r = Post::toArray($statuses);
1789 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1790 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1793 $condition[0] .= " AND `id` <= ?";
1794 $condition[] = $max_id;
1796 if ($conversation_id > 0) {
1797 $condition[0] .= " AND `parent` = ?";
1798 $condition[] = $conversation_id;
1801 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1802 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1804 $r = Post::toArray($statuses);
1807 $ret = api_format_items($r, $user_info, false, $type);
1811 $data = ['status' => $ret];
1816 $data = api_rss_extra($a, $data, $user_info);
1820 return api_format_data("statuses", $type, $data);
1823 /// @TODO move to top of file or somewhere better
1824 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1827 * Returns the most recent statuses posted by users this node knows about.
1829 * @param string $type Return format: json, xml, atom, rss
1830 * @return array|string
1831 * @throws BadRequestException
1832 * @throws ForbiddenException
1833 * @throws ImagickException
1834 * @throws InternalServerErrorException
1835 * @throws UnauthorizedException
1837 function api_statuses_networkpublic_timeline($type)
1840 $user_info = api_get_user($a);
1842 if (api_user() === false || $user_info === false) {
1843 throw new ForbiddenException();
1846 $since_id = $_REQUEST['since_id'] ?? 0;
1847 $max_id = $_REQUEST['max_id'] ?? 0;
1850 $count = $_REQUEST['count'] ?? 20;
1851 $page = $_REQUEST['page'] ?? 1;
1853 $start = max(0, ($page - 1) * $count);
1855 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1856 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1859 $condition[0] .= " AND `id` <= ?";
1860 $condition[] = $max_id;
1863 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1864 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1866 $ret = api_format_items($statuses, $user_info, false, $type);
1870 $data = ['status' => $ret];
1875 $data = api_rss_extra($a, $data, $user_info);
1879 return api_format_data("statuses", $type, $data);
1882 /// @TODO move to top of file or somewhere better
1883 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1886 * Returns a single status.
1888 * @param string $type Return type (atom, rss, xml, json)
1890 * @return array|string
1891 * @throws BadRequestException
1892 * @throws ForbiddenException
1893 * @throws ImagickException
1894 * @throws InternalServerErrorException
1895 * @throws UnauthorizedException
1896 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1898 function api_statuses_show($type)
1901 $user_info = api_get_user($a);
1903 if (api_user() === false || $user_info === false) {
1904 throw new ForbiddenException();
1908 $id = intval($a->argv[3] ?? 0);
1911 $id = intval($_REQUEST['id'] ?? 0);
1916 $id = intval($a->argv[4] ?? 0);
1919 Logger::log('API: api_statuses_show: ' . $id);
1921 $conversation = !empty($_REQUEST['conversation']);
1923 // try to fetch the item for the local user - or the public item, if there is no local one
1924 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1925 if (!DBA::isResult($uri_item)) {
1926 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1929 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1930 if (!DBA::isResult($item)) {
1931 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1936 if ($conversation) {
1937 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1938 $params = ['order' => ['id' => true]];
1940 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1944 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1946 /// @TODO How about copying this to above methods which don't check $r ?
1947 if (!DBA::isResult($statuses)) {
1948 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1951 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1953 if ($conversation) {
1954 $data = ['status' => $ret];
1955 return api_format_data("statuses", $type, $data);
1957 $data = ['status' => $ret[0]];
1958 return api_format_data("status", $type, $data);
1962 /// @TODO move to top of file or somewhere better
1963 api_register_func('api/statuses/show', 'api_statuses_show', true);
1967 * @param string $type Return type (atom, rss, xml, json)
1969 * @return array|string
1970 * @throws BadRequestException
1971 * @throws ForbiddenException
1972 * @throws ImagickException
1973 * @throws InternalServerErrorException
1974 * @throws UnauthorizedException
1975 * @todo nothing to say?
1977 function api_conversation_show($type)
1980 $user_info = api_get_user($a);
1982 if (api_user() === false || $user_info === false) {
1983 throw new ForbiddenException();
1987 $id = intval($a->argv[3] ?? 0);
1988 $since_id = intval($_REQUEST['since_id'] ?? 0);
1989 $max_id = intval($_REQUEST['max_id'] ?? 0);
1990 $count = intval($_REQUEST['count'] ?? 20);
1991 $page = intval($_REQUEST['page'] ?? 1);
1993 $start = max(0, ($page - 1) * $count);
1996 $id = intval($_REQUEST['id'] ?? 0);
2001 $id = intval($a->argv[4] ?? 0);
2004 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
2006 // try to fetch the item for the local user - or the public item, if there is no local one
2007 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
2008 if (!DBA::isResult($item)) {
2009 throw new BadRequestException("There is no status with this id.");
2012 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2013 if (!DBA::isResult($parent)) {
2014 throw new BadRequestException("There is no status with this id.");
2017 $id = $parent['id'];
2019 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2020 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2023 $condition[0] .= " AND `id` <= ?";
2024 $condition[] = $max_id;
2027 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2028 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2030 if (!DBA::isResult($statuses)) {
2031 throw new BadRequestException("There is no status with id $id.");
2034 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2036 $data = ['status' => $ret];
2037 return api_format_data("statuses", $type, $data);
2040 /// @TODO move to top of file or somewhere better
2041 api_register_func('api/conversation/show', 'api_conversation_show', true);
2042 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2047 * @param string $type Return type (atom, rss, xml, json)
2049 * @return array|string
2050 * @throws BadRequestException
2051 * @throws ForbiddenException
2052 * @throws ImagickException
2053 * @throws InternalServerErrorException
2054 * @throws UnauthorizedException
2055 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2057 function api_statuses_repeat($type)
2063 if (api_user() === false) {
2064 throw new ForbiddenException();
2070 $id = intval($a->argv[3] ?? 0);
2073 $id = intval($_REQUEST['id'] ?? 0);
2078 $id = intval($a->argv[4] ?? 0);
2081 Logger::log('API: api_statuses_repeat: '.$id);
2083 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2084 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2086 if (DBA::isResult($item) && !empty($item['body'])) {
2087 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2088 if (!Item::performActivity($id, 'announce', local_user())) {
2089 throw new InternalServerErrorException();
2094 if (strpos($item['body'], "[/share]") !== false) {
2095 $pos = strpos($item['body'], "[share");
2096 $post = substr($item['body'], $pos);
2098 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2100 if (!empty($item['title'])) {
2101 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2104 $post .= $item['body'];
2105 $post .= "[/share]";
2107 $_REQUEST['body'] = $post;
2108 $_REQUEST['profile_uid'] = api_user();
2109 $_REQUEST['api_source'] = true;
2111 if (empty($_REQUEST['source'])) {
2112 $_REQUEST["source"] = api_source();
2115 $item_id = item_post($a);
2118 throw new ForbiddenException();
2121 // output the post that we just posted.
2123 return api_status_show($type, $item_id);
2126 /// @TODO move to top of file or somewhere better
2127 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2130 * Destroys a specific status.
2132 * @param string $type Return type (atom, rss, xml, json)
2134 * @return array|string
2135 * @throws BadRequestException
2136 * @throws ForbiddenException
2137 * @throws ImagickException
2138 * @throws InternalServerErrorException
2139 * @throws UnauthorizedException
2140 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2142 function api_statuses_destroy($type)
2146 if (api_user() === false) {
2147 throw new ForbiddenException();
2153 $id = intval($a->argv[3] ?? 0);
2156 $id = intval($_REQUEST['id'] ?? 0);
2161 $id = intval($a->argv[4] ?? 0);
2164 Logger::log('API: api_statuses_destroy: '.$id);
2166 $ret = api_statuses_show($type);
2168 Item::deleteForUser(['id' => $id], api_user());
2173 /// @TODO move to top of file or somewhere better
2174 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2177 * Returns the most recent mentions.
2179 * @param string $type Return type (atom, rss, xml, json)
2181 * @return array|string
2182 * @throws BadRequestException
2183 * @throws ForbiddenException
2184 * @throws ImagickException
2185 * @throws InternalServerErrorException
2186 * @throws UnauthorizedException
2187 * @see http://developer.twitter.com/doc/get/statuses/mentions
2189 function api_statuses_mentions($type)
2192 $user_info = api_get_user($a);
2194 if (api_user() === false || $user_info === false) {
2195 throw new ForbiddenException();
2198 unset($_REQUEST["user_id"]);
2199 unset($_GET["user_id"]);
2201 unset($_REQUEST["screen_name"]);
2202 unset($_GET["screen_name"]);
2204 // get last network messages
2207 $since_id = intval($_REQUEST['since_id'] ?? 0);
2208 $max_id = intval($_REQUEST['max_id'] ?? 0);
2209 $count = intval($_REQUEST['count'] ?? 20);
2210 $page = intval($_REQUEST['page'] ?? 1);
2212 $start = max(0, ($page - 1) * $count);
2214 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2215 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2216 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2218 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2219 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2220 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2221 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2222 api_user(), $since_id];
2225 $query .= " AND `id` <= ?";
2226 $condition[] = $max_id;
2229 array_unshift($condition, $query);
2231 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2232 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2234 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2236 $data = ['status' => $ret];
2241 $data = api_rss_extra($a, $data, $user_info);
2245 return api_format_data("statuses", $type, $data);
2248 /// @TODO move to top of file or somewhere better
2249 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2250 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2253 * Returns the most recent statuses posted by the user.
2255 * @param string $type Either "json" or "xml"
2256 * @return string|array
2257 * @throws BadRequestException
2258 * @throws ForbiddenException
2259 * @throws ImagickException
2260 * @throws InternalServerErrorException
2261 * @throws UnauthorizedException
2262 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2264 function api_statuses_user_timeline($type)
2267 $user_info = api_get_user($a);
2269 if (api_user() === false || $user_info === false) {
2270 throw new ForbiddenException();
2273 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2275 $since_id = $_REQUEST['since_id'] ?? 0;
2276 $max_id = $_REQUEST['max_id'] ?? 0;
2277 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2278 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2281 $count = $_REQUEST['count'] ?? 20;
2282 $page = $_REQUEST['page'] ?? 1;
2284 $start = max(0, ($page - 1) * $count);
2286 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2287 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2289 if ($user_info['self'] == 1) {
2290 $condition[0] .= ' AND `wall` ';
2293 if ($exclude_replies) {
2294 $condition[0] .= ' AND `gravity` = ?';
2295 $condition[] = GRAVITY_PARENT;
2298 if ($conversation_id > 0) {
2299 $condition[0] .= " AND `parent` = ?";
2300 $condition[] = $conversation_id;
2304 $condition[0] .= " AND `id` <= ?";
2305 $condition[] = $max_id;
2307 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2308 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2310 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2314 $data = ['status' => $ret];
2319 $data = api_rss_extra($a, $data, $user_info);
2323 return api_format_data("statuses", $type, $data);
2326 /// @TODO move to top of file or somewhere better
2327 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2330 * Star/unstar an item.
2331 * param: id : id of the item
2333 * @param string $type Return type (atom, rss, xml, json)
2335 * @return array|string
2336 * @throws BadRequestException
2337 * @throws ForbiddenException
2338 * @throws ImagickException
2339 * @throws InternalServerErrorException
2340 * @throws UnauthorizedException
2341 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2343 function api_favorites_create_destroy($type)
2347 if (api_user() === false) {
2348 throw new ForbiddenException();
2351 // for versioned api.
2352 /// @TODO We need a better global soluton
2353 $action_argv_id = 2;
2354 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2355 $action_argv_id = 3;
2358 if ($a->argc <= $action_argv_id) {
2359 throw new BadRequestException("Invalid request.");
2361 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2362 if ($a->argc == $action_argv_id + 2) {
2363 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2365 $itemid = intval($_REQUEST['id'] ?? 0);
2368 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2370 if (!DBA::isResult($item)) {
2371 throw new BadRequestException("Invalid item.");
2376 $item['starred'] = 1;
2379 $item['starred'] = 0;
2382 throw new BadRequestException("Invalid action ".$action);
2385 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2388 throw new InternalServerErrorException("DB error");
2392 $user_info = api_get_user($a);
2393 $rets = api_format_items([$item], $user_info, false, $type);
2396 $data = ['status' => $ret];
2401 $data = api_rss_extra($a, $data, $user_info);
2405 return api_format_data("status", $type, $data);
2408 /// @TODO move to top of file or somewhere better
2409 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2410 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2413 * Returns the most recent favorite statuses.
2415 * @param string $type Return type (atom, rss, xml, json)
2417 * @return string|array
2418 * @throws BadRequestException
2419 * @throws ForbiddenException
2420 * @throws ImagickException
2421 * @throws InternalServerErrorException
2422 * @throws UnauthorizedException
2424 function api_favorites($type)
2429 $user_info = api_get_user($a);
2431 if (api_user() === false || $user_info === false) {
2432 throw new ForbiddenException();
2437 // in friendica starred item are private
2438 // return favorites only for self
2439 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2441 if ($user_info['self'] == 0) {
2445 $since_id = $_REQUEST['since_id'] ?? 0;
2446 $max_id = $_REQUEST['max_id'] ?? 0;
2447 $count = $_GET['count'] ?? 20;
2448 $page = $_REQUEST['page'] ?? 1;
2450 $start = max(0, ($page - 1) * $count);
2452 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2453 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2455 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2458 $condition[0] .= " AND `id` <= ?";
2459 $condition[] = $max_id;
2462 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2464 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2469 $data = ['status' => $ret];
2474 $data = api_rss_extra($a, $data, $user_info);
2478 return api_format_data("statuses", $type, $data);
2481 /// @TODO move to top of file or somewhere better
2482 api_register_func('api/favorites', 'api_favorites', true);
2486 * @param array $item
2487 * @param array $recipient
2488 * @param array $sender
2491 * @throws InternalServerErrorException
2493 function api_format_messages($item, $recipient, $sender)
2495 // standard meta information
2497 'id' => $item['id'],
2498 'sender_id' => $sender['id'],
2500 'recipient_id' => $recipient['id'],
2501 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2502 'sender_screen_name' => $sender['screen_name'],
2503 'recipient_screen_name' => $recipient['screen_name'],
2504 'sender' => $sender,
2505 'recipient' => $recipient,
2507 'friendica_seen' => $item['seen'] ?? 0,
2508 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2511 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2512 if (isset($ret['sender']['uid'])) {
2513 unset($ret['sender']['uid']);
2515 if (isset($ret['sender']['self'])) {
2516 unset($ret['sender']['self']);
2518 if (isset($ret['recipient']['uid'])) {
2519 unset($ret['recipient']['uid']);
2521 if (isset($ret['recipient']['self'])) {
2522 unset($ret['recipient']['self']);
2525 //don't send title to regular StatusNET requests to avoid confusing these apps
2526 if (!empty($_GET['getText'])) {
2527 $ret['title'] = $item['title'];
2528 if ($_GET['getText'] == 'html') {
2529 $ret['text'] = BBCode::convert($item['body'], false);
2530 } elseif ($_GET['getText'] == 'plain') {
2531 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2534 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2536 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2537 unset($ret['sender']);
2538 unset($ret['recipient']);
2546 * @param array $item
2549 * @throws InternalServerErrorException
2551 function api_convert_item($item)
2553 $body = api_add_attachments_to_body($item);
2555 $entities = api_get_entitities($statustext, $body);
2557 // Add pictures to the attachment array and remove them from the body
2558 $attachments = api_get_attachments($body);
2560 // Workaround for ostatus messages where the title is identically to the body
2561 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2562 $statusbody = trim(HTML::toPlaintext($html, 0));
2564 // handle data: images
2565 $statusbody = api_format_items_embeded_images($item, $statusbody);
2567 $statustitle = trim($item['title']);
2569 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2570 $statustext = trim($statusbody);
2572 $statustext = trim($statustitle."\n\n".$statusbody);
2575 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2576 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2579 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2581 // Workaround for clients with limited HTML parser functionality
2582 $search = ["<br>", "<blockquote>", "</blockquote>",
2583 "<h1>", "</h1>", "<h2>", "</h2>",
2584 "<h3>", "</h3>", "<h4>", "</h4>",
2585 "<h5>", "</h5>", "<h6>", "</h6>"];
2586 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2587 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2588 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2589 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2590 $statushtml = str_replace($search, $replace, $statushtml);
2592 if ($item['title'] != "") {
2593 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2597 $oldtext = $statushtml;
2598 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2599 } while ($oldtext != $statushtml);
2601 if (substr($statushtml, 0, 4) == '<br>') {
2602 $statushtml = substr($statushtml, 4);
2605 if (substr($statushtml, 0, -4) == '<br>') {
2606 $statushtml = substr($statushtml, -4);
2609 // feeds without body should contain the link
2610 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2611 $statushtml .= BBCode::convert($item['plink']);
2615 "text" => $statustext,
2616 "html" => $statushtml,
2617 "attachments" => $attachments,
2618 "entities" => $entities
2623 * Add media attachments to the body
2625 * @param array $item
2626 * @return string body with added media
2628 function api_add_attachments_to_body(array $item)
2630 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2632 if (strpos($body, '[/img]') !== false) {
2636 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2637 if (!empty($media['preview'])) {
2638 $description = $media['description'] ?: $media['name'];
2639 if (!empty($description)) {
2640 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2642 $body .= "\n[img]" . $media['preview'] .'[/img]';
2652 * @param string $body
2655 * @throws InternalServerErrorException
2657 function api_get_attachments(&$body)
2659 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2660 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2662 $URLSearchString = "^\[\]";
2663 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2667 // Remove all embedded pictures, since they are added as attachments
2668 foreach ($images[0] as $orig) {
2669 $body = str_replace($orig, '', $body);
2674 foreach ($images[1] as $image) {
2675 $imagedata = Images::getInfoFromURLCached($image);
2678 if (DI::config()->get("system", "proxy_disabled")) {
2679 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2681 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2686 return $attachments;
2691 * @param string $text
2692 * @param string $bbcode
2695 * @throws InternalServerErrorException
2696 * @todo Links at the first character of the post
2698 function api_get_entitities(&$text, $bbcode)
2700 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2702 if ($include_entities != "true") {
2703 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2705 foreach ($images[1] as $image) {
2706 $replace = ProxyUtils::proxifyUrl($image, false);
2707 $text = str_replace($image, $replace, $text);
2712 $bbcode = BBCode::cleanPictureLinks($bbcode);
2714 // Change pure links in text to bbcode uris
2715 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2718 $entities["hashtags"] = [];
2719 $entities["symbols"] = [];
2720 $entities["urls"] = [];
2721 $entities["user_mentions"] = [];
2723 $URLSearchString = "^\[\]";
2725 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2727 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2728 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2730 $bbcode = preg_replace(
2731 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2732 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2735 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2737 $bbcode = preg_replace(
2738 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2739 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2742 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2744 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2746 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2749 foreach ($urls[1] as $id => $url) {
2750 $start = iconv_strpos($text, $url, 0, "UTF-8");
2751 if (!($start === false)) {
2752 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2756 ksort($ordered_urls);
2760 foreach ($ordered_urls as $url) {
2761 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2762 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2764 $display_url = $url["title"];
2766 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2767 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2769 if (strlen($display_url) > 26) {
2770 $display_url = substr($display_url, 0, 25)."…";
2774 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2775 if (!($start === false)) {
2776 $entities["urls"][] = ["url" => $url["url"],
2777 "expanded_url" => $url["url"],
2778 "display_url" => $display_url,
2779 "indices" => [$start, $start+strlen($url["url"])]];
2780 $offset = $start + 1;
2784 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2785 $ordered_images = [];
2786 foreach ($images as $image) {
2787 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2788 if (!($start === false)) {
2789 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2793 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2794 foreach ($images[1] as $image) {
2795 $start = iconv_strpos($text, $image, 0, "UTF-8");
2796 if (!($start === false)) {
2797 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2803 foreach ($ordered_images as $image) {
2804 $url = $image['url'];
2805 $ext_alt_text = $image['alt'];
2807 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2808 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2810 if (strlen($display_url) > 26) {
2811 $display_url = substr($display_url, 0, 25)."…";
2814 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2815 if (!($start === false)) {
2816 $image = Images::getInfoFromURLCached($url);
2818 // If image cache is activated, then use the following sizes:
2819 // thumb (150), small (340), medium (600) and large (1024)
2820 if (!DI::config()->get("system", "proxy_disabled")) {
2821 $media_url = ProxyUtils::proxifyUrl($url, false);
2824 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2825 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2827 if (($image[0] > 150) || ($image[1] > 150)) {
2828 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2829 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2832 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2833 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2835 if (($image[0] > 600) || ($image[1] > 600)) {
2836 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2837 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2841 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2844 $entities["media"][] = [
2846 "id_str" => (string) ($start + 1),
2847 "indices" => [$start, $start+strlen($url)],
2848 "media_url" => Strings::normaliseLink($media_url),
2849 "media_url_https" => $media_url,
2851 "display_url" => $display_url,
2852 "expanded_url" => $url,
2853 "ext_alt_text" => $ext_alt_text,
2857 $offset = $start + 1;
2866 * @param array $item
2867 * @param string $text
2871 function api_format_items_embeded_images($item, $text)
2873 $text = preg_replace_callback(
2874 '|data:image/([^;]+)[^=]+=*|m',
2875 function () use ($item) {
2876 return DI::baseUrl() . '/display/' . $item['guid'];
2884 * return <a href='url'>name</a> as array
2886 * @param string $txt text
2891 function api_contactlink_to_array($txt)
2894 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2895 if ($r && count($match)==3) {
2897 'name' => $match[2],
2911 * return likes, dislikes and attend status for item
2913 * @param array $item array
2914 * @param string $type Return type (atom, rss, xml, json)
2917 * likes => int count,
2918 * dislikes => int count
2919 * @throws BadRequestException
2920 * @throws ImagickException
2921 * @throws InternalServerErrorException
2922 * @throws UnauthorizedException
2924 function api_format_items_activities($item, $type = "json")
2933 'attendmaybe' => [],
2937 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2938 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2940 while ($parent_item = Post::fetch($ret)) {
2941 // not used as result should be structured like other user data
2942 //builtin_activity_puller($i, $activities);
2944 // get user data and add it to the array of the activity
2945 $user = api_get_user($a, $parent_item['author-id']);
2946 switch ($parent_item['verb']) {
2947 case Activity::LIKE:
2948 $activities['like'][] = $user;
2950 case Activity::DISLIKE:
2951 $activities['dislike'][] = $user;
2953 case Activity::ATTEND:
2954 $activities['attendyes'][] = $user;
2956 case Activity::ATTENDNO:
2957 $activities['attendno'][] = $user;
2959 case Activity::ATTENDMAYBE:
2960 $activities['attendmaybe'][] = $user;
2962 case Activity::ANNOUNCE:
2963 $activities['announce'][] = $user;
2972 if ($type == "xml") {
2973 $xml_activities = [];
2974 foreach ($activities as $k => $v) {
2975 // change xml element from "like" to "friendica:like"
2976 $xml_activities["friendica:".$k] = $v;
2977 // add user data into xml output
2979 foreach ($v as $user) {
2980 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2983 $activities = $xml_activities;
2990 * format items to be returned by api
2992 * @param array $items array of items
2993 * @param array $user_info
2994 * @param bool $filter_user filter items by $user_info
2995 * @param string $type Return type (atom, rss, xml, json)
2997 * @throws BadRequestException
2998 * @throws ImagickException
2999 * @throws InternalServerErrorException
3000 * @throws UnauthorizedException
3002 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
3004 $a = Friendica\DI::app();
3008 if (empty($items)) {
3012 foreach ((array)$items as $item) {
3013 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3015 // Look if the posts are matching if they should be filtered by user id
3016 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3020 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3029 * @param array $item Item record
3030 * @param string $type Return format (atom, rss, xml, json)
3031 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3032 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3033 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3034 * @return array API-formatted status
3035 * @throws BadRequestException
3036 * @throws ImagickException
3037 * @throws InternalServerErrorException
3038 * @throws UnauthorizedException
3040 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3042 $a = Friendica\DI::app();
3044 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3045 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3048 localize_item($item);
3050 $in_reply_to = api_in_reply_to($item);
3052 $converted = api_convert_item($item);
3054 if ($type == "xml") {
3055 $geo = "georss:point";
3061 'text' => $converted["text"],
3062 'truncated' => false,
3063 'created_at'=> api_date($item['created']),
3064 'in_reply_to_status_id' => $in_reply_to['status_id'],
3065 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3066 'source' => (($item['app']) ? $item['app'] : 'web'),
3067 'id' => intval($item['id']),
3068 'id_str' => (string) intval($item['id']),
3069 'in_reply_to_user_id' => $in_reply_to['user_id'],
3070 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3071 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3073 'favorited' => $item['starred'] ? true : false,
3074 'user' => $status_user,
3075 'friendica_author' => $author_user,
3076 'friendica_owner' => $owner_user,
3077 'friendica_private' => $item['private'] == Item::PRIVATE,
3078 //'entities' => NULL,
3079 'statusnet_html' => $converted["html"],
3080 'statusnet_conversation_id' => $item['parent'],
3081 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3082 'friendica_activities' => api_format_items_activities($item, $type),
3083 'friendica_title' => $item['title'],
3084 'friendica_html' => BBCode::convert($item['body'], false)
3087 if (count($converted["attachments"]) > 0) {
3088 $status["attachments"] = $converted["attachments"];
3091 if (count($converted["entities"]) > 0) {
3092 $status["entities"] = $converted["entities"];
3095 if ($status["source"] == 'web') {
3096 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3097 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3098 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3101 $retweeted_item = [];
3104 if ($item['gravity'] == GRAVITY_PARENT) {
3105 $body = $item['body'];
3106 $retweeted_item = api_share_as_retweet($item);
3107 if ($body != $item['body']) {
3108 $quoted_item = $retweeted_item;
3109 $retweeted_item = [];
3113 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3114 $announce = api_get_announce($item);
3115 if (!empty($announce)) {
3116 $retweeted_item = $item;
3118 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3122 if (!empty($quoted_item)) {
3123 if ($quoted_item['id'] != $item['id']) {
3124 $quoted_status = api_format_item($quoted_item);
3125 /// @todo Only remove the attachments that are also contained in the quotes status
3126 unset($status['attachments']);
3127 unset($status['entities']);
3129 $conv_quoted = api_convert_item($quoted_item);
3130 $quoted_status = $status;
3131 unset($quoted_status['attachments']);
3132 unset($quoted_status['entities']);
3133 unset($quoted_status['statusnet_conversation_id']);
3134 $quoted_status['text'] = $conv_quoted['text'];
3135 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3137 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3138 } catch (BadRequestException $e) {
3139 // user not found. should be found?
3140 /// @todo check if the user should be always found
3141 $quoted_status["user"] = [];
3144 unset($quoted_status['friendica_author']);
3145 unset($quoted_status['friendica_owner']);
3146 unset($quoted_status['friendica_activities']);
3147 unset($quoted_status['friendica_private']);
3150 if (!empty($retweeted_item)) {
3151 $retweeted_status = $status;
3152 unset($retweeted_status['friendica_author']);
3153 unset($retweeted_status['friendica_owner']);
3154 unset($retweeted_status['friendica_activities']);
3155 unset($retweeted_status['friendica_private']);
3156 unset($retweeted_status['statusnet_conversation_id']);
3157 $status['user'] = $status['friendica_owner'];
3159 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3160 } catch (BadRequestException $e) {
3161 // user not found. should be found?
3162 /// @todo check if the user should be always found
3163 $retweeted_status["user"] = [];
3166 $rt_converted = api_convert_item($retweeted_item);
3168 $retweeted_status['text'] = $rt_converted["text"];
3169 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3170 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3172 if (!empty($quoted_status)) {
3173 $retweeted_status['quoted_status'] = $quoted_status;
3176 $status['friendica_author'] = $retweeted_status['user'];
3177 $status['retweeted_status'] = $retweeted_status;
3178 } elseif (!empty($quoted_status)) {
3179 $root_status = api_convert_item($item);
3181 $status['text'] = $root_status["text"];
3182 $status['statusnet_html'] = $root_status["html"];
3183 $status['quoted_status'] = $quoted_status;
3186 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3187 unset($status["user"]["uid"]);
3188 unset($status["user"]["self"]);
3190 if ($item["coord"] != "") {
3191 $coords = explode(' ', $item["coord"]);
3192 if (count($coords) == 2) {
3193 if ($type == "json") {
3194 $status["geo"] = ['type' => 'Point',
3195 'coordinates' => [(float) $coords[0],
3196 (float) $coords[1]]];
3197 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3198 $status["georss:point"] = $item["coord"];
3207 * Returns the remaining number of API requests available to the user before the API limit is reached.
3209 * @param string $type Return type (atom, rss, xml, json)
3211 * @return array|string
3214 function api_account_rate_limit_status($type)
3216 if ($type == "xml") {
3218 'remaining-hits' => '150',
3219 '@attributes' => ["type" => "integer"],
3220 'hourly-limit' => '150',
3221 '@attributes2' => ["type" => "integer"],
3222 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3223 '@attributes3' => ["type" => "datetime"],
3224 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3225 '@attributes4' => ["type" => "integer"],
3229 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3230 'remaining_hits' => '150',
3231 'hourly_limit' => '150',
3232 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3236 return api_format_data('hash', $type, ['hash' => $hash]);
3239 /// @TODO move to top of file or somewhere better
3240 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3243 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3245 * @param string $type Return type (atom, rss, xml, json)
3247 * @return array|string
3249 function api_help_test($type)
3251 if ($type == 'xml') {
3257 return api_format_data('ok', $type, ["ok" => $ok]);
3260 /// @TODO move to top of file or somewhere better
3261 api_register_func('api/help/test', 'api_help_test', false);
3264 * Returns all lists the user subscribes to.
3266 * @param string $type Return type (atom, rss, xml, json)
3268 * @return array|string
3269 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3271 function api_lists_list($type)
3274 /// @TODO $ret is not filled here?
3275 return api_format_data('lists', $type, ["lists_list" => $ret]);
3278 /// @TODO move to top of file or somewhere better
3279 api_register_func('api/lists/list', 'api_lists_list', true);
3280 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3283 * Returns all groups the user owns.
3285 * @param string $type Return type (atom, rss, xml, json)
3287 * @return array|string
3288 * @throws BadRequestException
3289 * @throws ForbiddenException
3290 * @throws ImagickException
3291 * @throws InternalServerErrorException
3292 * @throws UnauthorizedException
3293 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3295 function api_lists_ownerships($type)
3299 if (api_user() === false) {
3300 throw new ForbiddenException();
3304 $user_info = api_get_user($a);
3305 $uid = $user_info['uid'];
3307 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3309 // loop through all groups
3311 foreach ($groups as $group) {
3312 if ($group['visible']) {
3318 'name' => $group['name'],
3319 'id' => intval($group['id']),
3320 'id_str' => (string) $group['id'],
3321 'user' => $user_info,
3325 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3328 /// @TODO move to top of file or somewhere better
3329 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3332 * Returns recent statuses from users in the specified group.
3334 * @param string $type Return type (atom, rss, xml, json)
3336 * @return array|string
3337 * @throws BadRequestException
3338 * @throws ForbiddenException
3339 * @throws ImagickException
3340 * @throws InternalServerErrorException
3341 * @throws UnauthorizedException
3342 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3344 function api_lists_statuses($type)
3348 $user_info = api_get_user($a);
3349 if (api_user() === false || $user_info === false) {
3350 throw new ForbiddenException();
3353 unset($_REQUEST["user_id"]);
3354 unset($_GET["user_id"]);
3356 unset($_REQUEST["screen_name"]);
3357 unset($_GET["screen_name"]);
3359 if (empty($_REQUEST['list_id'])) {
3360 throw new BadRequestException('list_id not specified');
3364 $count = $_REQUEST['count'] ?? 20;
3365 $page = $_REQUEST['page'] ?? 1;
3366 $since_id = $_REQUEST['since_id'] ?? 0;
3367 $max_id = $_REQUEST['max_id'] ?? 0;
3368 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3369 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3371 $start = max(0, ($page - 1) * $count);
3373 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3374 $gids = array_column($groups, 'contact-id');
3375 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3376 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3379 $condition[0] .= " AND `id` <= ?";
3380 $condition[] = $max_id;
3382 if ($exclude_replies > 0) {
3383 $condition[0] .= ' AND `gravity` = ?';
3384 $condition[] = GRAVITY_PARENT;
3386 if ($conversation_id > 0) {
3387 $condition[0] .= " AND `parent` = ?";
3388 $condition[] = $conversation_id;
3391 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3392 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3394 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3396 $data = ['status' => $items];
3401 $data = api_rss_extra($a, $data, $user_info);
3405 return api_format_data("statuses", $type, $data);
3408 /// @TODO move to top of file or somewhere better
3409 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3412 * Returns either the friends of the follower list
3414 * Considers friends and followers lists to be private and won't return
3415 * anything if any user_id parameter is passed.
3417 * @param string $qtype Either "friends" or "followers"
3418 * @return boolean|array
3419 * @throws BadRequestException
3420 * @throws ForbiddenException
3421 * @throws ImagickException
3422 * @throws InternalServerErrorException
3423 * @throws UnauthorizedException
3425 function api_statuses_f($qtype)
3429 if (api_user() === false) {
3430 throw new ForbiddenException();
3434 $count = $_GET['count'] ?? 20;
3435 $page = $_GET['page'] ?? 1;
3437 $start = max(0, ($page - 1) * $count);
3439 $user_info = api_get_user($a);
3441 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3442 /* this is to stop Hotot to load friends multiple times
3443 * I'm not sure if I'm missing return something or
3444 * is a bug in hotot. Workaround, meantime
3448 return array('$users' => $ret);*/
3453 if ($qtype == 'friends') {
3454 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3455 } elseif ($qtype == 'followers') {
3456 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3459 // friends and followers only for self
3460 if ($user_info['self'] == 0) {
3461 $sql_extra = " AND false ";
3464 if ($qtype == 'blocks') {
3465 $sql_filter = 'AND `blocked` AND NOT `pending`';
3466 } elseif ($qtype == 'incoming') {
3467 $sql_filter = 'AND `pending`';
3469 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3487 foreach ($r as $cid) {
3488 $user = api_get_user($a, $cid['nurl']);
3489 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3490 unset($user["uid"]);
3491 unset($user["self"]);
3498 return ['user' => $ret];
3503 * Returns the list of friends of the provided user
3505 * @deprecated By Twitter API in favor of friends/list
3507 * @param string $type Either "json" or "xml"
3508 * @return boolean|string|array
3509 * @throws BadRequestException
3510 * @throws ForbiddenException
3512 function api_statuses_friends($type)
3514 $data = api_statuses_f("friends");
3515 if ($data === false) {
3518 return api_format_data("users", $type, $data);
3522 * Returns the list of followers of the provided user
3524 * @deprecated By Twitter API in favor of friends/list
3526 * @param string $type Either "json" or "xml"
3527 * @return boolean|string|array
3528 * @throws BadRequestException
3529 * @throws ForbiddenException
3531 function api_statuses_followers($type)
3533 $data = api_statuses_f("followers");
3534 if ($data === false) {
3537 return api_format_data("users", $type, $data);
3540 /// @TODO move to top of file or somewhere better
3541 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3542 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3545 * Returns the list of blocked users
3547 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3549 * @param string $type Either "json" or "xml"
3551 * @return boolean|string|array
3552 * @throws BadRequestException
3553 * @throws ForbiddenException
3555 function api_blocks_list($type)
3557 $data = api_statuses_f('blocks');
3558 if ($data === false) {
3561 return api_format_data("users", $type, $data);
3564 /// @TODO move to top of file or somewhere better
3565 api_register_func('api/blocks/list', 'api_blocks_list', true);
3568 * Returns the list of pending users IDs
3570 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3572 * @param string $type Either "json" or "xml"
3574 * @return boolean|string|array
3575 * @throws BadRequestException
3576 * @throws ForbiddenException
3578 function api_friendships_incoming($type)
3580 $data = api_statuses_f('incoming');
3581 if ($data === false) {
3586 foreach ($data['user'] as $user) {
3587 $ids[] = $user['id'];
3590 return api_format_data("ids", $type, ['id' => $ids]);
3593 /// @TODO move to top of file or somewhere better
3594 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3597 * Returns the instance's configuration information.
3599 * @param string $type Return type (atom, rss, xml, json)
3601 * @return array|string
3602 * @throws InternalServerErrorException
3604 function api_statusnet_config($type)
3606 $name = DI::config()->get('config', 'sitename');
3607 $server = DI::baseUrl()->getHostname();
3608 $logo = DI::baseUrl() . '/images/friendica-64.png';
3609 $email = DI::config()->get('config', 'admin_email');
3610 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3611 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3612 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3613 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3614 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3617 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3618 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3619 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3620 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3621 'shorturllength' => '30',
3623 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3624 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3625 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3626 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3631 return api_format_data('config', $type, ['config' => $config]);
3634 /// @TODO move to top of file or somewhere better
3635 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3636 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3640 * @param string $type Return type (atom, rss, xml, json)
3642 * @return array|string
3644 function api_statusnet_version($type)
3647 $fake_statusnet_version = "0.9.7";
3649 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3652 /// @TODO move to top of file or somewhere better
3653 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3654 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3657 * Sends a new direct message.
3659 * @param string $type Return type (atom, rss, xml, json)
3661 * @return array|string
3662 * @throws BadRequestException
3663 * @throws ForbiddenException
3664 * @throws ImagickException
3665 * @throws InternalServerErrorException
3666 * @throws NotFoundException
3667 * @throws UnauthorizedException
3668 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3670 function api_direct_messages_new($type)
3674 if (api_user() === false) {
3675 throw new ForbiddenException();
3678 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3682 $sender = api_get_user($a);
3685 if (!empty($_POST['screen_name'])) {
3687 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3689 DBA::escape($_POST['screen_name'])
3692 if (DBA::isResult($r)) {
3693 // Selecting the id by priority, friendica first
3694 api_best_nickname($r);
3696 $recipient = api_get_user($a, $r[0]['nurl']);
3699 $recipient = api_get_user($a, $_POST['user_id']);
3702 if (empty($recipient)) {
3703 throw new NotFoundException('Recipient not found');
3707 if (!empty($_REQUEST['replyto'])) {
3709 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3711 intval($_REQUEST['replyto'])
3713 $replyto = $r[0]['parent-uri'];
3714 $sub = $r[0]['title'];
3716 if (!empty($_REQUEST['title'])) {
3717 $sub = $_REQUEST['title'];
3719 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3723 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3726 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3727 $ret = api_format_messages($r[0], $recipient, $sender);
3729 $ret = ["error"=>$id];
3732 $data = ['direct_message'=>$ret];
3738 $data = api_rss_extra($a, $data, $sender);
3742 return api_format_data("direct-messages", $type, $data);
3745 /// @TODO move to top of file or somewhere better
3746 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3749 * delete a direct_message from mail table through api
3751 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3752 * @return string|array
3753 * @throws BadRequestException
3754 * @throws ForbiddenException
3755 * @throws ImagickException
3756 * @throws InternalServerErrorException
3757 * @throws UnauthorizedException
3758 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3760 function api_direct_messages_destroy($type)
3764 if (api_user() === false) {
3765 throw new ForbiddenException();
3769 $user_info = api_get_user($a);
3771 $id = $_REQUEST['id'] ?? 0;
3773 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3774 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3775 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3777 $uid = $user_info['uid'];
3778 // error if no id or parenturi specified (for clients posting parent-uri as well)
3779 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3780 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3781 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3784 // BadRequestException if no id specified (for clients using Twitter API)
3786 throw new BadRequestException('Message id not specified');
3789 // add parent-uri to sql command if specified by calling app
3790 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3792 // get data of the specified message id
3794 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3799 // error message if specified id is not in database
3800 if (!DBA::isResult($r)) {
3801 if ($verbose == "true") {
3802 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3803 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3805 /// @todo BadRequestException ok for Twitter API clients?
3806 throw new BadRequestException('message id not in database');
3811 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3816 if ($verbose == "true") {
3819 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3820 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3822 $answer = ['result' => 'error', 'message' => 'unknown error'];
3823 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3826 /// @todo return JSON data like Twitter API not yet implemented
3829 /// @TODO move to top of file or somewhere better
3830 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3835 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3836 * @return string|array
3837 * @throws BadRequestException
3838 * @throws ForbiddenException
3839 * @throws ImagickException
3840 * @throws InternalServerErrorException
3841 * @throws NotFoundException
3842 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3844 function api_friendships_destroy($type)
3848 if ($uid === false) {
3849 throw new ForbiddenException();
3852 $contact_id = $_REQUEST['user_id'] ?? 0;
3854 if (empty($contact_id)) {
3855 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3856 throw new BadRequestException("no user_id specified");
3859 // Get Contact by given id
3860 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3862 if(!DBA::isResult($contact)) {
3863 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3864 throw new NotFoundException("no contact found to given ID");
3867 $url = $contact["url"];
3869 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3870 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3871 Strings::normaliseLink($url), $url];
3872 $contact = DBA::selectFirst('contact', [], $condition);
3874 if (!DBA::isResult($contact)) {
3875 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3876 throw new NotFoundException("Not following Contact");
3879 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3880 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3881 throw new ExpectationFailedException("Not supported");
3884 $dissolve = ($contact['rel'] == Contact::SHARING);
3886 $owner = User::getOwnerDataById($uid);
3888 Contact::terminateFriendship($owner, $contact, $dissolve);
3891 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3892 throw new NotFoundException("Error Processing Request");
3895 // Sharing-only contacts get deleted as there no relationship any more
3897 Contact::remove($contact['id']);
3899 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3902 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3903 unset($contact["uid"]);
3904 unset($contact["self"]);
3906 // Set screen_name since Twidere requests it
3907 $contact["screen_name"] = $contact["nick"];
3909 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3911 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3915 * @param string $type Return type (atom, rss, xml, json)
3916 * @param string $box
3917 * @param string $verbose
3919 * @return array|string
3920 * @throws BadRequestException
3921 * @throws ForbiddenException
3922 * @throws ImagickException
3923 * @throws InternalServerErrorException
3924 * @throws UnauthorizedException
3926 function api_direct_messages_box($type, $box, $verbose)
3929 if (api_user() === false) {
3930 throw new ForbiddenException();
3933 $count = $_GET['count'] ?? 20;
3934 $page = $_REQUEST['page'] ?? 1;
3936 $since_id = $_REQUEST['since_id'] ?? 0;
3937 $max_id = $_REQUEST['max_id'] ?? 0;
3939 $user_id = $_REQUEST['user_id'] ?? '';
3940 $screen_name = $_REQUEST['screen_name'] ?? '';
3943 unset($_REQUEST["user_id"]);
3944 unset($_GET["user_id"]);
3946 unset($_REQUEST["screen_name"]);
3947 unset($_GET["screen_name"]);
3949 $user_info = api_get_user($a);
3950 if ($user_info === false) {
3951 throw new ForbiddenException();
3953 $profile_url = $user_info["url"];
3956 $start = max(0, ($page - 1) * $count);
3961 if ($box=="sentbox") {
3962 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3963 } elseif ($box == "conversation") {
3964 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3965 } elseif ($box == "all") {
3966 $sql_extra = "true";
3967 } elseif ($box == "inbox") {
3968 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3972 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3975 if ($user_id != "") {
3976 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3977 } elseif ($screen_name !="") {
3978 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3982 "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",
3988 if ($verbose == "true" && !DBA::isResult($r)) {
3989 $answer = ['result' => 'error', 'message' => 'no mails available'];
3990 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3994 foreach ($r as $item) {
3995 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3996 $recipient = $user_info;
3997 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3998 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3999 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4000 $sender = $user_info;
4003 if (isset($recipient) && isset($sender)) {
4004 $ret[] = api_format_messages($item, $recipient, $sender);
4009 $data = ['direct_message' => $ret];
4014 $data = api_rss_extra($a, $data, $user_info);
4018 return api_format_data("direct-messages", $type, $data);
4022 * Returns the most recent direct messages sent by the user.
4024 * @param string $type Return type (atom, rss, xml, json)
4026 * @return array|string
4027 * @throws BadRequestException
4028 * @throws ForbiddenException
4029 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4031 function api_direct_messages_sentbox($type)
4033 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4034 return api_direct_messages_box($type, "sentbox", $verbose);
4038 * Returns the most recent direct messages sent to the user.
4040 * @param string $type Return type (atom, rss, xml, json)
4042 * @return array|string
4043 * @throws BadRequestException
4044 * @throws ForbiddenException
4045 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4047 function api_direct_messages_inbox($type)
4049 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4050 return api_direct_messages_box($type, "inbox", $verbose);
4055 * @param string $type Return type (atom, rss, xml, json)
4057 * @return array|string
4058 * @throws BadRequestException
4059 * @throws ForbiddenException
4061 function api_direct_messages_all($type)
4063 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4064 return api_direct_messages_box($type, "all", $verbose);
4069 * @param string $type Return type (atom, rss, xml, json)
4071 * @return array|string
4072 * @throws BadRequestException
4073 * @throws ForbiddenException
4075 function api_direct_messages_conversation($type)
4077 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4078 return api_direct_messages_box($type, "conversation", $verbose);
4081 /// @TODO move to top of file or somewhere better
4082 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4083 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4084 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4085 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4088 * Returns an OAuth Request Token.
4090 * @see https://oauth.net/core/1.0/#auth_step1
4092 function api_oauth_request_token()
4094 $oauth1 = new FKOAuth1();
4096 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4097 } catch (Exception $e) {
4098 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4106 * Returns an OAuth Access Token.
4108 * @return array|string
4109 * @see https://oauth.net/core/1.0/#auth_step3
4111 function api_oauth_access_token()
4113 $oauth1 = new FKOAuth1();
4115 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4116 } catch (Exception $e) {
4117 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4124 /// @TODO move to top of file or somewhere better
4125 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4126 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4130 * delete a complete photoalbum with all containing photos from database through api
4132 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4133 * @return string|array
4134 * @throws BadRequestException
4135 * @throws ForbiddenException
4136 * @throws InternalServerErrorException
4138 function api_fr_photoalbum_delete($type)
4140 if (api_user() === false) {
4141 throw new ForbiddenException();
4144 $album = $_REQUEST['album'] ?? '';
4146 // we do not allow calls without album string
4148 throw new BadRequestException("no albumname specified");
4150 // check if album is existing
4152 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4153 if (!DBA::isResult($photos)) {
4154 throw new BadRequestException("album not available");
4157 $resourceIds = array_column($photos, 'resource-id');
4159 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4160 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4161 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4162 Item::deleteForUser($condition, api_user());
4164 // now let's delete all photos from the album
4165 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4167 // return success of deletion or error message
4169 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4170 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4172 throw new InternalServerErrorException("unknown error - deleting from database failed");
4177 * update the name of the album for all photos of an album
4179 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4180 * @return string|array
4181 * @throws BadRequestException
4182 * @throws ForbiddenException
4183 * @throws InternalServerErrorException
4185 function api_fr_photoalbum_update($type)
4187 if (api_user() === false) {
4188 throw new ForbiddenException();
4191 $album = $_REQUEST['album'] ?? '';
4192 $album_new = $_REQUEST['album_new'] ?? '';
4194 // we do not allow calls without album string
4196 throw new BadRequestException("no albumname specified");
4198 if ($album_new == "") {
4199 throw new BadRequestException("no new albumname specified");
4201 // check if album is existing
4202 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4203 throw new BadRequestException("album not available");
4205 // now let's update all photos to the albumname
4206 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4208 // return success of updating or error message
4210 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4211 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4213 throw new InternalServerErrorException("unknown error - updating in database failed");
4219 * list all photos of the authenticated user
4221 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4222 * @return string|array
4223 * @throws ForbiddenException
4224 * @throws InternalServerErrorException
4226 function api_fr_photos_list($type)
4228 if (api_user() === false) {
4229 throw new ForbiddenException();
4232 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4233 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4234 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4235 intval(local_user())
4238 'image/jpeg' => 'jpg',
4239 'image/png' => 'png',
4240 'image/gif' => 'gif'
4242 $data = ['photo'=>[]];
4243 if (DBA::isResult($r)) {
4244 foreach ($r as $rr) {
4246 $photo['id'] = $rr['resource-id'];
4247 $photo['album'] = $rr['album'];
4248 $photo['filename'] = $rr['filename'];
4249 $photo['type'] = $rr['type'];
4250 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4251 $photo['created'] = $rr['created'];
4252 $photo['edited'] = $rr['edited'];
4253 $photo['desc'] = $rr['desc'];
4255 if ($type == "xml") {
4256 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4258 $photo['thumb'] = $thumb;
4259 $data['photo'][] = $photo;
4263 return api_format_data("photos", $type, $data);
4267 * upload a new photo or change an existing photo
4269 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4270 * @return string|array
4271 * @throws BadRequestException
4272 * @throws ForbiddenException
4273 * @throws ImagickException
4274 * @throws InternalServerErrorException
4275 * @throws NotFoundException
4277 function api_fr_photo_create_update($type)
4279 if (api_user() === false) {
4280 throw new ForbiddenException();
4283 $photo_id = $_REQUEST['photo_id'] ?? null;
4284 $desc = $_REQUEST['desc'] ?? null;
4285 $album = $_REQUEST['album'] ?? null;
4286 $album_new = $_REQUEST['album_new'] ?? null;
4287 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4288 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4289 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4290 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4291 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4293 // do several checks on input parameters
4294 // we do not allow calls without album string
4295 if ($album == null) {
4296 throw new BadRequestException("no albumname specified");
4298 // if photo_id == null --> we are uploading a new photo
4299 if ($photo_id == null) {
4302 // error if no media posted in create-mode
4303 if (empty($_FILES['media'])) {
4305 throw new BadRequestException("no media data submitted");
4308 // album_new will be ignored in create-mode
4313 // check if photo is existing in databasei
4314 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4315 throw new BadRequestException("photo not available");
4319 // checks on acl strings provided by clients
4320 $acl_input_error = false;
4321 $acl_input_error |= check_acl_input($allow_cid);
4322 $acl_input_error |= check_acl_input($deny_cid);
4323 $acl_input_error |= check_acl_input($allow_gid);
4324 $acl_input_error |= check_acl_input($deny_gid);
4325 if ($acl_input_error) {
4326 throw new BadRequestException("acl data invalid");
4328 // now let's upload the new media in create-mode
4329 if ($mode == "create") {
4330 $media = $_FILES['media'];
4331 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4333 // return success of updating or error message
4334 if (!is_null($data)) {
4335 return api_format_data("photo_create", $type, $data);
4337 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4341 // now let's do the changes in update-mode
4342 if ($mode == "update") {
4343 $updated_fields = [];
4345 if (!is_null($desc)) {
4346 $updated_fields['desc'] = $desc;
4349 if (!is_null($album_new)) {
4350 $updated_fields['album'] = $album_new;
4353 if (!is_null($allow_cid)) {
4354 $allow_cid = trim($allow_cid);
4355 $updated_fields['allow_cid'] = $allow_cid;
4358 if (!is_null($deny_cid)) {
4359 $deny_cid = trim($deny_cid);
4360 $updated_fields['deny_cid'] = $deny_cid;
4363 if (!is_null($allow_gid)) {
4364 $allow_gid = trim($allow_gid);
4365 $updated_fields['allow_gid'] = $allow_gid;
4368 if (!is_null($deny_gid)) {
4369 $deny_gid = trim($deny_gid);
4370 $updated_fields['deny_gid'] = $deny_gid;
4374 if (count($updated_fields) > 0) {
4375 $nothingtodo = false;
4376 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4378 $nothingtodo = true;
4381 if (!empty($_FILES['media'])) {
4382 $nothingtodo = false;
4383 $media = $_FILES['media'];
4384 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4385 if (!is_null($data)) {
4386 return api_format_data("photo_update", $type, $data);
4390 // return success of updating or error message
4392 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4393 return api_format_data("photo_update", $type, ['$result' => $answer]);
4396 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4397 return api_format_data("photo_update", $type, ['$result' => $answer]);
4399 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4402 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4406 * delete a single photo from the database through api
4408 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4409 * @return string|array
4410 * @throws BadRequestException
4411 * @throws ForbiddenException
4412 * @throws InternalServerErrorException
4414 function api_fr_photo_delete($type)
4416 if (api_user() === false) {
4417 throw new ForbiddenException();
4421 $photo_id = $_REQUEST['photo_id'] ?? null;
4423 // do several checks on input parameters
4424 // we do not allow calls without photo id
4425 if ($photo_id == null) {
4426 throw new BadRequestException("no photo_id specified");
4429 // check if photo is existing in database
4430 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4431 throw new BadRequestException("photo not available");
4434 // now we can perform on the deletion of the photo
4435 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4437 // return success of deletion or error message
4439 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4440 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4441 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4442 Item::deleteForUser($condition, api_user());
4444 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4445 return api_format_data("photo_delete", $type, ['$result' => $result]);
4447 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4453 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4455 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4456 * @return string|array
4457 * @throws BadRequestException
4458 * @throws ForbiddenException
4459 * @throws InternalServerErrorException
4460 * @throws NotFoundException
4462 function api_fr_photo_detail($type)
4464 if (api_user() === false) {
4465 throw new ForbiddenException();
4467 if (empty($_REQUEST['photo_id'])) {
4468 throw new BadRequestException("No photo id.");
4471 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4472 $photo_id = $_REQUEST['photo_id'];
4474 // prepare json/xml output with data from database for the requested photo
4475 $data = prepare_photo_data($type, $scale, $photo_id);
4477 return api_format_data("photo_detail", $type, $data);
4482 * updates the profile image for the user (either a specified profile or the default profile)
4484 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4486 * @return string|array
4487 * @throws BadRequestException
4488 * @throws ForbiddenException
4489 * @throws ImagickException
4490 * @throws InternalServerErrorException
4491 * @throws NotFoundException
4492 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4494 function api_account_update_profile_image($type)
4496 if (api_user() === false) {
4497 throw new ForbiddenException();
4500 $profile_id = $_REQUEST['profile_id'] ?? 0;
4502 // error if image data is missing
4503 if (empty($_FILES['image'])) {
4504 throw new BadRequestException("no media data submitted");
4507 // check if specified profile id is valid
4508 if ($profile_id != 0) {
4509 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4510 // error message if specified profile id is not in database
4511 if (!DBA::isResult($profile)) {
4512 throw new BadRequestException("profile_id not available");
4514 $is_default_profile = $profile['is-default'];
4516 $is_default_profile = 1;
4519 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4521 if (!empty($_FILES['image'])) {
4522 $media = $_FILES['image'];
4523 } elseif (!empty($_FILES['media'])) {
4524 $media = $_FILES['media'];
4526 // save new profile image
4527 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4530 if (is_array($media['type'])) {
4531 $filetype = $media['type'][0];
4533 $filetype = $media['type'];
4535 if ($filetype == "image/jpeg") {
4537 } elseif ($filetype == "image/png") {
4540 throw new InternalServerErrorException('Unsupported filetype');
4543 // change specified profile or all profiles to the new resource-id
4544 if ($is_default_profile) {
4545 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4546 Photo::update(['profile' => false], $condition);
4548 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4549 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4550 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4553 Contact::updateSelfFromUserID(api_user(), true);
4555 // Update global directory in background
4556 Profile::publishUpdate(api_user());
4558 // output for client
4560 return api_account_verify_credentials($type);
4562 // SaveMediaToDatabase failed for some reason
4563 throw new InternalServerErrorException("image upload failed");
4567 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4568 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4569 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4570 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4571 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4572 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4573 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4574 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4575 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4578 * Update user profile
4580 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4582 * @return array|string
4583 * @throws BadRequestException
4584 * @throws ForbiddenException
4585 * @throws ImagickException
4586 * @throws InternalServerErrorException
4587 * @throws UnauthorizedException
4589 function api_account_update_profile($type)
4591 $local_user = api_user();
4592 $api_user = api_get_user(DI::app());
4594 if (!empty($_POST['name'])) {
4595 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4596 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4597 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4598 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4601 if (isset($_POST['description'])) {
4602 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4603 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4604 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4607 Profile::publishUpdate($local_user);
4609 return api_account_verify_credentials($type);
4612 /// @TODO move to top of file or somewhere better
4613 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4617 * @param string $acl_string
4621 function check_acl_input($acl_string)
4623 if (empty($acl_string)) {
4627 $contact_not_found = false;
4629 // split <x><y><z> into array of cid's
4630 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4632 // check for each cid if it is available on server
4633 $cid_array = $array[0];
4634 foreach ($cid_array as $cid) {
4635 $cid = str_replace("<", "", $cid);
4636 $cid = str_replace(">", "", $cid);
4637 $condition = ['id' => $cid, 'uid' => api_user()];
4638 $contact_not_found |= !DBA::exists('contact', $condition);
4640 return $contact_not_found;
4644 * @param string $mediatype
4645 * @param array $media
4646 * @param string $type
4647 * @param string $album
4648 * @param string $allow_cid
4649 * @param string $deny_cid
4650 * @param string $allow_gid
4651 * @param string $deny_gid
4652 * @param string $desc
4653 * @param integer $profile
4654 * @param boolean $visibility
4655 * @param string $photo_id
4657 * @throws BadRequestException
4658 * @throws ForbiddenException
4659 * @throws ImagickException
4660 * @throws InternalServerErrorException
4661 * @throws NotFoundException
4662 * @throws UnauthorizedException
4664 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)
4672 if (is_array($media)) {
4673 if (is_array($media['tmp_name'])) {
4674 $src = $media['tmp_name'][0];
4676 $src = $media['tmp_name'];
4678 if (is_array($media['name'])) {
4679 $filename = basename($media['name'][0]);
4681 $filename = basename($media['name']);
4683 if (is_array($media['size'])) {
4684 $filesize = intval($media['size'][0]);
4686 $filesize = intval($media['size']);
4688 if (is_array($media['type'])) {
4689 $filetype = $media['type'][0];
4691 $filetype = $media['type'];
4695 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4698 "File upload src: " . $src . " - filename: " . $filename .
4699 " - size: " . $filesize . " - type: " . $filetype,
4703 // check if there was a php upload error
4704 if ($filesize == 0 && $media['error'] == 1) {
4705 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4707 // check against max upload size within Friendica instance
4708 $maximagesize = DI::config()->get('system', 'maximagesize');
4709 if ($maximagesize && ($filesize > $maximagesize)) {
4710 $formattedBytes = Strings::formatBytes($maximagesize);
4711 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4714 // create Photo instance with the data of the image
4715 $imagedata = @file_get_contents($src);
4716 $Image = new Image($imagedata, $filetype);
4717 if (!$Image->isValid()) {
4718 throw new InternalServerErrorException("unable to process image data");
4721 // check orientation of image
4722 $Image->orient($src);
4725 // check max length of images on server
4726 $max_length = DI::config()->get('system', 'max_image_length');
4728 $max_length = MAX_IMAGE_LENGTH;
4730 if ($max_length > 0) {
4731 $Image->scaleDown($max_length);
4732 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4734 $width = $Image->getWidth();
4735 $height = $Image->getHeight();
4737 // create a new resource-id if not already provided
4738 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4740 if ($mediatype == "photo") {
4741 // upload normal image (scales 0, 1, 2)
4742 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4744 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4746 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4748 if ($width > 640 || $height > 640) {
4749 $Image->scaleDown(640);
4750 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4752 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4756 if ($width > 320 || $height > 320) {
4757 $Image->scaleDown(320);
4758 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4760 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4763 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4764 } elseif ($mediatype == "profileimage") {
4765 // upload profile image (scales 4, 5, 6)
4766 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4768 if ($width > 300 || $height > 300) {
4769 $Image->scaleDown(300);
4770 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4772 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4776 if ($width > 80 || $height > 80) {
4777 $Image->scaleDown(80);
4778 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4780 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4784 if ($width > 48 || $height > 48) {
4785 $Image->scaleDown(48);
4786 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4788 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4791 $Image->__destruct();
4792 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4796 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4797 if ($photo_id == null && $mediatype == "photo") {
4798 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4800 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4801 return prepare_photo_data($type, false, $resource_id);
4803 throw new InternalServerErrorException("image upload failed");
4809 * @param string $hash
4810 * @param string $allow_cid
4811 * @param string $deny_cid
4812 * @param string $allow_gid
4813 * @param string $deny_gid
4814 * @param string $filetype
4815 * @param boolean $visibility
4816 * @throws InternalServerErrorException
4818 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4820 // get data about the api authenticated user
4821 $uri = Item::newURI(intval(api_user()));
4822 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4825 $arr['guid'] = System::createUUID();
4826 $arr['uid'] = intval(api_user());
4828 $arr['type'] = 'photo';
4830 $arr['resource-id'] = $hash;
4831 $arr['contact-id'] = $owner_record['id'];
4832 $arr['owner-name'] = $owner_record['name'];
4833 $arr['owner-link'] = $owner_record['url'];
4834 $arr['owner-avatar'] = $owner_record['thumb'];
4835 $arr['author-name'] = $owner_record['name'];
4836 $arr['author-link'] = $owner_record['url'];
4837 $arr['author-avatar'] = $owner_record['thumb'];
4839 $arr['allow_cid'] = $allow_cid;
4840 $arr['allow_gid'] = $allow_gid;
4841 $arr['deny_cid'] = $deny_cid;
4842 $arr['deny_gid'] = $deny_gid;
4843 $arr['visible'] = $visibility;
4847 'image/jpeg' => 'jpg',
4848 'image/png' => 'png',
4849 'image/gif' => 'gif'
4852 // adds link to the thumbnail scale photo
4853 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4854 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4857 // do the magic for storing the item in the database and trigger the federation to other contacts
4863 * @param string $type
4865 * @param string $photo_id
4868 * @throws BadRequestException
4869 * @throws ForbiddenException
4870 * @throws ImagickException
4871 * @throws InternalServerErrorException
4872 * @throws NotFoundException
4873 * @throws UnauthorizedException
4875 function prepare_photo_data($type, $scale, $photo_id)
4878 $user_info = api_get_user($a);
4880 if ($user_info === false) {
4881 throw new ForbiddenException();
4884 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4885 $data_sql = ($scale === false ? "" : "data, ");
4887 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4888 // clients needs to convert this in their way for further processing
4890 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4891 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4892 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4893 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4894 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4895 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4897 intval(local_user()),
4898 DBA::escape($photo_id),
4903 'image/jpeg' => 'jpg',
4904 'image/png' => 'png',
4905 'image/gif' => 'gif'
4908 // prepare output data for photo
4909 if (DBA::isResult($r)) {
4910 $data = ['photo' => $r[0]];
4911 $data['photo']['id'] = $data['photo']['resource-id'];
4912 if ($scale !== false) {
4913 $data['photo']['data'] = base64_encode($data['photo']['data']);
4915 unset($data['photo']['datasize']); //needed only with scale param
4917 if ($type == "xml") {
4918 $data['photo']['links'] = [];
4919 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4920 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4922 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4925 $data['photo']['link'] = [];
4926 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4928 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4929 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4933 unset($data['photo']['resource-id']);
4934 unset($data['photo']['minscale']);
4935 unset($data['photo']['maxscale']);
4937 throw new NotFoundException();
4940 // retrieve item element for getting activities (like, dislike etc.) related to photo
4941 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4942 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4943 if (!DBA::isResult($item)) {
4944 throw new NotFoundException('Photo-related item not found.');
4947 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4949 // retrieve comments on photo
4950 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4951 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4953 $statuses = Post::selectForUser(api_user(), [], $condition);
4955 // prepare output of comments
4956 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4958 if ($type == "xml") {
4960 foreach ($commentData as $comment) {
4961 $comments[$k++ . ":comment"] = $comment;
4964 foreach ($commentData as $comment) {
4965 $comments[] = $comment;
4968 $data['photo']['friendica_comments'] = $comments;
4970 // include info if rights on photo and rights on item are mismatching
4971 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4972 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4973 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4974 $data['photo']['deny_gid'] != $item['deny_gid'];
4975 $data['photo']['rights_mismatch'] = $rights_mismatch;
4982 * Similar as /mod/redir.php
4983 * redirect to 'url' after dfrn auth
4985 * Why this when there is mod/redir.php already?
4986 * This use api_user() and api_login()
4989 * c_url: url of remote contact to auth to
4990 * url: string, url to redirect after auth
4992 function api_friendica_remoteauth()
4994 $url = $_GET['url'] ?? '';
4995 $c_url = $_GET['c_url'] ?? '';
4997 if ($url === '' || $c_url === '') {
4998 throw new BadRequestException("Wrong parameters.");
5001 $c_url = Strings::normaliseLink($c_url);
5005 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5006 if (!DBA::isResult($contact)) {
5007 throw new BadRequestException("Unknown contact");
5010 $cid = $contact['id'];
5012 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5014 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5015 System::externalRedirect($url ?: $c_url);
5018 if ($contact['duplex'] && $contact['issued-id']) {
5019 $orig_id = $contact['issued-id'];
5020 $dfrn_id = '1:' . $orig_id;
5022 if ($contact['duplex'] && $contact['dfrn-id']) {
5023 $orig_id = $contact['dfrn-id'];
5024 $dfrn_id = '0:' . $orig_id;
5027 $sec = Strings::getRandomHex();
5029 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5030 'sec' => $sec, 'expire' => time() + 45];
5031 DBA::insert('profile_check', $fields);
5033 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5034 $dest = ($url ? '&destination_url=' . $url : '');
5036 System::externalRedirect(
5037 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5038 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5039 . '&type=profile&sec=' . $sec . $dest
5042 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5045 * Return an item with announcer data if it had been announced
5047 * @param array $item Item array
5048 * @return array Item array with announce data
5050 function api_get_announce($item)
5052 // Quit if the item already has got a different owner and author
5053 if ($item['owner-id'] != $item['author-id']) {
5057 // Don't change original or Diaspora posts
5058 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5062 // Quit if we do now the original author and it had been a post from a native network
5063 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5067 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5068 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5069 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5070 if (!DBA::isResult($announce)) {
5074 return array_merge($item, $announce);
5078 * Return the item shared, if the item contains only the [share] tag
5080 * @param array $item Sharer item
5081 * @return array|false Shared item or false if not a reshare
5082 * @throws ImagickException
5083 * @throws InternalServerErrorException
5085 function api_share_as_retweet(&$item)
5087 $body = trim($item["body"]);
5089 if (Diaspora::isReshare($body, false) === false) {
5090 if ($item['author-id'] == $item['owner-id']) {
5093 // Reshares from OStatus, ActivityPub and Twitter
5094 $reshared_item = $item;
5095 $reshared_item['owner-id'] = $reshared_item['author-id'];
5096 $reshared_item['owner-link'] = $reshared_item['author-link'];
5097 $reshared_item['owner-name'] = $reshared_item['author-name'];
5098 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5099 return $reshared_item;
5103 $reshared = Item::getShareArray($item);
5104 if (empty($reshared)) {
5108 $reshared_item = $item;
5110 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5114 if (!empty($reshared['comment'])) {
5115 $item['body'] = $reshared['comment'];
5118 $reshared_item["share-pre-body"] = $reshared['comment'];
5119 $reshared_item["body"] = $reshared['shared'];
5120 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5121 $reshared_item["author-name"] = $reshared['author'];
5122 $reshared_item["author-link"] = $reshared['profile'];
5123 $reshared_item["author-avatar"] = $reshared['avatar'];
5124 $reshared_item["plink"] = $reshared['link'] ?? '';
5125 $reshared_item["created"] = $reshared['posted'];
5126 $reshared_item["edited"] = $reshared['posted'];
5128 // Try to fetch the original item
5129 if (!empty($reshared['guid'])) {
5130 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5131 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5132 $condition = ['id' => $original_id];
5137 if (!empty($condition)) {
5138 $original_item = Post::selectFirst([], $condition);
5139 if (DBA::isResult($original_item)) {
5140 $reshared_item = array_merge($reshared_item, $original_item);
5144 return $reshared_item;
5149 * @param array $item
5154 function api_in_reply_to($item)
5158 $in_reply_to['status_id'] = null;
5159 $in_reply_to['user_id'] = null;
5160 $in_reply_to['status_id_str'] = null;
5161 $in_reply_to['user_id_str'] = null;
5162 $in_reply_to['screen_name'] = null;
5164 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5165 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5166 if (DBA::isResult($parent)) {
5167 $in_reply_to['status_id'] = intval($parent['id']);
5169 $in_reply_to['status_id'] = intval($item['parent']);
5172 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5174 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5175 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5177 if (DBA::isResult($parent)) {
5178 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5179 $in_reply_to['user_id'] = intval($parent['author-id']);
5180 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5183 // There seems to be situation, where both fields are identical:
5184 // https://github.com/friendica/friendica/issues/1010
5185 // This is a bugfix for that.
5186 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5187 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']]);
5188 $in_reply_to['status_id'] = null;
5189 $in_reply_to['user_id'] = null;
5190 $in_reply_to['status_id_str'] = null;
5191 $in_reply_to['user_id_str'] = null;
5192 $in_reply_to['screen_name'] = null;
5196 return $in_reply_to;
5201 * @param string $text
5204 * @throws InternalServerErrorException
5206 function api_clean_plain_items($text)
5208 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5210 $text = BBCode::cleanPictureLinks($text);
5211 $URLSearchString = "^\[\]";
5213 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5215 if ($include_entities == "true") {
5216 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5219 // Simplify "attachment" element
5220 $text = BBCode::removeAttachment($text);
5227 * @param array $contacts
5231 function api_best_nickname(&$contacts)
5235 if (count($contacts) == 0) {
5239 foreach ($contacts as $contact) {
5240 if ($contact["network"] == "") {
5241 $contact["network"] = "dfrn";
5242 $best_contact = [$contact];
5246 if (sizeof($best_contact) == 0) {
5247 foreach ($contacts as $contact) {
5248 if ($contact["network"] == "dfrn") {
5249 $best_contact = [$contact];
5254 if (sizeof($best_contact) == 0) {
5255 foreach ($contacts as $contact) {
5256 if ($contact["network"] == "dspr") {
5257 $best_contact = [$contact];
5262 if (sizeof($best_contact) == 0) {
5263 foreach ($contacts as $contact) {
5264 if ($contact["network"] == "stat") {
5265 $best_contact = [$contact];
5270 if (sizeof($best_contact) == 0) {
5271 foreach ($contacts as $contact) {
5272 if ($contact["network"] == "pump") {
5273 $best_contact = [$contact];
5278 if (sizeof($best_contact) == 0) {
5279 foreach ($contacts as $contact) {
5280 if ($contact["network"] == "twit") {
5281 $best_contact = [$contact];
5286 if (sizeof($best_contact) == 1) {
5287 $contacts = $best_contact;
5289 $contacts = [$contacts[0]];
5294 * Return all or a specified group of the user with the containing contacts.
5296 * @param string $type Return type (atom, rss, xml, json)
5298 * @return array|string
5299 * @throws BadRequestException
5300 * @throws ForbiddenException
5301 * @throws ImagickException
5302 * @throws InternalServerErrorException
5303 * @throws UnauthorizedException
5305 function api_friendica_group_show($type)
5309 if (api_user() === false) {
5310 throw new ForbiddenException();
5314 $user_info = api_get_user($a);
5315 $gid = $_REQUEST['gid'] ?? 0;
5316 $uid = $user_info['uid'];
5318 // get data of the specified group id or all groups if not specified
5321 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5325 // error message if specified gid is not in database
5326 if (!DBA::isResult($r)) {
5327 throw new BadRequestException("gid not available");
5331 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5336 // loop through all groups and retrieve all members for adding data in the user array
5338 foreach ($r as $rr) {
5339 $members = Contact\Group::getById($rr['id']);
5342 if ($type == "xml") {
5343 $user_element = "users";
5345 foreach ($members as $member) {
5346 $user = api_get_user($a, $member['nurl']);
5347 $users[$k++.":user"] = $user;
5350 $user_element = "user";
5351 foreach ($members as $member) {
5352 $user = api_get_user($a, $member['nurl']);
5356 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5358 return api_format_data("groups", $type, ['group' => $grps]);
5360 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5364 * Delete the specified group of the user.
5366 * @param string $type Return type (atom, rss, xml, json)
5368 * @return array|string
5369 * @throws BadRequestException
5370 * @throws ForbiddenException
5371 * @throws ImagickException
5372 * @throws InternalServerErrorException
5373 * @throws UnauthorizedException
5375 function api_friendica_group_delete($type)
5379 if (api_user() === false) {
5380 throw new ForbiddenException();
5384 $user_info = api_get_user($a);
5385 $gid = $_REQUEST['gid'] ?? 0;
5386 $name = $_REQUEST['name'] ?? '';
5387 $uid = $user_info['uid'];
5389 // error if no gid specified
5390 if ($gid == 0 || $name == "") {
5391 throw new BadRequestException('gid or name not specified');
5394 // get data of the specified group id
5396 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5400 // error message if specified gid is not in database
5401 if (!DBA::isResult($r)) {
5402 throw new BadRequestException('gid not available');
5405 // get data of the specified group id and group name
5407 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5412 // error message if specified gid is not in database
5413 if (!DBA::isResult($rname)) {
5414 throw new BadRequestException('wrong group name');
5418 $ret = Group::removeByName($uid, $name);
5421 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5422 return api_format_data("group_delete", $type, ['result' => $success]);
5424 throw new BadRequestException('other API error');
5427 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5432 * @param string $type Return type (atom, rss, xml, json)
5434 * @return array|string
5435 * @throws BadRequestException
5436 * @throws ForbiddenException
5437 * @throws ImagickException
5438 * @throws InternalServerErrorException
5439 * @throws UnauthorizedException
5440 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5442 function api_lists_destroy($type)
5446 if (api_user() === false) {
5447 throw new ForbiddenException();
5451 $user_info = api_get_user($a);
5452 $gid = $_REQUEST['list_id'] ?? 0;
5453 $uid = $user_info['uid'];
5455 // error if no gid specified
5457 throw new BadRequestException('gid not specified');
5460 // get data of the specified group id
5461 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5462 // error message if specified gid is not in database
5464 throw new BadRequestException('gid not available');
5467 if (Group::remove($gid)) {
5469 'name' => $group['name'],
5470 'id' => intval($gid),
5471 'id_str' => (string) $gid,
5472 'user' => $user_info
5475 return api_format_data("lists", $type, ['lists' => $list]);
5478 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5481 * Add a new group to the database.
5483 * @param string $name Group name
5484 * @param int $uid User ID
5485 * @param array $users List of users to add to the group
5488 * @throws BadRequestException
5490 function group_create($name, $uid, $users = [])
5492 // error if no name specified
5494 throw new BadRequestException('group name not specified');
5497 // get data of the specified group name
5499 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5503 // error message if specified group name already exists
5504 if (DBA::isResult($rname)) {
5505 throw new BadRequestException('group name already exists');
5508 // check if specified group name is a deleted group
5510 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5514 // error message if specified group name already exists
5515 if (DBA::isResult($rname)) {
5516 $reactivate_group = true;
5520 $ret = Group::create($uid, $name);
5522 $gid = Group::getIdByName($uid, $name);
5524 throw new BadRequestException('other API error');
5528 $erroraddinguser = false;
5530 foreach ($users as $user) {
5531 $cid = $user['cid'];
5532 // check if user really exists as contact
5534 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5538 if (count($contact)) {
5539 Group::addMember($gid, $cid);
5541 $erroraddinguser = true;
5542 $errorusers[] = $cid;
5546 // return success message incl. missing users in array
5547 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5549 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5553 * Create the specified group with the posted array of contacts.
5555 * @param string $type Return type (atom, rss, xml, json)
5557 * @return array|string
5558 * @throws BadRequestException
5559 * @throws ForbiddenException
5560 * @throws ImagickException
5561 * @throws InternalServerErrorException
5562 * @throws UnauthorizedException
5564 function api_friendica_group_create($type)
5568 if (api_user() === false) {
5569 throw new ForbiddenException();
5573 $user_info = api_get_user($a);
5574 $name = $_REQUEST['name'] ?? '';
5575 $uid = $user_info['uid'];
5576 $json = json_decode($_POST['json'], true);
5577 $users = $json['user'];
5579 $success = group_create($name, $uid, $users);
5581 return api_format_data("group_create", $type, ['result' => $success]);
5583 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5586 * Create a new group.
5588 * @param string $type Return type (atom, rss, xml, json)
5590 * @return array|string
5591 * @throws BadRequestException
5592 * @throws ForbiddenException
5593 * @throws ImagickException
5594 * @throws InternalServerErrorException
5595 * @throws UnauthorizedException
5596 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5598 function api_lists_create($type)
5602 if (api_user() === false) {
5603 throw new ForbiddenException();
5607 $user_info = api_get_user($a);
5608 $name = $_REQUEST['name'] ?? '';
5609 $uid = $user_info['uid'];
5611 $success = group_create($name, $uid);
5612 if ($success['success']) {
5614 'name' => $success['name'],
5615 'id' => intval($success['gid']),
5616 'id_str' => (string) $success['gid'],
5617 'user' => $user_info
5620 return api_format_data("lists", $type, ['lists'=>$grp]);
5623 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5626 * Update the specified group with the posted array of contacts.
5628 * @param string $type Return type (atom, rss, xml, json)
5630 * @return array|string
5631 * @throws BadRequestException
5632 * @throws ForbiddenException
5633 * @throws ImagickException
5634 * @throws InternalServerErrorException
5635 * @throws UnauthorizedException
5637 function api_friendica_group_update($type)
5641 if (api_user() === false) {
5642 throw new ForbiddenException();
5646 $user_info = api_get_user($a);
5647 $uid = $user_info['uid'];
5648 $gid = $_REQUEST['gid'] ?? 0;
5649 $name = $_REQUEST['name'] ?? '';
5650 $json = json_decode($_POST['json'], true);
5651 $users = $json['user'];
5653 // error if no name specified
5655 throw new BadRequestException('group name not specified');
5658 // error if no gid specified
5660 throw new BadRequestException('gid not specified');
5664 $members = Contact\Group::getById($gid);
5665 foreach ($members as $member) {
5666 $cid = $member['id'];
5667 foreach ($users as $user) {
5668 $found = ($user['cid'] == $cid ? true : false);
5670 if (!isset($found) || !$found) {
5671 Group::removeMemberByName($uid, $name, $cid);
5676 $erroraddinguser = false;
5678 foreach ($users as $user) {
5679 $cid = $user['cid'];
5680 // check if user really exists as contact
5682 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5687 if (count($contact)) {
5688 Group::addMember($gid, $cid);
5690 $erroraddinguser = true;
5691 $errorusers[] = $cid;
5695 // return success message incl. missing users in array
5696 $status = ($erroraddinguser ? "missing user" : "ok");
5697 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5698 return api_format_data("group_update", $type, ['result' => $success]);
5701 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5704 * Update information about a group.
5706 * @param string $type Return type (atom, rss, xml, json)
5708 * @return array|string
5709 * @throws BadRequestException
5710 * @throws ForbiddenException
5711 * @throws ImagickException
5712 * @throws InternalServerErrorException
5713 * @throws UnauthorizedException
5714 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5716 function api_lists_update($type)
5720 if (api_user() === false) {
5721 throw new ForbiddenException();
5725 $user_info = api_get_user($a);
5726 $gid = $_REQUEST['list_id'] ?? 0;
5727 $name = $_REQUEST['name'] ?? '';
5728 $uid = $user_info['uid'];
5730 // error if no gid specified
5732 throw new BadRequestException('gid not specified');
5735 // get data of the specified group id
5736 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5737 // error message if specified gid is not in database
5739 throw new BadRequestException('gid not available');
5742 if (Group::update($gid, $name)) {
5745 'id' => intval($gid),
5746 'id_str' => (string) $gid,
5747 'user' => $user_info
5750 return api_format_data("lists", $type, ['lists' => $list]);
5754 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5758 * @param string $type Return type (atom, rss, xml, json)
5760 * @return array|string
5761 * @throws BadRequestException
5762 * @throws ForbiddenException
5763 * @throws ImagickException
5764 * @throws InternalServerErrorException
5766 function api_friendica_activity($type)
5770 if (api_user() === false) {
5771 throw new ForbiddenException();
5773 $verb = strtolower($a->argv[3]);
5774 $verb = preg_replace("|\..*$|", "", $verb);
5776 $id = $_REQUEST['id'] ?? 0;
5778 $res = Item::performActivity($id, $verb, api_user());
5781 if ($type == "xml") {
5786 return api_format_data('ok', $type, ['ok' => $ok]);
5788 throw new BadRequestException('Error adding activity');
5792 /// @TODO move to top of file or somewhere better
5793 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5794 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5795 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5796 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5797 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5798 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5799 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5800 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5801 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5802 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5805 * Returns notifications
5807 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5809 * @return string|array
5810 * @throws ForbiddenException
5811 * @throws BadRequestException
5814 function api_friendica_notification($type)
5818 if (api_user() === false) {
5819 throw new ForbiddenException();
5822 throw new BadRequestException("Invalid argument count");
5825 $notifications = DI::notification()->getApiList(local_user());
5827 if ($type == "xml") {
5829 if (!empty($notifications)) {
5830 foreach ($notifications as $notification) {
5831 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5835 $result = $xmlnotes;
5836 } elseif (count($notifications) > 0) {
5837 $result = $notifications->getArrayCopy();
5842 return api_format_data("notes", $type, ['note' => $result]);
5846 * Set notification as seen and returns associated item (if possible)
5848 * POST request with 'id' param as notification id
5850 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5851 * @return string|array
5852 * @throws BadRequestException
5853 * @throws ForbiddenException
5854 * @throws ImagickException
5855 * @throws InternalServerErrorException
5856 * @throws UnauthorizedException
5858 function api_friendica_notification_seen($type)
5861 $user_info = api_get_user($a);
5863 if (api_user() === false || $user_info === false) {
5864 throw new ForbiddenException();
5866 if ($a->argc !== 4) {
5867 throw new BadRequestException("Invalid argument count");
5870 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5873 $notify = DI::notify()->getByID($id, api_user());
5874 DI::notify()->setSeen(true, $notify);
5876 if ($notify->otype === Notification\ObjectType::ITEM) {
5877 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5878 if (DBA::isResult($item)) {
5879 // we found the item, return it to the user
5880 $ret = api_format_items([$item], $user_info, false, $type);
5881 $data = ['status' => $ret];
5882 return api_format_data("status", $type, $data);
5884 // the item can't be found, but we set the notification as seen, so we count this as a success
5886 return api_format_data('result', $type, ['result' => "success"]);
5887 } catch (NotFoundException $e) {
5888 throw new BadRequestException('Invalid argument', $e);
5889 } catch (Exception $e) {
5890 throw new InternalServerErrorException('Internal Server exception', $e);
5894 /// @TODO move to top of file or somewhere better
5895 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5896 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5899 * update a direct_message to seen state
5901 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5902 * @return string|array (success result=ok, error result=error with error message)
5903 * @throws BadRequestException
5904 * @throws ForbiddenException
5905 * @throws ImagickException
5906 * @throws InternalServerErrorException
5907 * @throws UnauthorizedException
5909 function api_friendica_direct_messages_setseen($type)
5912 if (api_user() === false) {
5913 throw new ForbiddenException();
5917 $user_info = api_get_user($a);
5918 $uid = $user_info['uid'];
5919 $id = $_REQUEST['id'] ?? 0;
5921 // return error if id is zero
5923 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5924 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5927 // error message if specified id is not in database
5928 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5929 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5930 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5933 // update seen indicator
5934 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5938 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5939 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5941 $answer = ['result' => 'error', 'message' => 'unknown error'];
5942 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5946 /// @TODO move to top of file or somewhere better
5947 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5950 * search for direct_messages containing a searchstring through api
5952 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5953 * @param string $box
5954 * @return string|array (success: success=true if found and search_result contains found messages,
5955 * success=false if nothing was found, search_result='nothing found',
5956 * error: result=error with error message)
5957 * @throws BadRequestException
5958 * @throws ForbiddenException
5959 * @throws ImagickException
5960 * @throws InternalServerErrorException
5961 * @throws UnauthorizedException
5963 function api_friendica_direct_messages_search($type, $box = "")
5967 if (api_user() === false) {
5968 throw new ForbiddenException();
5972 $user_info = api_get_user($a);
5973 $searchstring = $_REQUEST['searchstring'] ?? '';
5974 $uid = $user_info['uid'];
5976 // error if no searchstring specified
5977 if ($searchstring == "") {
5978 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5979 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5982 // get data for the specified searchstring
5984 "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",
5986 DBA::escape('%'.$searchstring.'%')
5989 $profile_url = $user_info["url"];
5991 // message if nothing was found
5992 if (!DBA::isResult($r)) {
5993 $success = ['success' => false, 'search_results' => 'problem with query'];
5994 } elseif (count($r) == 0) {
5995 $success = ['success' => false, 'search_results' => 'nothing found'];
5998 foreach ($r as $item) {
5999 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6000 $recipient = $user_info;
6001 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6002 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6003 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6004 $sender = $user_info;
6007 if (isset($recipient) && isset($sender)) {
6008 $ret[] = api_format_messages($item, $recipient, $sender);
6011 $success = ['success' => true, 'search_results' => $ret];
6014 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6017 /// @TODO move to top of file or somewhere better
6018 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6021 * Returns a list of saved searches.
6023 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6025 * @param string $type Return format: json or xml
6027 * @return string|array
6030 function api_saved_searches_list($type)
6032 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6035 while ($term = DBA::fetch($terms)) {
6037 'created_at' => api_date(time()),
6038 'id' => intval($term['id']),
6039 'id_str' => $term['id'],
6040 'name' => $term['term'],
6042 'query' => $term['term']
6048 return api_format_data("terms", $type, ['terms' => $result]);
6051 /// @TODO move to top of file or somewhere better
6052 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6055 * Number of comments
6057 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6059 * @param object $data [Status, Status]
6063 function bindComments(&$data)
6065 if (count($data) == 0) {
6071 foreach ($data as $item) {
6072 $ids[] = $item['id'];
6075 $idStr = DBA::escape(implode(', ', $ids));
6076 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6077 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6078 $itemsData = DBA::toArray($items);
6080 foreach ($itemsData as $item) {
6081 $comments[$item['parent']] = $item['comments'];
6084 foreach ($data as $idx => $item) {
6086 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6091 @TODO Maybe open to implement?
6093 [pagename] => api/1.1/statuses/lookup.json
6094 [id] => 605138389168451584
6095 [include_cards] => true
6096 [cards_platform] => Android-12
6097 [include_entities] => true
6098 [include_my_retweet] => 1
6100 [include_reply_count] => true
6101 [include_descendent_reply_count] => true
6105 Not implemented by now:
6106 statuses/retweets_of_me
6111 account/update_location
6112 account/update_profile_background_image
6115 friendica/profile/update
6116 friendica/profile/create
6117 friendica/profile/delete
6119 Not implemented in status.net:
6120 statuses/retweeted_to_me
6121 statuses/retweeted_by_me
6122 direct_messages/destroy
6124 account/update_delivery_device
6125 notifications/follow