3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\UserItem;
47 use Friendica\Model\Verb;
48 use Friendica\Network\HTTPException;
49 use Friendica\Network\HTTPException\BadRequestException;
50 use Friendica\Network\HTTPException\ExpectationFailedException;
51 use Friendica\Network\HTTPException\ForbiddenException;
52 use Friendica\Network\HTTPException\InternalServerErrorException;
53 use Friendica\Network\HTTPException\MethodNotAllowedException;
54 use Friendica\Network\HTTPException\NotFoundException;
55 use Friendica\Network\HTTPException\TooManyRequestsException;
56 use Friendica\Network\HTTPException\UnauthorizedException;
57 use Friendica\Object\Image;
58 use Friendica\Protocol\Activity;
59 use Friendica\Protocol\Diaspora;
60 use Friendica\Security\FKOAuth1;
61 use Friendica\Security\OAuth1\OAuthRequest;
62 use Friendica\Security\OAuth1\OAuthUtil;
63 use Friendica\Util\DateTimeFormat;
64 use Friendica\Util\Images;
65 use Friendica\Util\Network;
66 use Friendica\Util\Proxy as ProxyUtils;
67 use Friendica\Util\Strings;
68 use Friendica\Util\XML;
70 require_once __DIR__ . '/../mod/item.php';
71 require_once __DIR__ . '/../mod/wall_upload.php';
73 define('API_METHOD_ANY', '*');
74 define('API_METHOD_GET', 'GET');
75 define('API_METHOD_POST', 'POST,PUT');
76 define('API_METHOD_DELETE', 'POST,DELETE');
78 define('API_LOG_PREFIX', 'API {action} - ');
86 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
87 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
88 * into a page, and visitors will post something without noticing it).
92 if (!empty($_SESSION['allow_api'])) {
100 * Get source name from API client
102 * Clients can send 'source' parameter to be show in post metadata
103 * as "sent via <source>".
104 * Some clients doesn't send a source param, we support ones we know
105 * (only Twidere, atm)
108 * Client source name, default to "api" if unset/unknown
111 function api_source()
113 if (requestdata('source')) {
114 return requestdata('source');
117 // Support for known clients that doesn't send a source name
118 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
119 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
123 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
125 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
132 * Format date for API
134 * @param string $str Source date, as UTC
135 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
138 function api_date($str)
140 // Wed May 23 06:01:13 +0000 2007
141 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
145 * Register a function to be the endpoint for defined API path.
147 * @param string $path API URL path, relative to DI::baseUrl()
148 * @param string $func Function name to call on path request
149 * @param bool $auth API need logged user
150 * @param string $method HTTP method reqiured to call this endpoint.
151 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152 * Default to API_METHOD_ANY
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
164 // Workaround for hotot
165 $path = str_replace("api/", "api/1.1/", $path);
175 * Log in user via OAuth1 or Simple HTTP Auth.
176 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
179 * @throws ForbiddenException
180 * @throws InternalServerErrorException
181 * @throws UnauthorizedException
182 * @hook 'authenticate'
184 * 'username' => username from login form
185 * 'password' => password from login form
186 * 'authenticated' => return status,
187 * 'user_record' => return authenticated user record
189 function api_login(App $a)
191 // workaround for HTTP-auth in CGI mode
192 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
193 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
194 if (strlen($userpass)) {
195 list($name, $password) = explode(':', $userpass);
196 $_SERVER['PHP_AUTH_USER'] = $name;
197 $_SERVER['PHP_AUTH_PW'] = $password;
201 if (empty($_SERVER['PHP_AUTH_USER'])) {
202 // Try OAuth when no user is provided
203 $oauth1 = new FKOAuth1();
206 $request = OAuthRequest::from_request();
207 list($consumer, $token) = $oauth1->verify_request($request);
208 if (!is_null($token)) {
209 $oauth1->loginUser($token->uid);
210 Session::set('allow_api', true);
213 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
214 var_dump($consumer, $token);
216 } catch (Exception $e) {
217 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
220 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
221 header('WWW-Authenticate: Basic realm="Friendica"');
222 throw new UnauthorizedException("This API requires login");
225 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
226 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
228 // allow "user@server" login (but ignore 'server' part)
229 $at = strstr($user, "@", true);
234 // next code from mod/auth.php. needs better solution
238 'username' => trim($user),
239 'password' => trim($password),
240 'authenticated' => 0,
241 'user_record' => null,
245 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
246 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
247 * and later addons should not interfere with an earlier one that succeeded.
249 Hook::callAll('authenticate', $addon_auth);
251 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
252 $record = $addon_auth['user_record'];
254 $user_id = User::authenticate(trim($user), trim($password), true);
255 if ($user_id !== false) {
256 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
260 if (!DBA::isResult($record)) {
261 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
262 header('WWW-Authenticate: Basic realm="Friendica"');
263 //header('HTTP/1.0 401 Unauthorized');
264 //die('This api requires login');
265 throw new UnauthorizedException("This API requires login");
268 // Don't refresh the login date more often than twice a day to spare database writes
269 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
271 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
273 $_SESSION["allow_api"] = true;
275 Hook::callAll('logged_in', $a->user);
279 * Check HTTP method of called API
281 * API endpoints can define which HTTP method to accept when called.
282 * This function check the current HTTP method agains endpoint
285 * @param string $method Required methods, uppercase, separated by comma
288 function api_check_method($method)
290 if ($method == "*") {
293 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
297 * Main API entry point
299 * Authenticate user, call registered API function, set HTTP headers
302 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
303 * @return string|array API call result
306 function api_call(App $a, App\Arguments $args = null)
308 global $API, $called_api;
315 if (strpos($args->getCommand(), ".xml") > 0) {
318 if (strpos($args->getCommand(), ".json") > 0) {
321 if (strpos($args->getCommand(), ".rss") > 0) {
324 if (strpos($args->getCommand(), ".atom") > 0) {
329 foreach ($API as $p => $info) {
330 if (strpos($args->getCommand(), $p) === 0) {
331 if (!api_check_method($info['method'])) {
332 throw new MethodNotAllowedException();
335 $called_api = explode("/", $p);
337 if (!empty($info['auth']) && api_user() === false) {
339 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
342 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
344 $stamp = microtime(true);
345 $return = call_user_func($info['func'], $type);
346 $duration = floatval(microtime(true) - $stamp);
348 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
350 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
352 if (false === $return) {
354 * api function returned false withour throw an
355 * exception. This should not happend, throw a 500
357 throw new InternalServerErrorException();
362 header("Content-Type: text/xml");
365 header("Content-Type: application/json");
366 if (!empty($return)) {
367 $json = json_encode(end($return));
368 if (!empty($_GET['callback'])) {
369 $json = $_GET['callback'] . "(" . $json . ")";
375 header("Content-Type: application/rss+xml");
376 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
379 header("Content-Type: application/atom+xml");
380 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
387 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
388 throw new NotFoundException();
389 } catch (HTTPException $e) {
390 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
391 return api_error($type, $e, $args);
396 * Format API error string
398 * @param string $type Return type (xml, json, rss, as)
399 * @param object $e HTTPException Error object
400 * @param App\Arguments $args The App arguments
401 * @return string|array error message formatted as $type
403 function api_error($type, $e, App\Arguments $args)
405 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
406 /// @TODO: https://dev.twitter.com/overview/api/response-codes
408 $error = ["error" => $error,
409 "code" => $e->getCode() . " " . $e->httpdesc,
410 "request" => $args->getQueryString()];
412 $return = api_format_data('status', $type, ['status' => $error]);
416 header("Content-Type: text/xml");
419 header("Content-Type: application/json");
420 $return = json_encode($return);
423 header("Content-Type: application/rss+xml");
426 header("Content-Type: application/atom+xml");
434 * Set values for RSS template
437 * @param array $arr Array to be passed to template
438 * @param array $user_info User info
440 * @throws BadRequestException
441 * @throws ImagickException
442 * @throws InternalServerErrorException
443 * @throws UnauthorizedException
444 * @todo find proper type-hints
446 function api_rss_extra(App $a, $arr, $user_info)
448 if (is_null($user_info)) {
449 $user_info = api_get_user($a);
452 $arr['$user'] = $user_info;
454 'alternate' => $user_info['url'],
455 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
456 'base' => DI::baseUrl(),
457 'updated' => api_date(null),
458 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
459 'language' => $user_info['lang'],
460 'logo' => DI::baseUrl() . "/images/friendica-32.png",
468 * Unique contact to contact url.
470 * @param int $id Contact id
471 * @return bool|string
472 * Contact url or False if contact id is unknown
475 function api_unique_id_to_nurl($id)
477 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
479 if (DBA::isResult($r)) {
487 * Get user info array.
490 * @param int|string $contact_id Contact ID or URL
492 * @throws BadRequestException
493 * @throws ImagickException
494 * @throws InternalServerErrorException
495 * @throws UnauthorizedException
497 function api_get_user(App $a, $contact_id = null)
505 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
507 // Searching for contact URL
508 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
509 $user = DBA::escape(Strings::normaliseLink($contact_id));
511 $extra_query = "AND `contact`.`nurl` = '%s' ";
512 if (api_user() !== false) {
513 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
517 // Searching for contact id with uid = 0
518 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
519 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
522 throw new BadRequestException("User ID ".$contact_id." not found.");
526 $extra_query = "AND `contact`.`nurl` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
532 if (is_null($user) && !empty($_GET['user_id'])) {
533 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
536 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
540 $extra_query = "AND `contact`.`nurl` = '%s' ";
541 if (api_user() !== false) {
542 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
545 if (is_null($user) && !empty($_GET['screen_name'])) {
546 $user = DBA::escape($_GET['screen_name']);
547 $extra_query = "AND `contact`.`nick` = '%s' ";
548 if (api_user() !== false) {
549 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
553 if (is_null($user) && !empty($_GET['profileurl'])) {
554 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
561 // $called_api is the API path exploded on / and is expected to have at least 2 elements
562 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
563 $argid = count($called_api);
564 if (!empty($a->argv[$argid])) {
565 $data = explode(".", $a->argv[$argid]);
566 if (count($data) > 1) {
567 list($user, $null) = $data;
570 if (is_numeric($user)) {
571 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
575 $extra_query = "AND `contact`.`nurl` = '%s' ";
576 if (api_user() !== false) {
577 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
581 $user = DBA::escape($user);
582 $extra_query = "AND `contact`.`nick` = '%s' ";
583 if (api_user() !== false) {
584 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
589 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
592 if (api_user() === false) {
596 $user = $_SESSION['uid'];
597 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
601 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
605 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
611 // Selecting the id by priority, friendica first
612 if (is_array($uinfo)) {
613 api_best_nickname($uinfo);
616 // if the contact wasn't found, fetch it from the contacts with uid = 0
617 if (!DBA::isResult($uinfo)) {
619 throw new BadRequestException("User not found.");
622 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
624 if (DBA::isResult($contact)) {
626 'id' => $contact["id"],
627 'id_str' => (string) $contact["id"],
628 'name' => $contact["name"],
629 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
630 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
631 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
632 'profile_image_url' => $contact["micro"],
633 'profile_image_url_https' => $contact["micro"],
634 'profile_image_url_profile_size' => $contact["thumb"],
635 'profile_image_url_large' => $contact["photo"],
636 'url' => $contact["url"],
637 'protected' => false,
638 'followers_count' => 0,
639 'friends_count' => 0,
641 'created_at' => api_date($contact["created"]),
642 'favourites_count' => 0,
644 'time_zone' => 'UTC',
645 'geo_enabled' => false,
647 'statuses_count' => 0,
649 'contributors_enabled' => false,
650 'is_translator' => false,
651 'is_translation_enabled' => false,
652 'following' => false,
653 'follow_request_sent' => false,
654 'statusnet_blocking' => false,
655 'notifications' => false,
656 'statusnet_profile_url' => $contact["url"],
658 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
659 'pid' => Contact::getIdForURL($contact["url"], 0, false),
661 'network' => $contact["network"],
666 throw new BadRequestException("User ".$url." not found.");
670 if ($uinfo[0]['self']) {
671 if ($uinfo[0]['network'] == "") {
672 $uinfo[0]['network'] = Protocol::DFRN;
675 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
676 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
683 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
685 if (!empty($profile['about'])) {
686 $description = $profile['about'];
688 $description = $uinfo[0]["about"];
691 if (!empty($usr['default-location'])) {
692 $location = $usr['default-location'];
693 } elseif (!empty($uinfo[0]["location"])) {
694 $location = $uinfo[0]["location"];
696 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
700 'id' => intval($pcontact_id),
701 'id_str' => (string) intval($pcontact_id),
702 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
703 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
704 'location' => $location,
705 'description' => BBCode::toPlaintext($description ?? ''),
706 'profile_image_url' => $uinfo[0]['micro'],
707 'profile_image_url_https' => $uinfo[0]['micro'],
708 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
709 'profile_image_url_large' => $uinfo[0]["photo"],
710 'url' => $uinfo[0]['url'],
711 'protected' => false,
712 'followers_count' => intval($countfollowers),
713 'friends_count' => intval($countfriends),
715 'created_at' => api_date($uinfo[0]['created']),
716 'favourites_count' => intval($starred),
718 'time_zone' => 'UTC',
719 'geo_enabled' => false,
721 'statuses_count' => intval($countitems),
723 'contributors_enabled' => false,
724 'is_translator' => false,
725 'is_translation_enabled' => false,
726 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
727 'follow_request_sent' => false,
728 'statusnet_blocking' => false,
729 'notifications' => false,
731 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
732 'statusnet_profile_url' => $uinfo[0]['url'],
733 'uid' => intval($uinfo[0]['uid']),
734 'cid' => intval($uinfo[0]['cid']),
735 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
736 'self' => $uinfo[0]['self'],
737 'network' => $uinfo[0]['network'],
740 // If this is a local user and it uses Frio, we can get its color preferences.
742 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
743 if ($theme_info['theme'] === 'frio') {
744 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
746 if ($schema && ($schema != '---')) {
747 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
748 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
749 require_once $schemefile;
752 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
753 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
754 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
756 if (empty($nav_bg)) {
759 if (empty($link_color)) {
760 $link_color = "#6fdbe8";
762 if (empty($bgcolor)) {
763 $bgcolor = "#ededed";
766 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
767 $ret['profile_link_color'] = str_replace('#', '', $link_color);
768 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
776 * return api-formatted array for item's author and owner
779 * @param array $item item from db
780 * @return array(array:author, array:owner)
781 * @throws BadRequestException
782 * @throws ImagickException
783 * @throws InternalServerErrorException
784 * @throws UnauthorizedException
786 function api_item_get_user(App $a, $item)
788 $status_user = api_get_user($a, $item['author-id'] ?? null);
790 $author_user = $status_user;
792 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
794 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
795 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
797 $owner_user = $author_user;
800 return ([$status_user, $author_user, $owner_user]);
804 * walks recursively through an array with the possibility to change value and key
806 * @param array $array The array to walk through
807 * @param callable $callback The callback function
809 * @return array the transformed array
811 function api_walk_recursive(array &$array, callable $callback)
815 foreach ($array as $k => $v) {
817 if ($callback($v, $k)) {
818 $new_array[$k] = api_walk_recursive($v, $callback);
821 if ($callback($v, $k)) {
832 * Callback function to transform the array in an array that can be transformed in a XML file
834 * @param mixed $item Array item value
835 * @param string $key Array key
837 * @return boolean Should the array item be deleted?
839 function api_reformat_xml(&$item, &$key)
841 if (is_bool($item)) {
842 $item = ($item ? "true" : "false");
845 if (substr($key, 0, 10) == "statusnet_") {
846 $key = "statusnet:".substr($key, 10);
847 } elseif (substr($key, 0, 10) == "friendica_") {
848 $key = "friendica:".substr($key, 10);
850 /// @TODO old-lost code?
852 // $key = "default:".$key;
858 * Creates the XML from a JSON style array
860 * @param array $data JSON style array
861 * @param string $root_element Name of the root element
863 * @return string The XML data
865 function api_create_xml(array $data, $root_element)
867 $childname = key($data);
868 $data2 = array_pop($data);
870 $namespaces = ["" => "http://api.twitter.com",
871 "statusnet" => "http://status.net/schema/api/1/",
872 "friendica" => "http://friendi.ca/schema/api/1/",
873 "georss" => "http://www.georss.org/georss"];
875 /// @todo Auto detection of needed namespaces
876 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
880 if (is_array($data2)) {
882 api_walk_recursive($data2, "api_reformat_xml");
888 foreach ($data2 as $item) {
889 $data4[$i++ . ":" . $childname] = $item;
896 $data3 = [$root_element => $data2];
898 $ret = XML::fromArray($data3, $xml, false, $namespaces);
903 * Formats the data according to the data type
905 * @param string $root_element Name of the root element
906 * @param string $type Return type (atom, rss, xml, json)
907 * @param array $data JSON style array
909 * @return array|string (string|array) XML data or JSON data
911 function api_format_data($root_element, $type, $data)
917 $ret = api_create_xml($data, $root_element);
932 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
933 * returns a 401 status code and an error message if not.
935 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
937 * @param string $type Return type (atom, rss, xml, json)
938 * @return array|string
939 * @throws BadRequestException
940 * @throws ForbiddenException
941 * @throws ImagickException
942 * @throws InternalServerErrorException
943 * @throws UnauthorizedException
945 function api_account_verify_credentials($type)
949 if (api_user() === false) {
950 throw new ForbiddenException();
953 unset($_REQUEST["user_id"]);
954 unset($_GET["user_id"]);
956 unset($_REQUEST["screen_name"]);
957 unset($_GET["screen_name"]);
959 $skip_status = $_REQUEST['skip_status'] ?? false;
961 $user_info = api_get_user($a);
963 // "verified" isn't used here in the standard
964 unset($user_info["verified"]);
966 // - Adding last status
968 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
970 $user_info['status'] = api_format_item($item, $type);
974 // "uid" and "self" are only needed for some internal stuff, so remove it from here
975 unset($user_info["uid"]);
976 unset($user_info["self"]);
978 return api_format_data("user", $type, ['user' => $user_info]);
981 /// @TODO move to top of file or somewhere better
982 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
985 * Get data from $_POST or $_GET
990 function requestdata($k)
992 if (!empty($_POST[$k])) {
995 if (!empty($_GET[$k])) {
1002 * Deprecated function to upload media.
1004 * @param string $type Return type (atom, rss, xml, json)
1006 * @return array|string
1007 * @throws BadRequestException
1008 * @throws ForbiddenException
1009 * @throws ImagickException
1010 * @throws InternalServerErrorException
1011 * @throws UnauthorizedException
1013 function api_statuses_mediap($type)
1017 if (api_user() === false) {
1018 Logger::log('api_statuses_update: no user');
1019 throw new ForbiddenException();
1021 $user_info = api_get_user($a);
1023 $_REQUEST['profile_uid'] = api_user();
1024 $_REQUEST['api_source'] = true;
1025 $txt = requestdata('status');
1026 /// @TODO old-lost code?
1027 //$txt = urldecode(requestdata('status'));
1029 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1030 $txt = HTML::toBBCodeVideo($txt);
1031 $config = HTMLPurifier_Config::createDefault();
1032 $config->set('Cache.DefinitionImpl', null);
1033 $purifier = new HTMLPurifier($config);
1034 $txt = $purifier->purify($txt);
1036 $txt = HTML::toBBCode($txt);
1038 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1040 $picture = wall_upload_post($a, false);
1042 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1043 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1044 $item_id = item_post($a);
1046 // output the post that we just posted.
1047 return api_status_show($type, $item_id);
1050 /// @TODO move this to top of file or somewhere better!
1051 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1054 * Updates the user’s current status.
1056 * @param string $type Return type (atom, rss, xml, json)
1058 * @return array|string
1059 * @throws BadRequestException
1060 * @throws ForbiddenException
1061 * @throws ImagickException
1062 * @throws InternalServerErrorException
1063 * @throws TooManyRequestsException
1064 * @throws UnauthorizedException
1065 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1067 function api_statuses_update($type)
1071 if (api_user() === false) {
1072 Logger::log('api_statuses_update: no user');
1073 throw new ForbiddenException();
1078 // convert $_POST array items to the form we use for web posts.
1079 if (requestdata('htmlstatus')) {
1080 $txt = requestdata('htmlstatus');
1081 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1082 $txt = HTML::toBBCodeVideo($txt);
1084 $config = HTMLPurifier_Config::createDefault();
1085 $config->set('Cache.DefinitionImpl', null);
1087 $purifier = new HTMLPurifier($config);
1088 $txt = $purifier->purify($txt);
1090 $_REQUEST['body'] = HTML::toBBCode($txt);
1093 $_REQUEST['body'] = requestdata('status');
1096 $_REQUEST['title'] = requestdata('title');
1098 $parent = requestdata('in_reply_to_status_id');
1100 // Twidere sends "-1" if it is no reply ...
1101 if ($parent == -1) {
1105 if (ctype_digit($parent)) {
1106 $_REQUEST['parent'] = $parent;
1108 $_REQUEST['parent_uri'] = $parent;
1111 if (requestdata('lat') && requestdata('long')) {
1112 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1114 $_REQUEST['profile_uid'] = api_user();
1117 // Check for throttling (maximum posts per day, week and month)
1118 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1119 if ($throttle_day > 0) {
1120 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1122 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1123 $posts_day = DBA::count('thread', $condition);
1125 if ($posts_day > $throttle_day) {
1126 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1127 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1128 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));
1132 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1133 if ($throttle_week > 0) {
1134 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1136 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1137 $posts_week = DBA::count('thread', $condition);
1139 if ($posts_week > $throttle_week) {
1140 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1141 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1142 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));
1146 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1147 if ($throttle_month > 0) {
1148 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1150 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1151 $posts_month = DBA::count('thread', $condition);
1153 if ($posts_month > $throttle_month) {
1154 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1155 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1156 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));
1161 if (!empty($_FILES['media'])) {
1162 // upload the image if we have one
1163 $picture = wall_upload_post($a, false);
1164 if (is_array($picture)) {
1165 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1169 if (requestdata('media_ids')) {
1170 $ids = explode(',', requestdata('media_ids'));
1171 foreach ($ids as $id) {
1173 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1177 if (DBA::isResult($r)) {
1178 $phototypes = Images::supportedTypes();
1179 $ext = $phototypes[$r[0]['type']];
1180 $description = $r[0]['desc'] ?? '';
1181 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1182 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1187 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1189 $_REQUEST['api_source'] = true;
1191 if (empty($_REQUEST['source'])) {
1192 $_REQUEST["source"] = api_source();
1195 // call out normal post function
1196 $item_id = item_post($a);
1198 // output the post that we just posted.
1199 return api_status_show($type, $item_id);
1202 /// @TODO move to top of file or somewhere better
1203 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1204 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1207 * Uploads an image to Friendica.
1210 * @throws BadRequestException
1211 * @throws ForbiddenException
1212 * @throws ImagickException
1213 * @throws InternalServerErrorException
1214 * @throws UnauthorizedException
1215 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1217 function api_media_upload()
1221 if (api_user() === false) {
1222 Logger::log('no user');
1223 throw new ForbiddenException();
1228 if (empty($_FILES['media'])) {
1230 throw new BadRequestException("No media.");
1233 $media = wall_upload_post($a, false);
1236 throw new InternalServerErrorException();
1240 $returndata["media_id"] = $media["id"];
1241 $returndata["media_id_string"] = (string)$media["id"];
1242 $returndata["size"] = $media["size"];
1243 $returndata["image"] = ["w" => $media["width"],
1244 "h" => $media["height"],
1245 "image_type" => $media["type"],
1246 "friendica_preview_url" => $media["preview"]];
1248 Logger::info('Media uploaded', ['return' => $returndata]);
1250 return ["media" => $returndata];
1253 /// @TODO move to top of file or somewhere better
1254 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1257 * Updates media meta data (picture descriptions)
1259 * @param string $type Return type (atom, rss, xml, json)
1261 * @return array|string
1262 * @throws BadRequestException
1263 * @throws ForbiddenException
1264 * @throws ImagickException
1265 * @throws InternalServerErrorException
1266 * @throws TooManyRequestsException
1267 * @throws UnauthorizedException
1268 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1270 * @todo Compare the corresponding Twitter function for correct return values
1272 function api_media_metadata_create($type)
1276 if (api_user() === false) {
1277 Logger::info('no user');
1278 throw new ForbiddenException();
1283 $postdata = Network::postdata();
1285 if (empty($postdata)) {
1286 throw new BadRequestException("No post data");
1289 $data = json_decode($postdata, true);
1291 throw new BadRequestException("Invalid post data");
1294 if (empty($data['media_id']) || empty($data['alt_text'])) {
1295 throw new BadRequestException("Missing post data values");
1298 if (empty($data['alt_text']['text'])) {
1299 throw new BadRequestException("No alt text.");
1302 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1304 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1305 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1306 if (!DBA::isResult($photo)) {
1307 throw new BadRequestException("Metadata not found.");
1310 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1313 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1316 * @param string $type Return format (atom, rss, xml, json)
1317 * @param int $item_id
1318 * @return array|string
1321 function api_status_show($type, $item_id)
1323 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1327 $item = api_get_item(['id' => $item_id]);
1328 if (!empty($item)) {
1329 $status_info = api_format_item($item, $type);
1332 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1334 return api_format_data('statuses', $type, ['status' => $status_info]);
1338 * Retrieves the last public status of the provided user info
1340 * @param int $ownerId Public contact Id
1341 * @param int $uid User Id
1345 function api_get_last_status($ownerId, $uid)
1348 'author-id'=> $ownerId,
1350 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1351 'private' => [Item::PUBLIC, Item::UNLISTED]
1354 $item = api_get_item($condition);
1360 * Retrieves a single item record based on the provided condition and converts it for API use.
1362 * @param array $condition Item table condition array
1366 function api_get_item(array $condition)
1368 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1374 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1375 * The author's most recent status will be returned inline.
1377 * @param string $type Return type (atom, rss, xml, json)
1378 * @return array|string
1379 * @throws BadRequestException
1380 * @throws ImagickException
1381 * @throws InternalServerErrorException
1382 * @throws UnauthorizedException
1383 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1385 function api_users_show($type)
1387 $a = Friendica\DI::app();
1389 $user_info = api_get_user($a);
1391 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1392 if (!empty($item)) {
1393 $user_info['status'] = api_format_item($item, $type);
1396 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1397 unset($user_info['uid']);
1398 unset($user_info['self']);
1400 return api_format_data('user', $type, ['user' => $user_info]);
1403 /// @TODO move to top of file or somewhere better
1404 api_register_func('api/users/show', 'api_users_show');
1405 api_register_func('api/externalprofile/show', 'api_users_show');
1408 * Search a public user account.
1410 * @param string $type Return type (atom, rss, xml, json)
1412 * @return array|string
1413 * @throws BadRequestException
1414 * @throws ImagickException
1415 * @throws InternalServerErrorException
1416 * @throws UnauthorizedException
1417 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1419 function api_users_search($type)
1425 if (!empty($_GET['q'])) {
1426 $contacts = Contact::selectToArray(
1429 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1437 if (DBA::isResult($contacts)) {
1439 foreach ($contacts as $contact) {
1440 $user_info = api_get_user($a, $contact['id']);
1442 if ($type == 'xml') {
1443 $userlist[$k++ . ':user'] = $user_info;
1445 $userlist[] = $user_info;
1448 $userlist = ['users' => $userlist];
1450 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1453 throw new BadRequestException('No search term specified.');
1456 return api_format_data('users', $type, $userlist);
1459 /// @TODO move to top of file or somewhere better
1460 api_register_func('api/users/search', 'api_users_search');
1463 * Return user objects
1465 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1467 * @param string $type Return format: json or xml
1469 * @return array|string
1470 * @throws BadRequestException
1471 * @throws ImagickException
1472 * @throws InternalServerErrorException
1473 * @throws NotFoundException if the results are empty.
1474 * @throws UnauthorizedException
1476 function api_users_lookup($type)
1480 if (!empty($_REQUEST['user_id'])) {
1481 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1483 $users[] = api_get_user(DI::app(), $id);
1488 if (empty($users)) {
1489 throw new NotFoundException;
1492 return api_format_data("users", $type, ['users' => $users]);
1495 /// @TODO move to top of file or somewhere better
1496 api_register_func('api/users/lookup', 'api_users_lookup', true);
1499 * Returns statuses that match a specified query.
1501 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1503 * @param string $type Return format: json, xml, atom, rss
1505 * @return array|string
1506 * @throws BadRequestException if the "q" parameter is missing.
1507 * @throws ForbiddenException
1508 * @throws ImagickException
1509 * @throws InternalServerErrorException
1510 * @throws UnauthorizedException
1512 function api_search($type)
1515 $user_info = api_get_user($a);
1517 if (api_user() === false || $user_info === false) {
1518 throw new ForbiddenException();
1521 if (empty($_REQUEST['q'])) {
1522 throw new BadRequestException('q parameter is required.');
1525 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1528 $data['status'] = [];
1530 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1531 if (!empty($_REQUEST['rpp'])) {
1532 $count = $_REQUEST['rpp'];
1533 } elseif (!empty($_REQUEST['count'])) {
1534 $count = $_REQUEST['count'];
1537 $since_id = $_REQUEST['since_id'] ?? 0;
1538 $max_id = $_REQUEST['max_id'] ?? 0;
1539 $page = $_REQUEST['page'] ?? 1;
1541 $start = max(0, ($page - 1) * $count);
1543 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1544 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1545 $searchTerm = $matches[1];
1546 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1547 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1549 while ($tag = DBA::fetch($tags)) {
1550 $uriids[] = $tag['uri-id'];
1554 if (empty($uriids)) {
1555 return api_format_data('statuses', $type, $data);
1558 $condition = ['uri-id' => $uriids];
1559 if ($exclude_replies) {
1560 $condition['gravity'] = GRAVITY_PARENT;
1563 $params['group_by'] = ['uri-id'];
1565 $condition = ["`id` > ?
1566 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1567 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1568 AND `body` LIKE CONCAT('%',?,'%')",
1569 $since_id, api_user(), $_REQUEST['q']];
1571 $condition[0] .= ' AND `id` <= ?';
1572 $condition[] = $max_id;
1578 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1579 $id = Item::fetchByLink($searchTerm, api_user());
1582 $id = Item::fetchByLink($searchTerm);
1586 $statuses = Post::select([], ['id' => $id]);
1590 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1592 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1594 bindComments($data['status']);
1596 return api_format_data('statuses', $type, $data);
1599 /// @TODO move to top of file or somewhere better
1600 api_register_func('api/search/tweets', 'api_search', true);
1601 api_register_func('api/search', 'api_search', true);
1604 * Returns the most recent statuses posted by the user and the users they follow.
1606 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1608 * @param string $type Return type (atom, rss, xml, json)
1610 * @return array|string
1611 * @throws BadRequestException
1612 * @throws ForbiddenException
1613 * @throws ImagickException
1614 * @throws InternalServerErrorException
1615 * @throws UnauthorizedException
1616 * @todo Optional parameters
1617 * @todo Add reply info
1619 function api_statuses_home_timeline($type)
1622 $user_info = api_get_user($a);
1624 if (api_user() === false || $user_info === false) {
1625 throw new ForbiddenException();
1628 unset($_REQUEST["user_id"]);
1629 unset($_GET["user_id"]);
1631 unset($_REQUEST["screen_name"]);
1632 unset($_GET["screen_name"]);
1634 // get last network messages
1637 $count = $_REQUEST['count'] ?? 20;
1638 $page = $_REQUEST['page']?? 0;
1639 $since_id = $_REQUEST['since_id'] ?? 0;
1640 $max_id = $_REQUEST['max_id'] ?? 0;
1641 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1642 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1644 $start = max(0, ($page - 1) * $count);
1646 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1647 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1650 $condition[0] .= " AND `id` <= ?";
1651 $condition[] = $max_id;
1653 if ($exclude_replies) {
1654 $condition[0] .= ' AND `gravity` = ?';
1655 $condition[] = GRAVITY_PARENT;
1657 if ($conversation_id > 0) {
1658 $condition[0] .= " AND `parent` = ?";
1659 $condition[] = $conversation_id;
1662 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1663 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1665 $items = Post::toArray($statuses);
1667 $ret = api_format_items($items, $user_info, false, $type);
1669 // Set all posts from the query above to seen
1671 foreach ($items as $item) {
1672 $idarray[] = intval($item["id"]);
1675 if (!empty($idarray)) {
1676 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1678 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1684 $data = ['status' => $ret];
1689 $data = api_rss_extra($a, $data, $user_info);
1693 return api_format_data("statuses", $type, $data);
1697 /// @TODO move to top of file or somewhere better
1698 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1699 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1702 * Returns the most recent statuses from public users.
1704 * @param string $type Return type (atom, rss, xml, json)
1706 * @return array|string
1707 * @throws BadRequestException
1708 * @throws ForbiddenException
1709 * @throws ImagickException
1710 * @throws InternalServerErrorException
1711 * @throws UnauthorizedException
1713 function api_statuses_public_timeline($type)
1716 $user_info = api_get_user($a);
1718 if (api_user() === false || $user_info === false) {
1719 throw new ForbiddenException();
1722 // get last network messages
1725 $count = $_REQUEST['count'] ?? 20;
1726 $page = $_REQUEST['page'] ?? 1;
1727 $since_id = $_REQUEST['since_id'] ?? 0;
1728 $max_id = $_REQUEST['max_id'] ?? 0;
1729 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1730 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1732 $start = max(0, ($page - 1) * $count);
1734 if ($exclude_replies && !$conversation_id) {
1735 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1736 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1739 $condition[0] .= " AND `iid` <= ?";
1740 $condition[] = $max_id;
1743 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1744 $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1746 $r = Post::toArray($statuses);
1748 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1749 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1752 $condition[0] .= " AND `id` <= ?";
1753 $condition[] = $max_id;
1755 if ($conversation_id > 0) {
1756 $condition[0] .= " AND `parent` = ?";
1757 $condition[] = $conversation_id;
1760 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1761 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1763 $r = Post::toArray($statuses);
1766 $ret = api_format_items($r, $user_info, false, $type);
1770 $data = ['status' => $ret];
1775 $data = api_rss_extra($a, $data, $user_info);
1779 return api_format_data("statuses", $type, $data);
1782 /// @TODO move to top of file or somewhere better
1783 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1786 * Returns the most recent statuses posted by users this node knows about.
1788 * @param string $type Return format: json, xml, atom, rss
1789 * @return array|string
1790 * @throws BadRequestException
1791 * @throws ForbiddenException
1792 * @throws ImagickException
1793 * @throws InternalServerErrorException
1794 * @throws UnauthorizedException
1796 function api_statuses_networkpublic_timeline($type)
1799 $user_info = api_get_user($a);
1801 if (api_user() === false || $user_info === false) {
1802 throw new ForbiddenException();
1805 $since_id = $_REQUEST['since_id'] ?? 0;
1806 $max_id = $_REQUEST['max_id'] ?? 0;
1809 $count = $_REQUEST['count'] ?? 20;
1810 $page = $_REQUEST['page'] ?? 1;
1812 $start = max(0, ($page - 1) * $count);
1814 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `iid` > ? AND `private` = ?",
1815 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1818 $condition[0] .= " AND `iid` <= ?";
1819 $condition[] = $max_id;
1822 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1823 $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1825 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1829 $data = ['status' => $ret];
1834 $data = api_rss_extra($a, $data, $user_info);
1838 return api_format_data("statuses", $type, $data);
1841 /// @TODO move to top of file or somewhere better
1842 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1845 * Returns a single status.
1847 * @param string $type Return type (atom, rss, xml, json)
1849 * @return array|string
1850 * @throws BadRequestException
1851 * @throws ForbiddenException
1852 * @throws ImagickException
1853 * @throws InternalServerErrorException
1854 * @throws UnauthorizedException
1855 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1857 function api_statuses_show($type)
1860 $user_info = api_get_user($a);
1862 if (api_user() === false || $user_info === false) {
1863 throw new ForbiddenException();
1867 $id = intval($a->argv[3] ?? 0);
1870 $id = intval($_REQUEST['id'] ?? 0);
1875 $id = intval($a->argv[4] ?? 0);
1878 Logger::log('API: api_statuses_show: ' . $id);
1880 $conversation = !empty($_REQUEST['conversation']);
1882 // try to fetch the item for the local user - or the public item, if there is no local one
1883 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1884 if (!DBA::isResult($uri_item)) {
1885 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1888 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1889 if (!DBA::isResult($item)) {
1890 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1895 if ($conversation) {
1896 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1897 $params = ['order' => ['id' => true]];
1899 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1903 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1905 /// @TODO How about copying this to above methods which don't check $r ?
1906 if (!DBA::isResult($statuses)) {
1907 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1910 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1912 if ($conversation) {
1913 $data = ['status' => $ret];
1914 return api_format_data("statuses", $type, $data);
1916 $data = ['status' => $ret[0]];
1917 return api_format_data("status", $type, $data);
1921 /// @TODO move to top of file or somewhere better
1922 api_register_func('api/statuses/show', 'api_statuses_show', true);
1926 * @param string $type Return type (atom, rss, xml, json)
1928 * @return array|string
1929 * @throws BadRequestException
1930 * @throws ForbiddenException
1931 * @throws ImagickException
1932 * @throws InternalServerErrorException
1933 * @throws UnauthorizedException
1934 * @todo nothing to say?
1936 function api_conversation_show($type)
1939 $user_info = api_get_user($a);
1941 if (api_user() === false || $user_info === false) {
1942 throw new ForbiddenException();
1946 $id = intval($a->argv[3] ?? 0);
1947 $since_id = intval($_REQUEST['since_id'] ?? 0);
1948 $max_id = intval($_REQUEST['max_id'] ?? 0);
1949 $count = intval($_REQUEST['count'] ?? 20);
1950 $page = intval($_REQUEST['page'] ?? 1);
1952 $start = max(0, ($page - 1) * $count);
1955 $id = intval($_REQUEST['id'] ?? 0);
1960 $id = intval($a->argv[4] ?? 0);
1963 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1965 // try to fetch the item for the local user - or the public item, if there is no local one
1966 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1967 if (!DBA::isResult($item)) {
1968 throw new BadRequestException("There is no status with this id.");
1971 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1972 if (!DBA::isResult($parent)) {
1973 throw new BadRequestException("There is no status with this id.");
1976 $id = $parent['id'];
1978 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1979 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1982 $condition[0] .= " AND `id` <= ?";
1983 $condition[] = $max_id;
1986 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1987 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1989 if (!DBA::isResult($statuses)) {
1990 throw new BadRequestException("There is no status with id $id.");
1993 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1995 $data = ['status' => $ret];
1996 return api_format_data("statuses", $type, $data);
1999 /// @TODO move to top of file or somewhere better
2000 api_register_func('api/conversation/show', 'api_conversation_show', true);
2001 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2006 * @param string $type Return type (atom, rss, xml, json)
2008 * @return array|string
2009 * @throws BadRequestException
2010 * @throws ForbiddenException
2011 * @throws ImagickException
2012 * @throws InternalServerErrorException
2013 * @throws UnauthorizedException
2014 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2016 function api_statuses_repeat($type)
2022 if (api_user() === false) {
2023 throw new ForbiddenException();
2029 $id = intval($a->argv[3] ?? 0);
2032 $id = intval($_REQUEST['id'] ?? 0);
2037 $id = intval($a->argv[4] ?? 0);
2040 Logger::log('API: api_statuses_repeat: '.$id);
2042 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2043 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2045 if (DBA::isResult($item) && !empty($item['body'])) {
2046 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2047 if (!Item::performActivity($id, 'announce', local_user())) {
2048 throw new InternalServerErrorException();
2053 if (strpos($item['body'], "[/share]") !== false) {
2054 $pos = strpos($item['body'], "[share");
2055 $post = substr($item['body'], $pos);
2057 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2059 if (!empty($item['title'])) {
2060 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2063 $post .= $item['body'];
2064 $post .= "[/share]";
2066 $_REQUEST['body'] = $post;
2067 $_REQUEST['profile_uid'] = api_user();
2068 $_REQUEST['api_source'] = true;
2070 if (empty($_REQUEST['source'])) {
2071 $_REQUEST["source"] = api_source();
2074 $item_id = item_post($a);
2077 throw new ForbiddenException();
2080 // output the post that we just posted.
2082 return api_status_show($type, $item_id);
2085 /// @TODO move to top of file or somewhere better
2086 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2089 * Destroys a specific status.
2091 * @param string $type Return type (atom, rss, xml, json)
2093 * @return array|string
2094 * @throws BadRequestException
2095 * @throws ForbiddenException
2096 * @throws ImagickException
2097 * @throws InternalServerErrorException
2098 * @throws UnauthorizedException
2099 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2101 function api_statuses_destroy($type)
2105 if (api_user() === false) {
2106 throw new ForbiddenException();
2112 $id = intval($a->argv[3] ?? 0);
2115 $id = intval($_REQUEST['id'] ?? 0);
2120 $id = intval($a->argv[4] ?? 0);
2123 Logger::log('API: api_statuses_destroy: '.$id);
2125 $ret = api_statuses_show($type);
2127 Item::deleteForUser(['id' => $id], api_user());
2132 /// @TODO move to top of file or somewhere better
2133 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2136 * Returns the most recent mentions.
2138 * @param string $type Return type (atom, rss, xml, json)
2140 * @return array|string
2141 * @throws BadRequestException
2142 * @throws ForbiddenException
2143 * @throws ImagickException
2144 * @throws InternalServerErrorException
2145 * @throws UnauthorizedException
2146 * @see http://developer.twitter.com/doc/get/statuses/mentions
2148 function api_statuses_mentions($type)
2151 $user_info = api_get_user($a);
2153 if (api_user() === false || $user_info === false) {
2154 throw new ForbiddenException();
2157 unset($_REQUEST["user_id"]);
2158 unset($_GET["user_id"]);
2160 unset($_REQUEST["screen_name"]);
2161 unset($_GET["screen_name"]);
2163 // get last network messages
2166 $since_id = intval($_REQUEST['since_id'] ?? 0);
2167 $max_id = intval($_REQUEST['max_id'] ?? 0);
2168 $count = intval($_REQUEST['count'] ?? 20);
2169 $page = intval($_REQUEST['page'] ?? 1);
2171 $start = max(0, ($page - 1) * $count);
2173 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2174 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2175 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2177 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2178 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2179 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2180 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2181 api_user(), $since_id];
2184 $query .= " AND `id` <= ?";
2185 $condition[] = $max_id;
2188 array_unshift($condition, $query);
2190 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2191 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2193 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2195 $data = ['status' => $ret];
2200 $data = api_rss_extra($a, $data, $user_info);
2204 return api_format_data("statuses", $type, $data);
2207 /// @TODO move to top of file or somewhere better
2208 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2209 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2212 * Returns the most recent statuses posted by the user.
2214 * @param string $type Either "json" or "xml"
2215 * @return string|array
2216 * @throws BadRequestException
2217 * @throws ForbiddenException
2218 * @throws ImagickException
2219 * @throws InternalServerErrorException
2220 * @throws UnauthorizedException
2221 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2223 function api_statuses_user_timeline($type)
2226 $user_info = api_get_user($a);
2228 if (api_user() === false || $user_info === false) {
2229 throw new ForbiddenException();
2232 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2234 $since_id = $_REQUEST['since_id'] ?? 0;
2235 $max_id = $_REQUEST['max_id'] ?? 0;
2236 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2237 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2240 $count = $_REQUEST['count'] ?? 20;
2241 $page = $_REQUEST['page'] ?? 1;
2243 $start = max(0, ($page - 1) * $count);
2245 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2246 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2248 if ($user_info['self'] == 1) {
2249 $condition[0] .= ' AND `wall` ';
2252 if ($exclude_replies) {
2253 $condition[0] .= ' AND `gravity` = ?';
2254 $condition[] = GRAVITY_PARENT;
2257 if ($conversation_id > 0) {
2258 $condition[0] .= " AND `parent` = ?";
2259 $condition[] = $conversation_id;
2263 $condition[0] .= " AND `id` <= ?";
2264 $condition[] = $max_id;
2267 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2268 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2270 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2274 $data = ['status' => $ret];
2279 $data = api_rss_extra($a, $data, $user_info);
2283 return api_format_data("statuses", $type, $data);
2286 /// @TODO move to top of file or somewhere better
2287 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2290 * Star/unstar an item.
2291 * param: id : id of the item
2293 * @param string $type Return type (atom, rss, xml, json)
2295 * @return array|string
2296 * @throws BadRequestException
2297 * @throws ForbiddenException
2298 * @throws ImagickException
2299 * @throws InternalServerErrorException
2300 * @throws UnauthorizedException
2301 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2303 function api_favorites_create_destroy($type)
2307 if (api_user() === false) {
2308 throw new ForbiddenException();
2311 // for versioned api.
2312 /// @TODO We need a better global soluton
2313 $action_argv_id = 2;
2314 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2315 $action_argv_id = 3;
2318 if ($a->argc <= $action_argv_id) {
2319 throw new BadRequestException("Invalid request.");
2321 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2322 if ($a->argc == $action_argv_id + 2) {
2323 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2325 $itemid = intval($_REQUEST['id'] ?? 0);
2328 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2330 if (!DBA::isResult($item)) {
2331 throw new BadRequestException("Invalid item.");
2336 $item['starred'] = 1;
2339 $item['starred'] = 0;
2342 throw new BadRequestException("Invalid action ".$action);
2345 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2348 throw new InternalServerErrorException("DB error");
2352 $user_info = api_get_user($a);
2353 $rets = api_format_items([$item], $user_info, false, $type);
2356 $data = ['status' => $ret];
2361 $data = api_rss_extra($a, $data, $user_info);
2365 return api_format_data("status", $type, $data);
2368 /// @TODO move to top of file or somewhere better
2369 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2370 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2373 * Returns the most recent favorite statuses.
2375 * @param string $type Return type (atom, rss, xml, json)
2377 * @return string|array
2378 * @throws BadRequestException
2379 * @throws ForbiddenException
2380 * @throws ImagickException
2381 * @throws InternalServerErrorException
2382 * @throws UnauthorizedException
2384 function api_favorites($type)
2389 $user_info = api_get_user($a);
2391 if (api_user() === false || $user_info === false) {
2392 throw new ForbiddenException();
2397 // in friendica starred item are private
2398 // return favorites only for self
2399 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2401 if ($user_info['self'] == 0) {
2405 $since_id = $_REQUEST['since_id'] ?? 0;
2406 $max_id = $_REQUEST['max_id'] ?? 0;
2407 $count = $_GET['count'] ?? 20;
2408 $page = $_REQUEST['page'] ?? 1;
2410 $start = max(0, ($page - 1) * $count);
2412 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2413 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2415 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2418 $condition[0] .= " AND `id` <= ?";
2419 $condition[] = $max_id;
2422 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2424 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2429 $data = ['status' => $ret];
2434 $data = api_rss_extra($a, $data, $user_info);
2438 return api_format_data("statuses", $type, $data);
2441 /// @TODO move to top of file or somewhere better
2442 api_register_func('api/favorites', 'api_favorites', true);
2446 * @param array $item
2447 * @param array $recipient
2448 * @param array $sender
2451 * @throws InternalServerErrorException
2453 function api_format_messages($item, $recipient, $sender)
2455 // standard meta information
2457 'id' => $item['id'],
2458 'sender_id' => $sender['id'],
2460 'recipient_id' => $recipient['id'],
2461 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2462 'sender_screen_name' => $sender['screen_name'],
2463 'recipient_screen_name' => $recipient['screen_name'],
2464 'sender' => $sender,
2465 'recipient' => $recipient,
2467 'friendica_seen' => $item['seen'] ?? 0,
2468 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2471 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2472 if (isset($ret['sender']['uid'])) {
2473 unset($ret['sender']['uid']);
2475 if (isset($ret['sender']['self'])) {
2476 unset($ret['sender']['self']);
2478 if (isset($ret['recipient']['uid'])) {
2479 unset($ret['recipient']['uid']);
2481 if (isset($ret['recipient']['self'])) {
2482 unset($ret['recipient']['self']);
2485 //don't send title to regular StatusNET requests to avoid confusing these apps
2486 if (!empty($_GET['getText'])) {
2487 $ret['title'] = $item['title'];
2488 if ($_GET['getText'] == 'html') {
2489 $ret['text'] = BBCode::convert($item['body'], false);
2490 } elseif ($_GET['getText'] == 'plain') {
2491 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2494 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2496 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2497 unset($ret['sender']);
2498 unset($ret['recipient']);
2506 * @param array $item
2509 * @throws InternalServerErrorException
2511 function api_convert_item($item)
2513 $body = $item['body'];
2514 $entities = api_get_entitities($statustext, $body);
2516 // Add pictures to the attachment array and remove them from the body
2517 $attachments = api_get_attachments($body);
2519 // Workaround for ostatus messages where the title is identically to the body
2520 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2521 $statusbody = trim(HTML::toPlaintext($html, 0));
2523 // handle data: images
2524 $statusbody = api_format_items_embeded_images($item, $statusbody);
2526 $statustitle = trim($item['title']);
2528 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2529 $statustext = trim($statusbody);
2531 $statustext = trim($statustitle."\n\n".$statusbody);
2534 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2535 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2538 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2540 // Workaround for clients with limited HTML parser functionality
2541 $search = ["<br>", "<blockquote>", "</blockquote>",
2542 "<h1>", "</h1>", "<h2>", "</h2>",
2543 "<h3>", "</h3>", "<h4>", "</h4>",
2544 "<h5>", "</h5>", "<h6>", "</h6>"];
2545 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2546 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2547 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2548 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2549 $statushtml = str_replace($search, $replace, $statushtml);
2551 if ($item['title'] != "") {
2552 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2556 $oldtext = $statushtml;
2557 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2558 } while ($oldtext != $statushtml);
2560 if (substr($statushtml, 0, 4) == '<br>') {
2561 $statushtml = substr($statushtml, 4);
2564 if (substr($statushtml, 0, -4) == '<br>') {
2565 $statushtml = substr($statushtml, -4);
2568 // feeds without body should contain the link
2569 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2570 $statushtml .= BBCode::convert($item['plink']);
2574 "text" => $statustext,
2575 "html" => $statushtml,
2576 "attachments" => $attachments,
2577 "entities" => $entities
2583 * @param string $body
2586 * @throws InternalServerErrorException
2588 function api_get_attachments(&$body)
2590 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2591 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2593 $URLSearchString = "^\[\]";
2594 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2598 // Remove all embedded pictures, since they are added as attachments
2599 foreach ($images[0] as $orig) {
2600 $body = str_replace($orig, '', $body);
2605 foreach ($images[1] as $image) {
2606 $imagedata = Images::getInfoFromURLCached($image);
2609 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2613 return $attachments;
2618 * @param string $text
2619 * @param string $bbcode
2622 * @throws InternalServerErrorException
2623 * @todo Links at the first character of the post
2625 function api_get_entitities(&$text, $bbcode)
2627 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2629 if ($include_entities != "true") {
2630 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2632 foreach ($images[1] as $image) {
2633 $replace = ProxyUtils::proxifyUrl($image);
2634 $text = str_replace($image, $replace, $text);
2639 $bbcode = BBCode::cleanPictureLinks($bbcode);
2641 // Change pure links in text to bbcode uris
2642 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2645 $entities["hashtags"] = [];
2646 $entities["symbols"] = [];
2647 $entities["urls"] = [];
2648 $entities["user_mentions"] = [];
2650 $URLSearchString = "^\[\]";
2652 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2654 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2655 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2657 $bbcode = preg_replace(
2658 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2659 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2662 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2664 $bbcode = preg_replace(
2665 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2666 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2669 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2671 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2673 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2676 foreach ($urls[1] as $id => $url) {
2677 $start = iconv_strpos($text, $url, 0, "UTF-8");
2678 if (!($start === false)) {
2679 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2683 ksort($ordered_urls);
2687 foreach ($ordered_urls as $url) {
2688 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2689 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2691 $display_url = $url["title"];
2693 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2694 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2696 if (strlen($display_url) > 26) {
2697 $display_url = substr($display_url, 0, 25)."…";
2701 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2702 if (!($start === false)) {
2703 $entities["urls"][] = ["url" => $url["url"],
2704 "expanded_url" => $url["url"],
2705 "display_url" => $display_url,
2706 "indices" => [$start, $start+strlen($url["url"])]];
2707 $offset = $start + 1;
2711 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2712 $ordered_images = [];
2713 foreach ($images as $image) {
2714 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2715 if (!($start === false)) {
2716 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2720 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2721 foreach ($images[1] as $image) {
2722 $start = iconv_strpos($text, $image, 0, "UTF-8");
2723 if (!($start === false)) {
2724 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2730 foreach ($ordered_images as $image) {
2731 $url = $image['url'];
2732 $ext_alt_text = $image['alt'];
2734 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2735 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2737 if (strlen($display_url) > 26) {
2738 $display_url = substr($display_url, 0, 25)."…";
2741 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2742 if (!($start === false)) {
2743 $image = Images::getInfoFromURLCached($url);
2745 // If image cache is activated, then use the following sizes:
2746 // thumb (150), small (340), medium (600) and large (1024)
2747 if (!DI::config()->get("system", "proxy_disabled")) {
2748 $media_url = ProxyUtils::proxifyUrl($url);
2751 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2752 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2754 if (($image[0] > 150) || ($image[1] > 150)) {
2755 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2756 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2759 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2760 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2762 if (($image[0] > 600) || ($image[1] > 600)) {
2763 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2764 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2768 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2771 $entities["media"][] = [
2773 "id_str" => (string) ($start + 1),
2774 "indices" => [$start, $start+strlen($url)],
2775 "media_url" => Strings::normaliseLink($media_url),
2776 "media_url_https" => $media_url,
2778 "display_url" => $display_url,
2779 "expanded_url" => $url,
2780 "ext_alt_text" => $ext_alt_text,
2784 $offset = $start + 1;
2793 * @param array $item
2794 * @param string $text
2798 function api_format_items_embeded_images($item, $text)
2800 $text = preg_replace_callback(
2801 '|data:image/([^;]+)[^=]+=*|m',
2802 function () use ($item) {
2803 return DI::baseUrl() . '/display/' . $item['guid'];
2811 * return <a href='url'>name</a> as array
2813 * @param string $txt text
2818 function api_contactlink_to_array($txt)
2821 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2822 if ($r && count($match)==3) {
2824 'name' => $match[2],
2838 * return likes, dislikes and attend status for item
2840 * @param array $item array
2841 * @param string $type Return type (atom, rss, xml, json)
2844 * likes => int count,
2845 * dislikes => int count
2846 * @throws BadRequestException
2847 * @throws ImagickException
2848 * @throws InternalServerErrorException
2849 * @throws UnauthorizedException
2851 function api_format_items_activities($item, $type = "json")
2860 'attendmaybe' => [],
2864 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2865 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2867 while ($parent_item = Post::fetch($ret)) {
2868 // not used as result should be structured like other user data
2869 //builtin_activity_puller($i, $activities);
2871 // get user data and add it to the array of the activity
2872 $user = api_get_user($a, $parent_item['author-id']);
2873 switch ($parent_item['verb']) {
2874 case Activity::LIKE:
2875 $activities['like'][] = $user;
2877 case Activity::DISLIKE:
2878 $activities['dislike'][] = $user;
2880 case Activity::ATTEND:
2881 $activities['attendyes'][] = $user;
2883 case Activity::ATTENDNO:
2884 $activities['attendno'][] = $user;
2886 case Activity::ATTENDMAYBE:
2887 $activities['attendmaybe'][] = $user;
2889 case Activity::ANNOUNCE:
2890 $activities['announce'][] = $user;
2899 if ($type == "xml") {
2900 $xml_activities = [];
2901 foreach ($activities as $k => $v) {
2902 // change xml element from "like" to "friendica:like"
2903 $xml_activities["friendica:".$k] = $v;
2904 // add user data into xml output
2906 foreach ($v as $user) {
2907 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2910 $activities = $xml_activities;
2917 * format items to be returned by api
2919 * @param array $items array of items
2920 * @param array $user_info
2921 * @param bool $filter_user filter items by $user_info
2922 * @param string $type Return type (atom, rss, xml, json)
2924 * @throws BadRequestException
2925 * @throws ImagickException
2926 * @throws InternalServerErrorException
2927 * @throws UnauthorizedException
2929 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2931 $a = Friendica\DI::app();
2935 foreach ((array)$items as $item) {
2936 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2938 // Look if the posts are matching if they should be filtered by user id
2939 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2943 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2952 * @param array $item Item record
2953 * @param string $type Return format (atom, rss, xml, json)
2954 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2955 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2956 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2957 * @return array API-formatted status
2958 * @throws BadRequestException
2959 * @throws ImagickException
2960 * @throws InternalServerErrorException
2961 * @throws UnauthorizedException
2963 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2965 $a = Friendica\DI::app();
2967 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2968 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2971 localize_item($item);
2973 $in_reply_to = api_in_reply_to($item);
2975 $converted = api_convert_item($item);
2977 if ($type == "xml") {
2978 $geo = "georss:point";
2984 'text' => $converted["text"],
2985 'truncated' => false,
2986 'created_at'=> api_date($item['created']),
2987 'in_reply_to_status_id' => $in_reply_to['status_id'],
2988 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2989 'source' => (($item['app']) ? $item['app'] : 'web'),
2990 'id' => intval($item['id']),
2991 'id_str' => (string) intval($item['id']),
2992 'in_reply_to_user_id' => $in_reply_to['user_id'],
2993 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2994 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2996 'favorited' => $item['starred'] ? true : false,
2997 'user' => $status_user,
2998 'friendica_author' => $author_user,
2999 'friendica_owner' => $owner_user,
3000 'friendica_private' => $item['private'] == Item::PRIVATE,
3001 //'entities' => NULL,
3002 'statusnet_html' => $converted["html"],
3003 'statusnet_conversation_id' => $item['parent'],
3004 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3005 'friendica_activities' => api_format_items_activities($item, $type),
3006 'friendica_title' => $item['title'],
3007 'friendica_html' => BBCode::convert($item['body'], false)
3010 if (count($converted["attachments"]) > 0) {
3011 $status["attachments"] = $converted["attachments"];
3014 if (count($converted["entities"]) > 0) {
3015 $status["entities"] = $converted["entities"];
3018 if ($status["source"] == 'web') {
3019 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3020 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3021 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3024 $retweeted_item = [];
3027 if ($item['gravity'] == GRAVITY_PARENT) {
3028 $body = $item['body'];
3029 $retweeted_item = api_share_as_retweet($item);
3030 if ($body != $item['body']) {
3031 $quoted_item = $retweeted_item;
3032 $retweeted_item = [];
3036 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3037 $announce = api_get_announce($item);
3038 if (!empty($announce)) {
3039 $retweeted_item = $item;
3041 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3045 if (!empty($quoted_item)) {
3046 if ($quoted_item['id'] != $item['id']) {
3047 $quoted_status = api_format_item($quoted_item);
3048 /// @todo Only remove the attachments that are also contained in the quotes status
3049 unset($status['attachments']);
3050 unset($status['entities']);
3052 $conv_quoted = api_convert_item($quoted_item);
3053 $quoted_status = $status;
3054 unset($quoted_status['attachments']);
3055 unset($quoted_status['entities']);
3056 unset($quoted_status['statusnet_conversation_id']);
3057 $quoted_status['text'] = $conv_quoted['text'];
3058 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3060 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3061 } catch (BadRequestException $e) {
3062 // user not found. should be found?
3063 /// @todo check if the user should be always found
3064 $quoted_status["user"] = [];
3067 unset($quoted_status['friendica_author']);
3068 unset($quoted_status['friendica_owner']);
3069 unset($quoted_status['friendica_activities']);
3070 unset($quoted_status['friendica_private']);
3073 if (!empty($retweeted_item)) {
3074 $retweeted_status = $status;
3075 unset($retweeted_status['friendica_author']);
3076 unset($retweeted_status['friendica_owner']);
3077 unset($retweeted_status['friendica_activities']);
3078 unset($retweeted_status['friendica_private']);
3079 unset($retweeted_status['statusnet_conversation_id']);
3080 $status['user'] = $status['friendica_owner'];
3082 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3083 } catch (BadRequestException $e) {
3084 // user not found. should be found?
3085 /// @todo check if the user should be always found
3086 $retweeted_status["user"] = [];
3089 $rt_converted = api_convert_item($retweeted_item);
3091 $retweeted_status['text'] = $rt_converted["text"];
3092 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3093 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3095 if (!empty($quoted_status)) {
3096 $retweeted_status['quoted_status'] = $quoted_status;
3099 $status['friendica_author'] = $retweeted_status['user'];
3100 $status['retweeted_status'] = $retweeted_status;
3101 } elseif (!empty($quoted_status)) {
3102 $root_status = api_convert_item($item);
3104 $status['text'] = $root_status["text"];
3105 $status['statusnet_html'] = $root_status["html"];
3106 $status['quoted_status'] = $quoted_status;
3109 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3110 unset($status["user"]["uid"]);
3111 unset($status["user"]["self"]);
3113 if ($item["coord"] != "") {
3114 $coords = explode(' ', $item["coord"]);
3115 if (count($coords) == 2) {
3116 if ($type == "json") {
3117 $status["geo"] = ['type' => 'Point',
3118 'coordinates' => [(float) $coords[0],
3119 (float) $coords[1]]];
3120 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3121 $status["georss:point"] = $item["coord"];
3130 * Returns the remaining number of API requests available to the user before the API limit is reached.
3132 * @param string $type Return type (atom, rss, xml, json)
3134 * @return array|string
3137 function api_account_rate_limit_status($type)
3139 if ($type == "xml") {
3141 'remaining-hits' => '150',
3142 '@attributes' => ["type" => "integer"],
3143 'hourly-limit' => '150',
3144 '@attributes2' => ["type" => "integer"],
3145 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3146 '@attributes3' => ["type" => "datetime"],
3147 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3148 '@attributes4' => ["type" => "integer"],
3152 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3153 'remaining_hits' => '150',
3154 'hourly_limit' => '150',
3155 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3159 return api_format_data('hash', $type, ['hash' => $hash]);
3162 /// @TODO move to top of file or somewhere better
3163 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3166 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3168 * @param string $type Return type (atom, rss, xml, json)
3170 * @return array|string
3172 function api_help_test($type)
3174 if ($type == 'xml') {
3180 return api_format_data('ok', $type, ["ok" => $ok]);
3183 /// @TODO move to top of file or somewhere better
3184 api_register_func('api/help/test', 'api_help_test', false);
3187 * Returns all lists the user subscribes to.
3189 * @param string $type Return type (atom, rss, xml, json)
3191 * @return array|string
3192 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3194 function api_lists_list($type)
3197 /// @TODO $ret is not filled here?
3198 return api_format_data('lists', $type, ["lists_list" => $ret]);
3201 /// @TODO move to top of file or somewhere better
3202 api_register_func('api/lists/list', 'api_lists_list', true);
3203 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3206 * Returns all groups the user owns.
3208 * @param string $type Return type (atom, rss, xml, json)
3210 * @return array|string
3211 * @throws BadRequestException
3212 * @throws ForbiddenException
3213 * @throws ImagickException
3214 * @throws InternalServerErrorException
3215 * @throws UnauthorizedException
3216 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3218 function api_lists_ownerships($type)
3222 if (api_user() === false) {
3223 throw new ForbiddenException();
3227 $user_info = api_get_user($a);
3228 $uid = $user_info['uid'];
3230 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3232 // loop through all groups
3234 foreach ($groups as $group) {
3235 if ($group['visible']) {
3241 'name' => $group['name'],
3242 'id' => intval($group['id']),
3243 'id_str' => (string) $group['id'],
3244 'user' => $user_info,
3248 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3251 /// @TODO move to top of file or somewhere better
3252 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3255 * Returns recent statuses from users in the specified group.
3257 * @param string $type Return type (atom, rss, xml, json)
3259 * @return array|string
3260 * @throws BadRequestException
3261 * @throws ForbiddenException
3262 * @throws ImagickException
3263 * @throws InternalServerErrorException
3264 * @throws UnauthorizedException
3265 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3267 function api_lists_statuses($type)
3271 $user_info = api_get_user($a);
3272 if (api_user() === false || $user_info === false) {
3273 throw new ForbiddenException();
3276 unset($_REQUEST["user_id"]);
3277 unset($_GET["user_id"]);
3279 unset($_REQUEST["screen_name"]);
3280 unset($_GET["screen_name"]);
3282 if (empty($_REQUEST['list_id'])) {
3283 throw new BadRequestException('list_id not specified');
3287 $count = $_REQUEST['count'] ?? 20;
3288 $page = $_REQUEST['page'] ?? 1;
3289 $since_id = $_REQUEST['since_id'] ?? 0;
3290 $max_id = $_REQUEST['max_id'] ?? 0;
3291 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3292 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3294 $start = max(0, ($page - 1) * $count);
3296 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3297 $gids = array_column($groups, 'contact-id');
3298 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3299 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3302 $condition[0] .= " AND `id` <= ?";
3303 $condition[] = $max_id;
3305 if ($exclude_replies > 0) {
3306 $condition[0] .= ' AND `gravity` = ?';
3307 $condition[] = GRAVITY_PARENT;
3309 if ($conversation_id > 0) {
3310 $condition[0] .= " AND `parent` = ?";
3311 $condition[] = $conversation_id;
3314 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3315 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3317 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3319 $data = ['status' => $items];
3324 $data = api_rss_extra($a, $data, $user_info);
3328 return api_format_data("statuses", $type, $data);
3331 /// @TODO move to top of file or somewhere better
3332 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3335 * Returns either the friends of the follower list
3337 * Considers friends and followers lists to be private and won't return
3338 * anything if any user_id parameter is passed.
3340 * @param string $qtype Either "friends" or "followers"
3341 * @return boolean|array
3342 * @throws BadRequestException
3343 * @throws ForbiddenException
3344 * @throws ImagickException
3345 * @throws InternalServerErrorException
3346 * @throws UnauthorizedException
3348 function api_statuses_f($qtype)
3352 if (api_user() === false) {
3353 throw new ForbiddenException();
3357 $count = $_GET['count'] ?? 20;
3358 $page = $_GET['page'] ?? 1;
3360 $start = max(0, ($page - 1) * $count);
3362 $user_info = api_get_user($a);
3364 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3365 /* this is to stop Hotot to load friends multiple times
3366 * I'm not sure if I'm missing return something or
3367 * is a bug in hotot. Workaround, meantime
3371 return array('$users' => $ret);*/
3376 if ($qtype == 'friends') {
3377 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3378 } elseif ($qtype == 'followers') {
3379 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3382 // friends and followers only for self
3383 if ($user_info['self'] == 0) {
3384 $sql_extra = " AND false ";
3387 if ($qtype == 'blocks') {
3388 $sql_filter = 'AND `blocked` AND NOT `pending`';
3389 } elseif ($qtype == 'incoming') {
3390 $sql_filter = 'AND `pending`';
3392 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3410 foreach ($r as $cid) {
3411 $user = api_get_user($a, $cid['nurl']);
3412 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3413 unset($user["uid"]);
3414 unset($user["self"]);
3421 return ['user' => $ret];
3426 * Returns the list of friends of the provided user
3428 * @deprecated By Twitter API in favor of friends/list
3430 * @param string $type Either "json" or "xml"
3431 * @return boolean|string|array
3432 * @throws BadRequestException
3433 * @throws ForbiddenException
3435 function api_statuses_friends($type)
3437 $data = api_statuses_f("friends");
3438 if ($data === false) {
3441 return api_format_data("users", $type, $data);
3445 * Returns the list of followers of the provided user
3447 * @deprecated By Twitter API in favor of friends/list
3449 * @param string $type Either "json" or "xml"
3450 * @return boolean|string|array
3451 * @throws BadRequestException
3452 * @throws ForbiddenException
3454 function api_statuses_followers($type)
3456 $data = api_statuses_f("followers");
3457 if ($data === false) {
3460 return api_format_data("users", $type, $data);
3463 /// @TODO move to top of file or somewhere better
3464 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3465 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3468 * Returns the list of blocked users
3470 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3472 * @param string $type Either "json" or "xml"
3474 * @return boolean|string|array
3475 * @throws BadRequestException
3476 * @throws ForbiddenException
3478 function api_blocks_list($type)
3480 $data = api_statuses_f('blocks');
3481 if ($data === false) {
3484 return api_format_data("users", $type, $data);
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/blocks/list', 'api_blocks_list', true);
3491 * Returns the list of pending users IDs
3493 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3495 * @param string $type Either "json" or "xml"
3497 * @return boolean|string|array
3498 * @throws BadRequestException
3499 * @throws ForbiddenException
3501 function api_friendships_incoming($type)
3503 $data = api_statuses_f('incoming');
3504 if ($data === false) {
3509 foreach ($data['user'] as $user) {
3510 $ids[] = $user['id'];
3513 return api_format_data("ids", $type, ['id' => $ids]);
3516 /// @TODO move to top of file or somewhere better
3517 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3520 * Returns the instance's configuration information.
3522 * @param string $type Return type (atom, rss, xml, json)
3524 * @return array|string
3525 * @throws InternalServerErrorException
3527 function api_statusnet_config($type)
3529 $name = DI::config()->get('config', 'sitename');
3530 $server = DI::baseUrl()->getHostname();
3531 $logo = DI::baseUrl() . '/images/friendica-64.png';
3532 $email = DI::config()->get('config', 'admin_email');
3533 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3534 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3535 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3536 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3537 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3540 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3541 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3542 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3543 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3544 'shorturllength' => '30',
3546 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3547 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3548 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3549 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3554 return api_format_data('config', $type, ['config' => $config]);
3557 /// @TODO move to top of file or somewhere better
3558 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3559 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3563 * @param string $type Return type (atom, rss, xml, json)
3565 * @return array|string
3567 function api_statusnet_version($type)
3570 $fake_statusnet_version = "0.9.7";
3572 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3575 /// @TODO move to top of file or somewhere better
3576 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3577 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3580 * Sends a new direct message.
3582 * @param string $type Return type (atom, rss, xml, json)
3584 * @return array|string
3585 * @throws BadRequestException
3586 * @throws ForbiddenException
3587 * @throws ImagickException
3588 * @throws InternalServerErrorException
3589 * @throws NotFoundException
3590 * @throws UnauthorizedException
3591 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3593 function api_direct_messages_new($type)
3597 if (api_user() === false) {
3598 throw new ForbiddenException();
3601 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3605 $sender = api_get_user($a);
3608 if (!empty($_POST['screen_name'])) {
3610 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3612 DBA::escape($_POST['screen_name'])
3615 if (DBA::isResult($r)) {
3616 // Selecting the id by priority, friendica first
3617 api_best_nickname($r);
3619 $recipient = api_get_user($a, $r[0]['nurl']);
3622 $recipient = api_get_user($a, $_POST['user_id']);
3625 if (empty($recipient)) {
3626 throw new NotFoundException('Recipient not found');
3630 if (!empty($_REQUEST['replyto'])) {
3632 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3634 intval($_REQUEST['replyto'])
3636 $replyto = $r[0]['parent-uri'];
3637 $sub = $r[0]['title'];
3639 if (!empty($_REQUEST['title'])) {
3640 $sub = $_REQUEST['title'];
3642 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3646 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3649 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3650 $ret = api_format_messages($r[0], $recipient, $sender);
3652 $ret = ["error"=>$id];
3655 $data = ['direct_message'=>$ret];
3661 $data = api_rss_extra($a, $data, $sender);
3665 return api_format_data("direct-messages", $type, $data);
3668 /// @TODO move to top of file or somewhere better
3669 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3672 * delete a direct_message from mail table through api
3674 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3675 * @return string|array
3676 * @throws BadRequestException
3677 * @throws ForbiddenException
3678 * @throws ImagickException
3679 * @throws InternalServerErrorException
3680 * @throws UnauthorizedException
3681 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3683 function api_direct_messages_destroy($type)
3687 if (api_user() === false) {
3688 throw new ForbiddenException();
3692 $user_info = api_get_user($a);
3694 $id = $_REQUEST['id'] ?? 0;
3696 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3697 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3698 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3700 $uid = $user_info['uid'];
3701 // error if no id or parenturi specified (for clients posting parent-uri as well)
3702 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3703 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3704 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3707 // BadRequestException if no id specified (for clients using Twitter API)
3709 throw new BadRequestException('Message id not specified');
3712 // add parent-uri to sql command if specified by calling app
3713 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3715 // get data of the specified message id
3717 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3722 // error message if specified id is not in database
3723 if (!DBA::isResult($r)) {
3724 if ($verbose == "true") {
3725 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3726 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3728 /// @todo BadRequestException ok for Twitter API clients?
3729 throw new BadRequestException('message id not in database');
3734 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3739 if ($verbose == "true") {
3742 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3743 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3745 $answer = ['result' => 'error', 'message' => 'unknown error'];
3746 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3749 /// @todo return JSON data like Twitter API not yet implemented
3752 /// @TODO move to top of file or somewhere better
3753 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3758 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3759 * @return string|array
3760 * @throws BadRequestException
3761 * @throws ForbiddenException
3762 * @throws ImagickException
3763 * @throws InternalServerErrorException
3764 * @throws NotFoundException
3765 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3767 function api_friendships_destroy($type)
3771 if ($uid === false) {
3772 throw new ForbiddenException();
3775 $contact_id = $_REQUEST['user_id'] ?? 0;
3777 if (empty($contact_id)) {
3778 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3779 throw new BadRequestException("no user_id specified");
3782 // Get Contact by given id
3783 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3785 if(!DBA::isResult($contact)) {
3786 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3787 throw new NotFoundException("no contact found to given ID");
3790 $url = $contact["url"];
3792 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3793 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3794 Strings::normaliseLink($url), $url];
3795 $contact = DBA::selectFirst('contact', [], $condition);
3797 if (!DBA::isResult($contact)) {
3798 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3799 throw new NotFoundException("Not following Contact");
3802 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3803 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3804 throw new ExpectationFailedException("Not supported");
3807 $dissolve = ($contact['rel'] == Contact::SHARING);
3809 $owner = User::getOwnerDataById($uid);
3811 Contact::terminateFriendship($owner, $contact, $dissolve);
3814 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3815 throw new NotFoundException("Error Processing Request");
3818 // Sharing-only contacts get deleted as there no relationship any more
3820 Contact::remove($contact['id']);
3822 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3825 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3826 unset($contact["uid"]);
3827 unset($contact["self"]);
3829 // Set screen_name since Twidere requests it
3830 $contact["screen_name"] = $contact["nick"];
3832 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3834 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3838 * @param string $type Return type (atom, rss, xml, json)
3839 * @param string $box
3840 * @param string $verbose
3842 * @return array|string
3843 * @throws BadRequestException
3844 * @throws ForbiddenException
3845 * @throws ImagickException
3846 * @throws InternalServerErrorException
3847 * @throws UnauthorizedException
3849 function api_direct_messages_box($type, $box, $verbose)
3852 if (api_user() === false) {
3853 throw new ForbiddenException();
3856 $count = $_GET['count'] ?? 20;
3857 $page = $_REQUEST['page'] ?? 1;
3859 $since_id = $_REQUEST['since_id'] ?? 0;
3860 $max_id = $_REQUEST['max_id'] ?? 0;
3862 $user_id = $_REQUEST['user_id'] ?? '';
3863 $screen_name = $_REQUEST['screen_name'] ?? '';
3866 unset($_REQUEST["user_id"]);
3867 unset($_GET["user_id"]);
3869 unset($_REQUEST["screen_name"]);
3870 unset($_GET["screen_name"]);
3872 $user_info = api_get_user($a);
3873 if ($user_info === false) {
3874 throw new ForbiddenException();
3876 $profile_url = $user_info["url"];
3879 $start = max(0, ($page - 1) * $count);
3884 if ($box=="sentbox") {
3885 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3886 } elseif ($box == "conversation") {
3887 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3888 } elseif ($box == "all") {
3889 $sql_extra = "true";
3890 } elseif ($box == "inbox") {
3891 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3895 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3898 if ($user_id != "") {
3899 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3900 } elseif ($screen_name !="") {
3901 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3905 "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",
3911 if ($verbose == "true" && !DBA::isResult($r)) {
3912 $answer = ['result' => 'error', 'message' => 'no mails available'];
3913 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3917 foreach ($r as $item) {
3918 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3919 $recipient = $user_info;
3920 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3921 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3922 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3923 $sender = $user_info;
3926 if (isset($recipient) && isset($sender)) {
3927 $ret[] = api_format_messages($item, $recipient, $sender);
3932 $data = ['direct_message' => $ret];
3937 $data = api_rss_extra($a, $data, $user_info);
3941 return api_format_data("direct-messages", $type, $data);
3945 * Returns the most recent direct messages sent by the user.
3947 * @param string $type Return type (atom, rss, xml, json)
3949 * @return array|string
3950 * @throws BadRequestException
3951 * @throws ForbiddenException
3952 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3954 function api_direct_messages_sentbox($type)
3956 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3957 return api_direct_messages_box($type, "sentbox", $verbose);
3961 * Returns the most recent direct messages sent to the user.
3963 * @param string $type Return type (atom, rss, xml, json)
3965 * @return array|string
3966 * @throws BadRequestException
3967 * @throws ForbiddenException
3968 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3970 function api_direct_messages_inbox($type)
3972 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3973 return api_direct_messages_box($type, "inbox", $verbose);
3978 * @param string $type Return type (atom, rss, xml, json)
3980 * @return array|string
3981 * @throws BadRequestException
3982 * @throws ForbiddenException
3984 function api_direct_messages_all($type)
3986 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3987 return api_direct_messages_box($type, "all", $verbose);
3992 * @param string $type Return type (atom, rss, xml, json)
3994 * @return array|string
3995 * @throws BadRequestException
3996 * @throws ForbiddenException
3998 function api_direct_messages_conversation($type)
4000 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4001 return api_direct_messages_box($type, "conversation", $verbose);
4004 /// @TODO move to top of file or somewhere better
4005 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4006 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4007 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4008 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4011 * Returns an OAuth Request Token.
4013 * @see https://oauth.net/core/1.0/#auth_step1
4015 function api_oauth_request_token()
4017 $oauth1 = new FKOAuth1();
4019 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4020 } catch (Exception $e) {
4021 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4029 * Returns an OAuth Access Token.
4031 * @return array|string
4032 * @see https://oauth.net/core/1.0/#auth_step3
4034 function api_oauth_access_token()
4036 $oauth1 = new FKOAuth1();
4038 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4039 } catch (Exception $e) {
4040 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4047 /// @TODO move to top of file or somewhere better
4048 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4049 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4053 * delete a complete photoalbum with all containing photos from database through api
4055 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4056 * @return string|array
4057 * @throws BadRequestException
4058 * @throws ForbiddenException
4059 * @throws InternalServerErrorException
4061 function api_fr_photoalbum_delete($type)
4063 if (api_user() === false) {
4064 throw new ForbiddenException();
4067 $album = $_REQUEST['album'] ?? '';
4069 // we do not allow calls without album string
4071 throw new BadRequestException("no albumname specified");
4073 // check if album is existing
4075 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4076 if (!DBA::isResult($photos)) {
4077 throw new BadRequestException("album not available");
4080 $resourceIds = array_column($photos, 'resource-id');
4082 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4083 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4084 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4085 Item::deleteForUser($condition, api_user());
4087 // now let's delete all photos from the album
4088 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4090 // return success of deletion or error message
4092 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4093 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4095 throw new InternalServerErrorException("unknown error - deleting from database failed");
4100 * update the name of the album for all photos of an album
4102 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4103 * @return string|array
4104 * @throws BadRequestException
4105 * @throws ForbiddenException
4106 * @throws InternalServerErrorException
4108 function api_fr_photoalbum_update($type)
4110 if (api_user() === false) {
4111 throw new ForbiddenException();
4114 $album = $_REQUEST['album'] ?? '';
4115 $album_new = $_REQUEST['album_new'] ?? '';
4117 // we do not allow calls without album string
4119 throw new BadRequestException("no albumname specified");
4121 if ($album_new == "") {
4122 throw new BadRequestException("no new albumname specified");
4124 // check if album is existing
4125 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4126 throw new BadRequestException("album not available");
4128 // now let's update all photos to the albumname
4129 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4131 // return success of updating or error message
4133 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4134 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4136 throw new InternalServerErrorException("unknown error - updating in database failed");
4142 * list all photos of the authenticated user
4144 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4145 * @return string|array
4146 * @throws ForbiddenException
4147 * @throws InternalServerErrorException
4149 function api_fr_photos_list($type)
4151 if (api_user() === false) {
4152 throw new ForbiddenException();
4155 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4156 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4157 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4158 intval(local_user())
4161 'image/jpeg' => 'jpg',
4162 'image/png' => 'png',
4163 'image/gif' => 'gif'
4165 $data = ['photo'=>[]];
4166 if (DBA::isResult($r)) {
4167 foreach ($r as $rr) {
4169 $photo['id'] = $rr['resource-id'];
4170 $photo['album'] = $rr['album'];
4171 $photo['filename'] = $rr['filename'];
4172 $photo['type'] = $rr['type'];
4173 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4174 $photo['created'] = $rr['created'];
4175 $photo['edited'] = $rr['edited'];
4176 $photo['desc'] = $rr['desc'];
4178 if ($type == "xml") {
4179 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4181 $photo['thumb'] = $thumb;
4182 $data['photo'][] = $photo;
4186 return api_format_data("photos", $type, $data);
4190 * upload a new photo or change an existing photo
4192 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4193 * @return string|array
4194 * @throws BadRequestException
4195 * @throws ForbiddenException
4196 * @throws ImagickException
4197 * @throws InternalServerErrorException
4198 * @throws NotFoundException
4200 function api_fr_photo_create_update($type)
4202 if (api_user() === false) {
4203 throw new ForbiddenException();
4206 $photo_id = $_REQUEST['photo_id'] ?? null;
4207 $desc = $_REQUEST['desc'] ?? null;
4208 $album = $_REQUEST['album'] ?? null;
4209 $album_new = $_REQUEST['album_new'] ?? null;
4210 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4211 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4212 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4213 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4214 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4216 // do several checks on input parameters
4217 // we do not allow calls without album string
4218 if ($album == null) {
4219 throw new BadRequestException("no albumname specified");
4221 // if photo_id == null --> we are uploading a new photo
4222 if ($photo_id == null) {
4225 // error if no media posted in create-mode
4226 if (empty($_FILES['media'])) {
4228 throw new BadRequestException("no media data submitted");
4231 // album_new will be ignored in create-mode
4236 // check if photo is existing in databasei
4237 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4238 throw new BadRequestException("photo not available");
4242 // checks on acl strings provided by clients
4243 $acl_input_error = false;
4244 $acl_input_error |= check_acl_input($allow_cid);
4245 $acl_input_error |= check_acl_input($deny_cid);
4246 $acl_input_error |= check_acl_input($allow_gid);
4247 $acl_input_error |= check_acl_input($deny_gid);
4248 if ($acl_input_error) {
4249 throw new BadRequestException("acl data invalid");
4251 // now let's upload the new media in create-mode
4252 if ($mode == "create") {
4253 $media = $_FILES['media'];
4254 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4256 // return success of updating or error message
4257 if (!is_null($data)) {
4258 return api_format_data("photo_create", $type, $data);
4260 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4264 // now let's do the changes in update-mode
4265 if ($mode == "update") {
4266 $updated_fields = [];
4268 if (!is_null($desc)) {
4269 $updated_fields['desc'] = $desc;
4272 if (!is_null($album_new)) {
4273 $updated_fields['album'] = $album_new;
4276 if (!is_null($allow_cid)) {
4277 $allow_cid = trim($allow_cid);
4278 $updated_fields['allow_cid'] = $allow_cid;
4281 if (!is_null($deny_cid)) {
4282 $deny_cid = trim($deny_cid);
4283 $updated_fields['deny_cid'] = $deny_cid;
4286 if (!is_null($allow_gid)) {
4287 $allow_gid = trim($allow_gid);
4288 $updated_fields['allow_gid'] = $allow_gid;
4291 if (!is_null($deny_gid)) {
4292 $deny_gid = trim($deny_gid);
4293 $updated_fields['deny_gid'] = $deny_gid;
4297 if (count($updated_fields) > 0) {
4298 $nothingtodo = false;
4299 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4301 $nothingtodo = true;
4304 if (!empty($_FILES['media'])) {
4305 $nothingtodo = false;
4306 $media = $_FILES['media'];
4307 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4308 if (!is_null($data)) {
4309 return api_format_data("photo_update", $type, $data);
4313 // return success of updating or error message
4315 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4316 return api_format_data("photo_update", $type, ['$result' => $answer]);
4319 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4320 return api_format_data("photo_update", $type, ['$result' => $answer]);
4322 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4325 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4329 * delete a single photo from the database through api
4331 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4332 * @return string|array
4333 * @throws BadRequestException
4334 * @throws ForbiddenException
4335 * @throws InternalServerErrorException
4337 function api_fr_photo_delete($type)
4339 if (api_user() === false) {
4340 throw new ForbiddenException();
4344 $photo_id = $_REQUEST['photo_id'] ?? null;
4346 // do several checks on input parameters
4347 // we do not allow calls without photo id
4348 if ($photo_id == null) {
4349 throw new BadRequestException("no photo_id specified");
4352 // check if photo is existing in database
4353 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4354 throw new BadRequestException("photo not available");
4357 // now we can perform on the deletion of the photo
4358 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4360 // return success of deletion or error message
4362 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4363 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4364 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4365 Item::deleteForUser($condition, api_user());
4367 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4368 return api_format_data("photo_delete", $type, ['$result' => $result]);
4370 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4376 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4378 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4379 * @return string|array
4380 * @throws BadRequestException
4381 * @throws ForbiddenException
4382 * @throws InternalServerErrorException
4383 * @throws NotFoundException
4385 function api_fr_photo_detail($type)
4387 if (api_user() === false) {
4388 throw new ForbiddenException();
4390 if (empty($_REQUEST['photo_id'])) {
4391 throw new BadRequestException("No photo id.");
4394 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4395 $photo_id = $_REQUEST['photo_id'];
4397 // prepare json/xml output with data from database for the requested photo
4398 $data = prepare_photo_data($type, $scale, $photo_id);
4400 return api_format_data("photo_detail", $type, $data);
4405 * updates the profile image for the user (either a specified profile or the default profile)
4407 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4409 * @return string|array
4410 * @throws BadRequestException
4411 * @throws ForbiddenException
4412 * @throws ImagickException
4413 * @throws InternalServerErrorException
4414 * @throws NotFoundException
4415 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4417 function api_account_update_profile_image($type)
4419 if (api_user() === false) {
4420 throw new ForbiddenException();
4423 $profile_id = $_REQUEST['profile_id'] ?? 0;
4425 // error if image data is missing
4426 if (empty($_FILES['image'])) {
4427 throw new BadRequestException("no media data submitted");
4430 // check if specified profile id is valid
4431 if ($profile_id != 0) {
4432 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4433 // error message if specified profile id is not in database
4434 if (!DBA::isResult($profile)) {
4435 throw new BadRequestException("profile_id not available");
4437 $is_default_profile = $profile['is-default'];
4439 $is_default_profile = 1;
4442 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4444 if (!empty($_FILES['image'])) {
4445 $media = $_FILES['image'];
4446 } elseif (!empty($_FILES['media'])) {
4447 $media = $_FILES['media'];
4449 // save new profile image
4450 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4453 if (is_array($media['type'])) {
4454 $filetype = $media['type'][0];
4456 $filetype = $media['type'];
4458 if ($filetype == "image/jpeg") {
4460 } elseif ($filetype == "image/png") {
4463 throw new InternalServerErrorException('Unsupported filetype');
4466 // change specified profile or all profiles to the new resource-id
4467 if ($is_default_profile) {
4468 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4469 Photo::update(['profile' => false], $condition);
4471 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4472 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4473 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4476 Contact::updateSelfFromUserID(api_user(), true);
4478 // Update global directory in background
4479 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4480 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4481 Worker::add(PRIORITY_LOW, "Directory", $url);
4484 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4486 // output for client
4488 return api_account_verify_credentials($type);
4490 // SaveMediaToDatabase failed for some reason
4491 throw new InternalServerErrorException("image upload failed");
4495 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4496 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4497 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4498 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4499 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4500 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4501 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4502 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4503 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4506 * Update user profile
4508 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4510 * @return array|string
4511 * @throws BadRequestException
4512 * @throws ForbiddenException
4513 * @throws ImagickException
4514 * @throws InternalServerErrorException
4515 * @throws UnauthorizedException
4517 function api_account_update_profile($type)
4519 $local_user = api_user();
4520 $api_user = api_get_user(DI::app());
4522 if (!empty($_POST['name'])) {
4523 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4524 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4525 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4526 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4529 if (isset($_POST['description'])) {
4530 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4531 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4532 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4535 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4536 // Update global directory in background
4537 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4538 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4541 return api_account_verify_credentials($type);
4544 /// @TODO move to top of file or somewhere better
4545 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4549 * @param string $acl_string
4553 function check_acl_input($acl_string)
4555 if (empty($acl_string)) {
4559 $contact_not_found = false;
4561 // split <x><y><z> into array of cid's
4562 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4564 // check for each cid if it is available on server
4565 $cid_array = $array[0];
4566 foreach ($cid_array as $cid) {
4567 $cid = str_replace("<", "", $cid);
4568 $cid = str_replace(">", "", $cid);
4569 $condition = ['id' => $cid, 'uid' => api_user()];
4570 $contact_not_found |= !DBA::exists('contact', $condition);
4572 return $contact_not_found;
4576 * @param string $mediatype
4577 * @param array $media
4578 * @param string $type
4579 * @param string $album
4580 * @param string $allow_cid
4581 * @param string $deny_cid
4582 * @param string $allow_gid
4583 * @param string $deny_gid
4584 * @param string $desc
4585 * @param integer $profile
4586 * @param boolean $visibility
4587 * @param string $photo_id
4589 * @throws BadRequestException
4590 * @throws ForbiddenException
4591 * @throws ImagickException
4592 * @throws InternalServerErrorException
4593 * @throws NotFoundException
4594 * @throws UnauthorizedException
4596 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)
4604 if (is_array($media)) {
4605 if (is_array($media['tmp_name'])) {
4606 $src = $media['tmp_name'][0];
4608 $src = $media['tmp_name'];
4610 if (is_array($media['name'])) {
4611 $filename = basename($media['name'][0]);
4613 $filename = basename($media['name']);
4615 if (is_array($media['size'])) {
4616 $filesize = intval($media['size'][0]);
4618 $filesize = intval($media['size']);
4620 if (is_array($media['type'])) {
4621 $filetype = $media['type'][0];
4623 $filetype = $media['type'];
4627 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4630 "File upload src: " . $src . " - filename: " . $filename .
4631 " - size: " . $filesize . " - type: " . $filetype,
4635 // check if there was a php upload error
4636 if ($filesize == 0 && $media['error'] == 1) {
4637 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4639 // check against max upload size within Friendica instance
4640 $maximagesize = DI::config()->get('system', 'maximagesize');
4641 if ($maximagesize && ($filesize > $maximagesize)) {
4642 $formattedBytes = Strings::formatBytes($maximagesize);
4643 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4646 // create Photo instance with the data of the image
4647 $imagedata = @file_get_contents($src);
4648 $Image = new Image($imagedata, $filetype);
4649 if (!$Image->isValid()) {
4650 throw new InternalServerErrorException("unable to process image data");
4653 // check orientation of image
4654 $Image->orient($src);
4657 // check max length of images on server
4658 $max_length = DI::config()->get('system', 'max_image_length');
4660 $max_length = MAX_IMAGE_LENGTH;
4662 if ($max_length > 0) {
4663 $Image->scaleDown($max_length);
4664 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4666 $width = $Image->getWidth();
4667 $height = $Image->getHeight();
4669 // create a new resource-id if not already provided
4670 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4672 if ($mediatype == "photo") {
4673 // upload normal image (scales 0, 1, 2)
4674 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4676 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4678 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4680 if ($width > 640 || $height > 640) {
4681 $Image->scaleDown(640);
4682 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4684 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4688 if ($width > 320 || $height > 320) {
4689 $Image->scaleDown(320);
4690 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4692 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4695 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4696 } elseif ($mediatype == "profileimage") {
4697 // upload profile image (scales 4, 5, 6)
4698 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4700 if ($width > 300 || $height > 300) {
4701 $Image->scaleDown(300);
4702 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4704 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4708 if ($width > 80 || $height > 80) {
4709 $Image->scaleDown(80);
4710 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4712 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4716 if ($width > 48 || $height > 48) {
4717 $Image->scaleDown(48);
4718 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4720 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4723 $Image->__destruct();
4724 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4728 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4729 if ($photo_id == null && $mediatype == "photo") {
4730 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4732 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4733 return prepare_photo_data($type, false, $resource_id);
4735 throw new InternalServerErrorException("image upload failed");
4741 * @param string $hash
4742 * @param string $allow_cid
4743 * @param string $deny_cid
4744 * @param string $allow_gid
4745 * @param string $deny_gid
4746 * @param string $filetype
4747 * @param boolean $visibility
4748 * @throws InternalServerErrorException
4750 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4752 // get data about the api authenticated user
4753 $uri = Item::newURI(intval(api_user()));
4754 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4757 $arr['guid'] = System::createUUID();
4758 $arr['uid'] = intval(api_user());
4760 $arr['type'] = 'photo';
4762 $arr['resource-id'] = $hash;
4763 $arr['contact-id'] = $owner_record['id'];
4764 $arr['owner-name'] = $owner_record['name'];
4765 $arr['owner-link'] = $owner_record['url'];
4766 $arr['owner-avatar'] = $owner_record['thumb'];
4767 $arr['author-name'] = $owner_record['name'];
4768 $arr['author-link'] = $owner_record['url'];
4769 $arr['author-avatar'] = $owner_record['thumb'];
4771 $arr['allow_cid'] = $allow_cid;
4772 $arr['allow_gid'] = $allow_gid;
4773 $arr['deny_cid'] = $deny_cid;
4774 $arr['deny_gid'] = $deny_gid;
4775 $arr['visible'] = $visibility;
4779 'image/jpeg' => 'jpg',
4780 'image/png' => 'png',
4781 'image/gif' => 'gif'
4784 // adds link to the thumbnail scale photo
4785 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4786 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4789 // do the magic for storing the item in the database and trigger the federation to other contacts
4795 * @param string $type
4797 * @param string $photo_id
4800 * @throws BadRequestException
4801 * @throws ForbiddenException
4802 * @throws ImagickException
4803 * @throws InternalServerErrorException
4804 * @throws NotFoundException
4805 * @throws UnauthorizedException
4807 function prepare_photo_data($type, $scale, $photo_id)
4810 $user_info = api_get_user($a);
4812 if ($user_info === false) {
4813 throw new ForbiddenException();
4816 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4817 $data_sql = ($scale === false ? "" : "data, ");
4819 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4820 // clients needs to convert this in their way for further processing
4822 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4823 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4824 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4825 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4826 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4827 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4829 intval(local_user()),
4830 DBA::escape($photo_id),
4835 'image/jpeg' => 'jpg',
4836 'image/png' => 'png',
4837 'image/gif' => 'gif'
4840 // prepare output data for photo
4841 if (DBA::isResult($r)) {
4842 $data = ['photo' => $r[0]];
4843 $data['photo']['id'] = $data['photo']['resource-id'];
4844 if ($scale !== false) {
4845 $data['photo']['data'] = base64_encode($data['photo']['data']);
4847 unset($data['photo']['datasize']); //needed only with scale param
4849 if ($type == "xml") {
4850 $data['photo']['links'] = [];
4851 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4852 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4854 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4857 $data['photo']['link'] = [];
4858 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4860 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4861 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4865 unset($data['photo']['resource-id']);
4866 unset($data['photo']['minscale']);
4867 unset($data['photo']['maxscale']);
4869 throw new NotFoundException();
4872 // retrieve item element for getting activities (like, dislike etc.) related to photo
4873 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4874 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4875 if (!DBA::isResult($item)) {
4876 throw new NotFoundException('Photo-related item not found.');
4879 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4881 // retrieve comments on photo
4882 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4883 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4885 $statuses = Post::selectForUser(api_user(), [], $condition);
4887 // prepare output of comments
4888 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4890 if ($type == "xml") {
4892 foreach ($commentData as $comment) {
4893 $comments[$k++ . ":comment"] = $comment;
4896 foreach ($commentData as $comment) {
4897 $comments[] = $comment;
4900 $data['photo']['friendica_comments'] = $comments;
4902 // include info if rights on photo and rights on item are mismatching
4903 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4904 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4905 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4906 $data['photo']['deny_gid'] != $item['deny_gid'];
4907 $data['photo']['rights_mismatch'] = $rights_mismatch;
4914 * Similar as /mod/redir.php
4915 * redirect to 'url' after dfrn auth
4917 * Why this when there is mod/redir.php already?
4918 * This use api_user() and api_login()
4921 * c_url: url of remote contact to auth to
4922 * url: string, url to redirect after auth
4924 function api_friendica_remoteauth()
4926 $url = $_GET['url'] ?? '';
4927 $c_url = $_GET['c_url'] ?? '';
4929 if ($url === '' || $c_url === '') {
4930 throw new BadRequestException("Wrong parameters.");
4933 $c_url = Strings::normaliseLink($c_url);
4937 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4938 if (!DBA::isResult($contact)) {
4939 throw new BadRequestException("Unknown contact");
4942 $cid = $contact['id'];
4944 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
4946 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
4947 System::externalRedirect($url ?: $c_url);
4950 if ($contact['duplex'] && $contact['issued-id']) {
4951 $orig_id = $contact['issued-id'];
4952 $dfrn_id = '1:' . $orig_id;
4954 if ($contact['duplex'] && $contact['dfrn-id']) {
4955 $orig_id = $contact['dfrn-id'];
4956 $dfrn_id = '0:' . $orig_id;
4959 $sec = Strings::getRandomHex();
4961 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4962 'sec' => $sec, 'expire' => time() + 45];
4963 DBA::insert('profile_check', $fields);
4965 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4966 $dest = ($url ? '&destination_url=' . $url : '');
4968 System::externalRedirect(
4969 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4970 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4971 . '&type=profile&sec=' . $sec . $dest
4974 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4977 * Return an item with announcer data if it had been announced
4979 * @param array $item Item array
4980 * @return array Item array with announce data
4982 function api_get_announce($item)
4984 // Quit if the item already has got a different owner and author
4985 if ($item['owner-id'] != $item['author-id']) {
4989 // Don't change original or Diaspora posts
4990 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4994 // Quit if we do now the original author and it had been a post from a native network
4995 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4999 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5000 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5001 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5002 if (!DBA::isResult($announce)) {
5006 return array_merge($item, $announce);
5010 * Return the item shared, if the item contains only the [share] tag
5012 * @param array $item Sharer item
5013 * @return array|false Shared item or false if not a reshare
5014 * @throws ImagickException
5015 * @throws InternalServerErrorException
5017 function api_share_as_retweet(&$item)
5019 $body = trim($item["body"]);
5021 if (Diaspora::isReshare($body, false) === false) {
5022 if ($item['author-id'] == $item['owner-id']) {
5025 // Reshares from OStatus, ActivityPub and Twitter
5026 $reshared_item = $item;
5027 $reshared_item['owner-id'] = $reshared_item['author-id'];
5028 $reshared_item['owner-link'] = $reshared_item['author-link'];
5029 $reshared_item['owner-name'] = $reshared_item['author-name'];
5030 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5031 return $reshared_item;
5035 $reshared = Item::getShareArray($item);
5036 if (empty($reshared)) {
5040 $reshared_item = $item;
5042 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5046 if (!empty($reshared['comment'])) {
5047 $item['body'] = $reshared['comment'];
5050 $reshared_item["share-pre-body"] = $reshared['comment'];
5051 $reshared_item["body"] = $reshared['shared'];
5052 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5053 $reshared_item["author-name"] = $reshared['author'];
5054 $reshared_item["author-link"] = $reshared['profile'];
5055 $reshared_item["author-avatar"] = $reshared['avatar'];
5056 $reshared_item["plink"] = $reshared['link'] ?? '';
5057 $reshared_item["created"] = $reshared['posted'];
5058 $reshared_item["edited"] = $reshared['posted'];
5060 // Try to fetch the original item
5061 if (!empty($reshared['guid'])) {
5062 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5063 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5064 $condition = ['id' => $original_id];
5069 if (!empty($condition)) {
5070 $original_item = Post::selectFirst([], $condition);
5071 if (DBA::isResult($original_item)) {
5072 $reshared_item = array_merge($reshared_item, $original_item);
5076 return $reshared_item;
5081 * @param array $item
5086 function api_in_reply_to($item)
5090 $in_reply_to['status_id'] = null;
5091 $in_reply_to['user_id'] = null;
5092 $in_reply_to['status_id_str'] = null;
5093 $in_reply_to['user_id_str'] = null;
5094 $in_reply_to['screen_name'] = null;
5096 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5097 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5098 if (DBA::isResult($parent)) {
5099 $in_reply_to['status_id'] = intval($parent['id']);
5101 $in_reply_to['status_id'] = intval($item['parent']);
5104 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5106 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5107 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5109 if (DBA::isResult($parent)) {
5110 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5111 $in_reply_to['user_id'] = intval($parent['author-id']);
5112 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5115 // There seems to be situation, where both fields are identical:
5116 // https://github.com/friendica/friendica/issues/1010
5117 // This is a bugfix for that.
5118 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5119 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']]);
5120 $in_reply_to['status_id'] = null;
5121 $in_reply_to['user_id'] = null;
5122 $in_reply_to['status_id_str'] = null;
5123 $in_reply_to['user_id_str'] = null;
5124 $in_reply_to['screen_name'] = null;
5128 return $in_reply_to;
5133 * @param string $text
5136 * @throws InternalServerErrorException
5138 function api_clean_plain_items($text)
5140 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5142 $text = BBCode::cleanPictureLinks($text);
5143 $URLSearchString = "^\[\]";
5145 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5147 if ($include_entities == "true") {
5148 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5151 // Simplify "attachment" element
5152 $text = BBCode::removeAttachment($text);
5159 * @param array $contacts
5163 function api_best_nickname(&$contacts)
5167 if (count($contacts) == 0) {
5171 foreach ($contacts as $contact) {
5172 if ($contact["network"] == "") {
5173 $contact["network"] = "dfrn";
5174 $best_contact = [$contact];
5178 if (sizeof($best_contact) == 0) {
5179 foreach ($contacts as $contact) {
5180 if ($contact["network"] == "dfrn") {
5181 $best_contact = [$contact];
5186 if (sizeof($best_contact) == 0) {
5187 foreach ($contacts as $contact) {
5188 if ($contact["network"] == "dspr") {
5189 $best_contact = [$contact];
5194 if (sizeof($best_contact) == 0) {
5195 foreach ($contacts as $contact) {
5196 if ($contact["network"] == "stat") {
5197 $best_contact = [$contact];
5202 if (sizeof($best_contact) == 0) {
5203 foreach ($contacts as $contact) {
5204 if ($contact["network"] == "pump") {
5205 $best_contact = [$contact];
5210 if (sizeof($best_contact) == 0) {
5211 foreach ($contacts as $contact) {
5212 if ($contact["network"] == "twit") {
5213 $best_contact = [$contact];
5218 if (sizeof($best_contact) == 1) {
5219 $contacts = $best_contact;
5221 $contacts = [$contacts[0]];
5226 * Return all or a specified group of the user with the containing contacts.
5228 * @param string $type Return type (atom, rss, xml, json)
5230 * @return array|string
5231 * @throws BadRequestException
5232 * @throws ForbiddenException
5233 * @throws ImagickException
5234 * @throws InternalServerErrorException
5235 * @throws UnauthorizedException
5237 function api_friendica_group_show($type)
5241 if (api_user() === false) {
5242 throw new ForbiddenException();
5246 $user_info = api_get_user($a);
5247 $gid = $_REQUEST['gid'] ?? 0;
5248 $uid = $user_info['uid'];
5250 // get data of the specified group id or all groups if not specified
5253 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5257 // error message if specified gid is not in database
5258 if (!DBA::isResult($r)) {
5259 throw new BadRequestException("gid not available");
5263 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5268 // loop through all groups and retrieve all members for adding data in the user array
5270 foreach ($r as $rr) {
5271 $members = Contact\Group::getById($rr['id']);
5274 if ($type == "xml") {
5275 $user_element = "users";
5277 foreach ($members as $member) {
5278 $user = api_get_user($a, $member['nurl']);
5279 $users[$k++.":user"] = $user;
5282 $user_element = "user";
5283 foreach ($members as $member) {
5284 $user = api_get_user($a, $member['nurl']);
5288 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5290 return api_format_data("groups", $type, ['group' => $grps]);
5292 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5296 * Delete the specified group of the user.
5298 * @param string $type Return type (atom, rss, xml, json)
5300 * @return array|string
5301 * @throws BadRequestException
5302 * @throws ForbiddenException
5303 * @throws ImagickException
5304 * @throws InternalServerErrorException
5305 * @throws UnauthorizedException
5307 function api_friendica_group_delete($type)
5311 if (api_user() === false) {
5312 throw new ForbiddenException();
5316 $user_info = api_get_user($a);
5317 $gid = $_REQUEST['gid'] ?? 0;
5318 $name = $_REQUEST['name'] ?? '';
5319 $uid = $user_info['uid'];
5321 // error if no gid specified
5322 if ($gid == 0 || $name == "") {
5323 throw new BadRequestException('gid or name not specified');
5326 // get data of the specified group id
5328 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5332 // error message if specified gid is not in database
5333 if (!DBA::isResult($r)) {
5334 throw new BadRequestException('gid not available');
5337 // get data of the specified group id and group name
5339 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5344 // error message if specified gid is not in database
5345 if (!DBA::isResult($rname)) {
5346 throw new BadRequestException('wrong group name');
5350 $ret = Group::removeByName($uid, $name);
5353 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5354 return api_format_data("group_delete", $type, ['result' => $success]);
5356 throw new BadRequestException('other API error');
5359 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
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
5372 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5374 function api_lists_destroy($type)
5378 if (api_user() === false) {
5379 throw new ForbiddenException();
5383 $user_info = api_get_user($a);
5384 $gid = $_REQUEST['list_id'] ?? 0;
5385 $uid = $user_info['uid'];
5387 // error if no gid specified
5389 throw new BadRequestException('gid not specified');
5392 // get data of the specified group id
5393 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5394 // error message if specified gid is not in database
5396 throw new BadRequestException('gid not available');
5399 if (Group::remove($gid)) {
5401 'name' => $group['name'],
5402 'id' => intval($gid),
5403 'id_str' => (string) $gid,
5404 'user' => $user_info
5407 return api_format_data("lists", $type, ['lists' => $list]);
5410 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5413 * Add a new group to the database.
5415 * @param string $name Group name
5416 * @param int $uid User ID
5417 * @param array $users List of users to add to the group
5420 * @throws BadRequestException
5422 function group_create($name, $uid, $users = [])
5424 // error if no name specified
5426 throw new BadRequestException('group name not specified');
5429 // get data of the specified group name
5431 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5435 // error message if specified group name already exists
5436 if (DBA::isResult($rname)) {
5437 throw new BadRequestException('group name already exists');
5440 // check if specified group name is a deleted group
5442 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5446 // error message if specified group name already exists
5447 if (DBA::isResult($rname)) {
5448 $reactivate_group = true;
5452 $ret = Group::create($uid, $name);
5454 $gid = Group::getIdByName($uid, $name);
5456 throw new BadRequestException('other API error');
5460 $erroraddinguser = false;
5462 foreach ($users as $user) {
5463 $cid = $user['cid'];
5464 // check if user really exists as contact
5466 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5470 if (count($contact)) {
5471 Group::addMember($gid, $cid);
5473 $erroraddinguser = true;
5474 $errorusers[] = $cid;
5478 // return success message incl. missing users in array
5479 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5481 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5485 * Create the specified group with the posted array of contacts.
5487 * @param string $type Return type (atom, rss, xml, json)
5489 * @return array|string
5490 * @throws BadRequestException
5491 * @throws ForbiddenException
5492 * @throws ImagickException
5493 * @throws InternalServerErrorException
5494 * @throws UnauthorizedException
5496 function api_friendica_group_create($type)
5500 if (api_user() === false) {
5501 throw new ForbiddenException();
5505 $user_info = api_get_user($a);
5506 $name = $_REQUEST['name'] ?? '';
5507 $uid = $user_info['uid'];
5508 $json = json_decode($_POST['json'], true);
5509 $users = $json['user'];
5511 $success = group_create($name, $uid, $users);
5513 return api_format_data("group_create", $type, ['result' => $success]);
5515 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5518 * Create a new group.
5520 * @param string $type Return type (atom, rss, xml, json)
5522 * @return array|string
5523 * @throws BadRequestException
5524 * @throws ForbiddenException
5525 * @throws ImagickException
5526 * @throws InternalServerErrorException
5527 * @throws UnauthorizedException
5528 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5530 function api_lists_create($type)
5534 if (api_user() === false) {
5535 throw new ForbiddenException();
5539 $user_info = api_get_user($a);
5540 $name = $_REQUEST['name'] ?? '';
5541 $uid = $user_info['uid'];
5543 $success = group_create($name, $uid);
5544 if ($success['success']) {
5546 'name' => $success['name'],
5547 'id' => intval($success['gid']),
5548 'id_str' => (string) $success['gid'],
5549 'user' => $user_info
5552 return api_format_data("lists", $type, ['lists'=>$grp]);
5555 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5558 * Update the specified group with the posted array of contacts.
5560 * @param string $type Return type (atom, rss, xml, json)
5562 * @return array|string
5563 * @throws BadRequestException
5564 * @throws ForbiddenException
5565 * @throws ImagickException
5566 * @throws InternalServerErrorException
5567 * @throws UnauthorizedException
5569 function api_friendica_group_update($type)
5573 if (api_user() === false) {
5574 throw new ForbiddenException();
5578 $user_info = api_get_user($a);
5579 $uid = $user_info['uid'];
5580 $gid = $_REQUEST['gid'] ?? 0;
5581 $name = $_REQUEST['name'] ?? '';
5582 $json = json_decode($_POST['json'], true);
5583 $users = $json['user'];
5585 // error if no name specified
5587 throw new BadRequestException('group name not specified');
5590 // error if no gid specified
5592 throw new BadRequestException('gid not specified');
5596 $members = Contact\Group::getById($gid);
5597 foreach ($members as $member) {
5598 $cid = $member['id'];
5599 foreach ($users as $user) {
5600 $found = ($user['cid'] == $cid ? true : false);
5602 if (!isset($found) || !$found) {
5603 Group::removeMemberByName($uid, $name, $cid);
5608 $erroraddinguser = false;
5610 foreach ($users as $user) {
5611 $cid = $user['cid'];
5612 // check if user really exists as contact
5614 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5619 if (count($contact)) {
5620 Group::addMember($gid, $cid);
5622 $erroraddinguser = true;
5623 $errorusers[] = $cid;
5627 // return success message incl. missing users in array
5628 $status = ($erroraddinguser ? "missing user" : "ok");
5629 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5630 return api_format_data("group_update", $type, ['result' => $success]);
5633 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5636 * Update information about a group.
5638 * @param string $type Return type (atom, rss, xml, json)
5640 * @return array|string
5641 * @throws BadRequestException
5642 * @throws ForbiddenException
5643 * @throws ImagickException
5644 * @throws InternalServerErrorException
5645 * @throws UnauthorizedException
5646 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5648 function api_lists_update($type)
5652 if (api_user() === false) {
5653 throw new ForbiddenException();
5657 $user_info = api_get_user($a);
5658 $gid = $_REQUEST['list_id'] ?? 0;
5659 $name = $_REQUEST['name'] ?? '';
5660 $uid = $user_info['uid'];
5662 // error if no gid specified
5664 throw new BadRequestException('gid not specified');
5667 // get data of the specified group id
5668 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5669 // error message if specified gid is not in database
5671 throw new BadRequestException('gid not available');
5674 if (Group::update($gid, $name)) {
5677 'id' => intval($gid),
5678 'id_str' => (string) $gid,
5679 'user' => $user_info
5682 return api_format_data("lists", $type, ['lists' => $list]);
5686 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5690 * @param string $type Return type (atom, rss, xml, json)
5692 * @return array|string
5693 * @throws BadRequestException
5694 * @throws ForbiddenException
5695 * @throws ImagickException
5696 * @throws InternalServerErrorException
5698 function api_friendica_activity($type)
5702 if (api_user() === false) {
5703 throw new ForbiddenException();
5705 $verb = strtolower($a->argv[3]);
5706 $verb = preg_replace("|\..*$|", "", $verb);
5708 $id = $_REQUEST['id'] ?? 0;
5710 $res = Item::performActivity($id, $verb, api_user());
5713 if ($type == "xml") {
5718 return api_format_data('ok', $type, ['ok' => $ok]);
5720 throw new BadRequestException('Error adding activity');
5724 /// @TODO move to top of file or somewhere better
5725 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5726 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5727 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5728 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5729 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5730 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5731 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5732 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5733 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5734 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5737 * Returns notifications
5739 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5741 * @return string|array
5742 * @throws ForbiddenException
5743 * @throws BadRequestException
5746 function api_friendica_notification($type)
5750 if (api_user() === false) {
5751 throw new ForbiddenException();
5754 throw new BadRequestException("Invalid argument count");
5757 $notifications = DI::notification()->getApiList(local_user());
5759 if ($type == "xml") {
5761 if (!empty($notifications)) {
5762 foreach ($notifications as $notification) {
5763 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5767 $result = $xmlnotes;
5768 } elseif (count($notifications) > 0) {
5769 $result = $notifications->getArrayCopy();
5774 return api_format_data("notes", $type, ['note' => $result]);
5778 * Set notification as seen and returns associated item (if possible)
5780 * POST request with 'id' param as notification id
5782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5783 * @return string|array
5784 * @throws BadRequestException
5785 * @throws ForbiddenException
5786 * @throws ImagickException
5787 * @throws InternalServerErrorException
5788 * @throws UnauthorizedException
5790 function api_friendica_notification_seen($type)
5793 $user_info = api_get_user($a);
5795 if (api_user() === false || $user_info === false) {
5796 throw new ForbiddenException();
5798 if ($a->argc !== 4) {
5799 throw new BadRequestException("Invalid argument count");
5802 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5805 $notify = DI::notify()->getByID($id, api_user());
5806 DI::notify()->setSeen(true, $notify);
5808 if ($notify->otype === Notification\ObjectType::ITEM) {
5809 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5810 if (DBA::isResult($item)) {
5811 // we found the item, return it to the user
5812 $ret = api_format_items([$item], $user_info, false, $type);
5813 $data = ['status' => $ret];
5814 return api_format_data("status", $type, $data);
5816 // the item can't be found, but we set the notification as seen, so we count this as a success
5818 return api_format_data('result', $type, ['result' => "success"]);
5819 } catch (NotFoundException $e) {
5820 throw new BadRequestException('Invalid argument', $e);
5821 } catch (Exception $e) {
5822 throw new InternalServerErrorException('Internal Server exception', $e);
5826 /// @TODO move to top of file or somewhere better
5827 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5828 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5831 * update a direct_message to seen state
5833 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5834 * @return string|array (success result=ok, error result=error with error message)
5835 * @throws BadRequestException
5836 * @throws ForbiddenException
5837 * @throws ImagickException
5838 * @throws InternalServerErrorException
5839 * @throws UnauthorizedException
5841 function api_friendica_direct_messages_setseen($type)
5844 if (api_user() === false) {
5845 throw new ForbiddenException();
5849 $user_info = api_get_user($a);
5850 $uid = $user_info['uid'];
5851 $id = $_REQUEST['id'] ?? 0;
5853 // return error if id is zero
5855 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5856 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5859 // error message if specified id is not in database
5860 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5861 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5862 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5865 // update seen indicator
5866 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5870 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5871 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5873 $answer = ['result' => 'error', 'message' => 'unknown error'];
5874 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5878 /// @TODO move to top of file or somewhere better
5879 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5882 * search for direct_messages containing a searchstring through api
5884 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5885 * @param string $box
5886 * @return string|array (success: success=true if found and search_result contains found messages,
5887 * success=false if nothing was found, search_result='nothing found',
5888 * error: result=error with error message)
5889 * @throws BadRequestException
5890 * @throws ForbiddenException
5891 * @throws ImagickException
5892 * @throws InternalServerErrorException
5893 * @throws UnauthorizedException
5895 function api_friendica_direct_messages_search($type, $box = "")
5899 if (api_user() === false) {
5900 throw new ForbiddenException();
5904 $user_info = api_get_user($a);
5905 $searchstring = $_REQUEST['searchstring'] ?? '';
5906 $uid = $user_info['uid'];
5908 // error if no searchstring specified
5909 if ($searchstring == "") {
5910 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5911 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5914 // get data for the specified searchstring
5916 "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",
5918 DBA::escape('%'.$searchstring.'%')
5921 $profile_url = $user_info["url"];
5923 // message if nothing was found
5924 if (!DBA::isResult($r)) {
5925 $success = ['success' => false, 'search_results' => 'problem with query'];
5926 } elseif (count($r) == 0) {
5927 $success = ['success' => false, 'search_results' => 'nothing found'];
5930 foreach ($r as $item) {
5931 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5932 $recipient = $user_info;
5933 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5934 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5935 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5936 $sender = $user_info;
5939 if (isset($recipient) && isset($sender)) {
5940 $ret[] = api_format_messages($item, $recipient, $sender);
5943 $success = ['success' => true, 'search_results' => $ret];
5946 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5949 /// @TODO move to top of file or somewhere better
5950 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5953 * Returns a list of saved searches.
5955 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5957 * @param string $type Return format: json or xml
5959 * @return string|array
5962 function api_saved_searches_list($type)
5964 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5967 while ($term = DBA::fetch($terms)) {
5969 'created_at' => api_date(time()),
5970 'id' => intval($term['id']),
5971 'id_str' => $term['id'],
5972 'name' => $term['term'],
5974 'query' => $term['term']
5980 return api_format_data("terms", $type, ['terms' => $result]);
5983 /// @TODO move to top of file or somewhere better
5984 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5987 * Number of comments
5989 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5991 * @param object $data [Status, Status]
5995 function bindComments(&$data)
5997 if (count($data) == 0) {
6003 foreach ($data as $item) {
6004 $ids[] = $item['id'];
6007 $idStr = DBA::escape(implode(', ', $ids));
6008 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6009 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6010 $itemsData = DBA::toArray($items);
6012 foreach ($itemsData as $item) {
6013 $comments[$item['parent']] = $item['comments'];
6016 foreach ($data as $idx => $item) {
6018 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6023 @TODO Maybe open to implement?
6025 [pagename] => api/1.1/statuses/lookup.json
6026 [id] => 605138389168451584
6027 [include_cards] => true
6028 [cards_platform] => Android-12
6029 [include_entities] => true
6030 [include_my_retweet] => 1
6032 [include_reply_count] => true
6033 [include_descendent_reply_count] => true
6037 Not implemented by now:
6038 statuses/retweets_of_me
6043 account/update_location
6044 account/update_profile_background_image
6047 friendica/profile/update
6048 friendica/profile/create
6049 friendica/profile/delete
6051 Not implemented in status.net:
6052 statuses/retweeted_to_me
6053 statuses/retweeted_by_me
6054 direct_messages/destroy
6056 account/update_delivery_device
6057 notifications/follow