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 if (!empty($_SESSION['allow_api'])) {
106 * Get source name from API client
108 * Clients can send 'source' parameter to be show in post metadata
109 * as "sent via <source>".
110 * Some clients doesn't send a source param, we support ones we know
111 * (only Twidere, atm)
114 * Client source name, default to "api" if unset/unknown
117 function api_source()
119 $application = OAuth::getCurrentApplicationToken();
120 if (empty($application)) {
121 $application = BasicAuth::getCurrentApplicationToken();
123 return $application['name'] ?? 'api';
127 * Format date for API
129 * @param string $str Source date, as UTC
130 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
133 function api_date($str)
135 // Wed May 23 06:01:13 +0000 2007
136 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
140 * Register a function to be the endpoint for defined API path.
142 * @param string $path API URL path, relative to DI::baseUrl()
143 * @param string $func Function name to call on path request
144 * @param bool $auth API need logged user
145 * @param string $method HTTP method reqiured to call this endpoint.
146 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
147 * Default to API_METHOD_ANY
149 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
159 // Workaround for hotot
160 $path = str_replace("api/", "api/1.1/", $path);
170 * Log in user via OAuth1 or Simple HTTP Auth.
171 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
174 * @throws ForbiddenException
175 * @throws InternalServerErrorException
176 * @throws UnauthorizedException
177 * @hook 'authenticate'
179 * 'username' => username from login form
180 * 'password' => password from login form
181 * 'authenticated' => return status,
182 * 'user_record' => return authenticated user record
184 function api_login(App $a)
186 $_SESSION["allow_api"] = false;
188 // workaround for HTTP-auth in CGI mode
189 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
190 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
191 if (strlen($userpass)) {
192 list($name, $password) = explode(':', $userpass);
193 $_SERVER['PHP_AUTH_USER'] = $name;
194 $_SERVER['PHP_AUTH_PW'] = $password;
198 if (empty($_SERVER['PHP_AUTH_USER'])) {
199 // Try OAuth when no user is provided
200 $oauth1 = new FKOAuth1();
203 $request = OAuthRequest::from_request();
204 list($consumer, $token) = $oauth1->verify_request($request);
205 if (!is_null($token)) {
206 $oauth1->loginUser($token->uid);
207 Session::set('allow_api', true);
210 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
211 var_dump($consumer, $token);
213 } catch (Exception $e) {
214 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
217 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
218 header('WWW-Authenticate: Basic realm="Friendica"');
219 throw new UnauthorizedException("This API requires login");
222 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
223 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
225 // allow "user@server" login (but ignore 'server' part)
226 $at = strstr($user, "@", true);
231 // next code from mod/auth.php. needs better solution
235 'username' => trim($user),
236 'password' => trim($password),
237 'authenticated' => 0,
238 'user_record' => null,
242 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
243 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
244 * and later addons should not interfere with an earlier one that succeeded.
246 Hook::callAll('authenticate', $addon_auth);
248 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
249 $record = $addon_auth['user_record'];
251 $user_id = User::authenticate(trim($user), trim($password), true);
252 if ($user_id !== false) {
253 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
257 if (!DBA::isResult($record)) {
258 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
259 header('WWW-Authenticate: Basic realm="Friendica"');
260 //header('HTTP/1.0 401 Unauthorized');
261 //die('This api requires login');
262 throw new UnauthorizedException("This API requires login");
265 // Don't refresh the login date more often than twice a day to spare database writes
266 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
268 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
270 $_SESSION["allow_api"] = true;
272 Hook::callAll('logged_in', $a->user);
276 * Check HTTP method of called API
278 * API endpoints can define which HTTP method to accept when called.
279 * This function check the current HTTP method agains endpoint
282 * @param string $method Required methods, uppercase, separated by comma
285 function api_check_method($method)
287 if ($method == "*") {
290 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
294 * Main API entry point
296 * Authenticate user, call registered API function, set HTTP headers
299 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
300 * @return string|array API call result
303 function api_call(App $a, App\Arguments $args = null)
305 global $API, $called_api;
312 if (strpos($args->getCommand(), ".xml") > 0) {
315 if (strpos($args->getCommand(), ".json") > 0) {
318 if (strpos($args->getCommand(), ".rss") > 0) {
321 if (strpos($args->getCommand(), ".atom") > 0) {
326 foreach ($API as $p => $info) {
327 if (strpos($args->getCommand(), $p) === 0) {
328 if (!api_check_method($info['method'])) {
329 throw new MethodNotAllowedException();
332 $called_api = explode("/", $p);
334 if (!empty($info['auth']) && api_user() === false) {
336 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
339 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
341 $stamp = microtime(true);
342 $return = call_user_func($info['func'], $type);
343 $duration = floatval(microtime(true) - $stamp);
345 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
347 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
349 if (false === $return) {
351 * api function returned false withour throw an
352 * exception. This should not happend, throw a 500
354 throw new InternalServerErrorException();
359 header("Content-Type: text/xml");
362 header("Content-Type: application/json");
363 if (!empty($return)) {
364 $json = json_encode(end($return));
365 if (!empty($_GET['callback'])) {
366 $json = $_GET['callback'] . "(" . $json . ")";
372 header("Content-Type: application/rss+xml");
373 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
376 header("Content-Type: application/atom+xml");
377 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
384 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
385 throw new NotFoundException();
386 } catch (HTTPException $e) {
387 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
388 return api_error($type, $e, $args);
393 * Format API error string
395 * @param string $type Return type (xml, json, rss, as)
396 * @param object $e HTTPException Error object
397 * @param App\Arguments $args The App arguments
398 * @return string|array error message formatted as $type
400 function api_error($type, $e, App\Arguments $args)
402 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
403 /// @TODO: https://dev.twitter.com/overview/api/response-codes
405 $error = ["error" => $error,
406 "code" => $e->getCode() . " " . $e->httpdesc,
407 "request" => $args->getQueryString()];
409 $return = api_format_data('status', $type, ['status' => $error]);
413 header("Content-Type: text/xml");
416 header("Content-Type: application/json");
417 $return = json_encode($return);
420 header("Content-Type: application/rss+xml");
423 header("Content-Type: application/atom+xml");
431 * Set values for RSS template
434 * @param array $arr Array to be passed to template
435 * @param array $user_info User info
437 * @throws BadRequestException
438 * @throws ImagickException
439 * @throws InternalServerErrorException
440 * @throws UnauthorizedException
441 * @todo find proper type-hints
443 function api_rss_extra(App $a, $arr, $user_info)
445 if (is_null($user_info)) {
446 $user_info = api_get_user($a);
449 $arr['$user'] = $user_info;
451 'alternate' => $user_info['url'],
452 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
453 'base' => DI::baseUrl(),
454 'updated' => api_date(null),
455 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
456 'language' => $user_info['lang'],
457 'logo' => DI::baseUrl() . "/images/friendica-32.png",
465 * Unique contact to contact url.
467 * @param int $id Contact id
468 * @return bool|string
469 * Contact url or False if contact id is unknown
472 function api_unique_id_to_nurl($id)
474 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
476 if (DBA::isResult($r)) {
484 * Get user info array.
487 * @param int|string $contact_id Contact ID or URL
489 * @throws BadRequestException
490 * @throws ImagickException
491 * @throws InternalServerErrorException
492 * @throws UnauthorizedException
494 function api_get_user(App $a, $contact_id = null)
502 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
504 // Searching for contact URL
505 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
506 $user = DBA::escape(Strings::normaliseLink($contact_id));
508 $extra_query = "AND `contact`.`nurl` = '%s' ";
509 if (api_user() !== false) {
510 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
514 // Searching for contact id with uid = 0
515 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
516 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
519 throw new BadRequestException("User ID ".$contact_id." not found.");
523 $extra_query = "AND `contact`.`nurl` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
529 if (is_null($user) && !empty($_GET['user_id'])) {
530 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
533 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
537 $extra_query = "AND `contact`.`nurl` = '%s' ";
538 if (api_user() !== false) {
539 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
542 if (is_null($user) && !empty($_GET['screen_name'])) {
543 $user = DBA::escape($_GET['screen_name']);
544 $extra_query = "AND `contact`.`nick` = '%s' ";
545 if (api_user() !== false) {
546 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
550 if (is_null($user) && !empty($_GET['profileurl'])) {
551 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
558 // $called_api is the API path exploded on / and is expected to have at least 2 elements
559 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
560 $argid = count($called_api);
561 if (!empty($a->argv[$argid])) {
562 $data = explode(".", $a->argv[$argid]);
563 if (count($data) > 1) {
564 list($user, $null) = $data;
567 if (is_numeric($user)) {
568 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
572 $extra_query = "AND `contact`.`nurl` = '%s' ";
573 if (api_user() !== false) {
574 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
578 $user = DBA::escape($user);
579 $extra_query = "AND `contact`.`nick` = '%s' ";
580 if (api_user() !== false) {
581 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
586 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
589 if (api_user() === false) {
594 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
598 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
602 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
608 // Selecting the id by priority, friendica first
609 if (is_array($uinfo)) {
610 api_best_nickname($uinfo);
613 // if the contact wasn't found, fetch it from the contacts with uid = 0
614 if (!DBA::isResult($uinfo)) {
616 throw new BadRequestException("User not found.");
619 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
621 if (DBA::isResult($contact)) {
623 'id' => $contact["id"],
624 'id_str' => (string) $contact["id"],
625 'name' => $contact["name"],
626 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
627 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
628 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
629 'profile_image_url' => $contact["micro"],
630 'profile_image_url_https' => $contact["micro"],
631 'profile_image_url_profile_size' => $contact["thumb"],
632 'profile_image_url_large' => $contact["photo"],
633 'url' => $contact["url"],
634 'protected' => false,
635 'followers_count' => 0,
636 'friends_count' => 0,
638 'created_at' => api_date($contact["created"]),
639 'favourites_count' => 0,
641 'time_zone' => 'UTC',
642 'geo_enabled' => false,
644 'statuses_count' => 0,
646 'contributors_enabled' => false,
647 'is_translator' => false,
648 'is_translation_enabled' => false,
649 'following' => false,
650 'follow_request_sent' => false,
651 'statusnet_blocking' => false,
652 'notifications' => false,
653 'statusnet_profile_url' => $contact["url"],
655 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
656 'pid' => Contact::getIdForURL($contact["url"], 0, false),
658 'network' => $contact["network"],
663 throw new BadRequestException("User ".$url." not found.");
667 if ($uinfo[0]['self']) {
668 if ($uinfo[0]['network'] == "") {
669 $uinfo[0]['network'] = Protocol::DFRN;
672 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
673 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
680 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
682 if (!empty($profile['about'])) {
683 $description = $profile['about'];
685 $description = $uinfo[0]["about"];
688 if (!empty($usr['default-location'])) {
689 $location = $usr['default-location'];
690 } elseif (!empty($uinfo[0]["location"])) {
691 $location = $uinfo[0]["location"];
693 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
697 'id' => intval($pcontact_id),
698 'id_str' => (string) intval($pcontact_id),
699 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
700 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
701 'location' => $location,
702 'description' => BBCode::toPlaintext($description ?? ''),
703 'profile_image_url' => $uinfo[0]['micro'],
704 'profile_image_url_https' => $uinfo[0]['micro'],
705 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
706 'profile_image_url_large' => $uinfo[0]["photo"],
707 'url' => $uinfo[0]['url'],
708 'protected' => false,
709 'followers_count' => intval($countfollowers),
710 'friends_count' => intval($countfriends),
712 'created_at' => api_date($uinfo[0]['created']),
713 'favourites_count' => intval($starred),
715 'time_zone' => 'UTC',
716 'geo_enabled' => false,
718 'statuses_count' => intval($countitems),
720 'contributors_enabled' => false,
721 'is_translator' => false,
722 'is_translation_enabled' => false,
723 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
724 'follow_request_sent' => false,
725 'statusnet_blocking' => false,
726 'notifications' => false,
728 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
729 'statusnet_profile_url' => $uinfo[0]['url'],
730 'uid' => intval($uinfo[0]['uid']),
731 'cid' => intval($uinfo[0]['cid']),
732 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
733 'self' => $uinfo[0]['self'],
734 'network' => $uinfo[0]['network'],
737 // If this is a local user and it uses Frio, we can get its color preferences.
739 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
740 if ($theme_info['theme'] === 'frio') {
741 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
743 if ($schema && ($schema != '---')) {
744 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
745 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
746 require_once $schemefile;
749 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
750 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
751 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
753 if (empty($nav_bg)) {
756 if (empty($link_color)) {
757 $link_color = "#6fdbe8";
759 if (empty($bgcolor)) {
760 $bgcolor = "#ededed";
763 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
764 $ret['profile_link_color'] = str_replace('#', '', $link_color);
765 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
773 * return api-formatted array for item's author and owner
776 * @param array $item item from db
777 * @return array(array:author, array:owner)
778 * @throws BadRequestException
779 * @throws ImagickException
780 * @throws InternalServerErrorException
781 * @throws UnauthorizedException
783 function api_item_get_user(App $a, $item)
785 $status_user = api_get_user($a, $item['author-id'] ?? null);
787 $author_user = $status_user;
789 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
791 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
792 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
794 $owner_user = $author_user;
797 return ([$status_user, $author_user, $owner_user]);
801 * walks recursively through an array with the possibility to change value and key
803 * @param array $array The array to walk through
804 * @param callable $callback The callback function
806 * @return array the transformed array
808 function api_walk_recursive(array &$array, callable $callback)
812 foreach ($array as $k => $v) {
814 if ($callback($v, $k)) {
815 $new_array[$k] = api_walk_recursive($v, $callback);
818 if ($callback($v, $k)) {
829 * Callback function to transform the array in an array that can be transformed in a XML file
831 * @param mixed $item Array item value
832 * @param string $key Array key
834 * @return boolean Should the array item be deleted?
836 function api_reformat_xml(&$item, &$key)
838 if (is_bool($item)) {
839 $item = ($item ? "true" : "false");
842 if (substr($key, 0, 10) == "statusnet_") {
843 $key = "statusnet:".substr($key, 10);
844 } elseif (substr($key, 0, 10) == "friendica_") {
845 $key = "friendica:".substr($key, 10);
847 /// @TODO old-lost code?
849 // $key = "default:".$key;
855 * Creates the XML from a JSON style array
857 * @param array $data JSON style array
858 * @param string $root_element Name of the root element
860 * @return string The XML data
862 function api_create_xml(array $data, $root_element)
864 $childname = key($data);
865 $data2 = array_pop($data);
867 $namespaces = ["" => "http://api.twitter.com",
868 "statusnet" => "http://status.net/schema/api/1/",
869 "friendica" => "http://friendi.ca/schema/api/1/",
870 "georss" => "http://www.georss.org/georss"];
872 /// @todo Auto detection of needed namespaces
873 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
877 if (is_array($data2)) {
879 api_walk_recursive($data2, "api_reformat_xml");
885 foreach ($data2 as $item) {
886 $data4[$i++ . ":" . $childname] = $item;
893 $data3 = [$root_element => $data2];
895 $ret = XML::fromArray($data3, $xml, false, $namespaces);
900 * Formats the data according to the data type
902 * @param string $root_element Name of the root element
903 * @param string $type Return type (atom, rss, xml, json)
904 * @param array $data JSON style array
906 * @return array|string (string|array) XML data or JSON data
908 function api_format_data($root_element, $type, $data)
914 $ret = api_create_xml($data, $root_element);
929 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
930 * returns a 401 status code and an error message if not.
932 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
934 * @param string $type Return type (atom, rss, xml, json)
935 * @return array|string
936 * @throws BadRequestException
937 * @throws ForbiddenException
938 * @throws ImagickException
939 * @throws InternalServerErrorException
940 * @throws UnauthorizedException
942 function api_account_verify_credentials($type)
946 if (api_user() === false) {
947 throw new ForbiddenException();
950 unset($_REQUEST["user_id"]);
951 unset($_GET["user_id"]);
953 unset($_REQUEST["screen_name"]);
954 unset($_GET["screen_name"]);
956 $skip_status = $_REQUEST['skip_status'] ?? false;
958 $user_info = api_get_user($a);
960 // "verified" isn't used here in the standard
961 unset($user_info["verified"]);
963 // - Adding last status
965 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
967 $user_info['status'] = api_format_item($item, $type);
971 // "uid" and "self" are only needed for some internal stuff, so remove it from here
972 unset($user_info["uid"]);
973 unset($user_info["self"]);
975 return api_format_data("user", $type, ['user' => $user_info]);
978 /// @TODO move to top of file or somewhere better
979 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
982 * Get data from $_POST or $_GET
987 function requestdata($k)
989 if (!empty($_POST[$k])) {
992 if (!empty($_GET[$k])) {
999 * Deprecated function to upload media.
1001 * @param string $type Return type (atom, rss, xml, json)
1003 * @return array|string
1004 * @throws BadRequestException
1005 * @throws ForbiddenException
1006 * @throws ImagickException
1007 * @throws InternalServerErrorException
1008 * @throws UnauthorizedException
1010 function api_statuses_mediap($type)
1014 if (api_user() === false) {
1015 Logger::log('api_statuses_update: no user');
1016 throw new ForbiddenException();
1018 $user_info = api_get_user($a);
1020 $_REQUEST['profile_uid'] = api_user();
1021 $_REQUEST['api_source'] = true;
1022 $txt = requestdata('status') ?? '';
1023 /// @TODO old-lost code?
1024 //$txt = urldecode(requestdata('status'));
1026 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1027 $txt = HTML::toBBCodeVideo($txt);
1028 $config = HTMLPurifier_Config::createDefault();
1029 $config->set('Cache.DefinitionImpl', null);
1030 $purifier = new HTMLPurifier($config);
1031 $txt = $purifier->purify($txt);
1033 $txt = HTML::toBBCode($txt);
1035 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1037 $picture = wall_upload_post($a, false);
1039 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1040 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1041 $item_id = item_post($a);
1043 // output the post that we just posted.
1044 return api_status_show($type, $item_id);
1047 /// @TODO move this to top of file or somewhere better!
1048 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1051 * Updates the user’s current status.
1053 * @param string $type Return type (atom, rss, xml, json)
1055 * @return array|string
1056 * @throws BadRequestException
1057 * @throws ForbiddenException
1058 * @throws ImagickException
1059 * @throws InternalServerErrorException
1060 * @throws TooManyRequestsException
1061 * @throws UnauthorizedException
1062 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1064 function api_statuses_update($type)
1068 if (api_user() === false) {
1069 Logger::log('api_statuses_update: no user');
1070 throw new ForbiddenException();
1075 // convert $_POST array items to the form we use for web posts.
1076 if (requestdata('htmlstatus')) {
1077 $txt = requestdata('htmlstatus') ?? '';
1078 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1079 $txt = HTML::toBBCodeVideo($txt);
1081 $config = HTMLPurifier_Config::createDefault();
1082 $config->set('Cache.DefinitionImpl', null);
1084 $purifier = new HTMLPurifier($config);
1085 $txt = $purifier->purify($txt);
1087 $_REQUEST['body'] = HTML::toBBCode($txt);
1090 $_REQUEST['body'] = requestdata('status');
1093 $_REQUEST['title'] = requestdata('title');
1095 $parent = requestdata('in_reply_to_status_id');
1097 // Twidere sends "-1" if it is no reply ...
1098 if ($parent == -1) {
1102 if (ctype_digit($parent)) {
1103 $_REQUEST['parent'] = $parent;
1105 $_REQUEST['parent_uri'] = $parent;
1108 if (requestdata('lat') && requestdata('long')) {
1109 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1111 $_REQUEST['profile_uid'] = api_user();
1114 // Check for throttling (maximum posts per day, week and month)
1115 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1116 if ($throttle_day > 0) {
1117 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1119 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1120 $posts_day = Post::count($condition);
1122 if ($posts_day > $throttle_day) {
1123 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1124 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1125 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));
1129 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1130 if ($throttle_week > 0) {
1131 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1133 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1134 $posts_week = Post::count($condition);
1136 if ($posts_week > $throttle_week) {
1137 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1138 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1139 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));
1143 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1144 if ($throttle_month > 0) {
1145 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1147 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1148 $posts_month = Post::count($condition);
1150 if ($posts_month > $throttle_month) {
1151 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1152 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1153 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));
1158 if (requestdata('media_ids')) {
1159 $ids = explode(',', requestdata('media_ids') ?? '');
1160 } elseif (!empty($_FILES['media'])) {
1161 // upload the image if we have one
1162 $picture = wall_upload_post($a, false);
1163 if (is_array($picture)) {
1164 $ids[] = $picture['id'];
1172 foreach ($ids as $id) {
1173 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1174 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1175 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1176 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1178 if (!empty($media)) {
1179 $ressources[] = $media[0]['resource-id'];
1180 $phototypes = Images::supportedTypes();
1181 $ext = $phototypes[$media[0]['type']];
1183 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1184 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1185 'size' => $media[0]['datasize'],
1186 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1187 'description' => $media[0]['desc'] ?? '',
1188 'width' => $media[0]['width'],
1189 'height' => $media[0]['height']];
1191 if (count($media) > 1) {
1192 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1193 $attachment['preview-width'] = $media[1]['width'];
1194 $attachment['preview-height'] = $media[1]['height'];
1196 $attachments[] = $attachment;
1200 // We have to avoid that the post is rejected because of an empty body
1201 if (empty($_REQUEST['body'])) {
1202 $_REQUEST['body'] = '[hr]';
1206 if (!empty($attachments)) {
1207 $_REQUEST['attachments'] = $attachments;
1210 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1212 $_REQUEST['api_source'] = true;
1214 if (empty($_REQUEST['source'])) {
1215 $_REQUEST["source"] = api_source();
1218 // call out normal post function
1219 $item_id = item_post($a);
1221 if (!empty($ressources) && !empty($item_id)) {
1222 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1223 foreach ($ressources as $ressource) {
1224 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1228 // output the post that we just posted.
1229 return api_status_show($type, $item_id);
1232 /// @TODO move to top of file or somewhere better
1233 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1234 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1237 * Uploads an image to Friendica.
1240 * @throws BadRequestException
1241 * @throws ForbiddenException
1242 * @throws ImagickException
1243 * @throws InternalServerErrorException
1244 * @throws UnauthorizedException
1245 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1247 function api_media_upload()
1251 if (api_user() === false) {
1252 Logger::log('no user');
1253 throw new ForbiddenException();
1258 if (empty($_FILES['media'])) {
1260 throw new BadRequestException("No media.");
1263 $media = wall_upload_post($a, false);
1266 throw new InternalServerErrorException();
1270 $returndata["media_id"] = $media["id"];
1271 $returndata["media_id_string"] = (string)$media["id"];
1272 $returndata["size"] = $media["size"];
1273 $returndata["image"] = ["w" => $media["width"],
1274 "h" => $media["height"],
1275 "image_type" => $media["type"],
1276 "friendica_preview_url" => $media["preview"]];
1278 Logger::info('Media uploaded', ['return' => $returndata]);
1280 return ["media" => $returndata];
1283 /// @TODO move to top of file or somewhere better
1284 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1287 * Updates media meta data (picture descriptions)
1289 * @param string $type Return type (atom, rss, xml, json)
1291 * @return array|string
1292 * @throws BadRequestException
1293 * @throws ForbiddenException
1294 * @throws ImagickException
1295 * @throws InternalServerErrorException
1296 * @throws TooManyRequestsException
1297 * @throws UnauthorizedException
1298 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1300 * @todo Compare the corresponding Twitter function for correct return values
1302 function api_media_metadata_create($type)
1306 if (api_user() === false) {
1307 Logger::info('no user');
1308 throw new ForbiddenException();
1313 $postdata = Network::postdata();
1315 if (empty($postdata)) {
1316 throw new BadRequestException("No post data");
1319 $data = json_decode($postdata, true);
1321 throw new BadRequestException("Invalid post data");
1324 if (empty($data['media_id']) || empty($data['alt_text'])) {
1325 throw new BadRequestException("Missing post data values");
1328 if (empty($data['alt_text']['text'])) {
1329 throw new BadRequestException("No alt text.");
1332 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1334 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1335 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1336 if (!DBA::isResult($photo)) {
1337 throw new BadRequestException("Metadata not found.");
1340 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1343 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1346 * @param string $type Return format (atom, rss, xml, json)
1347 * @param int $item_id
1348 * @return array|string
1351 function api_status_show($type, $item_id)
1353 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1357 $item = api_get_item(['id' => $item_id]);
1358 if (!empty($item)) {
1359 $status_info = api_format_item($item, $type);
1362 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1364 return api_format_data('statuses', $type, ['status' => $status_info]);
1368 * Retrieves the last public status of the provided user info
1370 * @param int $ownerId Public contact Id
1371 * @param int $uid User Id
1375 function api_get_last_status($ownerId, $uid)
1378 'author-id'=> $ownerId,
1380 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1381 'private' => [Item::PUBLIC, Item::UNLISTED]
1384 $item = api_get_item($condition);
1390 * Retrieves a single item record based on the provided condition and converts it for API use.
1392 * @param array $condition Item table condition array
1396 function api_get_item(array $condition)
1398 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1404 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1405 * The author's most recent status will be returned inline.
1407 * @param string $type Return type (atom, rss, xml, json)
1408 * @return array|string
1409 * @throws BadRequestException
1410 * @throws ImagickException
1411 * @throws InternalServerErrorException
1412 * @throws UnauthorizedException
1413 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1415 function api_users_show($type)
1417 $a = Friendica\DI::app();
1419 $user_info = api_get_user($a);
1421 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1422 if (!empty($item)) {
1423 $user_info['status'] = api_format_item($item, $type);
1426 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1427 unset($user_info['uid']);
1428 unset($user_info['self']);
1430 return api_format_data('user', $type, ['user' => $user_info]);
1433 /// @TODO move to top of file or somewhere better
1434 api_register_func('api/users/show', 'api_users_show');
1435 api_register_func('api/externalprofile/show', 'api_users_show');
1438 * Search a public user account.
1440 * @param string $type Return type (atom, rss, xml, json)
1442 * @return array|string
1443 * @throws BadRequestException
1444 * @throws ImagickException
1445 * @throws InternalServerErrorException
1446 * @throws UnauthorizedException
1447 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1449 function api_users_search($type)
1455 if (!empty($_GET['q'])) {
1456 $contacts = Contact::selectToArray(
1459 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1467 if (DBA::isResult($contacts)) {
1469 foreach ($contacts as $contact) {
1470 $user_info = api_get_user($a, $contact['id']);
1472 if ($type == 'xml') {
1473 $userlist[$k++ . ':user'] = $user_info;
1475 $userlist[] = $user_info;
1478 $userlist = ['users' => $userlist];
1480 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1483 throw new BadRequestException('No search term specified.');
1486 return api_format_data('users', $type, $userlist);
1489 /// @TODO move to top of file or somewhere better
1490 api_register_func('api/users/search', 'api_users_search');
1493 * Return user objects
1495 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1497 * @param string $type Return format: json or xml
1499 * @return array|string
1500 * @throws BadRequestException
1501 * @throws ImagickException
1502 * @throws InternalServerErrorException
1503 * @throws NotFoundException if the results are empty.
1504 * @throws UnauthorizedException
1506 function api_users_lookup($type)
1510 if (!empty($_REQUEST['user_id'])) {
1511 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1513 $users[] = api_get_user(DI::app(), $id);
1518 if (empty($users)) {
1519 throw new NotFoundException;
1522 return api_format_data("users", $type, ['users' => $users]);
1525 /// @TODO move to top of file or somewhere better
1526 api_register_func('api/users/lookup', 'api_users_lookup', true);
1529 * Returns statuses that match a specified query.
1531 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1533 * @param string $type Return format: json, xml, atom, rss
1535 * @return array|string
1536 * @throws BadRequestException if the "q" parameter is missing.
1537 * @throws ForbiddenException
1538 * @throws ImagickException
1539 * @throws InternalServerErrorException
1540 * @throws UnauthorizedException
1542 function api_search($type)
1545 $user_info = api_get_user($a);
1547 if (api_user() === false || $user_info === false) {
1548 throw new ForbiddenException();
1551 if (empty($_REQUEST['q'])) {
1552 throw new BadRequestException('q parameter is required.');
1555 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1558 $data['status'] = [];
1560 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1561 if (!empty($_REQUEST['rpp'])) {
1562 $count = $_REQUEST['rpp'];
1563 } elseif (!empty($_REQUEST['count'])) {
1564 $count = $_REQUEST['count'];
1567 $since_id = $_REQUEST['since_id'] ?? 0;
1568 $max_id = $_REQUEST['max_id'] ?? 0;
1569 $page = $_REQUEST['page'] ?? 1;
1571 $start = max(0, ($page - 1) * $count);
1573 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1574 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1575 $searchTerm = $matches[1];
1576 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1577 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1579 while ($tag = DBA::fetch($tags)) {
1580 $uriids[] = $tag['uri-id'];
1584 if (empty($uriids)) {
1585 return api_format_data('statuses', $type, $data);
1588 $condition = ['uri-id' => $uriids];
1589 if ($exclude_replies) {
1590 $condition['gravity'] = GRAVITY_PARENT;
1593 $params['group_by'] = ['uri-id'];
1595 $condition = ["`id` > ?
1596 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1597 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1598 AND `body` LIKE CONCAT('%',?,'%')",
1599 $since_id, api_user(), $_REQUEST['q']];
1601 $condition[0] .= ' AND `id` <= ?';
1602 $condition[] = $max_id;
1608 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1609 $id = Item::fetchByLink($searchTerm, api_user());
1612 $id = Item::fetchByLink($searchTerm);
1616 $statuses = Post::select([], ['id' => $id]);
1620 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1622 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1624 bindComments($data['status']);
1626 return api_format_data('statuses', $type, $data);
1629 /// @TODO move to top of file or somewhere better
1630 api_register_func('api/search/tweets', 'api_search', true);
1631 api_register_func('api/search', 'api_search', true);
1634 * Returns the most recent statuses posted by the user and the users they follow.
1636 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1638 * @param string $type Return type (atom, rss, xml, json)
1640 * @return array|string
1641 * @throws BadRequestException
1642 * @throws ForbiddenException
1643 * @throws ImagickException
1644 * @throws InternalServerErrorException
1645 * @throws UnauthorizedException
1646 * @todo Optional parameters
1647 * @todo Add reply info
1649 function api_statuses_home_timeline($type)
1652 $user_info = api_get_user($a);
1654 if (api_user() === false || $user_info === false) {
1655 throw new ForbiddenException();
1658 unset($_REQUEST["user_id"]);
1659 unset($_GET["user_id"]);
1661 unset($_REQUEST["screen_name"]);
1662 unset($_GET["screen_name"]);
1664 // get last network messages
1667 $count = $_REQUEST['count'] ?? 20;
1668 $page = $_REQUEST['page']?? 0;
1669 $since_id = $_REQUEST['since_id'] ?? 0;
1670 $max_id = $_REQUEST['max_id'] ?? 0;
1671 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1672 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1674 $start = max(0, ($page - 1) * $count);
1676 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1677 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1680 $condition[0] .= " AND `id` <= ?";
1681 $condition[] = $max_id;
1683 if ($exclude_replies) {
1684 $condition[0] .= ' AND `gravity` = ?';
1685 $condition[] = GRAVITY_PARENT;
1687 if ($conversation_id > 0) {
1688 $condition[0] .= " AND `parent` = ?";
1689 $condition[] = $conversation_id;
1692 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1693 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1695 $items = Post::toArray($statuses);
1697 $ret = api_format_items($items, $user_info, false, $type);
1699 // Set all posts from the query above to seen
1701 foreach ($items as $item) {
1702 $idarray[] = intval($item["id"]);
1705 if (!empty($idarray)) {
1706 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1708 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1714 $data = ['status' => $ret];
1719 $data = api_rss_extra($a, $data, $user_info);
1723 return api_format_data("statuses", $type, $data);
1727 /// @TODO move to top of file or somewhere better
1728 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1729 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1732 * Returns the most recent statuses from public users.
1734 * @param string $type Return type (atom, rss, xml, json)
1736 * @return array|string
1737 * @throws BadRequestException
1738 * @throws ForbiddenException
1739 * @throws ImagickException
1740 * @throws InternalServerErrorException
1741 * @throws UnauthorizedException
1743 function api_statuses_public_timeline($type)
1746 $user_info = api_get_user($a);
1748 if (api_user() === false || $user_info === false) {
1749 throw new ForbiddenException();
1752 // get last network messages
1755 $count = $_REQUEST['count'] ?? 20;
1756 $page = $_REQUEST['page'] ?? 1;
1757 $since_id = $_REQUEST['since_id'] ?? 0;
1758 $max_id = $_REQUEST['max_id'] ?? 0;
1759 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1760 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1762 $start = max(0, ($page - 1) * $count);
1764 if ($exclude_replies && !$conversation_id) {
1765 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1766 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1769 $condition[0] .= " AND `id` <= ?";
1770 $condition[] = $max_id;
1773 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1774 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1776 $r = Post::toArray($statuses);
1778 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1779 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1782 $condition[0] .= " AND `id` <= ?";
1783 $condition[] = $max_id;
1785 if ($conversation_id > 0) {
1786 $condition[0] .= " AND `parent` = ?";
1787 $condition[] = $conversation_id;
1790 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1791 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1793 $r = Post::toArray($statuses);
1796 $ret = api_format_items($r, $user_info, false, $type);
1800 $data = ['status' => $ret];
1805 $data = api_rss_extra($a, $data, $user_info);
1809 return api_format_data("statuses", $type, $data);
1812 /// @TODO move to top of file or somewhere better
1813 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1816 * Returns the most recent statuses posted by users this node knows about.
1818 * @param string $type Return format: json, xml, atom, rss
1819 * @return array|string
1820 * @throws BadRequestException
1821 * @throws ForbiddenException
1822 * @throws ImagickException
1823 * @throws InternalServerErrorException
1824 * @throws UnauthorizedException
1826 function api_statuses_networkpublic_timeline($type)
1829 $user_info = api_get_user($a);
1831 if (api_user() === false || $user_info === false) {
1832 throw new ForbiddenException();
1835 $since_id = $_REQUEST['since_id'] ?? 0;
1836 $max_id = $_REQUEST['max_id'] ?? 0;
1839 $count = $_REQUEST['count'] ?? 20;
1840 $page = $_REQUEST['page'] ?? 1;
1842 $start = max(0, ($page - 1) * $count);
1844 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1845 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1848 $condition[0] .= " AND `id` <= ?";
1849 $condition[] = $max_id;
1852 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1853 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1855 $ret = api_format_items($statuses, $user_info, false, $type);
1859 $data = ['status' => $ret];
1864 $data = api_rss_extra($a, $data, $user_info);
1868 return api_format_data("statuses", $type, $data);
1871 /// @TODO move to top of file or somewhere better
1872 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1875 * Returns a single status.
1877 * @param string $type Return type (atom, rss, xml, json)
1879 * @return array|string
1880 * @throws BadRequestException
1881 * @throws ForbiddenException
1882 * @throws ImagickException
1883 * @throws InternalServerErrorException
1884 * @throws UnauthorizedException
1885 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1887 function api_statuses_show($type)
1890 $user_info = api_get_user($a);
1892 if (api_user() === false || $user_info === false) {
1893 throw new ForbiddenException();
1897 $id = intval($a->argv[3] ?? 0);
1900 $id = intval($_REQUEST['id'] ?? 0);
1905 $id = intval($a->argv[4] ?? 0);
1908 Logger::log('API: api_statuses_show: ' . $id);
1910 $conversation = !empty($_REQUEST['conversation']);
1912 // try to fetch the item for the local user - or the public item, if there is no local one
1913 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1914 if (!DBA::isResult($uri_item)) {
1915 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1918 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1919 if (!DBA::isResult($item)) {
1920 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1925 if ($conversation) {
1926 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1927 $params = ['order' => ['id' => true]];
1929 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1933 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1935 /// @TODO How about copying this to above methods which don't check $r ?
1936 if (!DBA::isResult($statuses)) {
1937 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1940 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1942 if ($conversation) {
1943 $data = ['status' => $ret];
1944 return api_format_data("statuses", $type, $data);
1946 $data = ['status' => $ret[0]];
1947 return api_format_data("status", $type, $data);
1951 /// @TODO move to top of file or somewhere better
1952 api_register_func('api/statuses/show', 'api_statuses_show', true);
1956 * @param string $type Return type (atom, rss, xml, json)
1958 * @return array|string
1959 * @throws BadRequestException
1960 * @throws ForbiddenException
1961 * @throws ImagickException
1962 * @throws InternalServerErrorException
1963 * @throws UnauthorizedException
1964 * @todo nothing to say?
1966 function api_conversation_show($type)
1969 $user_info = api_get_user($a);
1971 if (api_user() === false || $user_info === false) {
1972 throw new ForbiddenException();
1976 $id = intval($a->argv[3] ?? 0);
1977 $since_id = intval($_REQUEST['since_id'] ?? 0);
1978 $max_id = intval($_REQUEST['max_id'] ?? 0);
1979 $count = intval($_REQUEST['count'] ?? 20);
1980 $page = intval($_REQUEST['page'] ?? 1);
1982 $start = max(0, ($page - 1) * $count);
1985 $id = intval($_REQUEST['id'] ?? 0);
1990 $id = intval($a->argv[4] ?? 0);
1993 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1995 // try to fetch the item for the local user - or the public item, if there is no local one
1996 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1997 if (!DBA::isResult($item)) {
1998 throw new BadRequestException("There is no status with this id.");
2001 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2002 if (!DBA::isResult($parent)) {
2003 throw new BadRequestException("There is no status with this id.");
2006 $id = $parent['id'];
2008 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2009 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2012 $condition[0] .= " AND `id` <= ?";
2013 $condition[] = $max_id;
2016 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2017 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2019 if (!DBA::isResult($statuses)) {
2020 throw new BadRequestException("There is no status with id $id.");
2023 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2025 $data = ['status' => $ret];
2026 return api_format_data("statuses", $type, $data);
2029 /// @TODO move to top of file or somewhere better
2030 api_register_func('api/conversation/show', 'api_conversation_show', true);
2031 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2036 * @param string $type Return type (atom, rss, xml, json)
2038 * @return array|string
2039 * @throws BadRequestException
2040 * @throws ForbiddenException
2041 * @throws ImagickException
2042 * @throws InternalServerErrorException
2043 * @throws UnauthorizedException
2044 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2046 function api_statuses_repeat($type)
2052 if (api_user() === false) {
2053 throw new ForbiddenException();
2059 $id = intval($a->argv[3] ?? 0);
2062 $id = intval($_REQUEST['id'] ?? 0);
2067 $id = intval($a->argv[4] ?? 0);
2070 Logger::log('API: api_statuses_repeat: '.$id);
2072 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2073 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2075 if (DBA::isResult($item) && !empty($item['body'])) {
2076 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2077 if (!Item::performActivity($id, 'announce', local_user())) {
2078 throw new InternalServerErrorException();
2083 if (strpos($item['body'], "[/share]") !== false) {
2084 $pos = strpos($item['body'], "[share");
2085 $post = substr($item['body'], $pos);
2087 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2089 if (!empty($item['title'])) {
2090 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2093 $post .= $item['body'];
2094 $post .= "[/share]";
2096 $_REQUEST['body'] = $post;
2097 $_REQUEST['profile_uid'] = api_user();
2098 $_REQUEST['api_source'] = true;
2100 if (empty($_REQUEST['source'])) {
2101 $_REQUEST["source"] = api_source();
2104 $item_id = item_post($a);
2107 throw new ForbiddenException();
2110 // output the post that we just posted.
2112 return api_status_show($type, $item_id);
2115 /// @TODO move to top of file or somewhere better
2116 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2119 * Destroys a specific status.
2121 * @param string $type Return type (atom, rss, xml, json)
2123 * @return array|string
2124 * @throws BadRequestException
2125 * @throws ForbiddenException
2126 * @throws ImagickException
2127 * @throws InternalServerErrorException
2128 * @throws UnauthorizedException
2129 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2131 function api_statuses_destroy($type)
2135 if (api_user() === false) {
2136 throw new ForbiddenException();
2142 $id = intval($a->argv[3] ?? 0);
2145 $id = intval($_REQUEST['id'] ?? 0);
2150 $id = intval($a->argv[4] ?? 0);
2153 Logger::log('API: api_statuses_destroy: '.$id);
2155 $ret = api_statuses_show($type);
2157 Item::deleteForUser(['id' => $id], api_user());
2162 /// @TODO move to top of file or somewhere better
2163 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2166 * Returns the most recent mentions.
2168 * @param string $type Return type (atom, rss, xml, json)
2170 * @return array|string
2171 * @throws BadRequestException
2172 * @throws ForbiddenException
2173 * @throws ImagickException
2174 * @throws InternalServerErrorException
2175 * @throws UnauthorizedException
2176 * @see http://developer.twitter.com/doc/get/statuses/mentions
2178 function api_statuses_mentions($type)
2181 $user_info = api_get_user($a);
2183 if (api_user() === false || $user_info === false) {
2184 throw new ForbiddenException();
2187 unset($_REQUEST["user_id"]);
2188 unset($_GET["user_id"]);
2190 unset($_REQUEST["screen_name"]);
2191 unset($_GET["screen_name"]);
2193 // get last network messages
2196 $since_id = intval($_REQUEST['since_id'] ?? 0);
2197 $max_id = intval($_REQUEST['max_id'] ?? 0);
2198 $count = intval($_REQUEST['count'] ?? 20);
2199 $page = intval($_REQUEST['page'] ?? 1);
2201 $start = max(0, ($page - 1) * $count);
2203 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2204 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2205 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2207 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2208 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2209 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2210 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2211 api_user(), $since_id];
2214 $query .= " AND `id` <= ?";
2215 $condition[] = $max_id;
2218 array_unshift($condition, $query);
2220 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2221 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2223 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2225 $data = ['status' => $ret];
2230 $data = api_rss_extra($a, $data, $user_info);
2234 return api_format_data("statuses", $type, $data);
2237 /// @TODO move to top of file or somewhere better
2238 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2239 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2242 * Returns the most recent statuses posted by the user.
2244 * @param string $type Either "json" or "xml"
2245 * @return string|array
2246 * @throws BadRequestException
2247 * @throws ForbiddenException
2248 * @throws ImagickException
2249 * @throws InternalServerErrorException
2250 * @throws UnauthorizedException
2251 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2253 function api_statuses_user_timeline($type)
2256 $user_info = api_get_user($a);
2258 if (api_user() === false || $user_info === false) {
2259 throw new ForbiddenException();
2262 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2264 $since_id = $_REQUEST['since_id'] ?? 0;
2265 $max_id = $_REQUEST['max_id'] ?? 0;
2266 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2267 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2270 $count = $_REQUEST['count'] ?? 20;
2271 $page = $_REQUEST['page'] ?? 1;
2273 $start = max(0, ($page - 1) * $count);
2275 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2276 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2278 if ($user_info['self'] == 1) {
2279 $condition[0] .= ' AND `wall` ';
2282 if ($exclude_replies) {
2283 $condition[0] .= ' AND `gravity` = ?';
2284 $condition[] = GRAVITY_PARENT;
2287 if ($conversation_id > 0) {
2288 $condition[0] .= " AND `parent` = ?";
2289 $condition[] = $conversation_id;
2293 $condition[0] .= " AND `id` <= ?";
2294 $condition[] = $max_id;
2296 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2297 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2299 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2303 $data = ['status' => $ret];
2308 $data = api_rss_extra($a, $data, $user_info);
2312 return api_format_data("statuses", $type, $data);
2315 /// @TODO move to top of file or somewhere better
2316 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2319 * Star/unstar an item.
2320 * param: id : id of the item
2322 * @param string $type Return type (atom, rss, xml, json)
2324 * @return array|string
2325 * @throws BadRequestException
2326 * @throws ForbiddenException
2327 * @throws ImagickException
2328 * @throws InternalServerErrorException
2329 * @throws UnauthorizedException
2330 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2332 function api_favorites_create_destroy($type)
2336 if (api_user() === false) {
2337 throw new ForbiddenException();
2340 // for versioned api.
2341 /// @TODO We need a better global soluton
2342 $action_argv_id = 2;
2343 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2344 $action_argv_id = 3;
2347 if ($a->argc <= $action_argv_id) {
2348 throw new BadRequestException("Invalid request.");
2350 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2351 if ($a->argc == $action_argv_id + 2) {
2352 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2354 $itemid = intval($_REQUEST['id'] ?? 0);
2357 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2359 if (!DBA::isResult($item)) {
2360 throw new BadRequestException("Invalid item.");
2365 $item['starred'] = 1;
2368 $item['starred'] = 0;
2371 throw new BadRequestException("Invalid action ".$action);
2374 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2377 throw new InternalServerErrorException("DB error");
2381 $user_info = api_get_user($a);
2382 $rets = api_format_items([$item], $user_info, false, $type);
2385 $data = ['status' => $ret];
2390 $data = api_rss_extra($a, $data, $user_info);
2394 return api_format_data("status", $type, $data);
2397 /// @TODO move to top of file or somewhere better
2398 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2399 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2402 * Returns the most recent favorite statuses.
2404 * @param string $type Return type (atom, rss, xml, json)
2406 * @return string|array
2407 * @throws BadRequestException
2408 * @throws ForbiddenException
2409 * @throws ImagickException
2410 * @throws InternalServerErrorException
2411 * @throws UnauthorizedException
2413 function api_favorites($type)
2418 $user_info = api_get_user($a);
2420 if (api_user() === false || $user_info === false) {
2421 throw new ForbiddenException();
2426 // in friendica starred item are private
2427 // return favorites only for self
2428 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2430 if ($user_info['self'] == 0) {
2434 $since_id = $_REQUEST['since_id'] ?? 0;
2435 $max_id = $_REQUEST['max_id'] ?? 0;
2436 $count = $_GET['count'] ?? 20;
2437 $page = $_REQUEST['page'] ?? 1;
2439 $start = max(0, ($page - 1) * $count);
2441 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2442 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2444 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2447 $condition[0] .= " AND `id` <= ?";
2448 $condition[] = $max_id;
2451 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2453 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2458 $data = ['status' => $ret];
2463 $data = api_rss_extra($a, $data, $user_info);
2467 return api_format_data("statuses", $type, $data);
2470 /// @TODO move to top of file or somewhere better
2471 api_register_func('api/favorites', 'api_favorites', true);
2475 * @param array $item
2476 * @param array $recipient
2477 * @param array $sender
2480 * @throws InternalServerErrorException
2482 function api_format_messages($item, $recipient, $sender)
2484 // standard meta information
2486 'id' => $item['id'],
2487 'sender_id' => $sender['id'],
2489 'recipient_id' => $recipient['id'],
2490 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2491 'sender_screen_name' => $sender['screen_name'],
2492 'recipient_screen_name' => $recipient['screen_name'],
2493 'sender' => $sender,
2494 'recipient' => $recipient,
2496 'friendica_seen' => $item['seen'] ?? 0,
2497 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2500 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2501 if (isset($ret['sender']['uid'])) {
2502 unset($ret['sender']['uid']);
2504 if (isset($ret['sender']['self'])) {
2505 unset($ret['sender']['self']);
2507 if (isset($ret['recipient']['uid'])) {
2508 unset($ret['recipient']['uid']);
2510 if (isset($ret['recipient']['self'])) {
2511 unset($ret['recipient']['self']);
2514 //don't send title to regular StatusNET requests to avoid confusing these apps
2515 if (!empty($_GET['getText'])) {
2516 $ret['title'] = $item['title'];
2517 if ($_GET['getText'] == 'html') {
2518 $ret['text'] = BBCode::convert($item['body'], false);
2519 } elseif ($_GET['getText'] == 'plain') {
2520 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2523 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2525 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2526 unset($ret['sender']);
2527 unset($ret['recipient']);
2535 * @param array $item
2538 * @throws InternalServerErrorException
2540 function api_convert_item($item)
2542 $body = api_add_attachments_to_body($item);
2544 $entities = api_get_entitities($statustext, $body);
2546 // Add pictures to the attachment array and remove them from the body
2547 $attachments = api_get_attachments($body);
2549 // Workaround for ostatus messages where the title is identically to the body
2550 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2551 $statusbody = trim(HTML::toPlaintext($html, 0));
2553 // handle data: images
2554 $statusbody = api_format_items_embeded_images($item, $statusbody);
2556 $statustitle = trim($item['title']);
2558 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2559 $statustext = trim($statusbody);
2561 $statustext = trim($statustitle."\n\n".$statusbody);
2564 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2565 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2568 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2570 // Workaround for clients with limited HTML parser functionality
2571 $search = ["<br>", "<blockquote>", "</blockquote>",
2572 "<h1>", "</h1>", "<h2>", "</h2>",
2573 "<h3>", "</h3>", "<h4>", "</h4>",
2574 "<h5>", "</h5>", "<h6>", "</h6>"];
2575 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2576 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2577 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2578 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2579 $statushtml = str_replace($search, $replace, $statushtml);
2581 if ($item['title'] != "") {
2582 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2586 $oldtext = $statushtml;
2587 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2588 } while ($oldtext != $statushtml);
2590 if (substr($statushtml, 0, 4) == '<br>') {
2591 $statushtml = substr($statushtml, 4);
2594 if (substr($statushtml, 0, -4) == '<br>') {
2595 $statushtml = substr($statushtml, -4);
2598 // feeds without body should contain the link
2599 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2600 $statushtml .= BBCode::convert($item['plink']);
2604 "text" => $statustext,
2605 "html" => $statushtml,
2606 "attachments" => $attachments,
2607 "entities" => $entities
2612 * Add media attachments to the body
2614 * @param array $item
2615 * @return string body with added media
2617 function api_add_attachments_to_body(array $item)
2619 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2621 if (strpos($body, '[/img]') !== false) {
2625 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2626 if (!empty($media['preview'])) {
2627 $description = $media['description'] ?: $media['name'];
2628 if (!empty($description)) {
2629 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2631 $body .= "\n[img]" . $media['preview'] .'[/img]';
2641 * @param string $body
2644 * @throws InternalServerErrorException
2646 function api_get_attachments(&$body)
2648 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2649 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2651 $URLSearchString = "^\[\]";
2652 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2656 // Remove all embedded pictures, since they are added as attachments
2657 foreach ($images[0] as $orig) {
2658 $body = str_replace($orig, '', $body);
2663 foreach ($images[1] as $image) {
2664 $imagedata = Images::getInfoFromURLCached($image);
2667 if (DI::config()->get("system", "proxy_disabled")) {
2668 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2670 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2675 return $attachments;
2680 * @param string $text
2681 * @param string $bbcode
2684 * @throws InternalServerErrorException
2685 * @todo Links at the first character of the post
2687 function api_get_entitities(&$text, $bbcode)
2689 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2691 if ($include_entities != "true") {
2692 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2694 foreach ($images[1] as $image) {
2695 $replace = ProxyUtils::proxifyUrl($image, false);
2696 $text = str_replace($image, $replace, $text);
2701 $bbcode = BBCode::cleanPictureLinks($bbcode);
2703 // Change pure links in text to bbcode uris
2704 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2707 $entities["hashtags"] = [];
2708 $entities["symbols"] = [];
2709 $entities["urls"] = [];
2710 $entities["user_mentions"] = [];
2712 $URLSearchString = "^\[\]";
2714 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2716 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2717 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2719 $bbcode = preg_replace(
2720 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2721 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2724 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2726 $bbcode = preg_replace(
2727 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2728 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2731 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2733 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2735 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2738 foreach ($urls[1] as $id => $url) {
2739 $start = iconv_strpos($text, $url, 0, "UTF-8");
2740 if (!($start === false)) {
2741 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2745 ksort($ordered_urls);
2749 foreach ($ordered_urls as $url) {
2750 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2751 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2753 $display_url = $url["title"];
2755 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2756 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2758 if (strlen($display_url) > 26) {
2759 $display_url = substr($display_url, 0, 25)."…";
2763 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2764 if (!($start === false)) {
2765 $entities["urls"][] = ["url" => $url["url"],
2766 "expanded_url" => $url["url"],
2767 "display_url" => $display_url,
2768 "indices" => [$start, $start+strlen($url["url"])]];
2769 $offset = $start + 1;
2773 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2774 $ordered_images = [];
2775 foreach ($images as $image) {
2776 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2777 if (!($start === false)) {
2778 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2782 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2783 foreach ($images[1] as $image) {
2784 $start = iconv_strpos($text, $image, 0, "UTF-8");
2785 if (!($start === false)) {
2786 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2792 foreach ($ordered_images as $image) {
2793 $url = $image['url'];
2794 $ext_alt_text = $image['alt'];
2796 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2797 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2799 if (strlen($display_url) > 26) {
2800 $display_url = substr($display_url, 0, 25)."…";
2803 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2804 if (!($start === false)) {
2805 $image = Images::getInfoFromURLCached($url);
2807 // If image cache is activated, then use the following sizes:
2808 // thumb (150), small (340), medium (600) and large (1024)
2809 if (!DI::config()->get("system", "proxy_disabled")) {
2810 $media_url = ProxyUtils::proxifyUrl($url, false);
2813 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2814 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2816 if (($image[0] > 150) || ($image[1] > 150)) {
2817 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2818 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2821 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2822 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2824 if (($image[0] > 600) || ($image[1] > 600)) {
2825 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2826 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2830 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2833 $entities["media"][] = [
2835 "id_str" => (string) ($start + 1),
2836 "indices" => [$start, $start+strlen($url)],
2837 "media_url" => Strings::normaliseLink($media_url),
2838 "media_url_https" => $media_url,
2840 "display_url" => $display_url,
2841 "expanded_url" => $url,
2842 "ext_alt_text" => $ext_alt_text,
2846 $offset = $start + 1;
2855 * @param array $item
2856 * @param string $text
2860 function api_format_items_embeded_images($item, $text)
2862 $text = preg_replace_callback(
2863 '|data:image/([^;]+)[^=]+=*|m',
2864 function () use ($item) {
2865 return DI::baseUrl() . '/display/' . $item['guid'];
2873 * return <a href='url'>name</a> as array
2875 * @param string $txt text
2880 function api_contactlink_to_array($txt)
2883 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2884 if ($r && count($match)==3) {
2886 'name' => $match[2],
2900 * return likes, dislikes and attend status for item
2902 * @param array $item array
2903 * @param string $type Return type (atom, rss, xml, json)
2906 * likes => int count,
2907 * dislikes => int count
2908 * @throws BadRequestException
2909 * @throws ImagickException
2910 * @throws InternalServerErrorException
2911 * @throws UnauthorizedException
2913 function api_format_items_activities($item, $type = "json")
2922 'attendmaybe' => [],
2926 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2927 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2929 while ($parent_item = Post::fetch($ret)) {
2930 // not used as result should be structured like other user data
2931 //builtin_activity_puller($i, $activities);
2933 // get user data and add it to the array of the activity
2934 $user = api_get_user($a, $parent_item['author-id']);
2935 switch ($parent_item['verb']) {
2936 case Activity::LIKE:
2937 $activities['like'][] = $user;
2939 case Activity::DISLIKE:
2940 $activities['dislike'][] = $user;
2942 case Activity::ATTEND:
2943 $activities['attendyes'][] = $user;
2945 case Activity::ATTENDNO:
2946 $activities['attendno'][] = $user;
2948 case Activity::ATTENDMAYBE:
2949 $activities['attendmaybe'][] = $user;
2951 case Activity::ANNOUNCE:
2952 $activities['announce'][] = $user;
2961 if ($type == "xml") {
2962 $xml_activities = [];
2963 foreach ($activities as $k => $v) {
2964 // change xml element from "like" to "friendica:like"
2965 $xml_activities["friendica:".$k] = $v;
2966 // add user data into xml output
2968 foreach ($v as $user) {
2969 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2972 $activities = $xml_activities;
2979 * format items to be returned by api
2981 * @param array $items array of items
2982 * @param array $user_info
2983 * @param bool $filter_user filter items by $user_info
2984 * @param string $type Return type (atom, rss, xml, json)
2986 * @throws BadRequestException
2987 * @throws ImagickException
2988 * @throws InternalServerErrorException
2989 * @throws UnauthorizedException
2991 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2993 $a = Friendica\DI::app();
2997 if (empty($items)) {
3001 foreach ((array)$items as $item) {
3002 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3004 // Look if the posts are matching if they should be filtered by user id
3005 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3009 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3018 * @param array $item Item record
3019 * @param string $type Return format (atom, rss, xml, json)
3020 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3021 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3022 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3023 * @return array API-formatted status
3024 * @throws BadRequestException
3025 * @throws ImagickException
3026 * @throws InternalServerErrorException
3027 * @throws UnauthorizedException
3029 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3031 $a = Friendica\DI::app();
3033 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3034 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3037 localize_item($item);
3039 $in_reply_to = api_in_reply_to($item);
3041 $converted = api_convert_item($item);
3043 if ($type == "xml") {
3044 $geo = "georss:point";
3050 'text' => $converted["text"],
3051 'truncated' => false,
3052 'created_at'=> api_date($item['created']),
3053 'in_reply_to_status_id' => $in_reply_to['status_id'],
3054 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3055 'source' => (($item['app']) ? $item['app'] : 'web'),
3056 'id' => intval($item['id']),
3057 'id_str' => (string) intval($item['id']),
3058 'in_reply_to_user_id' => $in_reply_to['user_id'],
3059 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3060 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3062 'favorited' => $item['starred'] ? true : false,
3063 'user' => $status_user,
3064 'friendica_author' => $author_user,
3065 'friendica_owner' => $owner_user,
3066 'friendica_private' => $item['private'] == Item::PRIVATE,
3067 //'entities' => NULL,
3068 'statusnet_html' => $converted["html"],
3069 'statusnet_conversation_id' => $item['parent'],
3070 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3071 'friendica_activities' => api_format_items_activities($item, $type),
3072 'friendica_title' => $item['title'],
3073 'friendica_html' => BBCode::convert($item['body'], false)
3076 if (count($converted["attachments"]) > 0) {
3077 $status["attachments"] = $converted["attachments"];
3080 if (count($converted["entities"]) > 0) {
3081 $status["entities"] = $converted["entities"];
3084 if ($status["source"] == 'web') {
3085 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3086 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3087 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3090 $retweeted_item = [];
3093 if ($item['gravity'] == GRAVITY_PARENT) {
3094 $body = $item['body'];
3095 $retweeted_item = api_share_as_retweet($item);
3096 if ($body != $item['body']) {
3097 $quoted_item = $retweeted_item;
3098 $retweeted_item = [];
3102 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3103 $announce = api_get_announce($item);
3104 if (!empty($announce)) {
3105 $retweeted_item = $item;
3107 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3111 if (!empty($quoted_item)) {
3112 if ($quoted_item['id'] != $item['id']) {
3113 $quoted_status = api_format_item($quoted_item);
3114 /// @todo Only remove the attachments that are also contained in the quotes status
3115 unset($status['attachments']);
3116 unset($status['entities']);
3118 $conv_quoted = api_convert_item($quoted_item);
3119 $quoted_status = $status;
3120 unset($quoted_status['attachments']);
3121 unset($quoted_status['entities']);
3122 unset($quoted_status['statusnet_conversation_id']);
3123 $quoted_status['text'] = $conv_quoted['text'];
3124 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3126 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3127 } catch (BadRequestException $e) {
3128 // user not found. should be found?
3129 /// @todo check if the user should be always found
3130 $quoted_status["user"] = [];
3133 unset($quoted_status['friendica_author']);
3134 unset($quoted_status['friendica_owner']);
3135 unset($quoted_status['friendica_activities']);
3136 unset($quoted_status['friendica_private']);
3139 if (!empty($retweeted_item)) {
3140 $retweeted_status = $status;
3141 unset($retweeted_status['friendica_author']);
3142 unset($retweeted_status['friendica_owner']);
3143 unset($retweeted_status['friendica_activities']);
3144 unset($retweeted_status['friendica_private']);
3145 unset($retweeted_status['statusnet_conversation_id']);
3146 $status['user'] = $status['friendica_owner'];
3148 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3149 } catch (BadRequestException $e) {
3150 // user not found. should be found?
3151 /// @todo check if the user should be always found
3152 $retweeted_status["user"] = [];
3155 $rt_converted = api_convert_item($retweeted_item);
3157 $retweeted_status['text'] = $rt_converted["text"];
3158 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3159 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3161 if (!empty($quoted_status)) {
3162 $retweeted_status['quoted_status'] = $quoted_status;
3165 $status['friendica_author'] = $retweeted_status['user'];
3166 $status['retweeted_status'] = $retweeted_status;
3167 } elseif (!empty($quoted_status)) {
3168 $root_status = api_convert_item($item);
3170 $status['text'] = $root_status["text"];
3171 $status['statusnet_html'] = $root_status["html"];
3172 $status['quoted_status'] = $quoted_status;
3175 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3176 unset($status["user"]["uid"]);
3177 unset($status["user"]["self"]);
3179 if ($item["coord"] != "") {
3180 $coords = explode(' ', $item["coord"]);
3181 if (count($coords) == 2) {
3182 if ($type == "json") {
3183 $status["geo"] = ['type' => 'Point',
3184 'coordinates' => [(float) $coords[0],
3185 (float) $coords[1]]];
3186 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3187 $status["georss:point"] = $item["coord"];
3196 * Returns the remaining number of API requests available to the user before the API limit is reached.
3198 * @param string $type Return type (atom, rss, xml, json)
3200 * @return array|string
3203 function api_account_rate_limit_status($type)
3205 if ($type == "xml") {
3207 'remaining-hits' => '150',
3208 '@attributes' => ["type" => "integer"],
3209 'hourly-limit' => '150',
3210 '@attributes2' => ["type" => "integer"],
3211 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3212 '@attributes3' => ["type" => "datetime"],
3213 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3214 '@attributes4' => ["type" => "integer"],
3218 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3219 'remaining_hits' => '150',
3220 'hourly_limit' => '150',
3221 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3225 return api_format_data('hash', $type, ['hash' => $hash]);
3228 /// @TODO move to top of file or somewhere better
3229 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3232 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3234 * @param string $type Return type (atom, rss, xml, json)
3236 * @return array|string
3238 function api_help_test($type)
3240 if ($type == 'xml') {
3246 return api_format_data('ok', $type, ["ok" => $ok]);
3249 /// @TODO move to top of file or somewhere better
3250 api_register_func('api/help/test', 'api_help_test', false);
3253 * Returns all lists the user subscribes to.
3255 * @param string $type Return type (atom, rss, xml, json)
3257 * @return array|string
3258 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3260 function api_lists_list($type)
3263 /// @TODO $ret is not filled here?
3264 return api_format_data('lists', $type, ["lists_list" => $ret]);
3267 /// @TODO move to top of file or somewhere better
3268 api_register_func('api/lists/list', 'api_lists_list', true);
3269 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3272 * Returns all groups the user owns.
3274 * @param string $type Return type (atom, rss, xml, json)
3276 * @return array|string
3277 * @throws BadRequestException
3278 * @throws ForbiddenException
3279 * @throws ImagickException
3280 * @throws InternalServerErrorException
3281 * @throws UnauthorizedException
3282 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3284 function api_lists_ownerships($type)
3288 if (api_user() === false) {
3289 throw new ForbiddenException();
3293 $user_info = api_get_user($a);
3294 $uid = $user_info['uid'];
3296 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3298 // loop through all groups
3300 foreach ($groups as $group) {
3301 if ($group['visible']) {
3307 'name' => $group['name'],
3308 'id' => intval($group['id']),
3309 'id_str' => (string) $group['id'],
3310 'user' => $user_info,
3314 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3317 /// @TODO move to top of file or somewhere better
3318 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3321 * Returns recent statuses from users in the specified group.
3323 * @param string $type Return type (atom, rss, xml, json)
3325 * @return array|string
3326 * @throws BadRequestException
3327 * @throws ForbiddenException
3328 * @throws ImagickException
3329 * @throws InternalServerErrorException
3330 * @throws UnauthorizedException
3331 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3333 function api_lists_statuses($type)
3337 $user_info = api_get_user($a);
3338 if (api_user() === false || $user_info === false) {
3339 throw new ForbiddenException();
3342 unset($_REQUEST["user_id"]);
3343 unset($_GET["user_id"]);
3345 unset($_REQUEST["screen_name"]);
3346 unset($_GET["screen_name"]);
3348 if (empty($_REQUEST['list_id'])) {
3349 throw new BadRequestException('list_id not specified');
3353 $count = $_REQUEST['count'] ?? 20;
3354 $page = $_REQUEST['page'] ?? 1;
3355 $since_id = $_REQUEST['since_id'] ?? 0;
3356 $max_id = $_REQUEST['max_id'] ?? 0;
3357 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3358 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3360 $start = max(0, ($page - 1) * $count);
3362 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3363 $gids = array_column($groups, 'contact-id');
3364 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3365 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3368 $condition[0] .= " AND `id` <= ?";
3369 $condition[] = $max_id;
3371 if ($exclude_replies > 0) {
3372 $condition[0] .= ' AND `gravity` = ?';
3373 $condition[] = GRAVITY_PARENT;
3375 if ($conversation_id > 0) {
3376 $condition[0] .= " AND `parent` = ?";
3377 $condition[] = $conversation_id;
3380 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3381 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3383 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3385 $data = ['status' => $items];
3390 $data = api_rss_extra($a, $data, $user_info);
3394 return api_format_data("statuses", $type, $data);
3397 /// @TODO move to top of file or somewhere better
3398 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3401 * Returns either the friends of the follower list
3403 * Considers friends and followers lists to be private and won't return
3404 * anything if any user_id parameter is passed.
3406 * @param string $qtype Either "friends" or "followers"
3407 * @return boolean|array
3408 * @throws BadRequestException
3409 * @throws ForbiddenException
3410 * @throws ImagickException
3411 * @throws InternalServerErrorException
3412 * @throws UnauthorizedException
3414 function api_statuses_f($qtype)
3418 if (api_user() === false) {
3419 throw new ForbiddenException();
3423 $count = $_GET['count'] ?? 20;
3424 $page = $_GET['page'] ?? 1;
3426 $start = max(0, ($page - 1) * $count);
3428 $user_info = api_get_user($a);
3430 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3431 /* this is to stop Hotot to load friends multiple times
3432 * I'm not sure if I'm missing return something or
3433 * is a bug in hotot. Workaround, meantime
3437 return array('$users' => $ret);*/
3442 if ($qtype == 'friends') {
3443 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3444 } elseif ($qtype == 'followers') {
3445 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3448 // friends and followers only for self
3449 if ($user_info['self'] == 0) {
3450 $sql_extra = " AND false ";
3453 if ($qtype == 'blocks') {
3454 $sql_filter = 'AND `blocked` AND NOT `pending`';
3455 } elseif ($qtype == 'incoming') {
3456 $sql_filter = 'AND `pending`';
3458 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3476 foreach ($r as $cid) {
3477 $user = api_get_user($a, $cid['nurl']);
3478 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3479 unset($user["uid"]);
3480 unset($user["self"]);
3487 return ['user' => $ret];
3492 * Returns the list of friends of the provided user
3494 * @deprecated By Twitter API in favor of friends/list
3496 * @param string $type Either "json" or "xml"
3497 * @return boolean|string|array
3498 * @throws BadRequestException
3499 * @throws ForbiddenException
3501 function api_statuses_friends($type)
3503 $data = api_statuses_f("friends");
3504 if ($data === false) {
3507 return api_format_data("users", $type, $data);
3511 * Returns the list of followers of the provided user
3513 * @deprecated By Twitter API in favor of friends/list
3515 * @param string $type Either "json" or "xml"
3516 * @return boolean|string|array
3517 * @throws BadRequestException
3518 * @throws ForbiddenException
3520 function api_statuses_followers($type)
3522 $data = api_statuses_f("followers");
3523 if ($data === false) {
3526 return api_format_data("users", $type, $data);
3529 /// @TODO move to top of file or somewhere better
3530 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3531 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3534 * Returns the list of blocked users
3536 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3538 * @param string $type Either "json" or "xml"
3540 * @return boolean|string|array
3541 * @throws BadRequestException
3542 * @throws ForbiddenException
3544 function api_blocks_list($type)
3546 $data = api_statuses_f('blocks');
3547 if ($data === false) {
3550 return api_format_data("users", $type, $data);
3553 /// @TODO move to top of file or somewhere better
3554 api_register_func('api/blocks/list', 'api_blocks_list', true);
3557 * Returns the list of pending users IDs
3559 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3561 * @param string $type Either "json" or "xml"
3563 * @return boolean|string|array
3564 * @throws BadRequestException
3565 * @throws ForbiddenException
3567 function api_friendships_incoming($type)
3569 $data = api_statuses_f('incoming');
3570 if ($data === false) {
3575 foreach ($data['user'] as $user) {
3576 $ids[] = $user['id'];
3579 return api_format_data("ids", $type, ['id' => $ids]);
3582 /// @TODO move to top of file or somewhere better
3583 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3586 * Returns the instance's configuration information.
3588 * @param string $type Return type (atom, rss, xml, json)
3590 * @return array|string
3591 * @throws InternalServerErrorException
3593 function api_statusnet_config($type)
3595 $name = DI::config()->get('config', 'sitename');
3596 $server = DI::baseUrl()->getHostname();
3597 $logo = DI::baseUrl() . '/images/friendica-64.png';
3598 $email = DI::config()->get('config', 'admin_email');
3599 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3600 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3601 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3602 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3603 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3606 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3607 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3608 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3609 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3610 'shorturllength' => '30',
3612 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3613 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3614 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3615 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3620 return api_format_data('config', $type, ['config' => $config]);
3623 /// @TODO move to top of file or somewhere better
3624 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3625 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3629 * @param string $type Return type (atom, rss, xml, json)
3631 * @return array|string
3633 function api_statusnet_version($type)
3636 $fake_statusnet_version = "0.9.7";
3638 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3641 /// @TODO move to top of file or somewhere better
3642 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3643 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3646 * Sends a new direct message.
3648 * @param string $type Return type (atom, rss, xml, json)
3650 * @return array|string
3651 * @throws BadRequestException
3652 * @throws ForbiddenException
3653 * @throws ImagickException
3654 * @throws InternalServerErrorException
3655 * @throws NotFoundException
3656 * @throws UnauthorizedException
3657 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3659 function api_direct_messages_new($type)
3663 if (api_user() === false) {
3664 throw new ForbiddenException();
3667 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3671 $sender = api_get_user($a);
3674 if (!empty($_POST['screen_name'])) {
3676 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3678 DBA::escape($_POST['screen_name'])
3681 if (DBA::isResult($r)) {
3682 // Selecting the id by priority, friendica first
3683 api_best_nickname($r);
3685 $recipient = api_get_user($a, $r[0]['nurl']);
3688 $recipient = api_get_user($a, $_POST['user_id']);
3691 if (empty($recipient)) {
3692 throw new NotFoundException('Recipient not found');
3696 if (!empty($_REQUEST['replyto'])) {
3698 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3700 intval($_REQUEST['replyto'])
3702 $replyto = $r[0]['parent-uri'];
3703 $sub = $r[0]['title'];
3705 if (!empty($_REQUEST['title'])) {
3706 $sub = $_REQUEST['title'];
3708 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3712 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3715 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3716 $ret = api_format_messages($r[0], $recipient, $sender);
3718 $ret = ["error"=>$id];
3721 $data = ['direct_message'=>$ret];
3727 $data = api_rss_extra($a, $data, $sender);
3731 return api_format_data("direct-messages", $type, $data);
3734 /// @TODO move to top of file or somewhere better
3735 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3738 * delete a direct_message from mail table through api
3740 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3741 * @return string|array
3742 * @throws BadRequestException
3743 * @throws ForbiddenException
3744 * @throws ImagickException
3745 * @throws InternalServerErrorException
3746 * @throws UnauthorizedException
3747 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3749 function api_direct_messages_destroy($type)
3753 if (api_user() === false) {
3754 throw new ForbiddenException();
3758 $user_info = api_get_user($a);
3760 $id = $_REQUEST['id'] ?? 0;
3762 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3763 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3764 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3766 $uid = $user_info['uid'];
3767 // error if no id or parenturi specified (for clients posting parent-uri as well)
3768 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3769 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3770 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3773 // BadRequestException if no id specified (for clients using Twitter API)
3775 throw new BadRequestException('Message id not specified');
3778 // add parent-uri to sql command if specified by calling app
3779 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3781 // get data of the specified message id
3783 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3788 // error message if specified id is not in database
3789 if (!DBA::isResult($r)) {
3790 if ($verbose == "true") {
3791 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3792 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3794 /// @todo BadRequestException ok for Twitter API clients?
3795 throw new BadRequestException('message id not in database');
3800 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3805 if ($verbose == "true") {
3808 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3809 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3811 $answer = ['result' => 'error', 'message' => 'unknown error'];
3812 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3815 /// @todo return JSON data like Twitter API not yet implemented
3818 /// @TODO move to top of file or somewhere better
3819 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3824 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3825 * @return string|array
3826 * @throws BadRequestException
3827 * @throws ForbiddenException
3828 * @throws ImagickException
3829 * @throws InternalServerErrorException
3830 * @throws NotFoundException
3831 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3833 function api_friendships_destroy($type)
3837 if ($uid === false) {
3838 throw new ForbiddenException();
3841 $contact_id = $_REQUEST['user_id'] ?? 0;
3843 if (empty($contact_id)) {
3844 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3845 throw new BadRequestException("no user_id specified");
3848 // Get Contact by given id
3849 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3851 if(!DBA::isResult($contact)) {
3852 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3853 throw new NotFoundException("no contact found to given ID");
3856 $url = $contact["url"];
3858 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3859 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3860 Strings::normaliseLink($url), $url];
3861 $contact = DBA::selectFirst('contact', [], $condition);
3863 if (!DBA::isResult($contact)) {
3864 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3865 throw new NotFoundException("Not following Contact");
3868 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3869 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3870 throw new ExpectationFailedException("Not supported");
3873 $dissolve = ($contact['rel'] == Contact::SHARING);
3875 $owner = User::getOwnerDataById($uid);
3877 Contact::terminateFriendship($owner, $contact, $dissolve);
3880 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3881 throw new NotFoundException("Error Processing Request");
3884 // Sharing-only contacts get deleted as there no relationship any more
3886 Contact::remove($contact['id']);
3888 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3891 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3892 unset($contact["uid"]);
3893 unset($contact["self"]);
3895 // Set screen_name since Twidere requests it
3896 $contact["screen_name"] = $contact["nick"];
3898 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3900 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3904 * @param string $type Return type (atom, rss, xml, json)
3905 * @param string $box
3906 * @param string $verbose
3908 * @return array|string
3909 * @throws BadRequestException
3910 * @throws ForbiddenException
3911 * @throws ImagickException
3912 * @throws InternalServerErrorException
3913 * @throws UnauthorizedException
3915 function api_direct_messages_box($type, $box, $verbose)
3918 if (api_user() === false) {
3919 throw new ForbiddenException();
3922 $count = $_GET['count'] ?? 20;
3923 $page = $_REQUEST['page'] ?? 1;
3925 $since_id = $_REQUEST['since_id'] ?? 0;
3926 $max_id = $_REQUEST['max_id'] ?? 0;
3928 $user_id = $_REQUEST['user_id'] ?? '';
3929 $screen_name = $_REQUEST['screen_name'] ?? '';
3932 unset($_REQUEST["user_id"]);
3933 unset($_GET["user_id"]);
3935 unset($_REQUEST["screen_name"]);
3936 unset($_GET["screen_name"]);
3938 $user_info = api_get_user($a);
3939 if ($user_info === false) {
3940 throw new ForbiddenException();
3942 $profile_url = $user_info["url"];
3945 $start = max(0, ($page - 1) * $count);
3950 if ($box=="sentbox") {
3951 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3952 } elseif ($box == "conversation") {
3953 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3954 } elseif ($box == "all") {
3955 $sql_extra = "true";
3956 } elseif ($box == "inbox") {
3957 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3961 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3964 if ($user_id != "") {
3965 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3966 } elseif ($screen_name !="") {
3967 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3971 "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",
3977 if ($verbose == "true" && !DBA::isResult($r)) {
3978 $answer = ['result' => 'error', 'message' => 'no mails available'];
3979 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3983 foreach ($r as $item) {
3984 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3985 $recipient = $user_info;
3986 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3987 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3988 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3989 $sender = $user_info;
3992 if (isset($recipient) && isset($sender)) {
3993 $ret[] = api_format_messages($item, $recipient, $sender);
3998 $data = ['direct_message' => $ret];
4003 $data = api_rss_extra($a, $data, $user_info);
4007 return api_format_data("direct-messages", $type, $data);
4011 * Returns the most recent direct messages sent by the user.
4013 * @param string $type Return type (atom, rss, xml, json)
4015 * @return array|string
4016 * @throws BadRequestException
4017 * @throws ForbiddenException
4018 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4020 function api_direct_messages_sentbox($type)
4022 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4023 return api_direct_messages_box($type, "sentbox", $verbose);
4027 * Returns the most recent direct messages sent to the user.
4029 * @param string $type Return type (atom, rss, xml, json)
4031 * @return array|string
4032 * @throws BadRequestException
4033 * @throws ForbiddenException
4034 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4036 function api_direct_messages_inbox($type)
4038 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4039 return api_direct_messages_box($type, "inbox", $verbose);
4044 * @param string $type Return type (atom, rss, xml, json)
4046 * @return array|string
4047 * @throws BadRequestException
4048 * @throws ForbiddenException
4050 function api_direct_messages_all($type)
4052 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4053 return api_direct_messages_box($type, "all", $verbose);
4058 * @param string $type Return type (atom, rss, xml, json)
4060 * @return array|string
4061 * @throws BadRequestException
4062 * @throws ForbiddenException
4064 function api_direct_messages_conversation($type)
4066 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4067 return api_direct_messages_box($type, "conversation", $verbose);
4070 /// @TODO move to top of file or somewhere better
4071 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4072 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4073 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4074 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4077 * Returns an OAuth Request Token.
4079 * @see https://oauth.net/core/1.0/#auth_step1
4081 function api_oauth_request_token()
4083 $oauth1 = new FKOAuth1();
4085 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4086 } catch (Exception $e) {
4087 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4095 * Returns an OAuth Access Token.
4097 * @return array|string
4098 * @see https://oauth.net/core/1.0/#auth_step3
4100 function api_oauth_access_token()
4102 $oauth1 = new FKOAuth1();
4104 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4105 } catch (Exception $e) {
4106 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4113 /// @TODO move to top of file or somewhere better
4114 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4115 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4119 * delete a complete photoalbum with all containing photos from database through api
4121 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4122 * @return string|array
4123 * @throws BadRequestException
4124 * @throws ForbiddenException
4125 * @throws InternalServerErrorException
4127 function api_fr_photoalbum_delete($type)
4129 if (api_user() === false) {
4130 throw new ForbiddenException();
4133 $album = $_REQUEST['album'] ?? '';
4135 // we do not allow calls without album string
4137 throw new BadRequestException("no albumname specified");
4139 // check if album is existing
4141 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4142 if (!DBA::isResult($photos)) {
4143 throw new BadRequestException("album not available");
4146 $resourceIds = array_column($photos, 'resource-id');
4148 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4149 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4150 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4151 Item::deleteForUser($condition, api_user());
4153 // now let's delete all photos from the album
4154 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4156 // return success of deletion or error message
4158 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4159 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4161 throw new InternalServerErrorException("unknown error - deleting from database failed");
4166 * update the name of the album for all photos of an album
4168 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4169 * @return string|array
4170 * @throws BadRequestException
4171 * @throws ForbiddenException
4172 * @throws InternalServerErrorException
4174 function api_fr_photoalbum_update($type)
4176 if (api_user() === false) {
4177 throw new ForbiddenException();
4180 $album = $_REQUEST['album'] ?? '';
4181 $album_new = $_REQUEST['album_new'] ?? '';
4183 // we do not allow calls without album string
4185 throw new BadRequestException("no albumname specified");
4187 if ($album_new == "") {
4188 throw new BadRequestException("no new albumname specified");
4190 // check if album is existing
4191 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4192 throw new BadRequestException("album not available");
4194 // now let's update all photos to the albumname
4195 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4197 // return success of updating or error message
4199 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4200 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4202 throw new InternalServerErrorException("unknown error - updating in database failed");
4208 * list all photos of the authenticated user
4210 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4211 * @return string|array
4212 * @throws ForbiddenException
4213 * @throws InternalServerErrorException
4215 function api_fr_photos_list($type)
4217 if (api_user() === false) {
4218 throw new ForbiddenException();
4221 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4222 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4223 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4224 intval(local_user())
4227 'image/jpeg' => 'jpg',
4228 'image/png' => 'png',
4229 'image/gif' => 'gif'
4231 $data = ['photo'=>[]];
4232 if (DBA::isResult($r)) {
4233 foreach ($r as $rr) {
4235 $photo['id'] = $rr['resource-id'];
4236 $photo['album'] = $rr['album'];
4237 $photo['filename'] = $rr['filename'];
4238 $photo['type'] = $rr['type'];
4239 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4240 $photo['created'] = $rr['created'];
4241 $photo['edited'] = $rr['edited'];
4242 $photo['desc'] = $rr['desc'];
4244 if ($type == "xml") {
4245 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4247 $photo['thumb'] = $thumb;
4248 $data['photo'][] = $photo;
4252 return api_format_data("photos", $type, $data);
4256 * upload a new photo or change an existing photo
4258 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4259 * @return string|array
4260 * @throws BadRequestException
4261 * @throws ForbiddenException
4262 * @throws ImagickException
4263 * @throws InternalServerErrorException
4264 * @throws NotFoundException
4266 function api_fr_photo_create_update($type)
4268 if (api_user() === false) {
4269 throw new ForbiddenException();
4272 $photo_id = $_REQUEST['photo_id'] ?? null;
4273 $desc = $_REQUEST['desc'] ?? null;
4274 $album = $_REQUEST['album'] ?? null;
4275 $album_new = $_REQUEST['album_new'] ?? null;
4276 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4277 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4278 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4279 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4280 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4282 // do several checks on input parameters
4283 // we do not allow calls without album string
4284 if ($album == null) {
4285 throw new BadRequestException("no albumname specified");
4287 // if photo_id == null --> we are uploading a new photo
4288 if ($photo_id == null) {
4291 // error if no media posted in create-mode
4292 if (empty($_FILES['media'])) {
4294 throw new BadRequestException("no media data submitted");
4297 // album_new will be ignored in create-mode
4302 // check if photo is existing in databasei
4303 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4304 throw new BadRequestException("photo not available");
4308 // checks on acl strings provided by clients
4309 $acl_input_error = false;
4310 $acl_input_error |= check_acl_input($allow_cid);
4311 $acl_input_error |= check_acl_input($deny_cid);
4312 $acl_input_error |= check_acl_input($allow_gid);
4313 $acl_input_error |= check_acl_input($deny_gid);
4314 if ($acl_input_error) {
4315 throw new BadRequestException("acl data invalid");
4317 // now let's upload the new media in create-mode
4318 if ($mode == "create") {
4319 $media = $_FILES['media'];
4320 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4322 // return success of updating or error message
4323 if (!is_null($data)) {
4324 return api_format_data("photo_create", $type, $data);
4326 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4330 // now let's do the changes in update-mode
4331 if ($mode == "update") {
4332 $updated_fields = [];
4334 if (!is_null($desc)) {
4335 $updated_fields['desc'] = $desc;
4338 if (!is_null($album_new)) {
4339 $updated_fields['album'] = $album_new;
4342 if (!is_null($allow_cid)) {
4343 $allow_cid = trim($allow_cid);
4344 $updated_fields['allow_cid'] = $allow_cid;
4347 if (!is_null($deny_cid)) {
4348 $deny_cid = trim($deny_cid);
4349 $updated_fields['deny_cid'] = $deny_cid;
4352 if (!is_null($allow_gid)) {
4353 $allow_gid = trim($allow_gid);
4354 $updated_fields['allow_gid'] = $allow_gid;
4357 if (!is_null($deny_gid)) {
4358 $deny_gid = trim($deny_gid);
4359 $updated_fields['deny_gid'] = $deny_gid;
4363 if (count($updated_fields) > 0) {
4364 $nothingtodo = false;
4365 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4367 $nothingtodo = true;
4370 if (!empty($_FILES['media'])) {
4371 $nothingtodo = false;
4372 $media = $_FILES['media'];
4373 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4374 if (!is_null($data)) {
4375 return api_format_data("photo_update", $type, $data);
4379 // return success of updating or error message
4381 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4382 return api_format_data("photo_update", $type, ['$result' => $answer]);
4385 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4386 return api_format_data("photo_update", $type, ['$result' => $answer]);
4388 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4391 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4395 * delete a single photo from the database through api
4397 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4398 * @return string|array
4399 * @throws BadRequestException
4400 * @throws ForbiddenException
4401 * @throws InternalServerErrorException
4403 function api_fr_photo_delete($type)
4405 if (api_user() === false) {
4406 throw new ForbiddenException();
4410 $photo_id = $_REQUEST['photo_id'] ?? null;
4412 // do several checks on input parameters
4413 // we do not allow calls without photo id
4414 if ($photo_id == null) {
4415 throw new BadRequestException("no photo_id specified");
4418 // check if photo is existing in database
4419 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4420 throw new BadRequestException("photo not available");
4423 // now we can perform on the deletion of the photo
4424 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4426 // return success of deletion or error message
4428 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4429 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4430 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4431 Item::deleteForUser($condition, api_user());
4433 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4434 return api_format_data("photo_delete", $type, ['$result' => $result]);
4436 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4442 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4444 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4445 * @return string|array
4446 * @throws BadRequestException
4447 * @throws ForbiddenException
4448 * @throws InternalServerErrorException
4449 * @throws NotFoundException
4451 function api_fr_photo_detail($type)
4453 if (api_user() === false) {
4454 throw new ForbiddenException();
4456 if (empty($_REQUEST['photo_id'])) {
4457 throw new BadRequestException("No photo id.");
4460 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4461 $photo_id = $_REQUEST['photo_id'];
4463 // prepare json/xml output with data from database for the requested photo
4464 $data = prepare_photo_data($type, $scale, $photo_id);
4466 return api_format_data("photo_detail", $type, $data);
4471 * updates the profile image for the user (either a specified profile or the default profile)
4473 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4475 * @return string|array
4476 * @throws BadRequestException
4477 * @throws ForbiddenException
4478 * @throws ImagickException
4479 * @throws InternalServerErrorException
4480 * @throws NotFoundException
4481 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4483 function api_account_update_profile_image($type)
4485 if (api_user() === false) {
4486 throw new ForbiddenException();
4489 $profile_id = $_REQUEST['profile_id'] ?? 0;
4491 // error if image data is missing
4492 if (empty($_FILES['image'])) {
4493 throw new BadRequestException("no media data submitted");
4496 // check if specified profile id is valid
4497 if ($profile_id != 0) {
4498 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4499 // error message if specified profile id is not in database
4500 if (!DBA::isResult($profile)) {
4501 throw new BadRequestException("profile_id not available");
4503 $is_default_profile = $profile['is-default'];
4505 $is_default_profile = 1;
4508 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4510 if (!empty($_FILES['image'])) {
4511 $media = $_FILES['image'];
4512 } elseif (!empty($_FILES['media'])) {
4513 $media = $_FILES['media'];
4515 // save new profile image
4516 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4519 if (is_array($media['type'])) {
4520 $filetype = $media['type'][0];
4522 $filetype = $media['type'];
4524 if ($filetype == "image/jpeg") {
4526 } elseif ($filetype == "image/png") {
4529 throw new InternalServerErrorException('Unsupported filetype');
4532 // change specified profile or all profiles to the new resource-id
4533 if ($is_default_profile) {
4534 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4535 Photo::update(['profile' => false], $condition);
4537 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4538 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4539 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4542 Contact::updateSelfFromUserID(api_user(), true);
4544 // Update global directory in background
4545 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4546 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4547 Worker::add(PRIORITY_LOW, "Directory", $url);
4550 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4552 // output for client
4554 return api_account_verify_credentials($type);
4556 // SaveMediaToDatabase failed for some reason
4557 throw new InternalServerErrorException("image upload failed");
4561 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4562 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4563 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4564 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4565 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4566 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4567 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4568 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4569 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4572 * Update user profile
4574 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4576 * @return array|string
4577 * @throws BadRequestException
4578 * @throws ForbiddenException
4579 * @throws ImagickException
4580 * @throws InternalServerErrorException
4581 * @throws UnauthorizedException
4583 function api_account_update_profile($type)
4585 $local_user = api_user();
4586 $api_user = api_get_user(DI::app());
4588 if (!empty($_POST['name'])) {
4589 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4590 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4591 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4592 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4595 if (isset($_POST['description'])) {
4596 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4597 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4598 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4601 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4602 // Update global directory in background
4603 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4604 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4607 return api_account_verify_credentials($type);
4610 /// @TODO move to top of file or somewhere better
4611 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4615 * @param string $acl_string
4619 function check_acl_input($acl_string)
4621 if (empty($acl_string)) {
4625 $contact_not_found = false;
4627 // split <x><y><z> into array of cid's
4628 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4630 // check for each cid if it is available on server
4631 $cid_array = $array[0];
4632 foreach ($cid_array as $cid) {
4633 $cid = str_replace("<", "", $cid);
4634 $cid = str_replace(">", "", $cid);
4635 $condition = ['id' => $cid, 'uid' => api_user()];
4636 $contact_not_found |= !DBA::exists('contact', $condition);
4638 return $contact_not_found;
4642 * @param string $mediatype
4643 * @param array $media
4644 * @param string $type
4645 * @param string $album
4646 * @param string $allow_cid
4647 * @param string $deny_cid
4648 * @param string $allow_gid
4649 * @param string $deny_gid
4650 * @param string $desc
4651 * @param integer $profile
4652 * @param boolean $visibility
4653 * @param string $photo_id
4655 * @throws BadRequestException
4656 * @throws ForbiddenException
4657 * @throws ImagickException
4658 * @throws InternalServerErrorException
4659 * @throws NotFoundException
4660 * @throws UnauthorizedException
4662 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)
4670 if (is_array($media)) {
4671 if (is_array($media['tmp_name'])) {
4672 $src = $media['tmp_name'][0];
4674 $src = $media['tmp_name'];
4676 if (is_array($media['name'])) {
4677 $filename = basename($media['name'][0]);
4679 $filename = basename($media['name']);
4681 if (is_array($media['size'])) {
4682 $filesize = intval($media['size'][0]);
4684 $filesize = intval($media['size']);
4686 if (is_array($media['type'])) {
4687 $filetype = $media['type'][0];
4689 $filetype = $media['type'];
4693 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4696 "File upload src: " . $src . " - filename: " . $filename .
4697 " - size: " . $filesize . " - type: " . $filetype,
4701 // check if there was a php upload error
4702 if ($filesize == 0 && $media['error'] == 1) {
4703 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4705 // check against max upload size within Friendica instance
4706 $maximagesize = DI::config()->get('system', 'maximagesize');
4707 if ($maximagesize && ($filesize > $maximagesize)) {
4708 $formattedBytes = Strings::formatBytes($maximagesize);
4709 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4712 // create Photo instance with the data of the image
4713 $imagedata = @file_get_contents($src);
4714 $Image = new Image($imagedata, $filetype);
4715 if (!$Image->isValid()) {
4716 throw new InternalServerErrorException("unable to process image data");
4719 // check orientation of image
4720 $Image->orient($src);
4723 // check max length of images on server
4724 $max_length = DI::config()->get('system', 'max_image_length');
4726 $max_length = MAX_IMAGE_LENGTH;
4728 if ($max_length > 0) {
4729 $Image->scaleDown($max_length);
4730 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4732 $width = $Image->getWidth();
4733 $height = $Image->getHeight();
4735 // create a new resource-id if not already provided
4736 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4738 if ($mediatype == "photo") {
4739 // upload normal image (scales 0, 1, 2)
4740 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4742 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4744 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4746 if ($width > 640 || $height > 640) {
4747 $Image->scaleDown(640);
4748 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4750 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4754 if ($width > 320 || $height > 320) {
4755 $Image->scaleDown(320);
4756 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4758 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4761 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4762 } elseif ($mediatype == "profileimage") {
4763 // upload profile image (scales 4, 5, 6)
4764 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4766 if ($width > 300 || $height > 300) {
4767 $Image->scaleDown(300);
4768 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4770 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4774 if ($width > 80 || $height > 80) {
4775 $Image->scaleDown(80);
4776 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4778 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4782 if ($width > 48 || $height > 48) {
4783 $Image->scaleDown(48);
4784 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4786 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4789 $Image->__destruct();
4790 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4794 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4795 if ($photo_id == null && $mediatype == "photo") {
4796 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4798 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4799 return prepare_photo_data($type, false, $resource_id);
4801 throw new InternalServerErrorException("image upload failed");
4807 * @param string $hash
4808 * @param string $allow_cid
4809 * @param string $deny_cid
4810 * @param string $allow_gid
4811 * @param string $deny_gid
4812 * @param string $filetype
4813 * @param boolean $visibility
4814 * @throws InternalServerErrorException
4816 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4818 // get data about the api authenticated user
4819 $uri = Item::newURI(intval(api_user()));
4820 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4823 $arr['guid'] = System::createUUID();
4824 $arr['uid'] = intval(api_user());
4826 $arr['type'] = 'photo';
4828 $arr['resource-id'] = $hash;
4829 $arr['contact-id'] = $owner_record['id'];
4830 $arr['owner-name'] = $owner_record['name'];
4831 $arr['owner-link'] = $owner_record['url'];
4832 $arr['owner-avatar'] = $owner_record['thumb'];
4833 $arr['author-name'] = $owner_record['name'];
4834 $arr['author-link'] = $owner_record['url'];
4835 $arr['author-avatar'] = $owner_record['thumb'];
4837 $arr['allow_cid'] = $allow_cid;
4838 $arr['allow_gid'] = $allow_gid;
4839 $arr['deny_cid'] = $deny_cid;
4840 $arr['deny_gid'] = $deny_gid;
4841 $arr['visible'] = $visibility;
4845 'image/jpeg' => 'jpg',
4846 'image/png' => 'png',
4847 'image/gif' => 'gif'
4850 // adds link to the thumbnail scale photo
4851 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4852 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4855 // do the magic for storing the item in the database and trigger the federation to other contacts
4861 * @param string $type
4863 * @param string $photo_id
4866 * @throws BadRequestException
4867 * @throws ForbiddenException
4868 * @throws ImagickException
4869 * @throws InternalServerErrorException
4870 * @throws NotFoundException
4871 * @throws UnauthorizedException
4873 function prepare_photo_data($type, $scale, $photo_id)
4876 $user_info = api_get_user($a);
4878 if ($user_info === false) {
4879 throw new ForbiddenException();
4882 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4883 $data_sql = ($scale === false ? "" : "data, ");
4885 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4886 // clients needs to convert this in their way for further processing
4888 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4889 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4890 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4891 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4892 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4893 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4895 intval(local_user()),
4896 DBA::escape($photo_id),
4901 'image/jpeg' => 'jpg',
4902 'image/png' => 'png',
4903 'image/gif' => 'gif'
4906 // prepare output data for photo
4907 if (DBA::isResult($r)) {
4908 $data = ['photo' => $r[0]];
4909 $data['photo']['id'] = $data['photo']['resource-id'];
4910 if ($scale !== false) {
4911 $data['photo']['data'] = base64_encode($data['photo']['data']);
4913 unset($data['photo']['datasize']); //needed only with scale param
4915 if ($type == "xml") {
4916 $data['photo']['links'] = [];
4917 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4918 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4920 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4923 $data['photo']['link'] = [];
4924 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4926 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4927 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4931 unset($data['photo']['resource-id']);
4932 unset($data['photo']['minscale']);
4933 unset($data['photo']['maxscale']);
4935 throw new NotFoundException();
4938 // retrieve item element for getting activities (like, dislike etc.) related to photo
4939 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4940 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4941 if (!DBA::isResult($item)) {
4942 throw new NotFoundException('Photo-related item not found.');
4945 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4947 // retrieve comments on photo
4948 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4949 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4951 $statuses = Post::selectForUser(api_user(), [], $condition);
4953 // prepare output of comments
4954 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4956 if ($type == "xml") {
4958 foreach ($commentData as $comment) {
4959 $comments[$k++ . ":comment"] = $comment;
4962 foreach ($commentData as $comment) {
4963 $comments[] = $comment;
4966 $data['photo']['friendica_comments'] = $comments;
4968 // include info if rights on photo and rights on item are mismatching
4969 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4970 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4971 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4972 $data['photo']['deny_gid'] != $item['deny_gid'];
4973 $data['photo']['rights_mismatch'] = $rights_mismatch;
4980 * Similar as /mod/redir.php
4981 * redirect to 'url' after dfrn auth
4983 * Why this when there is mod/redir.php already?
4984 * This use api_user() and api_login()
4987 * c_url: url of remote contact to auth to
4988 * url: string, url to redirect after auth
4990 function api_friendica_remoteauth()
4992 $url = $_GET['url'] ?? '';
4993 $c_url = $_GET['c_url'] ?? '';
4995 if ($url === '' || $c_url === '') {
4996 throw new BadRequestException("Wrong parameters.");
4999 $c_url = Strings::normaliseLink($c_url);
5003 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5004 if (!DBA::isResult($contact)) {
5005 throw new BadRequestException("Unknown contact");
5008 $cid = $contact['id'];
5010 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5012 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5013 System::externalRedirect($url ?: $c_url);
5016 if ($contact['duplex'] && $contact['issued-id']) {
5017 $orig_id = $contact['issued-id'];
5018 $dfrn_id = '1:' . $orig_id;
5020 if ($contact['duplex'] && $contact['dfrn-id']) {
5021 $orig_id = $contact['dfrn-id'];
5022 $dfrn_id = '0:' . $orig_id;
5025 $sec = Strings::getRandomHex();
5027 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5028 'sec' => $sec, 'expire' => time() + 45];
5029 DBA::insert('profile_check', $fields);
5031 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5032 $dest = ($url ? '&destination_url=' . $url : '');
5034 System::externalRedirect(
5035 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5036 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5037 . '&type=profile&sec=' . $sec . $dest
5040 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5043 * Return an item with announcer data if it had been announced
5045 * @param array $item Item array
5046 * @return array Item array with announce data
5048 function api_get_announce($item)
5050 // Quit if the item already has got a different owner and author
5051 if ($item['owner-id'] != $item['author-id']) {
5055 // Don't change original or Diaspora posts
5056 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5060 // Quit if we do now the original author and it had been a post from a native network
5061 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5065 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5066 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5067 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5068 if (!DBA::isResult($announce)) {
5072 return array_merge($item, $announce);
5076 * Return the item shared, if the item contains only the [share] tag
5078 * @param array $item Sharer item
5079 * @return array|false Shared item or false if not a reshare
5080 * @throws ImagickException
5081 * @throws InternalServerErrorException
5083 function api_share_as_retweet(&$item)
5085 $body = trim($item["body"]);
5087 if (Diaspora::isReshare($body, false) === false) {
5088 if ($item['author-id'] == $item['owner-id']) {
5091 // Reshares from OStatus, ActivityPub and Twitter
5092 $reshared_item = $item;
5093 $reshared_item['owner-id'] = $reshared_item['author-id'];
5094 $reshared_item['owner-link'] = $reshared_item['author-link'];
5095 $reshared_item['owner-name'] = $reshared_item['author-name'];
5096 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5097 return $reshared_item;
5101 $reshared = Item::getShareArray($item);
5102 if (empty($reshared)) {
5106 $reshared_item = $item;
5108 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5112 if (!empty($reshared['comment'])) {
5113 $item['body'] = $reshared['comment'];
5116 $reshared_item["share-pre-body"] = $reshared['comment'];
5117 $reshared_item["body"] = $reshared['shared'];
5118 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5119 $reshared_item["author-name"] = $reshared['author'];
5120 $reshared_item["author-link"] = $reshared['profile'];
5121 $reshared_item["author-avatar"] = $reshared['avatar'];
5122 $reshared_item["plink"] = $reshared['link'] ?? '';
5123 $reshared_item["created"] = $reshared['posted'];
5124 $reshared_item["edited"] = $reshared['posted'];
5126 // Try to fetch the original item
5127 if (!empty($reshared['guid'])) {
5128 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5129 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5130 $condition = ['id' => $original_id];
5135 if (!empty($condition)) {
5136 $original_item = Post::selectFirst([], $condition);
5137 if (DBA::isResult($original_item)) {
5138 $reshared_item = array_merge($reshared_item, $original_item);
5142 return $reshared_item;
5147 * @param array $item
5152 function api_in_reply_to($item)
5156 $in_reply_to['status_id'] = null;
5157 $in_reply_to['user_id'] = null;
5158 $in_reply_to['status_id_str'] = null;
5159 $in_reply_to['user_id_str'] = null;
5160 $in_reply_to['screen_name'] = null;
5162 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5163 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5164 if (DBA::isResult($parent)) {
5165 $in_reply_to['status_id'] = intval($parent['id']);
5167 $in_reply_to['status_id'] = intval($item['parent']);
5170 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5172 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5173 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5175 if (DBA::isResult($parent)) {
5176 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5177 $in_reply_to['user_id'] = intval($parent['author-id']);
5178 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5181 // There seems to be situation, where both fields are identical:
5182 // https://github.com/friendica/friendica/issues/1010
5183 // This is a bugfix for that.
5184 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5185 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']]);
5186 $in_reply_to['status_id'] = null;
5187 $in_reply_to['user_id'] = null;
5188 $in_reply_to['status_id_str'] = null;
5189 $in_reply_to['user_id_str'] = null;
5190 $in_reply_to['screen_name'] = null;
5194 return $in_reply_to;
5199 * @param string $text
5202 * @throws InternalServerErrorException
5204 function api_clean_plain_items($text)
5206 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5208 $text = BBCode::cleanPictureLinks($text);
5209 $URLSearchString = "^\[\]";
5211 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5213 if ($include_entities == "true") {
5214 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5217 // Simplify "attachment" element
5218 $text = BBCode::removeAttachment($text);
5225 * @param array $contacts
5229 function api_best_nickname(&$contacts)
5233 if (count($contacts) == 0) {
5237 foreach ($contacts as $contact) {
5238 if ($contact["network"] == "") {
5239 $contact["network"] = "dfrn";
5240 $best_contact = [$contact];
5244 if (sizeof($best_contact) == 0) {
5245 foreach ($contacts as $contact) {
5246 if ($contact["network"] == "dfrn") {
5247 $best_contact = [$contact];
5252 if (sizeof($best_contact) == 0) {
5253 foreach ($contacts as $contact) {
5254 if ($contact["network"] == "dspr") {
5255 $best_contact = [$contact];
5260 if (sizeof($best_contact) == 0) {
5261 foreach ($contacts as $contact) {
5262 if ($contact["network"] == "stat") {
5263 $best_contact = [$contact];
5268 if (sizeof($best_contact) == 0) {
5269 foreach ($contacts as $contact) {
5270 if ($contact["network"] == "pump") {
5271 $best_contact = [$contact];
5276 if (sizeof($best_contact) == 0) {
5277 foreach ($contacts as $contact) {
5278 if ($contact["network"] == "twit") {
5279 $best_contact = [$contact];
5284 if (sizeof($best_contact) == 1) {
5285 $contacts = $best_contact;
5287 $contacts = [$contacts[0]];
5292 * Return all or a specified group of the user with the containing contacts.
5294 * @param string $type Return type (atom, rss, xml, json)
5296 * @return array|string
5297 * @throws BadRequestException
5298 * @throws ForbiddenException
5299 * @throws ImagickException
5300 * @throws InternalServerErrorException
5301 * @throws UnauthorizedException
5303 function api_friendica_group_show($type)
5307 if (api_user() === false) {
5308 throw new ForbiddenException();
5312 $user_info = api_get_user($a);
5313 $gid = $_REQUEST['gid'] ?? 0;
5314 $uid = $user_info['uid'];
5316 // get data of the specified group id or all groups if not specified
5319 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5323 // error message if specified gid is not in database
5324 if (!DBA::isResult($r)) {
5325 throw new BadRequestException("gid not available");
5329 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5334 // loop through all groups and retrieve all members for adding data in the user array
5336 foreach ($r as $rr) {
5337 $members = Contact\Group::getById($rr['id']);
5340 if ($type == "xml") {
5341 $user_element = "users";
5343 foreach ($members as $member) {
5344 $user = api_get_user($a, $member['nurl']);
5345 $users[$k++.":user"] = $user;
5348 $user_element = "user";
5349 foreach ($members as $member) {
5350 $user = api_get_user($a, $member['nurl']);
5354 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5356 return api_format_data("groups", $type, ['group' => $grps]);
5358 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5362 * Delete the specified group of the user.
5364 * @param string $type Return type (atom, rss, xml, json)
5366 * @return array|string
5367 * @throws BadRequestException
5368 * @throws ForbiddenException
5369 * @throws ImagickException
5370 * @throws InternalServerErrorException
5371 * @throws UnauthorizedException
5373 function api_friendica_group_delete($type)
5377 if (api_user() === false) {
5378 throw new ForbiddenException();
5382 $user_info = api_get_user($a);
5383 $gid = $_REQUEST['gid'] ?? 0;
5384 $name = $_REQUEST['name'] ?? '';
5385 $uid = $user_info['uid'];
5387 // error if no gid specified
5388 if ($gid == 0 || $name == "") {
5389 throw new BadRequestException('gid or name not specified');
5392 // get data of the specified group id
5394 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5398 // error message if specified gid is not in database
5399 if (!DBA::isResult($r)) {
5400 throw new BadRequestException('gid not available');
5403 // get data of the specified group id and group name
5405 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5410 // error message if specified gid is not in database
5411 if (!DBA::isResult($rname)) {
5412 throw new BadRequestException('wrong group name');
5416 $ret = Group::removeByName($uid, $name);
5419 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5420 return api_format_data("group_delete", $type, ['result' => $success]);
5422 throw new BadRequestException('other API error');
5425 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5430 * @param string $type Return type (atom, rss, xml, json)
5432 * @return array|string
5433 * @throws BadRequestException
5434 * @throws ForbiddenException
5435 * @throws ImagickException
5436 * @throws InternalServerErrorException
5437 * @throws UnauthorizedException
5438 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5440 function api_lists_destroy($type)
5444 if (api_user() === false) {
5445 throw new ForbiddenException();
5449 $user_info = api_get_user($a);
5450 $gid = $_REQUEST['list_id'] ?? 0;
5451 $uid = $user_info['uid'];
5453 // error if no gid specified
5455 throw new BadRequestException('gid not specified');
5458 // get data of the specified group id
5459 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5460 // error message if specified gid is not in database
5462 throw new BadRequestException('gid not available');
5465 if (Group::remove($gid)) {
5467 'name' => $group['name'],
5468 'id' => intval($gid),
5469 'id_str' => (string) $gid,
5470 'user' => $user_info
5473 return api_format_data("lists", $type, ['lists' => $list]);
5476 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5479 * Add a new group to the database.
5481 * @param string $name Group name
5482 * @param int $uid User ID
5483 * @param array $users List of users to add to the group
5486 * @throws BadRequestException
5488 function group_create($name, $uid, $users = [])
5490 // error if no name specified
5492 throw new BadRequestException('group name not specified');
5495 // get data of the specified group name
5497 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5501 // error message if specified group name already exists
5502 if (DBA::isResult($rname)) {
5503 throw new BadRequestException('group name already exists');
5506 // check if specified group name is a deleted group
5508 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5512 // error message if specified group name already exists
5513 if (DBA::isResult($rname)) {
5514 $reactivate_group = true;
5518 $ret = Group::create($uid, $name);
5520 $gid = Group::getIdByName($uid, $name);
5522 throw new BadRequestException('other API error');
5526 $erroraddinguser = false;
5528 foreach ($users as $user) {
5529 $cid = $user['cid'];
5530 // check if user really exists as contact
5532 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5536 if (count($contact)) {
5537 Group::addMember($gid, $cid);
5539 $erroraddinguser = true;
5540 $errorusers[] = $cid;
5544 // return success message incl. missing users in array
5545 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5547 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5551 * Create the specified group with the posted array of contacts.
5553 * @param string $type Return type (atom, rss, xml, json)
5555 * @return array|string
5556 * @throws BadRequestException
5557 * @throws ForbiddenException
5558 * @throws ImagickException
5559 * @throws InternalServerErrorException
5560 * @throws UnauthorizedException
5562 function api_friendica_group_create($type)
5566 if (api_user() === false) {
5567 throw new ForbiddenException();
5571 $user_info = api_get_user($a);
5572 $name = $_REQUEST['name'] ?? '';
5573 $uid = $user_info['uid'];
5574 $json = json_decode($_POST['json'], true);
5575 $users = $json['user'];
5577 $success = group_create($name, $uid, $users);
5579 return api_format_data("group_create", $type, ['result' => $success]);
5581 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5584 * Create a new group.
5586 * @param string $type Return type (atom, rss, xml, json)
5588 * @return array|string
5589 * @throws BadRequestException
5590 * @throws ForbiddenException
5591 * @throws ImagickException
5592 * @throws InternalServerErrorException
5593 * @throws UnauthorizedException
5594 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5596 function api_lists_create($type)
5600 if (api_user() === false) {
5601 throw new ForbiddenException();
5605 $user_info = api_get_user($a);
5606 $name = $_REQUEST['name'] ?? '';
5607 $uid = $user_info['uid'];
5609 $success = group_create($name, $uid);
5610 if ($success['success']) {
5612 'name' => $success['name'],
5613 'id' => intval($success['gid']),
5614 'id_str' => (string) $success['gid'],
5615 'user' => $user_info
5618 return api_format_data("lists", $type, ['lists'=>$grp]);
5621 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5624 * Update the specified group with the posted array of contacts.
5626 * @param string $type Return type (atom, rss, xml, json)
5628 * @return array|string
5629 * @throws BadRequestException
5630 * @throws ForbiddenException
5631 * @throws ImagickException
5632 * @throws InternalServerErrorException
5633 * @throws UnauthorizedException
5635 function api_friendica_group_update($type)
5639 if (api_user() === false) {
5640 throw new ForbiddenException();
5644 $user_info = api_get_user($a);
5645 $uid = $user_info['uid'];
5646 $gid = $_REQUEST['gid'] ?? 0;
5647 $name = $_REQUEST['name'] ?? '';
5648 $json = json_decode($_POST['json'], true);
5649 $users = $json['user'];
5651 // error if no name specified
5653 throw new BadRequestException('group name not specified');
5656 // error if no gid specified
5658 throw new BadRequestException('gid not specified');
5662 $members = Contact\Group::getById($gid);
5663 foreach ($members as $member) {
5664 $cid = $member['id'];
5665 foreach ($users as $user) {
5666 $found = ($user['cid'] == $cid ? true : false);
5668 if (!isset($found) || !$found) {
5669 Group::removeMemberByName($uid, $name, $cid);
5674 $erroraddinguser = false;
5676 foreach ($users as $user) {
5677 $cid = $user['cid'];
5678 // check if user really exists as contact
5680 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5685 if (count($contact)) {
5686 Group::addMember($gid, $cid);
5688 $erroraddinguser = true;
5689 $errorusers[] = $cid;
5693 // return success message incl. missing users in array
5694 $status = ($erroraddinguser ? "missing user" : "ok");
5695 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5696 return api_format_data("group_update", $type, ['result' => $success]);
5699 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5702 * Update information about a group.
5704 * @param string $type Return type (atom, rss, xml, json)
5706 * @return array|string
5707 * @throws BadRequestException
5708 * @throws ForbiddenException
5709 * @throws ImagickException
5710 * @throws InternalServerErrorException
5711 * @throws UnauthorizedException
5712 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5714 function api_lists_update($type)
5718 if (api_user() === false) {
5719 throw new ForbiddenException();
5723 $user_info = api_get_user($a);
5724 $gid = $_REQUEST['list_id'] ?? 0;
5725 $name = $_REQUEST['name'] ?? '';
5726 $uid = $user_info['uid'];
5728 // error if no gid specified
5730 throw new BadRequestException('gid not specified');
5733 // get data of the specified group id
5734 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5735 // error message if specified gid is not in database
5737 throw new BadRequestException('gid not available');
5740 if (Group::update($gid, $name)) {
5743 'id' => intval($gid),
5744 'id_str' => (string) $gid,
5745 'user' => $user_info
5748 return api_format_data("lists", $type, ['lists' => $list]);
5752 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5756 * @param string $type Return type (atom, rss, xml, json)
5758 * @return array|string
5759 * @throws BadRequestException
5760 * @throws ForbiddenException
5761 * @throws ImagickException
5762 * @throws InternalServerErrorException
5764 function api_friendica_activity($type)
5768 if (api_user() === false) {
5769 throw new ForbiddenException();
5771 $verb = strtolower($a->argv[3]);
5772 $verb = preg_replace("|\..*$|", "", $verb);
5774 $id = $_REQUEST['id'] ?? 0;
5776 $res = Item::performActivity($id, $verb, api_user());
5779 if ($type == "xml") {
5784 return api_format_data('ok', $type, ['ok' => $ok]);
5786 throw new BadRequestException('Error adding activity');
5790 /// @TODO move to top of file or somewhere better
5791 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5792 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5793 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5794 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5795 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5796 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5797 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5798 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5799 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5800 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5803 * Returns notifications
5805 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5807 * @return string|array
5808 * @throws ForbiddenException
5809 * @throws BadRequestException
5812 function api_friendica_notification($type)
5816 if (api_user() === false) {
5817 throw new ForbiddenException();
5820 throw new BadRequestException("Invalid argument count");
5823 $notifications = DI::notification()->getApiList(local_user());
5825 if ($type == "xml") {
5827 if (!empty($notifications)) {
5828 foreach ($notifications as $notification) {
5829 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5833 $result = $xmlnotes;
5834 } elseif (count($notifications) > 0) {
5835 $result = $notifications->getArrayCopy();
5840 return api_format_data("notes", $type, ['note' => $result]);
5844 * Set notification as seen and returns associated item (if possible)
5846 * POST request with 'id' param as notification id
5848 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5849 * @return string|array
5850 * @throws BadRequestException
5851 * @throws ForbiddenException
5852 * @throws ImagickException
5853 * @throws InternalServerErrorException
5854 * @throws UnauthorizedException
5856 function api_friendica_notification_seen($type)
5859 $user_info = api_get_user($a);
5861 if (api_user() === false || $user_info === false) {
5862 throw new ForbiddenException();
5864 if ($a->argc !== 4) {
5865 throw new BadRequestException("Invalid argument count");
5868 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5871 $notify = DI::notify()->getByID($id, api_user());
5872 DI::notify()->setSeen(true, $notify);
5874 if ($notify->otype === Notification\ObjectType::ITEM) {
5875 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5876 if (DBA::isResult($item)) {
5877 // we found the item, return it to the user
5878 $ret = api_format_items([$item], $user_info, false, $type);
5879 $data = ['status' => $ret];
5880 return api_format_data("status", $type, $data);
5882 // the item can't be found, but we set the notification as seen, so we count this as a success
5884 return api_format_data('result', $type, ['result' => "success"]);
5885 } catch (NotFoundException $e) {
5886 throw new BadRequestException('Invalid argument', $e);
5887 } catch (Exception $e) {
5888 throw new InternalServerErrorException('Internal Server exception', $e);
5892 /// @TODO move to top of file or somewhere better
5893 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5894 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5897 * update a direct_message to seen state
5899 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5900 * @return string|array (success result=ok, error result=error with error message)
5901 * @throws BadRequestException
5902 * @throws ForbiddenException
5903 * @throws ImagickException
5904 * @throws InternalServerErrorException
5905 * @throws UnauthorizedException
5907 function api_friendica_direct_messages_setseen($type)
5910 if (api_user() === false) {
5911 throw new ForbiddenException();
5915 $user_info = api_get_user($a);
5916 $uid = $user_info['uid'];
5917 $id = $_REQUEST['id'] ?? 0;
5919 // return error if id is zero
5921 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5922 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5925 // error message if specified id is not in database
5926 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5927 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5928 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5931 // update seen indicator
5932 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5936 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5937 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5939 $answer = ['result' => 'error', 'message' => 'unknown error'];
5940 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5944 /// @TODO move to top of file or somewhere better
5945 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5948 * search for direct_messages containing a searchstring through api
5950 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5951 * @param string $box
5952 * @return string|array (success: success=true if found and search_result contains found messages,
5953 * success=false if nothing was found, search_result='nothing found',
5954 * error: result=error with error message)
5955 * @throws BadRequestException
5956 * @throws ForbiddenException
5957 * @throws ImagickException
5958 * @throws InternalServerErrorException
5959 * @throws UnauthorizedException
5961 function api_friendica_direct_messages_search($type, $box = "")
5965 if (api_user() === false) {
5966 throw new ForbiddenException();
5970 $user_info = api_get_user($a);
5971 $searchstring = $_REQUEST['searchstring'] ?? '';
5972 $uid = $user_info['uid'];
5974 // error if no searchstring specified
5975 if ($searchstring == "") {
5976 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5977 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5980 // get data for the specified searchstring
5982 "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",
5984 DBA::escape('%'.$searchstring.'%')
5987 $profile_url = $user_info["url"];
5989 // message if nothing was found
5990 if (!DBA::isResult($r)) {
5991 $success = ['success' => false, 'search_results' => 'problem with query'];
5992 } elseif (count($r) == 0) {
5993 $success = ['success' => false, 'search_results' => 'nothing found'];
5996 foreach ($r as $item) {
5997 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5998 $recipient = $user_info;
5999 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6000 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6001 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6002 $sender = $user_info;
6005 if (isset($recipient) && isset($sender)) {
6006 $ret[] = api_format_messages($item, $recipient, $sender);
6009 $success = ['success' => true, 'search_results' => $ret];
6012 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6015 /// @TODO move to top of file or somewhere better
6016 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6019 * Returns a list of saved searches.
6021 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6023 * @param string $type Return format: json or xml
6025 * @return string|array
6028 function api_saved_searches_list($type)
6030 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6033 while ($term = DBA::fetch($terms)) {
6035 'created_at' => api_date(time()),
6036 'id' => intval($term['id']),
6037 'id_str' => $term['id'],
6038 'name' => $term['term'],
6040 'query' => $term['term']
6046 return api_format_data("terms", $type, ['terms' => $result]);
6049 /// @TODO move to top of file or somewhere better
6050 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6053 * Number of comments
6055 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6057 * @param object $data [Status, Status]
6061 function bindComments(&$data)
6063 if (count($data) == 0) {
6069 foreach ($data as $item) {
6070 $ids[] = $item['id'];
6073 $idStr = DBA::escape(implode(', ', $ids));
6074 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6075 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6076 $itemsData = DBA::toArray($items);
6078 foreach ($itemsData as $item) {
6079 $comments[$item['parent']] = $item['comments'];
6082 foreach ($data as $idx => $item) {
6084 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6089 @TODO Maybe open to implement?
6091 [pagename] => api/1.1/statuses/lookup.json
6092 [id] => 605138389168451584
6093 [include_cards] => true
6094 [cards_platform] => Android-12
6095 [include_entities] => true
6096 [include_my_retweet] => 1
6098 [include_reply_count] => true
6099 [include_descendent_reply_count] => true
6103 Not implemented by now:
6104 statuses/retweets_of_me
6109 account/update_location
6110 account/update_profile_background_image
6113 friendica/profile/update
6114 friendica/profile/create
6115 friendica/profile/delete
6117 Not implemented in status.net:
6118 statuses/retweeted_to_me
6119 statuses/retweeted_by_me
6120 direct_messages/destroy
6122 account/update_delivery_device
6123 notifications/follow