3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\Verb;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\TooManyRequestsException;
55 use Friendica\Network\HTTPException\UnauthorizedException;
56 use Friendica\Object\Image;
57 use Friendica\Protocol\Activity;
58 use Friendica\Protocol\Diaspora;
59 use Friendica\Security\BasicAuth;
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 $user = BasicAuth::getCurrentUserID(false);
107 * Get source name from API client
109 * Clients can send 'source' parameter to be show in post metadata
110 * as "sent via <source>".
111 * Some clients doesn't send a source param, we support ones we know
112 * (only Twidere, atm)
115 * Client source name, default to "api" if unset/unknown
118 function api_source()
120 $application = OAuth::getCurrentApplicationToken();
121 if (empty($application)) {
122 $application = BasicAuth::getCurrentApplicationToken();
124 return $application['name'] ?? 'api';
128 * Format date for API
130 * @param string $str Source date, as UTC
131 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
134 function api_date($str)
136 // Wed May 23 06:01:13 +0000 2007
137 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
141 * Register a function to be the endpoint for defined API path.
143 * @param string $path API URL path, relative to DI::baseUrl()
144 * @param string $func Function name to call on path request
145 * @param bool $auth API need logged user
146 * @param string $method HTTP method reqiured to call this endpoint.
147 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
148 * Default to API_METHOD_ANY
150 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
160 // Workaround for hotot
161 $path = str_replace("api/", "api/1.1/", $path);
171 * Log in user via OAuth1 or Simple HTTP Auth.
172 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
175 * @throws ForbiddenException
176 * @throws InternalServerErrorException
177 * @throws UnauthorizedException
178 * @hook 'authenticate'
180 * 'username' => username from login form
181 * 'password' => password from login form
182 * 'authenticated' => return status,
183 * 'user_record' => return authenticated user record
185 function api_login(App $a)
187 $_SESSION["allow_api"] = false;
189 // workaround for HTTP-auth in CGI mode
190 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
191 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
192 if (strlen($userpass)) {
193 list($name, $password) = explode(':', $userpass);
194 $_SERVER['PHP_AUTH_USER'] = $name;
195 $_SERVER['PHP_AUTH_PW'] = $password;
199 if (empty($_SERVER['PHP_AUTH_USER'])) {
200 // Try OAuth when no user is provided
201 $oauth1 = new FKOAuth1();
204 $request = OAuthRequest::from_request();
205 list($consumer, $token) = $oauth1->verify_request($request);
206 if (!is_null($token)) {
207 $oauth1->loginUser($token->uid);
208 Session::set('allow_api', true);
211 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
212 var_dump($consumer, $token);
214 } catch (Exception $e) {
215 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
218 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
219 header('WWW-Authenticate: Basic realm="Friendica"');
220 throw new UnauthorizedException("This API requires login");
223 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
224 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
226 // allow "user@server" login (but ignore 'server' part)
227 $at = strstr($user, "@", true);
232 // next code from mod/auth.php. needs better solution
236 'username' => trim($user),
237 'password' => trim($password),
238 'authenticated' => 0,
239 'user_record' => null,
243 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
244 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
245 * and later addons should not interfere with an earlier one that succeeded.
247 Hook::callAll('authenticate', $addon_auth);
249 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
250 $record = $addon_auth['user_record'];
252 $user_id = User::authenticate(trim($user), trim($password), true);
253 if ($user_id !== false) {
254 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
258 if (!DBA::isResult($record)) {
259 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
260 header('WWW-Authenticate: Basic realm="Friendica"');
261 //header('HTTP/1.0 401 Unauthorized');
262 //die('This api requires login');
263 throw new UnauthorizedException("This API requires login");
266 // Don't refresh the login date more often than twice a day to spare database writes
267 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
269 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
271 $_SESSION["allow_api"] = true;
273 Hook::callAll('logged_in', $a->user);
277 * Check HTTP method of called API
279 * API endpoints can define which HTTP method to accept when called.
280 * This function check the current HTTP method agains endpoint
283 * @param string $method Required methods, uppercase, separated by comma
286 function api_check_method($method)
288 if ($method == "*") {
291 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
295 * Main API entry point
297 * Authenticate user, call registered API function, set HTTP headers
300 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
301 * @return string|array API call result
304 function api_call(App $a, App\Arguments $args = null)
306 global $API, $called_api;
313 if (strpos($args->getCommand(), ".xml") > 0) {
316 if (strpos($args->getCommand(), ".json") > 0) {
319 if (strpos($args->getCommand(), ".rss") > 0) {
322 if (strpos($args->getCommand(), ".atom") > 0) {
327 foreach ($API as $p => $info) {
328 if (strpos($args->getCommand(), $p) === 0) {
329 if (!api_check_method($info['method'])) {
330 throw new MethodNotAllowedException();
333 $called_api = explode("/", $p);
335 if (!empty($info['auth']) && api_user() === false) {
337 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
340 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
342 $stamp = microtime(true);
343 $return = call_user_func($info['func'], $type);
344 $duration = floatval(microtime(true) - $stamp);
346 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
348 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
350 if (false === $return) {
352 * api function returned false withour throw an
353 * exception. This should not happend, throw a 500
355 throw new InternalServerErrorException();
360 header("Content-Type: text/xml");
363 header("Content-Type: application/json");
364 if (!empty($return)) {
365 $json = json_encode(end($return));
366 if (!empty($_GET['callback'])) {
367 $json = $_GET['callback'] . "(" . $json . ")";
373 header("Content-Type: application/rss+xml");
374 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
377 header("Content-Type: application/atom+xml");
378 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
385 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
386 throw new NotFoundException();
387 } catch (HTTPException $e) {
388 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
389 return api_error($type, $e, $args);
394 * Format API error string
396 * @param string $type Return type (xml, json, rss, as)
397 * @param object $e HTTPException Error object
398 * @param App\Arguments $args The App arguments
399 * @return string|array error message formatted as $type
401 function api_error($type, $e, App\Arguments $args)
403 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
404 /// @TODO: https://dev.twitter.com/overview/api/response-codes
406 $error = ["error" => $error,
407 "code" => $e->getCode() . " " . $e->httpdesc,
408 "request" => $args->getQueryString()];
410 $return = api_format_data('status', $type, ['status' => $error]);
414 header("Content-Type: text/xml");
417 header("Content-Type: application/json");
418 $return = json_encode($return);
421 header("Content-Type: application/rss+xml");
424 header("Content-Type: application/atom+xml");
432 * Set values for RSS template
435 * @param array $arr Array to be passed to template
436 * @param array $user_info User info
438 * @throws BadRequestException
439 * @throws ImagickException
440 * @throws InternalServerErrorException
441 * @throws UnauthorizedException
442 * @todo find proper type-hints
444 function api_rss_extra(App $a, $arr, $user_info)
446 if (is_null($user_info)) {
447 $user_info = api_get_user($a);
450 $arr['$user'] = $user_info;
452 'alternate' => $user_info['url'],
453 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
454 'base' => DI::baseUrl(),
455 'updated' => api_date(null),
456 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
457 'language' => $user_info['lang'],
458 'logo' => DI::baseUrl() . "/images/friendica-32.png",
466 * Unique contact to contact url.
468 * @param int $id Contact id
469 * @return bool|string
470 * Contact url or False if contact id is unknown
473 function api_unique_id_to_nurl($id)
475 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
477 if (DBA::isResult($r)) {
485 * Get user info array.
488 * @param int|string $contact_id Contact ID or URL
490 * @throws BadRequestException
491 * @throws ImagickException
492 * @throws InternalServerErrorException
493 * @throws UnauthorizedException
495 function api_get_user(App $a, $contact_id = null)
503 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
505 // Searching for contact URL
506 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
507 $user = DBA::escape(Strings::normaliseLink($contact_id));
509 $extra_query = "AND `contact`.`nurl` = '%s' ";
510 if (api_user() !== false) {
511 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
515 // Searching for contact id with uid = 0
516 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
517 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
520 throw new BadRequestException("User ID ".$contact_id." not found.");
524 $extra_query = "AND `contact`.`nurl` = '%s' ";
525 if (api_user() !== false) {
526 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
530 if (is_null($user) && !empty($_GET['user_id'])) {
531 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
534 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
538 $extra_query = "AND `contact`.`nurl` = '%s' ";
539 if (api_user() !== false) {
540 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
543 if (is_null($user) && !empty($_GET['screen_name'])) {
544 $user = DBA::escape($_GET['screen_name']);
545 $extra_query = "AND `contact`.`nick` = '%s' ";
546 if (api_user() !== false) {
547 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
551 if (is_null($user) && !empty($_GET['profileurl'])) {
552 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
553 $extra_query = "AND `contact`.`nurl` = '%s' ";
554 if (api_user() !== false) {
555 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
559 // $called_api is the API path exploded on / and is expected to have at least 2 elements
560 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
561 $argid = count($called_api);
562 if (!empty($a->argv[$argid])) {
563 $data = explode(".", $a->argv[$argid]);
564 if (count($data) > 1) {
565 list($user, $null) = $data;
568 if (is_numeric($user)) {
569 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
573 $extra_query = "AND `contact`.`nurl` = '%s' ";
574 if (api_user() !== false) {
575 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
579 $user = DBA::escape($user);
580 $extra_query = "AND `contact`.`nick` = '%s' ";
581 if (api_user() !== false) {
582 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
587 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
590 if (api_user() === false) {
595 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
599 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
603 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
609 // Selecting the id by priority, friendica first
610 if (is_array($uinfo)) {
611 api_best_nickname($uinfo);
614 // if the contact wasn't found, fetch it from the contacts with uid = 0
615 if (!DBA::isResult($uinfo)) {
617 throw new BadRequestException("User not found.");
620 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
622 if (DBA::isResult($contact)) {
624 'id' => $contact["id"],
625 'id_str' => (string) $contact["id"],
626 'name' => $contact["name"],
627 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
628 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
629 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
630 'profile_image_url' => $contact["micro"],
631 'profile_image_url_https' => $contact["micro"],
632 'profile_image_url_profile_size' => $contact["thumb"],
633 'profile_image_url_large' => $contact["photo"],
634 'url' => $contact["url"],
635 'protected' => false,
636 'followers_count' => 0,
637 'friends_count' => 0,
639 'created_at' => api_date($contact["created"]),
640 'favourites_count' => 0,
642 'time_zone' => 'UTC',
643 'geo_enabled' => false,
645 'statuses_count' => 0,
647 'contributors_enabled' => false,
648 'is_translator' => false,
649 'is_translation_enabled' => false,
650 'following' => false,
651 'follow_request_sent' => false,
652 'statusnet_blocking' => false,
653 'notifications' => false,
654 'statusnet_profile_url' => $contact["url"],
656 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
657 'pid' => Contact::getIdForURL($contact["url"], 0, false),
659 'network' => $contact["network"],
664 throw new BadRequestException("User ".$url." not found.");
668 if ($uinfo[0]['self']) {
669 if ($uinfo[0]['network'] == "") {
670 $uinfo[0]['network'] = Protocol::DFRN;
673 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
674 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
681 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
683 if (!empty($profile['about'])) {
684 $description = $profile['about'];
686 $description = $uinfo[0]["about"];
689 if (!empty($usr['default-location'])) {
690 $location = $usr['default-location'];
691 } elseif (!empty($uinfo[0]["location"])) {
692 $location = $uinfo[0]["location"];
694 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
698 'id' => intval($pcontact_id),
699 'id_str' => (string) intval($pcontact_id),
700 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
701 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
702 'location' => $location,
703 'description' => BBCode::toPlaintext($description ?? ''),
704 'profile_image_url' => $uinfo[0]['micro'],
705 'profile_image_url_https' => $uinfo[0]['micro'],
706 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
707 'profile_image_url_large' => $uinfo[0]["photo"],
708 'url' => $uinfo[0]['url'],
709 'protected' => false,
710 'followers_count' => intval($countfollowers),
711 'friends_count' => intval($countfriends),
713 'created_at' => api_date($uinfo[0]['created']),
714 'favourites_count' => intval($starred),
716 'time_zone' => 'UTC',
717 'geo_enabled' => false,
719 'statuses_count' => intval($countitems),
721 'contributors_enabled' => false,
722 'is_translator' => false,
723 'is_translation_enabled' => false,
724 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
725 'follow_request_sent' => false,
726 'statusnet_blocking' => false,
727 'notifications' => false,
729 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
730 'statusnet_profile_url' => $uinfo[0]['url'],
731 'uid' => intval($uinfo[0]['uid']),
732 'cid' => intval($uinfo[0]['cid']),
733 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
734 'self' => $uinfo[0]['self'],
735 'network' => $uinfo[0]['network'],
738 // If this is a local user and it uses Frio, we can get its color preferences.
740 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
741 if ($theme_info['theme'] === 'frio') {
742 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
744 if ($schema && ($schema != '---')) {
745 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
746 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
747 require_once $schemefile;
750 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
751 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
752 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
754 if (empty($nav_bg)) {
757 if (empty($link_color)) {
758 $link_color = "#6fdbe8";
760 if (empty($bgcolor)) {
761 $bgcolor = "#ededed";
764 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
765 $ret['profile_link_color'] = str_replace('#', '', $link_color);
766 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
774 * return api-formatted array for item's author and owner
777 * @param array $item item from db
778 * @return array(array:author, array:owner)
779 * @throws BadRequestException
780 * @throws ImagickException
781 * @throws InternalServerErrorException
782 * @throws UnauthorizedException
784 function api_item_get_user(App $a, $item)
786 $status_user = api_get_user($a, $item['author-id'] ?? null);
788 $author_user = $status_user;
790 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
792 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
793 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
795 $owner_user = $author_user;
798 return ([$status_user, $author_user, $owner_user]);
802 * walks recursively through an array with the possibility to change value and key
804 * @param array $array The array to walk through
805 * @param callable $callback The callback function
807 * @return array the transformed array
809 function api_walk_recursive(array &$array, callable $callback)
813 foreach ($array as $k => $v) {
815 if ($callback($v, $k)) {
816 $new_array[$k] = api_walk_recursive($v, $callback);
819 if ($callback($v, $k)) {
830 * Callback function to transform the array in an array that can be transformed in a XML file
832 * @param mixed $item Array item value
833 * @param string $key Array key
835 * @return boolean Should the array item be deleted?
837 function api_reformat_xml(&$item, &$key)
839 if (is_bool($item)) {
840 $item = ($item ? "true" : "false");
843 if (substr($key, 0, 10) == "statusnet_") {
844 $key = "statusnet:".substr($key, 10);
845 } elseif (substr($key, 0, 10) == "friendica_") {
846 $key = "friendica:".substr($key, 10);
848 /// @TODO old-lost code?
850 // $key = "default:".$key;
856 * Creates the XML from a JSON style array
858 * @param array $data JSON style array
859 * @param string $root_element Name of the root element
861 * @return string The XML data
863 function api_create_xml(array $data, $root_element)
865 $childname = key($data);
866 $data2 = array_pop($data);
868 $namespaces = ["" => "http://api.twitter.com",
869 "statusnet" => "http://status.net/schema/api/1/",
870 "friendica" => "http://friendi.ca/schema/api/1/",
871 "georss" => "http://www.georss.org/georss"];
873 /// @todo Auto detection of needed namespaces
874 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
878 if (is_array($data2)) {
880 api_walk_recursive($data2, "api_reformat_xml");
886 foreach ($data2 as $item) {
887 $data4[$i++ . ":" . $childname] = $item;
894 $data3 = [$root_element => $data2];
896 $ret = XML::fromArray($data3, $xml, false, $namespaces);
901 * Formats the data according to the data type
903 * @param string $root_element Name of the root element
904 * @param string $type Return type (atom, rss, xml, json)
905 * @param array $data JSON style array
907 * @return array|string (string|array) XML data or JSON data
909 function api_format_data($root_element, $type, $data)
915 $ret = api_create_xml($data, $root_element);
930 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
931 * returns a 401 status code and an error message if not.
933 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
935 * @param string $type Return type (atom, rss, xml, json)
936 * @return array|string
937 * @throws BadRequestException
938 * @throws ForbiddenException
939 * @throws ImagickException
940 * @throws InternalServerErrorException
941 * @throws UnauthorizedException
943 function api_account_verify_credentials($type)
947 if (api_user() === false) {
948 throw new ForbiddenException();
951 unset($_REQUEST["user_id"]);
952 unset($_GET["user_id"]);
954 unset($_REQUEST["screen_name"]);
955 unset($_GET["screen_name"]);
957 $skip_status = $_REQUEST['skip_status'] ?? false;
959 $user_info = api_get_user($a);
961 // "verified" isn't used here in the standard
962 unset($user_info["verified"]);
964 // - Adding last status
966 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
968 $user_info['status'] = api_format_item($item, $type);
972 // "uid" and "self" are only needed for some internal stuff, so remove it from here
973 unset($user_info["uid"]);
974 unset($user_info["self"]);
976 return api_format_data("user", $type, ['user' => $user_info]);
979 /// @TODO move to top of file or somewhere better
980 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
983 * Get data from $_POST or $_GET
988 function requestdata($k)
990 if (!empty($_POST[$k])) {
993 if (!empty($_GET[$k])) {
1000 * Deprecated function to upload media.
1002 * @param string $type Return type (atom, rss, xml, json)
1004 * @return array|string
1005 * @throws BadRequestException
1006 * @throws ForbiddenException
1007 * @throws ImagickException
1008 * @throws InternalServerErrorException
1009 * @throws UnauthorizedException
1011 function api_statuses_mediap($type)
1015 if (api_user() === false) {
1016 Logger::log('api_statuses_update: no user');
1017 throw new ForbiddenException();
1019 $user_info = api_get_user($a);
1021 $_REQUEST['profile_uid'] = api_user();
1022 $_REQUEST['api_source'] = true;
1023 $txt = requestdata('status') ?? '';
1024 /// @TODO old-lost code?
1025 //$txt = urldecode(requestdata('status'));
1027 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1028 $txt = HTML::toBBCodeVideo($txt);
1029 $config = HTMLPurifier_Config::createDefault();
1030 $config->set('Cache.DefinitionImpl', null);
1031 $purifier = new HTMLPurifier($config);
1032 $txt = $purifier->purify($txt);
1034 $txt = HTML::toBBCode($txt);
1036 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1038 $picture = wall_upload_post($a, false);
1040 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1041 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1042 $item_id = item_post($a);
1044 // output the post that we just posted.
1045 return api_status_show($type, $item_id);
1048 /// @TODO move this to top of file or somewhere better!
1049 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1052 * Updates the user’s current status.
1054 * @param string $type Return type (atom, rss, xml, json)
1056 * @return array|string
1057 * @throws BadRequestException
1058 * @throws ForbiddenException
1059 * @throws ImagickException
1060 * @throws InternalServerErrorException
1061 * @throws TooManyRequestsException
1062 * @throws UnauthorizedException
1063 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1065 function api_statuses_update($type)
1069 if (api_user() === false) {
1070 Logger::log('api_statuses_update: no user');
1071 throw new ForbiddenException();
1076 // convert $_POST array items to the form we use for web posts.
1077 if (requestdata('htmlstatus')) {
1078 $txt = requestdata('htmlstatus') ?? '';
1079 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1080 $txt = HTML::toBBCodeVideo($txt);
1082 $config = HTMLPurifier_Config::createDefault();
1083 $config->set('Cache.DefinitionImpl', null);
1085 $purifier = new HTMLPurifier($config);
1086 $txt = $purifier->purify($txt);
1088 $_REQUEST['body'] = HTML::toBBCode($txt);
1091 $_REQUEST['body'] = requestdata('status');
1094 $_REQUEST['title'] = requestdata('title');
1096 $parent = requestdata('in_reply_to_status_id');
1098 // Twidere sends "-1" if it is no reply ...
1099 if ($parent == -1) {
1103 if (ctype_digit($parent)) {
1104 $_REQUEST['parent'] = $parent;
1106 $_REQUEST['parent_uri'] = $parent;
1109 if (requestdata('lat') && requestdata('long')) {
1110 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1112 $_REQUEST['profile_uid'] = api_user();
1115 // Check for throttling (maximum posts per day, week and month)
1116 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1117 if ($throttle_day > 0) {
1118 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1120 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1121 $posts_day = Post::count($condition);
1123 if ($posts_day > $throttle_day) {
1124 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1125 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1126 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));
1130 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1131 if ($throttle_week > 0) {
1132 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1134 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1135 $posts_week = Post::count($condition);
1137 if ($posts_week > $throttle_week) {
1138 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1139 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1140 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));
1144 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1145 if ($throttle_month > 0) {
1146 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1148 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1149 $posts_month = Post::count($condition);
1151 if ($posts_month > $throttle_month) {
1152 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1153 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1154 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));
1159 if (requestdata('media_ids')) {
1160 $ids = explode(',', requestdata('media_ids') ?? '');
1161 } elseif (!empty($_FILES['media'])) {
1162 // upload the image if we have one
1163 $picture = wall_upload_post($a, false);
1164 if (is_array($picture)) {
1165 $ids[] = $picture['id'];
1173 foreach ($ids as $id) {
1174 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1175 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1176 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1177 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1179 if (!empty($media)) {
1180 $ressources[] = $media[0]['resource-id'];
1181 $phototypes = Images::supportedTypes();
1182 $ext = $phototypes[$media[0]['type']];
1184 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1185 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1186 'size' => $media[0]['datasize'],
1187 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1188 'description' => $media[0]['desc'] ?? '',
1189 'width' => $media[0]['width'],
1190 'height' => $media[0]['height']];
1192 if (count($media) > 1) {
1193 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1194 $attachment['preview-width'] = $media[1]['width'];
1195 $attachment['preview-height'] = $media[1]['height'];
1197 $attachments[] = $attachment;
1201 // We have to avoid that the post is rejected because of an empty body
1202 if (empty($_REQUEST['body'])) {
1203 $_REQUEST['body'] = '[hr]';
1207 if (!empty($attachments)) {
1208 $_REQUEST['attachments'] = $attachments;
1211 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1213 $_REQUEST['api_source'] = true;
1215 if (empty($_REQUEST['source'])) {
1216 $_REQUEST["source"] = api_source();
1219 // call out normal post function
1220 $item_id = item_post($a);
1222 if (!empty($ressources) && !empty($item_id)) {
1223 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1224 foreach ($ressources as $ressource) {
1225 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1229 // output the post that we just posted.
1230 return api_status_show($type, $item_id);
1233 /// @TODO move to top of file or somewhere better
1234 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1235 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1238 * Uploads an image to Friendica.
1241 * @throws BadRequestException
1242 * @throws ForbiddenException
1243 * @throws ImagickException
1244 * @throws InternalServerErrorException
1245 * @throws UnauthorizedException
1246 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1248 function api_media_upload()
1252 if (api_user() === false) {
1253 Logger::log('no user');
1254 throw new ForbiddenException();
1259 if (empty($_FILES['media'])) {
1261 throw new BadRequestException("No media.");
1264 $media = wall_upload_post($a, false);
1267 throw new InternalServerErrorException();
1271 $returndata["media_id"] = $media["id"];
1272 $returndata["media_id_string"] = (string)$media["id"];
1273 $returndata["size"] = $media["size"];
1274 $returndata["image"] = ["w" => $media["width"],
1275 "h" => $media["height"],
1276 "image_type" => $media["type"],
1277 "friendica_preview_url" => $media["preview"]];
1279 Logger::info('Media uploaded', ['return' => $returndata]);
1281 return ["media" => $returndata];
1284 /// @TODO move to top of file or somewhere better
1285 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1288 * Updates media meta data (picture descriptions)
1290 * @param string $type Return type (atom, rss, xml, json)
1292 * @return array|string
1293 * @throws BadRequestException
1294 * @throws ForbiddenException
1295 * @throws ImagickException
1296 * @throws InternalServerErrorException
1297 * @throws TooManyRequestsException
1298 * @throws UnauthorizedException
1299 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1301 * @todo Compare the corresponding Twitter function for correct return values
1303 function api_media_metadata_create($type)
1307 if (api_user() === false) {
1308 Logger::info('no user');
1309 throw new ForbiddenException();
1314 $postdata = Network::postdata();
1316 if (empty($postdata)) {
1317 throw new BadRequestException("No post data");
1320 $data = json_decode($postdata, true);
1322 throw new BadRequestException("Invalid post data");
1325 if (empty($data['media_id']) || empty($data['alt_text'])) {
1326 throw new BadRequestException("Missing post data values");
1329 if (empty($data['alt_text']['text'])) {
1330 throw new BadRequestException("No alt text.");
1333 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1335 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1336 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1337 if (!DBA::isResult($photo)) {
1338 throw new BadRequestException("Metadata not found.");
1341 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1344 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1347 * @param string $type Return format (atom, rss, xml, json)
1348 * @param int $item_id
1349 * @return array|string
1352 function api_status_show($type, $item_id)
1354 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1358 $item = api_get_item(['id' => $item_id]);
1359 if (!empty($item)) {
1360 $status_info = api_format_item($item, $type);
1363 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1365 return api_format_data('statuses', $type, ['status' => $status_info]);
1369 * Retrieves the last public status of the provided user info
1371 * @param int $ownerId Public contact Id
1372 * @param int $uid User Id
1376 function api_get_last_status($ownerId, $uid)
1379 'author-id'=> $ownerId,
1381 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1382 'private' => [Item::PUBLIC, Item::UNLISTED]
1385 $item = api_get_item($condition);
1391 * Retrieves a single item record based on the provided condition and converts it for API use.
1393 * @param array $condition Item table condition array
1397 function api_get_item(array $condition)
1399 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1405 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1406 * The author's most recent status will be returned inline.
1408 * @param string $type Return type (atom, rss, xml, json)
1409 * @return array|string
1410 * @throws BadRequestException
1411 * @throws ImagickException
1412 * @throws InternalServerErrorException
1413 * @throws UnauthorizedException
1414 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1416 function api_users_show($type)
1418 $a = Friendica\DI::app();
1420 $user_info = api_get_user($a);
1422 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1423 if (!empty($item)) {
1424 $user_info['status'] = api_format_item($item, $type);
1427 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1428 unset($user_info['uid']);
1429 unset($user_info['self']);
1431 return api_format_data('user', $type, ['user' => $user_info]);
1434 /// @TODO move to top of file or somewhere better
1435 api_register_func('api/users/show', 'api_users_show');
1436 api_register_func('api/externalprofile/show', 'api_users_show');
1439 * Search a public user account.
1441 * @param string $type Return type (atom, rss, xml, json)
1443 * @return array|string
1444 * @throws BadRequestException
1445 * @throws ImagickException
1446 * @throws InternalServerErrorException
1447 * @throws UnauthorizedException
1448 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1450 function api_users_search($type)
1456 if (!empty($_GET['q'])) {
1457 $contacts = Contact::selectToArray(
1460 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1468 if (DBA::isResult($contacts)) {
1470 foreach ($contacts as $contact) {
1471 $user_info = api_get_user($a, $contact['id']);
1473 if ($type == 'xml') {
1474 $userlist[$k++ . ':user'] = $user_info;
1476 $userlist[] = $user_info;
1479 $userlist = ['users' => $userlist];
1481 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1484 throw new BadRequestException('No search term specified.');
1487 return api_format_data('users', $type, $userlist);
1490 /// @TODO move to top of file or somewhere better
1491 api_register_func('api/users/search', 'api_users_search');
1494 * Return user objects
1496 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1498 * @param string $type Return format: json or xml
1500 * @return array|string
1501 * @throws BadRequestException
1502 * @throws ImagickException
1503 * @throws InternalServerErrorException
1504 * @throws NotFoundException if the results are empty.
1505 * @throws UnauthorizedException
1507 function api_users_lookup($type)
1511 if (!empty($_REQUEST['user_id'])) {
1512 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1514 $users[] = api_get_user(DI::app(), $id);
1519 if (empty($users)) {
1520 throw new NotFoundException;
1523 return api_format_data("users", $type, ['users' => $users]);
1526 /// @TODO move to top of file or somewhere better
1527 api_register_func('api/users/lookup', 'api_users_lookup', true);
1530 * Returns statuses that match a specified query.
1532 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1534 * @param string $type Return format: json, xml, atom, rss
1536 * @return array|string
1537 * @throws BadRequestException if the "q" parameter is missing.
1538 * @throws ForbiddenException
1539 * @throws ImagickException
1540 * @throws InternalServerErrorException
1541 * @throws UnauthorizedException
1543 function api_search($type)
1546 $user_info = api_get_user($a);
1548 if (api_user() === false || $user_info === false) {
1549 throw new ForbiddenException();
1552 if (empty($_REQUEST['q'])) {
1553 throw new BadRequestException('q parameter is required.');
1556 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1559 $data['status'] = [];
1561 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1562 if (!empty($_REQUEST['rpp'])) {
1563 $count = $_REQUEST['rpp'];
1564 } elseif (!empty($_REQUEST['count'])) {
1565 $count = $_REQUEST['count'];
1568 $since_id = $_REQUEST['since_id'] ?? 0;
1569 $max_id = $_REQUEST['max_id'] ?? 0;
1570 $page = $_REQUEST['page'] ?? 1;
1572 $start = max(0, ($page - 1) * $count);
1574 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1575 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1576 $searchTerm = $matches[1];
1577 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1578 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1580 while ($tag = DBA::fetch($tags)) {
1581 $uriids[] = $tag['uri-id'];
1585 if (empty($uriids)) {
1586 return api_format_data('statuses', $type, $data);
1589 $condition = ['uri-id' => $uriids];
1590 if ($exclude_replies) {
1591 $condition['gravity'] = GRAVITY_PARENT;
1594 $params['group_by'] = ['uri-id'];
1596 $condition = ["`id` > ?
1597 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1598 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1599 AND `body` LIKE CONCAT('%',?,'%')",
1600 $since_id, api_user(), $_REQUEST['q']];
1602 $condition[0] .= ' AND `id` <= ?';
1603 $condition[] = $max_id;
1609 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1610 $id = Item::fetchByLink($searchTerm, api_user());
1613 $id = Item::fetchByLink($searchTerm);
1617 $statuses = Post::select([], ['id' => $id]);
1621 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1623 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1625 bindComments($data['status']);
1627 return api_format_data('statuses', $type, $data);
1630 /// @TODO move to top of file or somewhere better
1631 api_register_func('api/search/tweets', 'api_search', true);
1632 api_register_func('api/search', 'api_search', true);
1635 * Returns the most recent statuses posted by the user and the users they follow.
1637 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1639 * @param string $type Return type (atom, rss, xml, json)
1641 * @return array|string
1642 * @throws BadRequestException
1643 * @throws ForbiddenException
1644 * @throws ImagickException
1645 * @throws InternalServerErrorException
1646 * @throws UnauthorizedException
1647 * @todo Optional parameters
1648 * @todo Add reply info
1650 function api_statuses_home_timeline($type)
1653 $user_info = api_get_user($a);
1655 if (api_user() === false || $user_info === false) {
1656 throw new ForbiddenException();
1659 unset($_REQUEST["user_id"]);
1660 unset($_GET["user_id"]);
1662 unset($_REQUEST["screen_name"]);
1663 unset($_GET["screen_name"]);
1665 // get last network messages
1668 $count = $_REQUEST['count'] ?? 20;
1669 $page = $_REQUEST['page']?? 0;
1670 $since_id = $_REQUEST['since_id'] ?? 0;
1671 $max_id = $_REQUEST['max_id'] ?? 0;
1672 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1673 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1675 $start = max(0, ($page - 1) * $count);
1677 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1678 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1681 $condition[0] .= " AND `id` <= ?";
1682 $condition[] = $max_id;
1684 if ($exclude_replies) {
1685 $condition[0] .= ' AND `gravity` = ?';
1686 $condition[] = GRAVITY_PARENT;
1688 if ($conversation_id > 0) {
1689 $condition[0] .= " AND `parent` = ?";
1690 $condition[] = $conversation_id;
1693 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1694 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1696 $items = Post::toArray($statuses);
1698 $ret = api_format_items($items, $user_info, false, $type);
1700 // Set all posts from the query above to seen
1702 foreach ($items as $item) {
1703 $idarray[] = intval($item["id"]);
1706 if (!empty($idarray)) {
1707 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1709 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1715 $data = ['status' => $ret];
1720 $data = api_rss_extra($a, $data, $user_info);
1724 return api_format_data("statuses", $type, $data);
1728 /// @TODO move to top of file or somewhere better
1729 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1730 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1733 * Returns the most recent statuses from public users.
1735 * @param string $type Return type (atom, rss, xml, json)
1737 * @return array|string
1738 * @throws BadRequestException
1739 * @throws ForbiddenException
1740 * @throws ImagickException
1741 * @throws InternalServerErrorException
1742 * @throws UnauthorizedException
1744 function api_statuses_public_timeline($type)
1747 $user_info = api_get_user($a);
1749 if (api_user() === false || $user_info === false) {
1750 throw new ForbiddenException();
1753 // get last network messages
1756 $count = $_REQUEST['count'] ?? 20;
1757 $page = $_REQUEST['page'] ?? 1;
1758 $since_id = $_REQUEST['since_id'] ?? 0;
1759 $max_id = $_REQUEST['max_id'] ?? 0;
1760 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1761 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1763 $start = max(0, ($page - 1) * $count);
1765 if ($exclude_replies && !$conversation_id) {
1766 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1767 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1770 $condition[0] .= " AND `id` <= ?";
1771 $condition[] = $max_id;
1774 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1775 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1777 $r = Post::toArray($statuses);
1779 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1780 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1783 $condition[0] .= " AND `id` <= ?";
1784 $condition[] = $max_id;
1786 if ($conversation_id > 0) {
1787 $condition[0] .= " AND `parent` = ?";
1788 $condition[] = $conversation_id;
1791 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1792 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1794 $r = Post::toArray($statuses);
1797 $ret = api_format_items($r, $user_info, false, $type);
1801 $data = ['status' => $ret];
1806 $data = api_rss_extra($a, $data, $user_info);
1810 return api_format_data("statuses", $type, $data);
1813 /// @TODO move to top of file or somewhere better
1814 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1817 * Returns the most recent statuses posted by users this node knows about.
1819 * @param string $type Return format: json, xml, atom, rss
1820 * @return array|string
1821 * @throws BadRequestException
1822 * @throws ForbiddenException
1823 * @throws ImagickException
1824 * @throws InternalServerErrorException
1825 * @throws UnauthorizedException
1827 function api_statuses_networkpublic_timeline($type)
1830 $user_info = api_get_user($a);
1832 if (api_user() === false || $user_info === false) {
1833 throw new ForbiddenException();
1836 $since_id = $_REQUEST['since_id'] ?? 0;
1837 $max_id = $_REQUEST['max_id'] ?? 0;
1840 $count = $_REQUEST['count'] ?? 20;
1841 $page = $_REQUEST['page'] ?? 1;
1843 $start = max(0, ($page - 1) * $count);
1845 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1846 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1849 $condition[0] .= " AND `id` <= ?";
1850 $condition[] = $max_id;
1853 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1854 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1856 $ret = api_format_items($statuses, $user_info, false, $type);
1860 $data = ['status' => $ret];
1865 $data = api_rss_extra($a, $data, $user_info);
1869 return api_format_data("statuses", $type, $data);
1872 /// @TODO move to top of file or somewhere better
1873 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1876 * Returns a single status.
1878 * @param string $type Return type (atom, rss, xml, json)
1880 * @return array|string
1881 * @throws BadRequestException
1882 * @throws ForbiddenException
1883 * @throws ImagickException
1884 * @throws InternalServerErrorException
1885 * @throws UnauthorizedException
1886 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1888 function api_statuses_show($type)
1891 $user_info = api_get_user($a);
1893 if (api_user() === false || $user_info === false) {
1894 throw new ForbiddenException();
1898 $id = intval($a->argv[3] ?? 0);
1901 $id = intval($_REQUEST['id'] ?? 0);
1906 $id = intval($a->argv[4] ?? 0);
1909 Logger::log('API: api_statuses_show: ' . $id);
1911 $conversation = !empty($_REQUEST['conversation']);
1913 // try to fetch the item for the local user - or the public item, if there is no local one
1914 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1915 if (!DBA::isResult($uri_item)) {
1916 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1919 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1920 if (!DBA::isResult($item)) {
1921 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1926 if ($conversation) {
1927 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1928 $params = ['order' => ['id' => true]];
1930 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1934 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1936 /// @TODO How about copying this to above methods which don't check $r ?
1937 if (!DBA::isResult($statuses)) {
1938 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1941 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1943 if ($conversation) {
1944 $data = ['status' => $ret];
1945 return api_format_data("statuses", $type, $data);
1947 $data = ['status' => $ret[0]];
1948 return api_format_data("status", $type, $data);
1952 /// @TODO move to top of file or somewhere better
1953 api_register_func('api/statuses/show', 'api_statuses_show', true);
1957 * @param string $type Return type (atom, rss, xml, json)
1959 * @return array|string
1960 * @throws BadRequestException
1961 * @throws ForbiddenException
1962 * @throws ImagickException
1963 * @throws InternalServerErrorException
1964 * @throws UnauthorizedException
1965 * @todo nothing to say?
1967 function api_conversation_show($type)
1970 $user_info = api_get_user($a);
1972 if (api_user() === false || $user_info === false) {
1973 throw new ForbiddenException();
1977 $id = intval($a->argv[3] ?? 0);
1978 $since_id = intval($_REQUEST['since_id'] ?? 0);
1979 $max_id = intval($_REQUEST['max_id'] ?? 0);
1980 $count = intval($_REQUEST['count'] ?? 20);
1981 $page = intval($_REQUEST['page'] ?? 1);
1983 $start = max(0, ($page - 1) * $count);
1986 $id = intval($_REQUEST['id'] ?? 0);
1991 $id = intval($a->argv[4] ?? 0);
1994 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1996 // try to fetch the item for the local user - or the public item, if there is no local one
1997 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1998 if (!DBA::isResult($item)) {
1999 throw new BadRequestException("There is no status with this id.");
2002 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2003 if (!DBA::isResult($parent)) {
2004 throw new BadRequestException("There is no status with this id.");
2007 $id = $parent['id'];
2009 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2010 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2013 $condition[0] .= " AND `id` <= ?";
2014 $condition[] = $max_id;
2017 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2018 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2020 if (!DBA::isResult($statuses)) {
2021 throw new BadRequestException("There is no status with id $id.");
2024 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2026 $data = ['status' => $ret];
2027 return api_format_data("statuses", $type, $data);
2030 /// @TODO move to top of file or somewhere better
2031 api_register_func('api/conversation/show', 'api_conversation_show', true);
2032 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2037 * @param string $type Return type (atom, rss, xml, json)
2039 * @return array|string
2040 * @throws BadRequestException
2041 * @throws ForbiddenException
2042 * @throws ImagickException
2043 * @throws InternalServerErrorException
2044 * @throws UnauthorizedException
2045 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2047 function api_statuses_repeat($type)
2053 if (api_user() === false) {
2054 throw new ForbiddenException();
2060 $id = intval($a->argv[3] ?? 0);
2063 $id = intval($_REQUEST['id'] ?? 0);
2068 $id = intval($a->argv[4] ?? 0);
2071 Logger::log('API: api_statuses_repeat: '.$id);
2073 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2074 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2076 if (DBA::isResult($item) && !empty($item['body'])) {
2077 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2078 if (!Item::performActivity($id, 'announce', local_user())) {
2079 throw new InternalServerErrorException();
2084 if (strpos($item['body'], "[/share]") !== false) {
2085 $pos = strpos($item['body'], "[share");
2086 $post = substr($item['body'], $pos);
2088 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2090 if (!empty($item['title'])) {
2091 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2094 $post .= $item['body'];
2095 $post .= "[/share]";
2097 $_REQUEST['body'] = $post;
2098 $_REQUEST['profile_uid'] = api_user();
2099 $_REQUEST['api_source'] = true;
2101 if (empty($_REQUEST['source'])) {
2102 $_REQUEST["source"] = api_source();
2105 $item_id = item_post($a);
2108 throw new ForbiddenException();
2111 // output the post that we just posted.
2113 return api_status_show($type, $item_id);
2116 /// @TODO move to top of file or somewhere better
2117 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2120 * Destroys a specific status.
2122 * @param string $type Return type (atom, rss, xml, json)
2124 * @return array|string
2125 * @throws BadRequestException
2126 * @throws ForbiddenException
2127 * @throws ImagickException
2128 * @throws InternalServerErrorException
2129 * @throws UnauthorizedException
2130 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2132 function api_statuses_destroy($type)
2136 if (api_user() === false) {
2137 throw new ForbiddenException();
2143 $id = intval($a->argv[3] ?? 0);
2146 $id = intval($_REQUEST['id'] ?? 0);
2151 $id = intval($a->argv[4] ?? 0);
2154 Logger::log('API: api_statuses_destroy: '.$id);
2156 $ret = api_statuses_show($type);
2158 Item::deleteForUser(['id' => $id], api_user());
2163 /// @TODO move to top of file or somewhere better
2164 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2167 * Returns the most recent mentions.
2169 * @param string $type Return type (atom, rss, xml, json)
2171 * @return array|string
2172 * @throws BadRequestException
2173 * @throws ForbiddenException
2174 * @throws ImagickException
2175 * @throws InternalServerErrorException
2176 * @throws UnauthorizedException
2177 * @see http://developer.twitter.com/doc/get/statuses/mentions
2179 function api_statuses_mentions($type)
2182 $user_info = api_get_user($a);
2184 if (api_user() === false || $user_info === false) {
2185 throw new ForbiddenException();
2188 unset($_REQUEST["user_id"]);
2189 unset($_GET["user_id"]);
2191 unset($_REQUEST["screen_name"]);
2192 unset($_GET["screen_name"]);
2194 // get last network messages
2197 $since_id = intval($_REQUEST['since_id'] ?? 0);
2198 $max_id = intval($_REQUEST['max_id'] ?? 0);
2199 $count = intval($_REQUEST['count'] ?? 20);
2200 $page = intval($_REQUEST['page'] ?? 1);
2202 $start = max(0, ($page - 1) * $count);
2204 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2205 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2206 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2208 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2209 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2210 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2211 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2212 api_user(), $since_id];
2215 $query .= " AND `id` <= ?";
2216 $condition[] = $max_id;
2219 array_unshift($condition, $query);
2221 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2222 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2224 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2226 $data = ['status' => $ret];
2231 $data = api_rss_extra($a, $data, $user_info);
2235 return api_format_data("statuses", $type, $data);
2238 /// @TODO move to top of file or somewhere better
2239 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2240 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2243 * Returns the most recent statuses posted by the user.
2245 * @param string $type Either "json" or "xml"
2246 * @return string|array
2247 * @throws BadRequestException
2248 * @throws ForbiddenException
2249 * @throws ImagickException
2250 * @throws InternalServerErrorException
2251 * @throws UnauthorizedException
2252 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2254 function api_statuses_user_timeline($type)
2257 $user_info = api_get_user($a);
2259 if (api_user() === false || $user_info === false) {
2260 throw new ForbiddenException();
2263 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2265 $since_id = $_REQUEST['since_id'] ?? 0;
2266 $max_id = $_REQUEST['max_id'] ?? 0;
2267 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2268 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2271 $count = $_REQUEST['count'] ?? 20;
2272 $page = $_REQUEST['page'] ?? 1;
2274 $start = max(0, ($page - 1) * $count);
2276 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2277 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2279 if ($user_info['self'] == 1) {
2280 $condition[0] .= ' AND `wall` ';
2283 if ($exclude_replies) {
2284 $condition[0] .= ' AND `gravity` = ?';
2285 $condition[] = GRAVITY_PARENT;
2288 if ($conversation_id > 0) {
2289 $condition[0] .= " AND `parent` = ?";
2290 $condition[] = $conversation_id;
2294 $condition[0] .= " AND `id` <= ?";
2295 $condition[] = $max_id;
2297 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2298 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2300 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2304 $data = ['status' => $ret];
2309 $data = api_rss_extra($a, $data, $user_info);
2313 return api_format_data("statuses", $type, $data);
2316 /// @TODO move to top of file or somewhere better
2317 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2320 * Star/unstar an item.
2321 * param: id : id of the item
2323 * @param string $type Return type (atom, rss, xml, json)
2325 * @return array|string
2326 * @throws BadRequestException
2327 * @throws ForbiddenException
2328 * @throws ImagickException
2329 * @throws InternalServerErrorException
2330 * @throws UnauthorizedException
2331 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2333 function api_favorites_create_destroy($type)
2337 if (api_user() === false) {
2338 throw new ForbiddenException();
2341 // for versioned api.
2342 /// @TODO We need a better global soluton
2343 $action_argv_id = 2;
2344 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2345 $action_argv_id = 3;
2348 if ($a->argc <= $action_argv_id) {
2349 throw new BadRequestException("Invalid request.");
2351 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2352 if ($a->argc == $action_argv_id + 2) {
2353 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2355 $itemid = intval($_REQUEST['id'] ?? 0);
2358 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2360 if (!DBA::isResult($item)) {
2361 throw new BadRequestException("Invalid item.");
2366 $item['starred'] = 1;
2369 $item['starred'] = 0;
2372 throw new BadRequestException("Invalid action ".$action);
2375 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2378 throw new InternalServerErrorException("DB error");
2382 $user_info = api_get_user($a);
2383 $rets = api_format_items([$item], $user_info, false, $type);
2386 $data = ['status' => $ret];
2391 $data = api_rss_extra($a, $data, $user_info);
2395 return api_format_data("status", $type, $data);
2398 /// @TODO move to top of file or somewhere better
2399 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2400 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2403 * Returns the most recent favorite statuses.
2405 * @param string $type Return type (atom, rss, xml, json)
2407 * @return string|array
2408 * @throws BadRequestException
2409 * @throws ForbiddenException
2410 * @throws ImagickException
2411 * @throws InternalServerErrorException
2412 * @throws UnauthorizedException
2414 function api_favorites($type)
2419 $user_info = api_get_user($a);
2421 if (api_user() === false || $user_info === false) {
2422 throw new ForbiddenException();
2427 // in friendica starred item are private
2428 // return favorites only for self
2429 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2431 if ($user_info['self'] == 0) {
2435 $since_id = $_REQUEST['since_id'] ?? 0;
2436 $max_id = $_REQUEST['max_id'] ?? 0;
2437 $count = $_GET['count'] ?? 20;
2438 $page = $_REQUEST['page'] ?? 1;
2440 $start = max(0, ($page - 1) * $count);
2442 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2443 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2445 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2448 $condition[0] .= " AND `id` <= ?";
2449 $condition[] = $max_id;
2452 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2454 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2459 $data = ['status' => $ret];
2464 $data = api_rss_extra($a, $data, $user_info);
2468 return api_format_data("statuses", $type, $data);
2471 /// @TODO move to top of file or somewhere better
2472 api_register_func('api/favorites', 'api_favorites', true);
2476 * @param array $item
2477 * @param array $recipient
2478 * @param array $sender
2481 * @throws InternalServerErrorException
2483 function api_format_messages($item, $recipient, $sender)
2485 // standard meta information
2487 'id' => $item['id'],
2488 'sender_id' => $sender['id'],
2490 'recipient_id' => $recipient['id'],
2491 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2492 'sender_screen_name' => $sender['screen_name'],
2493 'recipient_screen_name' => $recipient['screen_name'],
2494 'sender' => $sender,
2495 'recipient' => $recipient,
2497 'friendica_seen' => $item['seen'] ?? 0,
2498 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2501 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2502 if (isset($ret['sender']['uid'])) {
2503 unset($ret['sender']['uid']);
2505 if (isset($ret['sender']['self'])) {
2506 unset($ret['sender']['self']);
2508 if (isset($ret['recipient']['uid'])) {
2509 unset($ret['recipient']['uid']);
2511 if (isset($ret['recipient']['self'])) {
2512 unset($ret['recipient']['self']);
2515 //don't send title to regular StatusNET requests to avoid confusing these apps
2516 if (!empty($_GET['getText'])) {
2517 $ret['title'] = $item['title'];
2518 if ($_GET['getText'] == 'html') {
2519 $ret['text'] = BBCode::convert($item['body'], false);
2520 } elseif ($_GET['getText'] == 'plain') {
2521 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2524 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2526 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2527 unset($ret['sender']);
2528 unset($ret['recipient']);
2536 * @param array $item
2539 * @throws InternalServerErrorException
2541 function api_convert_item($item)
2543 $body = api_add_attachments_to_body($item);
2545 $entities = api_get_entitities($statustext, $body);
2547 // Add pictures to the attachment array and remove them from the body
2548 $attachments = api_get_attachments($body);
2550 // Workaround for ostatus messages where the title is identically to the body
2551 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2552 $statusbody = trim(HTML::toPlaintext($html, 0));
2554 // handle data: images
2555 $statusbody = api_format_items_embeded_images($item, $statusbody);
2557 $statustitle = trim($item['title']);
2559 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2560 $statustext = trim($statusbody);
2562 $statustext = trim($statustitle."\n\n".$statusbody);
2565 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2566 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2569 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2571 // Workaround for clients with limited HTML parser functionality
2572 $search = ["<br>", "<blockquote>", "</blockquote>",
2573 "<h1>", "</h1>", "<h2>", "</h2>",
2574 "<h3>", "</h3>", "<h4>", "</h4>",
2575 "<h5>", "</h5>", "<h6>", "</h6>"];
2576 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2577 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2578 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2579 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2580 $statushtml = str_replace($search, $replace, $statushtml);
2582 if ($item['title'] != "") {
2583 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2587 $oldtext = $statushtml;
2588 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2589 } while ($oldtext != $statushtml);
2591 if (substr($statushtml, 0, 4) == '<br>') {
2592 $statushtml = substr($statushtml, 4);
2595 if (substr($statushtml, 0, -4) == '<br>') {
2596 $statushtml = substr($statushtml, -4);
2599 // feeds without body should contain the link
2600 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2601 $statushtml .= BBCode::convert($item['plink']);
2605 "text" => $statustext,
2606 "html" => $statushtml,
2607 "attachments" => $attachments,
2608 "entities" => $entities
2613 * Add media attachments to the body
2615 * @param array $item
2616 * @return string body with added media
2618 function api_add_attachments_to_body(array $item)
2620 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2622 if (strpos($body, '[/img]') !== false) {
2626 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2627 if (!empty($media['preview'])) {
2628 $description = $media['description'] ?: $media['name'];
2629 if (!empty($description)) {
2630 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2632 $body .= "\n[img]" . $media['preview'] .'[/img]';
2642 * @param string $body
2645 * @throws InternalServerErrorException
2647 function api_get_attachments(&$body)
2649 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2650 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2652 $URLSearchString = "^\[\]";
2653 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2657 // Remove all embedded pictures, since they are added as attachments
2658 foreach ($images[0] as $orig) {
2659 $body = str_replace($orig, '', $body);
2664 foreach ($images[1] as $image) {
2665 $imagedata = Images::getInfoFromURLCached($image);
2668 if (DI::config()->get("system", "proxy_disabled")) {
2669 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2671 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2676 return $attachments;
2681 * @param string $text
2682 * @param string $bbcode
2685 * @throws InternalServerErrorException
2686 * @todo Links at the first character of the post
2688 function api_get_entitities(&$text, $bbcode)
2690 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2692 if ($include_entities != "true") {
2693 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2695 foreach ($images[1] as $image) {
2696 $replace = ProxyUtils::proxifyUrl($image, false);
2697 $text = str_replace($image, $replace, $text);
2702 $bbcode = BBCode::cleanPictureLinks($bbcode);
2704 // Change pure links in text to bbcode uris
2705 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2708 $entities["hashtags"] = [];
2709 $entities["symbols"] = [];
2710 $entities["urls"] = [];
2711 $entities["user_mentions"] = [];
2713 $URLSearchString = "^\[\]";
2715 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2717 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2718 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2720 $bbcode = preg_replace(
2721 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2722 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2725 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2727 $bbcode = preg_replace(
2728 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2729 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2732 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2734 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2736 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2739 foreach ($urls[1] as $id => $url) {
2740 $start = iconv_strpos($text, $url, 0, "UTF-8");
2741 if (!($start === false)) {
2742 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2746 ksort($ordered_urls);
2750 foreach ($ordered_urls as $url) {
2751 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2752 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2754 $display_url = $url["title"];
2756 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2757 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2759 if (strlen($display_url) > 26) {
2760 $display_url = substr($display_url, 0, 25)."…";
2764 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2765 if (!($start === false)) {
2766 $entities["urls"][] = ["url" => $url["url"],
2767 "expanded_url" => $url["url"],
2768 "display_url" => $display_url,
2769 "indices" => [$start, $start+strlen($url["url"])]];
2770 $offset = $start + 1;
2774 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2775 $ordered_images = [];
2776 foreach ($images as $image) {
2777 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2778 if (!($start === false)) {
2779 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2783 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2784 foreach ($images[1] as $image) {
2785 $start = iconv_strpos($text, $image, 0, "UTF-8");
2786 if (!($start === false)) {
2787 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2793 foreach ($ordered_images as $image) {
2794 $url = $image['url'];
2795 $ext_alt_text = $image['alt'];
2797 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2798 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2800 if (strlen($display_url) > 26) {
2801 $display_url = substr($display_url, 0, 25)."…";
2804 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2805 if (!($start === false)) {
2806 $image = Images::getInfoFromURLCached($url);
2808 // If image cache is activated, then use the following sizes:
2809 // thumb (150), small (340), medium (600) and large (1024)
2810 if (!DI::config()->get("system", "proxy_disabled")) {
2811 $media_url = ProxyUtils::proxifyUrl($url, false);
2814 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2815 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2817 if (($image[0] > 150) || ($image[1] > 150)) {
2818 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2819 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2822 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2823 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2825 if (($image[0] > 600) || ($image[1] > 600)) {
2826 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2827 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2831 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2834 $entities["media"][] = [
2836 "id_str" => (string) ($start + 1),
2837 "indices" => [$start, $start+strlen($url)],
2838 "media_url" => Strings::normaliseLink($media_url),
2839 "media_url_https" => $media_url,
2841 "display_url" => $display_url,
2842 "expanded_url" => $url,
2843 "ext_alt_text" => $ext_alt_text,
2847 $offset = $start + 1;
2856 * @param array $item
2857 * @param string $text
2861 function api_format_items_embeded_images($item, $text)
2863 $text = preg_replace_callback(
2864 '|data:image/([^;]+)[^=]+=*|m',
2865 function () use ($item) {
2866 return DI::baseUrl() . '/display/' . $item['guid'];
2874 * return <a href='url'>name</a> as array
2876 * @param string $txt text
2881 function api_contactlink_to_array($txt)
2884 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2885 if ($r && count($match)==3) {
2887 'name' => $match[2],
2901 * return likes, dislikes and attend status for item
2903 * @param array $item array
2904 * @param string $type Return type (atom, rss, xml, json)
2907 * likes => int count,
2908 * dislikes => int count
2909 * @throws BadRequestException
2910 * @throws ImagickException
2911 * @throws InternalServerErrorException
2912 * @throws UnauthorizedException
2914 function api_format_items_activities($item, $type = "json")
2923 'attendmaybe' => [],
2927 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2928 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2930 while ($parent_item = Post::fetch($ret)) {
2931 // not used as result should be structured like other user data
2932 //builtin_activity_puller($i, $activities);
2934 // get user data and add it to the array of the activity
2935 $user = api_get_user($a, $parent_item['author-id']);
2936 switch ($parent_item['verb']) {
2937 case Activity::LIKE:
2938 $activities['like'][] = $user;
2940 case Activity::DISLIKE:
2941 $activities['dislike'][] = $user;
2943 case Activity::ATTEND:
2944 $activities['attendyes'][] = $user;
2946 case Activity::ATTENDNO:
2947 $activities['attendno'][] = $user;
2949 case Activity::ATTENDMAYBE:
2950 $activities['attendmaybe'][] = $user;
2952 case Activity::ANNOUNCE:
2953 $activities['announce'][] = $user;
2962 if ($type == "xml") {
2963 $xml_activities = [];
2964 foreach ($activities as $k => $v) {
2965 // change xml element from "like" to "friendica:like"
2966 $xml_activities["friendica:".$k] = $v;
2967 // add user data into xml output
2969 foreach ($v as $user) {
2970 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2973 $activities = $xml_activities;
2980 * format items to be returned by api
2982 * @param array $items array of items
2983 * @param array $user_info
2984 * @param bool $filter_user filter items by $user_info
2985 * @param string $type Return type (atom, rss, xml, json)
2987 * @throws BadRequestException
2988 * @throws ImagickException
2989 * @throws InternalServerErrorException
2990 * @throws UnauthorizedException
2992 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2994 $a = Friendica\DI::app();
2998 if (empty($items)) {
3002 foreach ((array)$items as $item) {
3003 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3005 // Look if the posts are matching if they should be filtered by user id
3006 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3010 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3019 * @param array $item Item record
3020 * @param string $type Return format (atom, rss, xml, json)
3021 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3022 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3023 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3024 * @return array API-formatted status
3025 * @throws BadRequestException
3026 * @throws ImagickException
3027 * @throws InternalServerErrorException
3028 * @throws UnauthorizedException
3030 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3032 $a = Friendica\DI::app();
3034 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3035 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3038 localize_item($item);
3040 $in_reply_to = api_in_reply_to($item);
3042 $converted = api_convert_item($item);
3044 if ($type == "xml") {
3045 $geo = "georss:point";
3051 'text' => $converted["text"],
3052 'truncated' => false,
3053 'created_at'=> api_date($item['created']),
3054 'in_reply_to_status_id' => $in_reply_to['status_id'],
3055 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3056 'source' => (($item['app']) ? $item['app'] : 'web'),
3057 'id' => intval($item['id']),
3058 'id_str' => (string) intval($item['id']),
3059 'in_reply_to_user_id' => $in_reply_to['user_id'],
3060 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3061 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3063 'favorited' => $item['starred'] ? true : false,
3064 'user' => $status_user,
3065 'friendica_author' => $author_user,
3066 'friendica_owner' => $owner_user,
3067 'friendica_private' => $item['private'] == Item::PRIVATE,
3068 //'entities' => NULL,
3069 'statusnet_html' => $converted["html"],
3070 'statusnet_conversation_id' => $item['parent'],
3071 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3072 'friendica_activities' => api_format_items_activities($item, $type),
3073 'friendica_title' => $item['title'],
3074 'friendica_html' => BBCode::convert($item['body'], false)
3077 if (count($converted["attachments"]) > 0) {
3078 $status["attachments"] = $converted["attachments"];
3081 if (count($converted["entities"]) > 0) {
3082 $status["entities"] = $converted["entities"];
3085 if ($status["source"] == 'web') {
3086 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3087 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3088 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3091 $retweeted_item = [];
3094 if ($item['gravity'] == GRAVITY_PARENT) {
3095 $body = $item['body'];
3096 $retweeted_item = api_share_as_retweet($item);
3097 if ($body != $item['body']) {
3098 $quoted_item = $retweeted_item;
3099 $retweeted_item = [];
3103 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3104 $announce = api_get_announce($item);
3105 if (!empty($announce)) {
3106 $retweeted_item = $item;
3108 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3112 if (!empty($quoted_item)) {
3113 if ($quoted_item['id'] != $item['id']) {
3114 $quoted_status = api_format_item($quoted_item);
3115 /// @todo Only remove the attachments that are also contained in the quotes status
3116 unset($status['attachments']);
3117 unset($status['entities']);
3119 $conv_quoted = api_convert_item($quoted_item);
3120 $quoted_status = $status;
3121 unset($quoted_status['attachments']);
3122 unset($quoted_status['entities']);
3123 unset($quoted_status['statusnet_conversation_id']);
3124 $quoted_status['text'] = $conv_quoted['text'];
3125 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3127 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3128 } catch (BadRequestException $e) {
3129 // user not found. should be found?
3130 /// @todo check if the user should be always found
3131 $quoted_status["user"] = [];
3134 unset($quoted_status['friendica_author']);
3135 unset($quoted_status['friendica_owner']);
3136 unset($quoted_status['friendica_activities']);
3137 unset($quoted_status['friendica_private']);
3140 if (!empty($retweeted_item)) {
3141 $retweeted_status = $status;
3142 unset($retweeted_status['friendica_author']);
3143 unset($retweeted_status['friendica_owner']);
3144 unset($retweeted_status['friendica_activities']);
3145 unset($retweeted_status['friendica_private']);
3146 unset($retweeted_status['statusnet_conversation_id']);
3147 $status['user'] = $status['friendica_owner'];
3149 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3150 } catch (BadRequestException $e) {
3151 // user not found. should be found?
3152 /// @todo check if the user should be always found
3153 $retweeted_status["user"] = [];
3156 $rt_converted = api_convert_item($retweeted_item);
3158 $retweeted_status['text'] = $rt_converted["text"];
3159 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3160 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3162 if (!empty($quoted_status)) {
3163 $retweeted_status['quoted_status'] = $quoted_status;
3166 $status['friendica_author'] = $retweeted_status['user'];
3167 $status['retweeted_status'] = $retweeted_status;
3168 } elseif (!empty($quoted_status)) {
3169 $root_status = api_convert_item($item);
3171 $status['text'] = $root_status["text"];
3172 $status['statusnet_html'] = $root_status["html"];
3173 $status['quoted_status'] = $quoted_status;
3176 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3177 unset($status["user"]["uid"]);
3178 unset($status["user"]["self"]);
3180 if ($item["coord"] != "") {
3181 $coords = explode(' ', $item["coord"]);
3182 if (count($coords) == 2) {
3183 if ($type == "json") {
3184 $status["geo"] = ['type' => 'Point',
3185 'coordinates' => [(float) $coords[0],
3186 (float) $coords[1]]];
3187 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3188 $status["georss:point"] = $item["coord"];
3197 * Returns the remaining number of API requests available to the user before the API limit is reached.
3199 * @param string $type Return type (atom, rss, xml, json)
3201 * @return array|string
3204 function api_account_rate_limit_status($type)
3206 if ($type == "xml") {
3208 'remaining-hits' => '150',
3209 '@attributes' => ["type" => "integer"],
3210 'hourly-limit' => '150',
3211 '@attributes2' => ["type" => "integer"],
3212 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3213 '@attributes3' => ["type" => "datetime"],
3214 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3215 '@attributes4' => ["type" => "integer"],
3219 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3220 'remaining_hits' => '150',
3221 'hourly_limit' => '150',
3222 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3226 return api_format_data('hash', $type, ['hash' => $hash]);
3229 /// @TODO move to top of file or somewhere better
3230 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3233 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3235 * @param string $type Return type (atom, rss, xml, json)
3237 * @return array|string
3239 function api_help_test($type)
3241 if ($type == 'xml') {
3247 return api_format_data('ok', $type, ["ok" => $ok]);
3250 /// @TODO move to top of file or somewhere better
3251 api_register_func('api/help/test', 'api_help_test', false);
3254 * Returns all lists the user subscribes to.
3256 * @param string $type Return type (atom, rss, xml, json)
3258 * @return array|string
3259 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3261 function api_lists_list($type)
3264 /// @TODO $ret is not filled here?
3265 return api_format_data('lists', $type, ["lists_list" => $ret]);
3268 /// @TODO move to top of file or somewhere better
3269 api_register_func('api/lists/list', 'api_lists_list', true);
3270 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3273 * Returns all groups the user owns.
3275 * @param string $type Return type (atom, rss, xml, json)
3277 * @return array|string
3278 * @throws BadRequestException
3279 * @throws ForbiddenException
3280 * @throws ImagickException
3281 * @throws InternalServerErrorException
3282 * @throws UnauthorizedException
3283 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3285 function api_lists_ownerships($type)
3289 if (api_user() === false) {
3290 throw new ForbiddenException();
3294 $user_info = api_get_user($a);
3295 $uid = $user_info['uid'];
3297 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3299 // loop through all groups
3301 foreach ($groups as $group) {
3302 if ($group['visible']) {
3308 'name' => $group['name'],
3309 'id' => intval($group['id']),
3310 'id_str' => (string) $group['id'],
3311 'user' => $user_info,
3315 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3318 /// @TODO move to top of file or somewhere better
3319 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3322 * Returns recent statuses from users in the specified group.
3324 * @param string $type Return type (atom, rss, xml, json)
3326 * @return array|string
3327 * @throws BadRequestException
3328 * @throws ForbiddenException
3329 * @throws ImagickException
3330 * @throws InternalServerErrorException
3331 * @throws UnauthorizedException
3332 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3334 function api_lists_statuses($type)
3338 $user_info = api_get_user($a);
3339 if (api_user() === false || $user_info === false) {
3340 throw new ForbiddenException();
3343 unset($_REQUEST["user_id"]);
3344 unset($_GET["user_id"]);
3346 unset($_REQUEST["screen_name"]);
3347 unset($_GET["screen_name"]);
3349 if (empty($_REQUEST['list_id'])) {
3350 throw new BadRequestException('list_id not specified');
3354 $count = $_REQUEST['count'] ?? 20;
3355 $page = $_REQUEST['page'] ?? 1;
3356 $since_id = $_REQUEST['since_id'] ?? 0;
3357 $max_id = $_REQUEST['max_id'] ?? 0;
3358 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3359 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3361 $start = max(0, ($page - 1) * $count);
3363 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3364 $gids = array_column($groups, 'contact-id');
3365 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3366 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3369 $condition[0] .= " AND `id` <= ?";
3370 $condition[] = $max_id;
3372 if ($exclude_replies > 0) {
3373 $condition[0] .= ' AND `gravity` = ?';
3374 $condition[] = GRAVITY_PARENT;
3376 if ($conversation_id > 0) {
3377 $condition[0] .= " AND `parent` = ?";
3378 $condition[] = $conversation_id;
3381 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3382 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3384 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3386 $data = ['status' => $items];
3391 $data = api_rss_extra($a, $data, $user_info);
3395 return api_format_data("statuses", $type, $data);
3398 /// @TODO move to top of file or somewhere better
3399 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3402 * Returns either the friends of the follower list
3404 * Considers friends and followers lists to be private and won't return
3405 * anything if any user_id parameter is passed.
3407 * @param string $qtype Either "friends" or "followers"
3408 * @return boolean|array
3409 * @throws BadRequestException
3410 * @throws ForbiddenException
3411 * @throws ImagickException
3412 * @throws InternalServerErrorException
3413 * @throws UnauthorizedException
3415 function api_statuses_f($qtype)
3419 if (api_user() === false) {
3420 throw new ForbiddenException();
3424 $count = $_GET['count'] ?? 20;
3425 $page = $_GET['page'] ?? 1;
3427 $start = max(0, ($page - 1) * $count);
3429 $user_info = api_get_user($a);
3431 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3432 /* this is to stop Hotot to load friends multiple times
3433 * I'm not sure if I'm missing return something or
3434 * is a bug in hotot. Workaround, meantime
3438 return array('$users' => $ret);*/
3443 if ($qtype == 'friends') {
3444 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3445 } elseif ($qtype == 'followers') {
3446 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3449 // friends and followers only for self
3450 if ($user_info['self'] == 0) {
3451 $sql_extra = " AND false ";
3454 if ($qtype == 'blocks') {
3455 $sql_filter = 'AND `blocked` AND NOT `pending`';
3456 } elseif ($qtype == 'incoming') {
3457 $sql_filter = 'AND `pending`';
3459 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3477 foreach ($r as $cid) {
3478 $user = api_get_user($a, $cid['nurl']);
3479 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3480 unset($user["uid"]);
3481 unset($user["self"]);
3488 return ['user' => $ret];
3493 * Returns the list of friends of the provided user
3495 * @deprecated By Twitter API in favor of friends/list
3497 * @param string $type Either "json" or "xml"
3498 * @return boolean|string|array
3499 * @throws BadRequestException
3500 * @throws ForbiddenException
3502 function api_statuses_friends($type)
3504 $data = api_statuses_f("friends");
3505 if ($data === false) {
3508 return api_format_data("users", $type, $data);
3512 * Returns the list of followers of the provided user
3514 * @deprecated By Twitter API in favor of friends/list
3516 * @param string $type Either "json" or "xml"
3517 * @return boolean|string|array
3518 * @throws BadRequestException
3519 * @throws ForbiddenException
3521 function api_statuses_followers($type)
3523 $data = api_statuses_f("followers");
3524 if ($data === false) {
3527 return api_format_data("users", $type, $data);
3530 /// @TODO move to top of file or somewhere better
3531 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3532 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3535 * Returns the list of blocked users
3537 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3539 * @param string $type Either "json" or "xml"
3541 * @return boolean|string|array
3542 * @throws BadRequestException
3543 * @throws ForbiddenException
3545 function api_blocks_list($type)
3547 $data = api_statuses_f('blocks');
3548 if ($data === false) {
3551 return api_format_data("users", $type, $data);
3554 /// @TODO move to top of file or somewhere better
3555 api_register_func('api/blocks/list', 'api_blocks_list', true);
3558 * Returns the list of pending users IDs
3560 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3562 * @param string $type Either "json" or "xml"
3564 * @return boolean|string|array
3565 * @throws BadRequestException
3566 * @throws ForbiddenException
3568 function api_friendships_incoming($type)
3570 $data = api_statuses_f('incoming');
3571 if ($data === false) {
3576 foreach ($data['user'] as $user) {
3577 $ids[] = $user['id'];
3580 return api_format_data("ids", $type, ['id' => $ids]);
3583 /// @TODO move to top of file or somewhere better
3584 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3587 * Returns the instance's configuration information.
3589 * @param string $type Return type (atom, rss, xml, json)
3591 * @return array|string
3592 * @throws InternalServerErrorException
3594 function api_statusnet_config($type)
3596 $name = DI::config()->get('config', 'sitename');
3597 $server = DI::baseUrl()->getHostname();
3598 $logo = DI::baseUrl() . '/images/friendica-64.png';
3599 $email = DI::config()->get('config', 'admin_email');
3600 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3601 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3602 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3603 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3604 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3607 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3608 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3609 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3610 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3611 'shorturllength' => '30',
3613 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3614 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3615 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3616 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3621 return api_format_data('config', $type, ['config' => $config]);
3624 /// @TODO move to top of file or somewhere better
3625 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3626 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3630 * @param string $type Return type (atom, rss, xml, json)
3632 * @return array|string
3634 function api_statusnet_version($type)
3637 $fake_statusnet_version = "0.9.7";
3639 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3642 /// @TODO move to top of file or somewhere better
3643 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3644 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3647 * Sends a new direct message.
3649 * @param string $type Return type (atom, rss, xml, json)
3651 * @return array|string
3652 * @throws BadRequestException
3653 * @throws ForbiddenException
3654 * @throws ImagickException
3655 * @throws InternalServerErrorException
3656 * @throws NotFoundException
3657 * @throws UnauthorizedException
3658 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3660 function api_direct_messages_new($type)
3664 if (api_user() === false) {
3665 throw new ForbiddenException();
3668 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3672 $sender = api_get_user($a);
3675 if (!empty($_POST['screen_name'])) {
3677 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3679 DBA::escape($_POST['screen_name'])
3682 if (DBA::isResult($r)) {
3683 // Selecting the id by priority, friendica first
3684 api_best_nickname($r);
3686 $recipient = api_get_user($a, $r[0]['nurl']);
3689 $recipient = api_get_user($a, $_POST['user_id']);
3692 if (empty($recipient)) {
3693 throw new NotFoundException('Recipient not found');
3697 if (!empty($_REQUEST['replyto'])) {
3699 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3701 intval($_REQUEST['replyto'])
3703 $replyto = $r[0]['parent-uri'];
3704 $sub = $r[0]['title'];
3706 if (!empty($_REQUEST['title'])) {
3707 $sub = $_REQUEST['title'];
3709 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3713 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3716 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3717 $ret = api_format_messages($r[0], $recipient, $sender);
3719 $ret = ["error"=>$id];
3722 $data = ['direct_message'=>$ret];
3728 $data = api_rss_extra($a, $data, $sender);
3732 return api_format_data("direct-messages", $type, $data);
3735 /// @TODO move to top of file or somewhere better
3736 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3739 * delete a direct_message from mail table through api
3741 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3742 * @return string|array
3743 * @throws BadRequestException
3744 * @throws ForbiddenException
3745 * @throws ImagickException
3746 * @throws InternalServerErrorException
3747 * @throws UnauthorizedException
3748 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3750 function api_direct_messages_destroy($type)
3754 if (api_user() === false) {
3755 throw new ForbiddenException();
3759 $user_info = api_get_user($a);
3761 $id = $_REQUEST['id'] ?? 0;
3763 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3764 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3765 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3767 $uid = $user_info['uid'];
3768 // error if no id or parenturi specified (for clients posting parent-uri as well)
3769 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3770 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3771 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3774 // BadRequestException if no id specified (for clients using Twitter API)
3776 throw new BadRequestException('Message id not specified');
3779 // add parent-uri to sql command if specified by calling app
3780 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3782 // get data of the specified message id
3784 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3789 // error message if specified id is not in database
3790 if (!DBA::isResult($r)) {
3791 if ($verbose == "true") {
3792 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3793 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3795 /// @todo BadRequestException ok for Twitter API clients?
3796 throw new BadRequestException('message id not in database');
3801 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3806 if ($verbose == "true") {
3809 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3810 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3812 $answer = ['result' => 'error', 'message' => 'unknown error'];
3813 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3816 /// @todo return JSON data like Twitter API not yet implemented
3819 /// @TODO move to top of file or somewhere better
3820 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3825 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3826 * @return string|array
3827 * @throws BadRequestException
3828 * @throws ForbiddenException
3829 * @throws ImagickException
3830 * @throws InternalServerErrorException
3831 * @throws NotFoundException
3832 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3834 function api_friendships_destroy($type)
3838 if ($uid === false) {
3839 throw new ForbiddenException();
3842 $contact_id = $_REQUEST['user_id'] ?? 0;
3844 if (empty($contact_id)) {
3845 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3846 throw new BadRequestException("no user_id specified");
3849 // Get Contact by given id
3850 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3852 if(!DBA::isResult($contact)) {
3853 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3854 throw new NotFoundException("no contact found to given ID");
3857 $url = $contact["url"];
3859 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3860 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3861 Strings::normaliseLink($url), $url];
3862 $contact = DBA::selectFirst('contact', [], $condition);
3864 if (!DBA::isResult($contact)) {
3865 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3866 throw new NotFoundException("Not following Contact");
3869 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3870 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3871 throw new ExpectationFailedException("Not supported");
3874 $dissolve = ($contact['rel'] == Contact::SHARING);
3876 $owner = User::getOwnerDataById($uid);
3878 Contact::terminateFriendship($owner, $contact, $dissolve);
3881 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3882 throw new NotFoundException("Error Processing Request");
3885 // Sharing-only contacts get deleted as there no relationship any more
3887 Contact::remove($contact['id']);
3889 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3892 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3893 unset($contact["uid"]);
3894 unset($contact["self"]);
3896 // Set screen_name since Twidere requests it
3897 $contact["screen_name"] = $contact["nick"];
3899 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3901 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3905 * @param string $type Return type (atom, rss, xml, json)
3906 * @param string $box
3907 * @param string $verbose
3909 * @return array|string
3910 * @throws BadRequestException
3911 * @throws ForbiddenException
3912 * @throws ImagickException
3913 * @throws InternalServerErrorException
3914 * @throws UnauthorizedException
3916 function api_direct_messages_box($type, $box, $verbose)
3919 if (api_user() === false) {
3920 throw new ForbiddenException();
3923 $count = $_GET['count'] ?? 20;
3924 $page = $_REQUEST['page'] ?? 1;
3926 $since_id = $_REQUEST['since_id'] ?? 0;
3927 $max_id = $_REQUEST['max_id'] ?? 0;
3929 $user_id = $_REQUEST['user_id'] ?? '';
3930 $screen_name = $_REQUEST['screen_name'] ?? '';
3933 unset($_REQUEST["user_id"]);
3934 unset($_GET["user_id"]);
3936 unset($_REQUEST["screen_name"]);
3937 unset($_GET["screen_name"]);
3939 $user_info = api_get_user($a);
3940 if ($user_info === false) {
3941 throw new ForbiddenException();
3943 $profile_url = $user_info["url"];
3946 $start = max(0, ($page - 1) * $count);
3951 if ($box=="sentbox") {
3952 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3953 } elseif ($box == "conversation") {
3954 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3955 } elseif ($box == "all") {
3956 $sql_extra = "true";
3957 } elseif ($box == "inbox") {
3958 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3962 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3965 if ($user_id != "") {
3966 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3967 } elseif ($screen_name !="") {
3968 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3972 "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",
3978 if ($verbose == "true" && !DBA::isResult($r)) {
3979 $answer = ['result' => 'error', 'message' => 'no mails available'];
3980 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3984 foreach ($r as $item) {
3985 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3986 $recipient = $user_info;
3987 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3988 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3989 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3990 $sender = $user_info;
3993 if (isset($recipient) && isset($sender)) {
3994 $ret[] = api_format_messages($item, $recipient, $sender);
3999 $data = ['direct_message' => $ret];
4004 $data = api_rss_extra($a, $data, $user_info);
4008 return api_format_data("direct-messages", $type, $data);
4012 * Returns the most recent direct messages sent by the user.
4014 * @param string $type Return type (atom, rss, xml, json)
4016 * @return array|string
4017 * @throws BadRequestException
4018 * @throws ForbiddenException
4019 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4021 function api_direct_messages_sentbox($type)
4023 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4024 return api_direct_messages_box($type, "sentbox", $verbose);
4028 * Returns the most recent direct messages sent to the user.
4030 * @param string $type Return type (atom, rss, xml, json)
4032 * @return array|string
4033 * @throws BadRequestException
4034 * @throws ForbiddenException
4035 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4037 function api_direct_messages_inbox($type)
4039 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4040 return api_direct_messages_box($type, "inbox", $verbose);
4045 * @param string $type Return type (atom, rss, xml, json)
4047 * @return array|string
4048 * @throws BadRequestException
4049 * @throws ForbiddenException
4051 function api_direct_messages_all($type)
4053 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4054 return api_direct_messages_box($type, "all", $verbose);
4059 * @param string $type Return type (atom, rss, xml, json)
4061 * @return array|string
4062 * @throws BadRequestException
4063 * @throws ForbiddenException
4065 function api_direct_messages_conversation($type)
4067 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4068 return api_direct_messages_box($type, "conversation", $verbose);
4071 /// @TODO move to top of file or somewhere better
4072 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4073 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4074 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4075 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4078 * Returns an OAuth Request Token.
4080 * @see https://oauth.net/core/1.0/#auth_step1
4082 function api_oauth_request_token()
4084 $oauth1 = new FKOAuth1();
4086 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4087 } catch (Exception $e) {
4088 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4096 * Returns an OAuth Access Token.
4098 * @return array|string
4099 * @see https://oauth.net/core/1.0/#auth_step3
4101 function api_oauth_access_token()
4103 $oauth1 = new FKOAuth1();
4105 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4106 } catch (Exception $e) {
4107 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4114 /// @TODO move to top of file or somewhere better
4115 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4116 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4120 * delete a complete photoalbum with all containing photos from database through api
4122 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4123 * @return string|array
4124 * @throws BadRequestException
4125 * @throws ForbiddenException
4126 * @throws InternalServerErrorException
4128 function api_fr_photoalbum_delete($type)
4130 if (api_user() === false) {
4131 throw new ForbiddenException();
4134 $album = $_REQUEST['album'] ?? '';
4136 // we do not allow calls without album string
4138 throw new BadRequestException("no albumname specified");
4140 // check if album is existing
4142 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4143 if (!DBA::isResult($photos)) {
4144 throw new BadRequestException("album not available");
4147 $resourceIds = array_column($photos, 'resource-id');
4149 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4150 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4151 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4152 Item::deleteForUser($condition, api_user());
4154 // now let's delete all photos from the album
4155 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4157 // return success of deletion or error message
4159 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4160 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4162 throw new InternalServerErrorException("unknown error - deleting from database failed");
4167 * update the name of the album for all photos of an album
4169 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4170 * @return string|array
4171 * @throws BadRequestException
4172 * @throws ForbiddenException
4173 * @throws InternalServerErrorException
4175 function api_fr_photoalbum_update($type)
4177 if (api_user() === false) {
4178 throw new ForbiddenException();
4181 $album = $_REQUEST['album'] ?? '';
4182 $album_new = $_REQUEST['album_new'] ?? '';
4184 // we do not allow calls without album string
4186 throw new BadRequestException("no albumname specified");
4188 if ($album_new == "") {
4189 throw new BadRequestException("no new albumname specified");
4191 // check if album is existing
4192 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4193 throw new BadRequestException("album not available");
4195 // now let's update all photos to the albumname
4196 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4198 // return success of updating or error message
4200 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4201 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4203 throw new InternalServerErrorException("unknown error - updating in database failed");
4209 * list all photos of the authenticated user
4211 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4212 * @return string|array
4213 * @throws ForbiddenException
4214 * @throws InternalServerErrorException
4216 function api_fr_photos_list($type)
4218 if (api_user() === false) {
4219 throw new ForbiddenException();
4222 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4223 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4224 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4225 intval(local_user())
4228 'image/jpeg' => 'jpg',
4229 'image/png' => 'png',
4230 'image/gif' => 'gif'
4232 $data = ['photo'=>[]];
4233 if (DBA::isResult($r)) {
4234 foreach ($r as $rr) {
4236 $photo['id'] = $rr['resource-id'];
4237 $photo['album'] = $rr['album'];
4238 $photo['filename'] = $rr['filename'];
4239 $photo['type'] = $rr['type'];
4240 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4241 $photo['created'] = $rr['created'];
4242 $photo['edited'] = $rr['edited'];
4243 $photo['desc'] = $rr['desc'];
4245 if ($type == "xml") {
4246 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4248 $photo['thumb'] = $thumb;
4249 $data['photo'][] = $photo;
4253 return api_format_data("photos", $type, $data);
4257 * upload a new photo or change an existing photo
4259 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4260 * @return string|array
4261 * @throws BadRequestException
4262 * @throws ForbiddenException
4263 * @throws ImagickException
4264 * @throws InternalServerErrorException
4265 * @throws NotFoundException
4267 function api_fr_photo_create_update($type)
4269 if (api_user() === false) {
4270 throw new ForbiddenException();
4273 $photo_id = $_REQUEST['photo_id'] ?? null;
4274 $desc = $_REQUEST['desc'] ?? null;
4275 $album = $_REQUEST['album'] ?? null;
4276 $album_new = $_REQUEST['album_new'] ?? null;
4277 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4278 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4279 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4280 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4281 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4283 // do several checks on input parameters
4284 // we do not allow calls without album string
4285 if ($album == null) {
4286 throw new BadRequestException("no albumname specified");
4288 // if photo_id == null --> we are uploading a new photo
4289 if ($photo_id == null) {
4292 // error if no media posted in create-mode
4293 if (empty($_FILES['media'])) {
4295 throw new BadRequestException("no media data submitted");
4298 // album_new will be ignored in create-mode
4303 // check if photo is existing in databasei
4304 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4305 throw new BadRequestException("photo not available");
4309 // checks on acl strings provided by clients
4310 $acl_input_error = false;
4311 $acl_input_error |= check_acl_input($allow_cid);
4312 $acl_input_error |= check_acl_input($deny_cid);
4313 $acl_input_error |= check_acl_input($allow_gid);
4314 $acl_input_error |= check_acl_input($deny_gid);
4315 if ($acl_input_error) {
4316 throw new BadRequestException("acl data invalid");
4318 // now let's upload the new media in create-mode
4319 if ($mode == "create") {
4320 $media = $_FILES['media'];
4321 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4323 // return success of updating or error message
4324 if (!is_null($data)) {
4325 return api_format_data("photo_create", $type, $data);
4327 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4331 // now let's do the changes in update-mode
4332 if ($mode == "update") {
4333 $updated_fields = [];
4335 if (!is_null($desc)) {
4336 $updated_fields['desc'] = $desc;
4339 if (!is_null($album_new)) {
4340 $updated_fields['album'] = $album_new;
4343 if (!is_null($allow_cid)) {
4344 $allow_cid = trim($allow_cid);
4345 $updated_fields['allow_cid'] = $allow_cid;
4348 if (!is_null($deny_cid)) {
4349 $deny_cid = trim($deny_cid);
4350 $updated_fields['deny_cid'] = $deny_cid;
4353 if (!is_null($allow_gid)) {
4354 $allow_gid = trim($allow_gid);
4355 $updated_fields['allow_gid'] = $allow_gid;
4358 if (!is_null($deny_gid)) {
4359 $deny_gid = trim($deny_gid);
4360 $updated_fields['deny_gid'] = $deny_gid;
4364 if (count($updated_fields) > 0) {
4365 $nothingtodo = false;
4366 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4368 $nothingtodo = true;
4371 if (!empty($_FILES['media'])) {
4372 $nothingtodo = false;
4373 $media = $_FILES['media'];
4374 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4375 if (!is_null($data)) {
4376 return api_format_data("photo_update", $type, $data);
4380 // return success of updating or error message
4382 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4383 return api_format_data("photo_update", $type, ['$result' => $answer]);
4386 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4387 return api_format_data("photo_update", $type, ['$result' => $answer]);
4389 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4392 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4396 * delete a single photo from the database through api
4398 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4399 * @return string|array
4400 * @throws BadRequestException
4401 * @throws ForbiddenException
4402 * @throws InternalServerErrorException
4404 function api_fr_photo_delete($type)
4406 if (api_user() === false) {
4407 throw new ForbiddenException();
4411 $photo_id = $_REQUEST['photo_id'] ?? null;
4413 // do several checks on input parameters
4414 // we do not allow calls without photo id
4415 if ($photo_id == null) {
4416 throw new BadRequestException("no photo_id specified");
4419 // check if photo is existing in database
4420 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4421 throw new BadRequestException("photo not available");
4424 // now we can perform on the deletion of the photo
4425 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4427 // return success of deletion or error message
4429 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4430 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4431 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4432 Item::deleteForUser($condition, api_user());
4434 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4435 return api_format_data("photo_delete", $type, ['$result' => $result]);
4437 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4443 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4445 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4446 * @return string|array
4447 * @throws BadRequestException
4448 * @throws ForbiddenException
4449 * @throws InternalServerErrorException
4450 * @throws NotFoundException
4452 function api_fr_photo_detail($type)
4454 if (api_user() === false) {
4455 throw new ForbiddenException();
4457 if (empty($_REQUEST['photo_id'])) {
4458 throw new BadRequestException("No photo id.");
4461 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4462 $photo_id = $_REQUEST['photo_id'];
4464 // prepare json/xml output with data from database for the requested photo
4465 $data = prepare_photo_data($type, $scale, $photo_id);
4467 return api_format_data("photo_detail", $type, $data);
4472 * updates the profile image for the user (either a specified profile or the default profile)
4474 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4476 * @return string|array
4477 * @throws BadRequestException
4478 * @throws ForbiddenException
4479 * @throws ImagickException
4480 * @throws InternalServerErrorException
4481 * @throws NotFoundException
4482 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4484 function api_account_update_profile_image($type)
4486 if (api_user() === false) {
4487 throw new ForbiddenException();
4490 $profile_id = $_REQUEST['profile_id'] ?? 0;
4492 // error if image data is missing
4493 if (empty($_FILES['image'])) {
4494 throw new BadRequestException("no media data submitted");
4497 // check if specified profile id is valid
4498 if ($profile_id != 0) {
4499 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4500 // error message if specified profile id is not in database
4501 if (!DBA::isResult($profile)) {
4502 throw new BadRequestException("profile_id not available");
4504 $is_default_profile = $profile['is-default'];
4506 $is_default_profile = 1;
4509 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4511 if (!empty($_FILES['image'])) {
4512 $media = $_FILES['image'];
4513 } elseif (!empty($_FILES['media'])) {
4514 $media = $_FILES['media'];
4516 // save new profile image
4517 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4520 if (is_array($media['type'])) {
4521 $filetype = $media['type'][0];
4523 $filetype = $media['type'];
4525 if ($filetype == "image/jpeg") {
4527 } elseif ($filetype == "image/png") {
4530 throw new InternalServerErrorException('Unsupported filetype');
4533 // change specified profile or all profiles to the new resource-id
4534 if ($is_default_profile) {
4535 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4536 Photo::update(['profile' => false], $condition);
4538 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4539 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4540 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4543 Contact::updateSelfFromUserID(api_user(), true);
4545 // Update global directory in background
4546 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4547 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4548 Worker::add(PRIORITY_LOW, "Directory", $url);
4551 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4553 // output for client
4555 return api_account_verify_credentials($type);
4557 // SaveMediaToDatabase failed for some reason
4558 throw new InternalServerErrorException("image upload failed");
4562 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4563 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4564 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4565 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4566 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4567 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4568 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4569 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4570 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4573 * Update user profile
4575 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4577 * @return array|string
4578 * @throws BadRequestException
4579 * @throws ForbiddenException
4580 * @throws ImagickException
4581 * @throws InternalServerErrorException
4582 * @throws UnauthorizedException
4584 function api_account_update_profile($type)
4586 $local_user = api_user();
4587 $api_user = api_get_user(DI::app());
4589 if (!empty($_POST['name'])) {
4590 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4591 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4592 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4593 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4596 if (isset($_POST['description'])) {
4597 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4598 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4599 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4602 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4603 // Update global directory in background
4604 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4605 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4608 return api_account_verify_credentials($type);
4611 /// @TODO move to top of file or somewhere better
4612 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4616 * @param string $acl_string
4620 function check_acl_input($acl_string)
4622 if (empty($acl_string)) {
4626 $contact_not_found = false;
4628 // split <x><y><z> into array of cid's
4629 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4631 // check for each cid if it is available on server
4632 $cid_array = $array[0];
4633 foreach ($cid_array as $cid) {
4634 $cid = str_replace("<", "", $cid);
4635 $cid = str_replace(">", "", $cid);
4636 $condition = ['id' => $cid, 'uid' => api_user()];
4637 $contact_not_found |= !DBA::exists('contact', $condition);
4639 return $contact_not_found;
4643 * @param string $mediatype
4644 * @param array $media
4645 * @param string $type
4646 * @param string $album
4647 * @param string $allow_cid
4648 * @param string $deny_cid
4649 * @param string $allow_gid
4650 * @param string $deny_gid
4651 * @param string $desc
4652 * @param integer $profile
4653 * @param boolean $visibility
4654 * @param string $photo_id
4656 * @throws BadRequestException
4657 * @throws ForbiddenException
4658 * @throws ImagickException
4659 * @throws InternalServerErrorException
4660 * @throws NotFoundException
4661 * @throws UnauthorizedException
4663 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)
4671 if (is_array($media)) {
4672 if (is_array($media['tmp_name'])) {
4673 $src = $media['tmp_name'][0];
4675 $src = $media['tmp_name'];
4677 if (is_array($media['name'])) {
4678 $filename = basename($media['name'][0]);
4680 $filename = basename($media['name']);
4682 if (is_array($media['size'])) {
4683 $filesize = intval($media['size'][0]);
4685 $filesize = intval($media['size']);
4687 if (is_array($media['type'])) {
4688 $filetype = $media['type'][0];
4690 $filetype = $media['type'];
4694 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4697 "File upload src: " . $src . " - filename: " . $filename .
4698 " - size: " . $filesize . " - type: " . $filetype,
4702 // check if there was a php upload error
4703 if ($filesize == 0 && $media['error'] == 1) {
4704 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4706 // check against max upload size within Friendica instance
4707 $maximagesize = DI::config()->get('system', 'maximagesize');
4708 if ($maximagesize && ($filesize > $maximagesize)) {
4709 $formattedBytes = Strings::formatBytes($maximagesize);
4710 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4713 // create Photo instance with the data of the image
4714 $imagedata = @file_get_contents($src);
4715 $Image = new Image($imagedata, $filetype);
4716 if (!$Image->isValid()) {
4717 throw new InternalServerErrorException("unable to process image data");
4720 // check orientation of image
4721 $Image->orient($src);
4724 // check max length of images on server
4725 $max_length = DI::config()->get('system', 'max_image_length');
4727 $max_length = MAX_IMAGE_LENGTH;
4729 if ($max_length > 0) {
4730 $Image->scaleDown($max_length);
4731 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4733 $width = $Image->getWidth();
4734 $height = $Image->getHeight();
4736 // create a new resource-id if not already provided
4737 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4739 if ($mediatype == "photo") {
4740 // upload normal image (scales 0, 1, 2)
4741 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4743 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4745 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4747 if ($width > 640 || $height > 640) {
4748 $Image->scaleDown(640);
4749 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4751 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4755 if ($width > 320 || $height > 320) {
4756 $Image->scaleDown(320);
4757 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4759 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4762 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4763 } elseif ($mediatype == "profileimage") {
4764 // upload profile image (scales 4, 5, 6)
4765 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4767 if ($width > 300 || $height > 300) {
4768 $Image->scaleDown(300);
4769 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4771 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4775 if ($width > 80 || $height > 80) {
4776 $Image->scaleDown(80);
4777 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4779 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4783 if ($width > 48 || $height > 48) {
4784 $Image->scaleDown(48);
4785 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4787 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4790 $Image->__destruct();
4791 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4795 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4796 if ($photo_id == null && $mediatype == "photo") {
4797 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4799 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4800 return prepare_photo_data($type, false, $resource_id);
4802 throw new InternalServerErrorException("image upload failed");
4808 * @param string $hash
4809 * @param string $allow_cid
4810 * @param string $deny_cid
4811 * @param string $allow_gid
4812 * @param string $deny_gid
4813 * @param string $filetype
4814 * @param boolean $visibility
4815 * @throws InternalServerErrorException
4817 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4819 // get data about the api authenticated user
4820 $uri = Item::newURI(intval(api_user()));
4821 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4824 $arr['guid'] = System::createUUID();
4825 $arr['uid'] = intval(api_user());
4827 $arr['type'] = 'photo';
4829 $arr['resource-id'] = $hash;
4830 $arr['contact-id'] = $owner_record['id'];
4831 $arr['owner-name'] = $owner_record['name'];
4832 $arr['owner-link'] = $owner_record['url'];
4833 $arr['owner-avatar'] = $owner_record['thumb'];
4834 $arr['author-name'] = $owner_record['name'];
4835 $arr['author-link'] = $owner_record['url'];
4836 $arr['author-avatar'] = $owner_record['thumb'];
4838 $arr['allow_cid'] = $allow_cid;
4839 $arr['allow_gid'] = $allow_gid;
4840 $arr['deny_cid'] = $deny_cid;
4841 $arr['deny_gid'] = $deny_gid;
4842 $arr['visible'] = $visibility;
4846 'image/jpeg' => 'jpg',
4847 'image/png' => 'png',
4848 'image/gif' => 'gif'
4851 // adds link to the thumbnail scale photo
4852 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4853 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4856 // do the magic for storing the item in the database and trigger the federation to other contacts
4862 * @param string $type
4864 * @param string $photo_id
4867 * @throws BadRequestException
4868 * @throws ForbiddenException
4869 * @throws ImagickException
4870 * @throws InternalServerErrorException
4871 * @throws NotFoundException
4872 * @throws UnauthorizedException
4874 function prepare_photo_data($type, $scale, $photo_id)
4877 $user_info = api_get_user($a);
4879 if ($user_info === false) {
4880 throw new ForbiddenException();
4883 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4884 $data_sql = ($scale === false ? "" : "data, ");
4886 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4887 // clients needs to convert this in their way for further processing
4889 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4890 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4891 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4892 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4893 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4894 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4896 intval(local_user()),
4897 DBA::escape($photo_id),
4902 'image/jpeg' => 'jpg',
4903 'image/png' => 'png',
4904 'image/gif' => 'gif'
4907 // prepare output data for photo
4908 if (DBA::isResult($r)) {
4909 $data = ['photo' => $r[0]];
4910 $data['photo']['id'] = $data['photo']['resource-id'];
4911 if ($scale !== false) {
4912 $data['photo']['data'] = base64_encode($data['photo']['data']);
4914 unset($data['photo']['datasize']); //needed only with scale param
4916 if ($type == "xml") {
4917 $data['photo']['links'] = [];
4918 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4919 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4921 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4924 $data['photo']['link'] = [];
4925 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4927 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4928 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4932 unset($data['photo']['resource-id']);
4933 unset($data['photo']['minscale']);
4934 unset($data['photo']['maxscale']);
4936 throw new NotFoundException();
4939 // retrieve item element for getting activities (like, dislike etc.) related to photo
4940 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4941 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4942 if (!DBA::isResult($item)) {
4943 throw new NotFoundException('Photo-related item not found.');
4946 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4948 // retrieve comments on photo
4949 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4950 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4952 $statuses = Post::selectForUser(api_user(), [], $condition);
4954 // prepare output of comments
4955 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4957 if ($type == "xml") {
4959 foreach ($commentData as $comment) {
4960 $comments[$k++ . ":comment"] = $comment;
4963 foreach ($commentData as $comment) {
4964 $comments[] = $comment;
4967 $data['photo']['friendica_comments'] = $comments;
4969 // include info if rights on photo and rights on item are mismatching
4970 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4971 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4972 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4973 $data['photo']['deny_gid'] != $item['deny_gid'];
4974 $data['photo']['rights_mismatch'] = $rights_mismatch;
4981 * Similar as /mod/redir.php
4982 * redirect to 'url' after dfrn auth
4984 * Why this when there is mod/redir.php already?
4985 * This use api_user() and api_login()
4988 * c_url: url of remote contact to auth to
4989 * url: string, url to redirect after auth
4991 function api_friendica_remoteauth()
4993 $url = $_GET['url'] ?? '';
4994 $c_url = $_GET['c_url'] ?? '';
4996 if ($url === '' || $c_url === '') {
4997 throw new BadRequestException("Wrong parameters.");
5000 $c_url = Strings::normaliseLink($c_url);
5004 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5005 if (!DBA::isResult($contact)) {
5006 throw new BadRequestException("Unknown contact");
5009 $cid = $contact['id'];
5011 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5013 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5014 System::externalRedirect($url ?: $c_url);
5017 if ($contact['duplex'] && $contact['issued-id']) {
5018 $orig_id = $contact['issued-id'];
5019 $dfrn_id = '1:' . $orig_id;
5021 if ($contact['duplex'] && $contact['dfrn-id']) {
5022 $orig_id = $contact['dfrn-id'];
5023 $dfrn_id = '0:' . $orig_id;
5026 $sec = Strings::getRandomHex();
5028 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5029 'sec' => $sec, 'expire' => time() + 45];
5030 DBA::insert('profile_check', $fields);
5032 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5033 $dest = ($url ? '&destination_url=' . $url : '');
5035 System::externalRedirect(
5036 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5037 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5038 . '&type=profile&sec=' . $sec . $dest
5041 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5044 * Return an item with announcer data if it had been announced
5046 * @param array $item Item array
5047 * @return array Item array with announce data
5049 function api_get_announce($item)
5051 // Quit if the item already has got a different owner and author
5052 if ($item['owner-id'] != $item['author-id']) {
5056 // Don't change original or Diaspora posts
5057 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5061 // Quit if we do now the original author and it had been a post from a native network
5062 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5066 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5067 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5068 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5069 if (!DBA::isResult($announce)) {
5073 return array_merge($item, $announce);
5077 * Return the item shared, if the item contains only the [share] tag
5079 * @param array $item Sharer item
5080 * @return array|false Shared item or false if not a reshare
5081 * @throws ImagickException
5082 * @throws InternalServerErrorException
5084 function api_share_as_retweet(&$item)
5086 $body = trim($item["body"]);
5088 if (Diaspora::isReshare($body, false) === false) {
5089 if ($item['author-id'] == $item['owner-id']) {
5092 // Reshares from OStatus, ActivityPub and Twitter
5093 $reshared_item = $item;
5094 $reshared_item['owner-id'] = $reshared_item['author-id'];
5095 $reshared_item['owner-link'] = $reshared_item['author-link'];
5096 $reshared_item['owner-name'] = $reshared_item['author-name'];
5097 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5098 return $reshared_item;
5102 $reshared = Item::getShareArray($item);
5103 if (empty($reshared)) {
5107 $reshared_item = $item;
5109 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5113 if (!empty($reshared['comment'])) {
5114 $item['body'] = $reshared['comment'];
5117 $reshared_item["share-pre-body"] = $reshared['comment'];
5118 $reshared_item["body"] = $reshared['shared'];
5119 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5120 $reshared_item["author-name"] = $reshared['author'];
5121 $reshared_item["author-link"] = $reshared['profile'];
5122 $reshared_item["author-avatar"] = $reshared['avatar'];
5123 $reshared_item["plink"] = $reshared['link'] ?? '';
5124 $reshared_item["created"] = $reshared['posted'];
5125 $reshared_item["edited"] = $reshared['posted'];
5127 // Try to fetch the original item
5128 if (!empty($reshared['guid'])) {
5129 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5130 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5131 $condition = ['id' => $original_id];
5136 if (!empty($condition)) {
5137 $original_item = Post::selectFirst([], $condition);
5138 if (DBA::isResult($original_item)) {
5139 $reshared_item = array_merge($reshared_item, $original_item);
5143 return $reshared_item;
5148 * @param array $item
5153 function api_in_reply_to($item)
5157 $in_reply_to['status_id'] = null;
5158 $in_reply_to['user_id'] = null;
5159 $in_reply_to['status_id_str'] = null;
5160 $in_reply_to['user_id_str'] = null;
5161 $in_reply_to['screen_name'] = null;
5163 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5164 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5165 if (DBA::isResult($parent)) {
5166 $in_reply_to['status_id'] = intval($parent['id']);
5168 $in_reply_to['status_id'] = intval($item['parent']);
5171 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5173 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5174 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5176 if (DBA::isResult($parent)) {
5177 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5178 $in_reply_to['user_id'] = intval($parent['author-id']);
5179 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5182 // There seems to be situation, where both fields are identical:
5183 // https://github.com/friendica/friendica/issues/1010
5184 // This is a bugfix for that.
5185 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5186 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']]);
5187 $in_reply_to['status_id'] = null;
5188 $in_reply_to['user_id'] = null;
5189 $in_reply_to['status_id_str'] = null;
5190 $in_reply_to['user_id_str'] = null;
5191 $in_reply_to['screen_name'] = null;
5195 return $in_reply_to;
5200 * @param string $text
5203 * @throws InternalServerErrorException
5205 function api_clean_plain_items($text)
5207 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5209 $text = BBCode::cleanPictureLinks($text);
5210 $URLSearchString = "^\[\]";
5212 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5214 if ($include_entities == "true") {
5215 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5218 // Simplify "attachment" element
5219 $text = BBCode::removeAttachment($text);
5226 * @param array $contacts
5230 function api_best_nickname(&$contacts)
5234 if (count($contacts) == 0) {
5238 foreach ($contacts as $contact) {
5239 if ($contact["network"] == "") {
5240 $contact["network"] = "dfrn";
5241 $best_contact = [$contact];
5245 if (sizeof($best_contact) == 0) {
5246 foreach ($contacts as $contact) {
5247 if ($contact["network"] == "dfrn") {
5248 $best_contact = [$contact];
5253 if (sizeof($best_contact) == 0) {
5254 foreach ($contacts as $contact) {
5255 if ($contact["network"] == "dspr") {
5256 $best_contact = [$contact];
5261 if (sizeof($best_contact) == 0) {
5262 foreach ($contacts as $contact) {
5263 if ($contact["network"] == "stat") {
5264 $best_contact = [$contact];
5269 if (sizeof($best_contact) == 0) {
5270 foreach ($contacts as $contact) {
5271 if ($contact["network"] == "pump") {
5272 $best_contact = [$contact];
5277 if (sizeof($best_contact) == 0) {
5278 foreach ($contacts as $contact) {
5279 if ($contact["network"] == "twit") {
5280 $best_contact = [$contact];
5285 if (sizeof($best_contact) == 1) {
5286 $contacts = $best_contact;
5288 $contacts = [$contacts[0]];
5293 * Return all or a specified group of the user with the containing contacts.
5295 * @param string $type Return type (atom, rss, xml, json)
5297 * @return array|string
5298 * @throws BadRequestException
5299 * @throws ForbiddenException
5300 * @throws ImagickException
5301 * @throws InternalServerErrorException
5302 * @throws UnauthorizedException
5304 function api_friendica_group_show($type)
5308 if (api_user() === false) {
5309 throw new ForbiddenException();
5313 $user_info = api_get_user($a);
5314 $gid = $_REQUEST['gid'] ?? 0;
5315 $uid = $user_info['uid'];
5317 // get data of the specified group id or all groups if not specified
5320 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5324 // error message if specified gid is not in database
5325 if (!DBA::isResult($r)) {
5326 throw new BadRequestException("gid not available");
5330 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5335 // loop through all groups and retrieve all members for adding data in the user array
5337 foreach ($r as $rr) {
5338 $members = Contact\Group::getById($rr['id']);
5341 if ($type == "xml") {
5342 $user_element = "users";
5344 foreach ($members as $member) {
5345 $user = api_get_user($a, $member['nurl']);
5346 $users[$k++.":user"] = $user;
5349 $user_element = "user";
5350 foreach ($members as $member) {
5351 $user = api_get_user($a, $member['nurl']);
5355 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5357 return api_format_data("groups", $type, ['group' => $grps]);
5359 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5363 * Delete the specified group of the user.
5365 * @param string $type Return type (atom, rss, xml, json)
5367 * @return array|string
5368 * @throws BadRequestException
5369 * @throws ForbiddenException
5370 * @throws ImagickException
5371 * @throws InternalServerErrorException
5372 * @throws UnauthorizedException
5374 function api_friendica_group_delete($type)
5378 if (api_user() === false) {
5379 throw new ForbiddenException();
5383 $user_info = api_get_user($a);
5384 $gid = $_REQUEST['gid'] ?? 0;
5385 $name = $_REQUEST['name'] ?? '';
5386 $uid = $user_info['uid'];
5388 // error if no gid specified
5389 if ($gid == 0 || $name == "") {
5390 throw new BadRequestException('gid or name not specified');
5393 // get data of the specified group id
5395 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5399 // error message if specified gid is not in database
5400 if (!DBA::isResult($r)) {
5401 throw new BadRequestException('gid not available');
5404 // get data of the specified group id and group name
5406 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5411 // error message if specified gid is not in database
5412 if (!DBA::isResult($rname)) {
5413 throw new BadRequestException('wrong group name');
5417 $ret = Group::removeByName($uid, $name);
5420 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5421 return api_format_data("group_delete", $type, ['result' => $success]);
5423 throw new BadRequestException('other API error');
5426 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5431 * @param string $type Return type (atom, rss, xml, json)
5433 * @return array|string
5434 * @throws BadRequestException
5435 * @throws ForbiddenException
5436 * @throws ImagickException
5437 * @throws InternalServerErrorException
5438 * @throws UnauthorizedException
5439 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5441 function api_lists_destroy($type)
5445 if (api_user() === false) {
5446 throw new ForbiddenException();
5450 $user_info = api_get_user($a);
5451 $gid = $_REQUEST['list_id'] ?? 0;
5452 $uid = $user_info['uid'];
5454 // error if no gid specified
5456 throw new BadRequestException('gid not specified');
5459 // get data of the specified group id
5460 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5461 // error message if specified gid is not in database
5463 throw new BadRequestException('gid not available');
5466 if (Group::remove($gid)) {
5468 'name' => $group['name'],
5469 'id' => intval($gid),
5470 'id_str' => (string) $gid,
5471 'user' => $user_info
5474 return api_format_data("lists", $type, ['lists' => $list]);
5477 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5480 * Add a new group to the database.
5482 * @param string $name Group name
5483 * @param int $uid User ID
5484 * @param array $users List of users to add to the group
5487 * @throws BadRequestException
5489 function group_create($name, $uid, $users = [])
5491 // error if no name specified
5493 throw new BadRequestException('group name not specified');
5496 // get data of the specified group name
5498 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5502 // error message if specified group name already exists
5503 if (DBA::isResult($rname)) {
5504 throw new BadRequestException('group name already exists');
5507 // check if specified group name is a deleted group
5509 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5513 // error message if specified group name already exists
5514 if (DBA::isResult($rname)) {
5515 $reactivate_group = true;
5519 $ret = Group::create($uid, $name);
5521 $gid = Group::getIdByName($uid, $name);
5523 throw new BadRequestException('other API error');
5527 $erroraddinguser = false;
5529 foreach ($users as $user) {
5530 $cid = $user['cid'];
5531 // check if user really exists as contact
5533 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5537 if (count($contact)) {
5538 Group::addMember($gid, $cid);
5540 $erroraddinguser = true;
5541 $errorusers[] = $cid;
5545 // return success message incl. missing users in array
5546 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5548 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5552 * Create the specified group with the posted array of contacts.
5554 * @param string $type Return type (atom, rss, xml, json)
5556 * @return array|string
5557 * @throws BadRequestException
5558 * @throws ForbiddenException
5559 * @throws ImagickException
5560 * @throws InternalServerErrorException
5561 * @throws UnauthorizedException
5563 function api_friendica_group_create($type)
5567 if (api_user() === false) {
5568 throw new ForbiddenException();
5572 $user_info = api_get_user($a);
5573 $name = $_REQUEST['name'] ?? '';
5574 $uid = $user_info['uid'];
5575 $json = json_decode($_POST['json'], true);
5576 $users = $json['user'];
5578 $success = group_create($name, $uid, $users);
5580 return api_format_data("group_create", $type, ['result' => $success]);
5582 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5585 * Create a new group.
5587 * @param string $type Return type (atom, rss, xml, json)
5589 * @return array|string
5590 * @throws BadRequestException
5591 * @throws ForbiddenException
5592 * @throws ImagickException
5593 * @throws InternalServerErrorException
5594 * @throws UnauthorizedException
5595 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5597 function api_lists_create($type)
5601 if (api_user() === false) {
5602 throw new ForbiddenException();
5606 $user_info = api_get_user($a);
5607 $name = $_REQUEST['name'] ?? '';
5608 $uid = $user_info['uid'];
5610 $success = group_create($name, $uid);
5611 if ($success['success']) {
5613 'name' => $success['name'],
5614 'id' => intval($success['gid']),
5615 'id_str' => (string) $success['gid'],
5616 'user' => $user_info
5619 return api_format_data("lists", $type, ['lists'=>$grp]);
5622 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5625 * Update the specified group with the posted array of contacts.
5627 * @param string $type Return type (atom, rss, xml, json)
5629 * @return array|string
5630 * @throws BadRequestException
5631 * @throws ForbiddenException
5632 * @throws ImagickException
5633 * @throws InternalServerErrorException
5634 * @throws UnauthorizedException
5636 function api_friendica_group_update($type)
5640 if (api_user() === false) {
5641 throw new ForbiddenException();
5645 $user_info = api_get_user($a);
5646 $uid = $user_info['uid'];
5647 $gid = $_REQUEST['gid'] ?? 0;
5648 $name = $_REQUEST['name'] ?? '';
5649 $json = json_decode($_POST['json'], true);
5650 $users = $json['user'];
5652 // error if no name specified
5654 throw new BadRequestException('group name not specified');
5657 // error if no gid specified
5659 throw new BadRequestException('gid not specified');
5663 $members = Contact\Group::getById($gid);
5664 foreach ($members as $member) {
5665 $cid = $member['id'];
5666 foreach ($users as $user) {
5667 $found = ($user['cid'] == $cid ? true : false);
5669 if (!isset($found) || !$found) {
5670 Group::removeMemberByName($uid, $name, $cid);
5675 $erroraddinguser = false;
5677 foreach ($users as $user) {
5678 $cid = $user['cid'];
5679 // check if user really exists as contact
5681 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5686 if (count($contact)) {
5687 Group::addMember($gid, $cid);
5689 $erroraddinguser = true;
5690 $errorusers[] = $cid;
5694 // return success message incl. missing users in array
5695 $status = ($erroraddinguser ? "missing user" : "ok");
5696 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5697 return api_format_data("group_update", $type, ['result' => $success]);
5700 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5703 * Update information about a group.
5705 * @param string $type Return type (atom, rss, xml, json)
5707 * @return array|string
5708 * @throws BadRequestException
5709 * @throws ForbiddenException
5710 * @throws ImagickException
5711 * @throws InternalServerErrorException
5712 * @throws UnauthorizedException
5713 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5715 function api_lists_update($type)
5719 if (api_user() === false) {
5720 throw new ForbiddenException();
5724 $user_info = api_get_user($a);
5725 $gid = $_REQUEST['list_id'] ?? 0;
5726 $name = $_REQUEST['name'] ?? '';
5727 $uid = $user_info['uid'];
5729 // error if no gid specified
5731 throw new BadRequestException('gid not specified');
5734 // get data of the specified group id
5735 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5736 // error message if specified gid is not in database
5738 throw new BadRequestException('gid not available');
5741 if (Group::update($gid, $name)) {
5744 'id' => intval($gid),
5745 'id_str' => (string) $gid,
5746 'user' => $user_info
5749 return api_format_data("lists", $type, ['lists' => $list]);
5753 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5757 * @param string $type Return type (atom, rss, xml, json)
5759 * @return array|string
5760 * @throws BadRequestException
5761 * @throws ForbiddenException
5762 * @throws ImagickException
5763 * @throws InternalServerErrorException
5765 function api_friendica_activity($type)
5769 if (api_user() === false) {
5770 throw new ForbiddenException();
5772 $verb = strtolower($a->argv[3]);
5773 $verb = preg_replace("|\..*$|", "", $verb);
5775 $id = $_REQUEST['id'] ?? 0;
5777 $res = Item::performActivity($id, $verb, api_user());
5780 if ($type == "xml") {
5785 return api_format_data('ok', $type, ['ok' => $ok]);
5787 throw new BadRequestException('Error adding activity');
5791 /// @TODO move to top of file or somewhere better
5792 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5793 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5794 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5795 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5796 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5797 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5798 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5799 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5800 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5801 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5804 * Returns notifications
5806 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5808 * @return string|array
5809 * @throws ForbiddenException
5810 * @throws BadRequestException
5813 function api_friendica_notification($type)
5817 if (api_user() === false) {
5818 throw new ForbiddenException();
5821 throw new BadRequestException("Invalid argument count");
5824 $notifications = DI::notification()->getApiList(local_user());
5826 if ($type == "xml") {
5828 if (!empty($notifications)) {
5829 foreach ($notifications as $notification) {
5830 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5834 $result = $xmlnotes;
5835 } elseif (count($notifications) > 0) {
5836 $result = $notifications->getArrayCopy();
5841 return api_format_data("notes", $type, ['note' => $result]);
5845 * Set notification as seen and returns associated item (if possible)
5847 * POST request with 'id' param as notification id
5849 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5850 * @return string|array
5851 * @throws BadRequestException
5852 * @throws ForbiddenException
5853 * @throws ImagickException
5854 * @throws InternalServerErrorException
5855 * @throws UnauthorizedException
5857 function api_friendica_notification_seen($type)
5860 $user_info = api_get_user($a);
5862 if (api_user() === false || $user_info === false) {
5863 throw new ForbiddenException();
5865 if ($a->argc !== 4) {
5866 throw new BadRequestException("Invalid argument count");
5869 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5872 $notify = DI::notify()->getByID($id, api_user());
5873 DI::notify()->setSeen(true, $notify);
5875 if ($notify->otype === Notification\ObjectType::ITEM) {
5876 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5877 if (DBA::isResult($item)) {
5878 // we found the item, return it to the user
5879 $ret = api_format_items([$item], $user_info, false, $type);
5880 $data = ['status' => $ret];
5881 return api_format_data("status", $type, $data);
5883 // the item can't be found, but we set the notification as seen, so we count this as a success
5885 return api_format_data('result', $type, ['result' => "success"]);
5886 } catch (NotFoundException $e) {
5887 throw new BadRequestException('Invalid argument', $e);
5888 } catch (Exception $e) {
5889 throw new InternalServerErrorException('Internal Server exception', $e);
5893 /// @TODO move to top of file or somewhere better
5894 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5895 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5898 * update a direct_message to seen state
5900 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5901 * @return string|array (success result=ok, error result=error with error message)
5902 * @throws BadRequestException
5903 * @throws ForbiddenException
5904 * @throws ImagickException
5905 * @throws InternalServerErrorException
5906 * @throws UnauthorizedException
5908 function api_friendica_direct_messages_setseen($type)
5911 if (api_user() === false) {
5912 throw new ForbiddenException();
5916 $user_info = api_get_user($a);
5917 $uid = $user_info['uid'];
5918 $id = $_REQUEST['id'] ?? 0;
5920 // return error if id is zero
5922 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5923 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5926 // error message if specified id is not in database
5927 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5928 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5929 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5932 // update seen indicator
5933 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5937 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5938 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5940 $answer = ['result' => 'error', 'message' => 'unknown error'];
5941 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5945 /// @TODO move to top of file or somewhere better
5946 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5949 * search for direct_messages containing a searchstring through api
5951 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5952 * @param string $box
5953 * @return string|array (success: success=true if found and search_result contains found messages,
5954 * success=false if nothing was found, search_result='nothing found',
5955 * error: result=error with error message)
5956 * @throws BadRequestException
5957 * @throws ForbiddenException
5958 * @throws ImagickException
5959 * @throws InternalServerErrorException
5960 * @throws UnauthorizedException
5962 function api_friendica_direct_messages_search($type, $box = "")
5966 if (api_user() === false) {
5967 throw new ForbiddenException();
5971 $user_info = api_get_user($a);
5972 $searchstring = $_REQUEST['searchstring'] ?? '';
5973 $uid = $user_info['uid'];
5975 // error if no searchstring specified
5976 if ($searchstring == "") {
5977 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5978 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5981 // get data for the specified searchstring
5983 "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",
5985 DBA::escape('%'.$searchstring.'%')
5988 $profile_url = $user_info["url"];
5990 // message if nothing was found
5991 if (!DBA::isResult($r)) {
5992 $success = ['success' => false, 'search_results' => 'problem with query'];
5993 } elseif (count($r) == 0) {
5994 $success = ['success' => false, 'search_results' => 'nothing found'];
5997 foreach ($r as $item) {
5998 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5999 $recipient = $user_info;
6000 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6001 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6002 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6003 $sender = $user_info;
6006 if (isset($recipient) && isset($sender)) {
6007 $ret[] = api_format_messages($item, $recipient, $sender);
6010 $success = ['success' => true, 'search_results' => $ret];
6013 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6016 /// @TODO move to top of file or somewhere better
6017 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6020 * Returns a list of saved searches.
6022 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6024 * @param string $type Return format: json or xml
6026 * @return string|array
6029 function api_saved_searches_list($type)
6031 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6034 while ($term = DBA::fetch($terms)) {
6036 'created_at' => api_date(time()),
6037 'id' => intval($term['id']),
6038 'id_str' => $term['id'],
6039 'name' => $term['term'],
6041 'query' => $term['term']
6047 return api_format_data("terms", $type, ['terms' => $result]);
6050 /// @TODO move to top of file or somewhere better
6051 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6054 * Number of comments
6056 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6058 * @param object $data [Status, Status]
6062 function bindComments(&$data)
6064 if (count($data) == 0) {
6070 foreach ($data as $item) {
6071 $ids[] = $item['id'];
6074 $idStr = DBA::escape(implode(', ', $ids));
6075 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6076 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6077 $itemsData = DBA::toArray($items);
6079 foreach ($itemsData as $item) {
6080 $comments[$item['parent']] = $item['comments'];
6083 foreach ($data as $idx => $item) {
6085 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6090 @TODO Maybe open to implement?
6092 [pagename] => api/1.1/statuses/lookup.json
6093 [id] => 605138389168451584
6094 [include_cards] => true
6095 [cards_platform] => Android-12
6096 [include_entities] => true
6097 [include_my_retweet] => 1
6099 [include_reply_count] => true
6100 [include_descendent_reply_count] => true
6104 Not implemented by now:
6105 statuses/retweets_of_me
6110 account/update_location
6111 account/update_profile_background_image
6114 friendica/profile/update
6115 friendica/profile/create
6116 friendica/profile/delete
6118 Not implemented in status.net:
6119 statuses/retweeted_to_me
6120 statuses/retweeted_by_me
6121 direct_messages/destroy
6123 account/update_delivery_device
6124 notifications/follow