3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\Verb;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\TooManyRequestsException;
55 use Friendica\Network\HTTPException\UnauthorizedException;
56 use Friendica\Object\Image;
57 use Friendica\Protocol\Activity;
58 use Friendica\Protocol\Diaspora;
59 use Friendica\Security\FKOAuth1;
60 use Friendica\Security\OAuth1\OAuthRequest;
61 use Friendica\Security\OAuth1\OAuthUtil;
62 use Friendica\Util\DateTimeFormat;
63 use Friendica\Util\Images;
64 use Friendica\Util\Network;
65 use Friendica\Util\Proxy as ProxyUtils;
66 use Friendica\Util\Strings;
67 use Friendica\Util\XML;
69 require_once __DIR__ . '/../mod/item.php';
70 require_once __DIR__ . '/../mod/wall_upload.php';
72 define('API_METHOD_ANY', '*');
73 define('API_METHOD_GET', 'GET');
74 define('API_METHOD_POST', 'POST,PUT');
75 define('API_METHOD_DELETE', 'POST,DELETE');
77 define('API_LOG_PREFIX', 'API {action} - ');
85 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
86 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
87 * into a page, and visitors will post something without noticing it).
91 if (!empty($_SESSION['allow_api'])) {
99 * Get source name from API client
101 * Clients can send 'source' parameter to be show in post metadata
102 * as "sent via <source>".
103 * Some clients doesn't send a source param, we support ones we know
104 * (only Twidere, atm)
107 * Client source name, default to "api" if unset/unknown
110 function api_source()
112 if (requestdata('source')) {
113 return requestdata('source');
116 // Support for known clients that doesn't send a source name
117 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
118 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
122 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
124 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
131 * Format date for API
133 * @param string $str Source date, as UTC
134 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
137 function api_date($str)
139 // Wed May 23 06:01:13 +0000 2007
140 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
144 * Register a function to be the endpoint for defined API path.
146 * @param string $path API URL path, relative to DI::baseUrl()
147 * @param string $func Function name to call on path request
148 * @param bool $auth API need logged user
149 * @param string $method HTTP method reqiured to call this endpoint.
150 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
151 * Default to API_METHOD_ANY
153 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
163 // Workaround for hotot
164 $path = str_replace("api/", "api/1.1/", $path);
174 * Log in user via OAuth1 or Simple HTTP Auth.
175 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
178 * @throws ForbiddenException
179 * @throws InternalServerErrorException
180 * @throws UnauthorizedException
181 * @hook 'authenticate'
183 * 'username' => username from login form
184 * 'password' => password from login form
185 * 'authenticated' => return status,
186 * 'user_record' => return authenticated user record
188 function api_login(App $a)
190 // workaround for HTTP-auth in CGI mode
191 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
192 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
193 if (strlen($userpass)) {
194 list($name, $password) = explode(':', $userpass);
195 $_SERVER['PHP_AUTH_USER'] = $name;
196 $_SERVER['PHP_AUTH_PW'] = $password;
200 if (empty($_SERVER['PHP_AUTH_USER'])) {
201 // Try OAuth when no user is provided
202 $oauth1 = new FKOAuth1();
205 $request = OAuthRequest::from_request();
206 list($consumer, $token) = $oauth1->verify_request($request);
207 if (!is_null($token)) {
208 $oauth1->loginUser($token->uid);
209 Session::set('allow_api', true);
212 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
213 var_dump($consumer, $token);
215 } catch (Exception $e) {
216 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
219 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
220 header('WWW-Authenticate: Basic realm="Friendica"');
221 throw new UnauthorizedException("This API requires login");
224 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
225 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
227 // allow "user@server" login (but ignore 'server' part)
228 $at = strstr($user, "@", true);
233 // next code from mod/auth.php. needs better solution
237 'username' => trim($user),
238 'password' => trim($password),
239 'authenticated' => 0,
240 'user_record' => null,
244 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
245 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
246 * and later addons should not interfere with an earlier one that succeeded.
248 Hook::callAll('authenticate', $addon_auth);
250 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
251 $record = $addon_auth['user_record'];
253 $user_id = User::authenticate(trim($user), trim($password), true);
254 if ($user_id !== false) {
255 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
259 if (!DBA::isResult($record)) {
260 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
261 header('WWW-Authenticate: Basic realm="Friendica"');
262 //header('HTTP/1.0 401 Unauthorized');
263 //die('This api requires login');
264 throw new UnauthorizedException("This API requires login");
267 // Don't refresh the login date more often than twice a day to spare database writes
268 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
270 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
272 $_SESSION["allow_api"] = true;
274 Hook::callAll('logged_in', $a->user);
278 * Check HTTP method of called API
280 * API endpoints can define which HTTP method to accept when called.
281 * This function check the current HTTP method agains endpoint
284 * @param string $method Required methods, uppercase, separated by comma
287 function api_check_method($method)
289 if ($method == "*") {
292 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
296 * Main API entry point
298 * Authenticate user, call registered API function, set HTTP headers
301 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
302 * @return string|array API call result
305 function api_call(App $a, App\Arguments $args = null)
307 global $API, $called_api;
314 if (strpos($args->getCommand(), ".xml") > 0) {
317 if (strpos($args->getCommand(), ".json") > 0) {
320 if (strpos($args->getCommand(), ".rss") > 0) {
323 if (strpos($args->getCommand(), ".atom") > 0) {
328 foreach ($API as $p => $info) {
329 if (strpos($args->getCommand(), $p) === 0) {
330 if (!api_check_method($info['method'])) {
331 throw new MethodNotAllowedException();
334 $called_api = explode("/", $p);
336 if (!empty($info['auth']) && api_user() === false) {
338 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
341 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
343 $stamp = microtime(true);
344 $return = call_user_func($info['func'], $type);
345 $duration = floatval(microtime(true) - $stamp);
347 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
349 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
351 if (false === $return) {
353 * api function returned false withour throw an
354 * exception. This should not happend, throw a 500
356 throw new InternalServerErrorException();
361 header("Content-Type: text/xml");
364 header("Content-Type: application/json");
365 if (!empty($return)) {
366 $json = json_encode(end($return));
367 if (!empty($_GET['callback'])) {
368 $json = $_GET['callback'] . "(" . $json . ")";
374 header("Content-Type: application/rss+xml");
375 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
378 header("Content-Type: application/atom+xml");
379 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
386 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
387 throw new NotFoundException();
388 } catch (HTTPException $e) {
389 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
390 return api_error($type, $e, $args);
395 * Format API error string
397 * @param string $type Return type (xml, json, rss, as)
398 * @param object $e HTTPException Error object
399 * @param App\Arguments $args The App arguments
400 * @return string|array error message formatted as $type
402 function api_error($type, $e, App\Arguments $args)
404 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
405 /// @TODO: https://dev.twitter.com/overview/api/response-codes
407 $error = ["error" => $error,
408 "code" => $e->getCode() . " " . $e->httpdesc,
409 "request" => $args->getQueryString()];
411 $return = api_format_data('status', $type, ['status' => $error]);
415 header("Content-Type: text/xml");
418 header("Content-Type: application/json");
419 $return = json_encode($return);
422 header("Content-Type: application/rss+xml");
425 header("Content-Type: application/atom+xml");
433 * Set values for RSS template
436 * @param array $arr Array to be passed to template
437 * @param array $user_info User info
439 * @throws BadRequestException
440 * @throws ImagickException
441 * @throws InternalServerErrorException
442 * @throws UnauthorizedException
443 * @todo find proper type-hints
445 function api_rss_extra(App $a, $arr, $user_info)
447 if (is_null($user_info)) {
448 $user_info = api_get_user($a);
451 $arr['$user'] = $user_info;
453 'alternate' => $user_info['url'],
454 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
455 'base' => DI::baseUrl(),
456 'updated' => api_date(null),
457 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
458 'language' => $user_info['lang'],
459 'logo' => DI::baseUrl() . "/images/friendica-32.png",
467 * Unique contact to contact url.
469 * @param int $id Contact id
470 * @return bool|string
471 * Contact url or False if contact id is unknown
474 function api_unique_id_to_nurl($id)
476 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
478 if (DBA::isResult($r)) {
486 * Get user info array.
489 * @param int|string $contact_id Contact ID or URL
491 * @throws BadRequestException
492 * @throws ImagickException
493 * @throws InternalServerErrorException
494 * @throws UnauthorizedException
496 function api_get_user(App $a, $contact_id = null)
504 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
506 // Searching for contact URL
507 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
508 $user = DBA::escape(Strings::normaliseLink($contact_id));
510 $extra_query = "AND `contact`.`nurl` = '%s' ";
511 if (api_user() !== false) {
512 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
516 // Searching for contact id with uid = 0
517 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
518 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
521 throw new BadRequestException("User ID ".$contact_id." not found.");
525 $extra_query = "AND `contact`.`nurl` = '%s' ";
526 if (api_user() !== false) {
527 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
531 if (is_null($user) && !empty($_GET['user_id'])) {
532 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
535 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
539 $extra_query = "AND `contact`.`nurl` = '%s' ";
540 if (api_user() !== false) {
541 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
544 if (is_null($user) && !empty($_GET['screen_name'])) {
545 $user = DBA::escape($_GET['screen_name']);
546 $extra_query = "AND `contact`.`nick` = '%s' ";
547 if (api_user() !== false) {
548 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
552 if (is_null($user) && !empty($_GET['profileurl'])) {
553 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
554 $extra_query = "AND `contact`.`nurl` = '%s' ";
555 if (api_user() !== false) {
556 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
560 // $called_api is the API path exploded on / and is expected to have at least 2 elements
561 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
562 $argid = count($called_api);
563 if (!empty($a->argv[$argid])) {
564 $data = explode(".", $a->argv[$argid]);
565 if (count($data) > 1) {
566 list($user, $null) = $data;
569 if (is_numeric($user)) {
570 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
574 $extra_query = "AND `contact`.`nurl` = '%s' ";
575 if (api_user() !== false) {
576 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
580 $user = DBA::escape($user);
581 $extra_query = "AND `contact`.`nick` = '%s' ";
582 if (api_user() !== false) {
583 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
588 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
591 if (api_user() === false) {
595 $user = $_SESSION['uid'];
596 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
600 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
604 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
610 // Selecting the id by priority, friendica first
611 if (is_array($uinfo)) {
612 api_best_nickname($uinfo);
615 // if the contact wasn't found, fetch it from the contacts with uid = 0
616 if (!DBA::isResult($uinfo)) {
618 throw new BadRequestException("User not found.");
621 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
623 if (DBA::isResult($contact)) {
625 'id' => $contact["id"],
626 'id_str' => (string) $contact["id"],
627 'name' => $contact["name"],
628 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
629 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
630 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
631 'profile_image_url' => $contact["micro"],
632 'profile_image_url_https' => $contact["micro"],
633 'profile_image_url_profile_size' => $contact["thumb"],
634 'profile_image_url_large' => $contact["photo"],
635 'url' => $contact["url"],
636 'protected' => false,
637 'followers_count' => 0,
638 'friends_count' => 0,
640 'created_at' => api_date($contact["created"]),
641 'favourites_count' => 0,
643 'time_zone' => 'UTC',
644 'geo_enabled' => false,
646 'statuses_count' => 0,
648 'contributors_enabled' => false,
649 'is_translator' => false,
650 'is_translation_enabled' => false,
651 'following' => false,
652 'follow_request_sent' => false,
653 'statusnet_blocking' => false,
654 'notifications' => false,
655 'statusnet_profile_url' => $contact["url"],
657 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
658 'pid' => Contact::getIdForURL($contact["url"], 0, false),
660 'network' => $contact["network"],
665 throw new BadRequestException("User ".$url." not found.");
669 if ($uinfo[0]['self']) {
670 if ($uinfo[0]['network'] == "") {
671 $uinfo[0]['network'] = Protocol::DFRN;
674 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
675 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
682 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
684 if (!empty($profile['about'])) {
685 $description = $profile['about'];
687 $description = $uinfo[0]["about"];
690 if (!empty($usr['default-location'])) {
691 $location = $usr['default-location'];
692 } elseif (!empty($uinfo[0]["location"])) {
693 $location = $uinfo[0]["location"];
695 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
699 'id' => intval($pcontact_id),
700 'id_str' => (string) intval($pcontact_id),
701 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
702 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
703 'location' => $location,
704 'description' => BBCode::toPlaintext($description ?? ''),
705 'profile_image_url' => $uinfo[0]['micro'],
706 'profile_image_url_https' => $uinfo[0]['micro'],
707 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
708 'profile_image_url_large' => $uinfo[0]["photo"],
709 'url' => $uinfo[0]['url'],
710 'protected' => false,
711 'followers_count' => intval($countfollowers),
712 'friends_count' => intval($countfriends),
714 'created_at' => api_date($uinfo[0]['created']),
715 'favourites_count' => intval($starred),
717 'time_zone' => 'UTC',
718 'geo_enabled' => false,
720 'statuses_count' => intval($countitems),
722 'contributors_enabled' => false,
723 'is_translator' => false,
724 'is_translation_enabled' => false,
725 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
726 'follow_request_sent' => false,
727 'statusnet_blocking' => false,
728 'notifications' => false,
730 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
731 'statusnet_profile_url' => $uinfo[0]['url'],
732 'uid' => intval($uinfo[0]['uid']),
733 'cid' => intval($uinfo[0]['cid']),
734 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
735 'self' => $uinfo[0]['self'],
736 'network' => $uinfo[0]['network'],
739 // If this is a local user and it uses Frio, we can get its color preferences.
741 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
742 if ($theme_info['theme'] === 'frio') {
743 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
745 if ($schema && ($schema != '---')) {
746 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
747 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
748 require_once $schemefile;
751 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
752 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
753 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
755 if (empty($nav_bg)) {
758 if (empty($link_color)) {
759 $link_color = "#6fdbe8";
761 if (empty($bgcolor)) {
762 $bgcolor = "#ededed";
765 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
766 $ret['profile_link_color'] = str_replace('#', '', $link_color);
767 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
775 * return api-formatted array for item's author and owner
778 * @param array $item item from db
779 * @return array(array:author, array:owner)
780 * @throws BadRequestException
781 * @throws ImagickException
782 * @throws InternalServerErrorException
783 * @throws UnauthorizedException
785 function api_item_get_user(App $a, $item)
787 $status_user = api_get_user($a, $item['author-id'] ?? null);
789 $author_user = $status_user;
791 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
793 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
794 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
796 $owner_user = $author_user;
799 return ([$status_user, $author_user, $owner_user]);
803 * walks recursively through an array with the possibility to change value and key
805 * @param array $array The array to walk through
806 * @param callable $callback The callback function
808 * @return array the transformed array
810 function api_walk_recursive(array &$array, callable $callback)
814 foreach ($array as $k => $v) {
816 if ($callback($v, $k)) {
817 $new_array[$k] = api_walk_recursive($v, $callback);
820 if ($callback($v, $k)) {
831 * Callback function to transform the array in an array that can be transformed in a XML file
833 * @param mixed $item Array item value
834 * @param string $key Array key
836 * @return boolean Should the array item be deleted?
838 function api_reformat_xml(&$item, &$key)
840 if (is_bool($item)) {
841 $item = ($item ? "true" : "false");
844 if (substr($key, 0, 10) == "statusnet_") {
845 $key = "statusnet:".substr($key, 10);
846 } elseif (substr($key, 0, 10) == "friendica_") {
847 $key = "friendica:".substr($key, 10);
849 /// @TODO old-lost code?
851 // $key = "default:".$key;
857 * Creates the XML from a JSON style array
859 * @param array $data JSON style array
860 * @param string $root_element Name of the root element
862 * @return string The XML data
864 function api_create_xml(array $data, $root_element)
866 $childname = key($data);
867 $data2 = array_pop($data);
869 $namespaces = ["" => "http://api.twitter.com",
870 "statusnet" => "http://status.net/schema/api/1/",
871 "friendica" => "http://friendi.ca/schema/api/1/",
872 "georss" => "http://www.georss.org/georss"];
874 /// @todo Auto detection of needed namespaces
875 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
879 if (is_array($data2)) {
881 api_walk_recursive($data2, "api_reformat_xml");
887 foreach ($data2 as $item) {
888 $data4[$i++ . ":" . $childname] = $item;
895 $data3 = [$root_element => $data2];
897 $ret = XML::fromArray($data3, $xml, false, $namespaces);
902 * Formats the data according to the data type
904 * @param string $root_element Name of the root element
905 * @param string $type Return type (atom, rss, xml, json)
906 * @param array $data JSON style array
908 * @return array|string (string|array) XML data or JSON data
910 function api_format_data($root_element, $type, $data)
916 $ret = api_create_xml($data, $root_element);
931 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
932 * returns a 401 status code and an error message if not.
934 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
936 * @param string $type Return type (atom, rss, xml, json)
937 * @return array|string
938 * @throws BadRequestException
939 * @throws ForbiddenException
940 * @throws ImagickException
941 * @throws InternalServerErrorException
942 * @throws UnauthorizedException
944 function api_account_verify_credentials($type)
948 if (api_user() === false) {
949 throw new ForbiddenException();
952 unset($_REQUEST["user_id"]);
953 unset($_GET["user_id"]);
955 unset($_REQUEST["screen_name"]);
956 unset($_GET["screen_name"]);
958 $skip_status = $_REQUEST['skip_status'] ?? false;
960 $user_info = api_get_user($a);
962 // "verified" isn't used here in the standard
963 unset($user_info["verified"]);
965 // - Adding last status
967 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
969 $user_info['status'] = api_format_item($item, $type);
973 // "uid" and "self" are only needed for some internal stuff, so remove it from here
974 unset($user_info["uid"]);
975 unset($user_info["self"]);
977 return api_format_data("user", $type, ['user' => $user_info]);
980 /// @TODO move to top of file or somewhere better
981 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
984 * Get data from $_POST or $_GET
989 function requestdata($k)
991 if (!empty($_POST[$k])) {
994 if (!empty($_GET[$k])) {
1001 * Deprecated function to upload media.
1003 * @param string $type Return type (atom, rss, xml, json)
1005 * @return array|string
1006 * @throws BadRequestException
1007 * @throws ForbiddenException
1008 * @throws ImagickException
1009 * @throws InternalServerErrorException
1010 * @throws UnauthorizedException
1012 function api_statuses_mediap($type)
1016 if (api_user() === false) {
1017 Logger::log('api_statuses_update: no user');
1018 throw new ForbiddenException();
1020 $user_info = api_get_user($a);
1022 $_REQUEST['profile_uid'] = api_user();
1023 $_REQUEST['api_source'] = true;
1024 $txt = requestdata('status') ?? '';
1025 /// @TODO old-lost code?
1026 //$txt = urldecode(requestdata('status'));
1028 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1029 $txt = HTML::toBBCodeVideo($txt);
1030 $config = HTMLPurifier_Config::createDefault();
1031 $config->set('Cache.DefinitionImpl', null);
1032 $purifier = new HTMLPurifier($config);
1033 $txt = $purifier->purify($txt);
1035 $txt = HTML::toBBCode($txt);
1037 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1039 $picture = wall_upload_post($a, false);
1041 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1042 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1043 $item_id = item_post($a);
1045 // output the post that we just posted.
1046 return api_status_show($type, $item_id);
1049 /// @TODO move this to top of file or somewhere better!
1050 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1053 * Updates the user’s current status.
1055 * @param string $type Return type (atom, rss, xml, json)
1057 * @return array|string
1058 * @throws BadRequestException
1059 * @throws ForbiddenException
1060 * @throws ImagickException
1061 * @throws InternalServerErrorException
1062 * @throws TooManyRequestsException
1063 * @throws UnauthorizedException
1064 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1066 function api_statuses_update($type)
1070 if (api_user() === false) {
1071 Logger::log('api_statuses_update: no user');
1072 throw new ForbiddenException();
1077 // convert $_POST array items to the form we use for web posts.
1078 if (requestdata('htmlstatus')) {
1079 $txt = requestdata('htmlstatus') ?? '';
1080 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1081 $txt = HTML::toBBCodeVideo($txt);
1083 $config = HTMLPurifier_Config::createDefault();
1084 $config->set('Cache.DefinitionImpl', null);
1086 $purifier = new HTMLPurifier($config);
1087 $txt = $purifier->purify($txt);
1089 $_REQUEST['body'] = HTML::toBBCode($txt);
1092 $_REQUEST['body'] = requestdata('status');
1095 $_REQUEST['title'] = requestdata('title');
1097 $parent = requestdata('in_reply_to_status_id');
1099 // Twidere sends "-1" if it is no reply ...
1100 if ($parent == -1) {
1104 if (ctype_digit($parent)) {
1105 $_REQUEST['parent'] = $parent;
1107 $_REQUEST['parent_uri'] = $parent;
1110 if (requestdata('lat') && requestdata('long')) {
1111 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1113 $_REQUEST['profile_uid'] = api_user();
1116 // Check for throttling (maximum posts per day, week and month)
1117 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1118 if ($throttle_day > 0) {
1119 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1121 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1122 $posts_day = Post::count($condition);
1124 if ($posts_day > $throttle_day) {
1125 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1126 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1127 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));
1131 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1132 if ($throttle_week > 0) {
1133 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1135 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1136 $posts_week = Post::count($condition);
1138 if ($posts_week > $throttle_week) {
1139 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1140 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1141 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));
1145 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1146 if ($throttle_month > 0) {
1147 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1149 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1150 $posts_month = Post::count($condition);
1152 if ($posts_month > $throttle_month) {
1153 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1154 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1155 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));
1160 if (requestdata('media_ids')) {
1161 $ids = explode(',', requestdata('media_ids') ?? '');
1162 } elseif (!empty($_FILES['media'])) {
1163 // upload the image if we have one
1164 $picture = wall_upload_post($a, false);
1165 if (is_array($picture)) {
1166 $ids[] = $picture['id'];
1174 foreach ($ids as $id) {
1175 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1176 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1177 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1178 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1180 if (!empty($media)) {
1181 $ressources[] = $media[0]['resource-id'];
1182 $phototypes = Images::supportedTypes();
1183 $ext = $phototypes[$media[0]['type']];
1185 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1186 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1187 'size' => $media[0]['datasize'],
1188 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1189 'description' => $media[0]['desc'] ?? '',
1190 'width' => $media[0]['width'],
1191 'height' => $media[0]['height']];
1193 if (count($media) > 1) {
1194 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1195 $attachment['preview-width'] = $media[1]['width'];
1196 $attachment['preview-height'] = $media[1]['height'];
1198 $attachments[] = $attachment;
1202 // We have to avoid that the post is rejected because of an empty body
1203 if (empty($_REQUEST['body'])) {
1204 $_REQUEST['body'] = '[hr]';
1208 if (!empty($attachments)) {
1209 $_REQUEST['attachments'] = $attachments;
1212 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1214 $_REQUEST['api_source'] = true;
1216 if (empty($_REQUEST['source'])) {
1217 $_REQUEST["source"] = api_source();
1220 // call out normal post function
1221 $item_id = item_post($a);
1223 if (!empty($ressources) && !empty($item_id)) {
1224 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1225 foreach ($ressources as $ressource) {
1226 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1230 // output the post that we just posted.
1231 return api_status_show($type, $item_id);
1234 /// @TODO move to top of file or somewhere better
1235 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1236 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1239 * Uploads an image to Friendica.
1242 * @throws BadRequestException
1243 * @throws ForbiddenException
1244 * @throws ImagickException
1245 * @throws InternalServerErrorException
1246 * @throws UnauthorizedException
1247 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1249 function api_media_upload()
1253 if (api_user() === false) {
1254 Logger::log('no user');
1255 throw new ForbiddenException();
1260 if (empty($_FILES['media'])) {
1262 throw new BadRequestException("No media.");
1265 $media = wall_upload_post($a, false);
1268 throw new InternalServerErrorException();
1272 $returndata["media_id"] = $media["id"];
1273 $returndata["media_id_string"] = (string)$media["id"];
1274 $returndata["size"] = $media["size"];
1275 $returndata["image"] = ["w" => $media["width"],
1276 "h" => $media["height"],
1277 "image_type" => $media["type"],
1278 "friendica_preview_url" => $media["preview"]];
1280 Logger::info('Media uploaded', ['return' => $returndata]);
1282 return ["media" => $returndata];
1285 /// @TODO move to top of file or somewhere better
1286 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1289 * Updates media meta data (picture descriptions)
1291 * @param string $type Return type (atom, rss, xml, json)
1293 * @return array|string
1294 * @throws BadRequestException
1295 * @throws ForbiddenException
1296 * @throws ImagickException
1297 * @throws InternalServerErrorException
1298 * @throws TooManyRequestsException
1299 * @throws UnauthorizedException
1300 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1302 * @todo Compare the corresponding Twitter function for correct return values
1304 function api_media_metadata_create($type)
1308 if (api_user() === false) {
1309 Logger::info('no user');
1310 throw new ForbiddenException();
1315 $postdata = Network::postdata();
1317 if (empty($postdata)) {
1318 throw new BadRequestException("No post data");
1321 $data = json_decode($postdata, true);
1323 throw new BadRequestException("Invalid post data");
1326 if (empty($data['media_id']) || empty($data['alt_text'])) {
1327 throw new BadRequestException("Missing post data values");
1330 if (empty($data['alt_text']['text'])) {
1331 throw new BadRequestException("No alt text.");
1334 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1336 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1337 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1338 if (!DBA::isResult($photo)) {
1339 throw new BadRequestException("Metadata not found.");
1342 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1345 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1348 * @param string $type Return format (atom, rss, xml, json)
1349 * @param int $item_id
1350 * @return array|string
1353 function api_status_show($type, $item_id)
1355 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1359 $item = api_get_item(['id' => $item_id]);
1360 if (!empty($item)) {
1361 $status_info = api_format_item($item, $type);
1364 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1366 return api_format_data('statuses', $type, ['status' => $status_info]);
1370 * Retrieves the last public status of the provided user info
1372 * @param int $ownerId Public contact Id
1373 * @param int $uid User Id
1377 function api_get_last_status($ownerId, $uid)
1380 'author-id'=> $ownerId,
1382 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1383 'private' => [Item::PUBLIC, Item::UNLISTED]
1386 $item = api_get_item($condition);
1392 * Retrieves a single item record based on the provided condition and converts it for API use.
1394 * @param array $condition Item table condition array
1398 function api_get_item(array $condition)
1400 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1406 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1407 * The author's most recent status will be returned inline.
1409 * @param string $type Return type (atom, rss, xml, json)
1410 * @return array|string
1411 * @throws BadRequestException
1412 * @throws ImagickException
1413 * @throws InternalServerErrorException
1414 * @throws UnauthorizedException
1415 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1417 function api_users_show($type)
1419 $a = Friendica\DI::app();
1421 $user_info = api_get_user($a);
1423 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1424 if (!empty($item)) {
1425 $user_info['status'] = api_format_item($item, $type);
1428 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1429 unset($user_info['uid']);
1430 unset($user_info['self']);
1432 return api_format_data('user', $type, ['user' => $user_info]);
1435 /// @TODO move to top of file or somewhere better
1436 api_register_func('api/users/show', 'api_users_show');
1437 api_register_func('api/externalprofile/show', 'api_users_show');
1440 * Search a public user account.
1442 * @param string $type Return type (atom, rss, xml, json)
1444 * @return array|string
1445 * @throws BadRequestException
1446 * @throws ImagickException
1447 * @throws InternalServerErrorException
1448 * @throws UnauthorizedException
1449 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1451 function api_users_search($type)
1457 if (!empty($_GET['q'])) {
1458 $contacts = Contact::selectToArray(
1461 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1469 if (DBA::isResult($contacts)) {
1471 foreach ($contacts as $contact) {
1472 $user_info = api_get_user($a, $contact['id']);
1474 if ($type == 'xml') {
1475 $userlist[$k++ . ':user'] = $user_info;
1477 $userlist[] = $user_info;
1480 $userlist = ['users' => $userlist];
1482 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1485 throw new BadRequestException('No search term specified.');
1488 return api_format_data('users', $type, $userlist);
1491 /// @TODO move to top of file or somewhere better
1492 api_register_func('api/users/search', 'api_users_search');
1495 * Return user objects
1497 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1499 * @param string $type Return format: json or xml
1501 * @return array|string
1502 * @throws BadRequestException
1503 * @throws ImagickException
1504 * @throws InternalServerErrorException
1505 * @throws NotFoundException if the results are empty.
1506 * @throws UnauthorizedException
1508 function api_users_lookup($type)
1512 if (!empty($_REQUEST['user_id'])) {
1513 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1515 $users[] = api_get_user(DI::app(), $id);
1520 if (empty($users)) {
1521 throw new NotFoundException;
1524 return api_format_data("users", $type, ['users' => $users]);
1527 /// @TODO move to top of file or somewhere better
1528 api_register_func('api/users/lookup', 'api_users_lookup', true);
1531 * Returns statuses that match a specified query.
1533 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1535 * @param string $type Return format: json, xml, atom, rss
1537 * @return array|string
1538 * @throws BadRequestException if the "q" parameter is missing.
1539 * @throws ForbiddenException
1540 * @throws ImagickException
1541 * @throws InternalServerErrorException
1542 * @throws UnauthorizedException
1544 function api_search($type)
1547 $user_info = api_get_user($a);
1549 if (api_user() === false || $user_info === false) {
1550 throw new ForbiddenException();
1553 if (empty($_REQUEST['q'])) {
1554 throw new BadRequestException('q parameter is required.');
1557 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1560 $data['status'] = [];
1562 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1563 if (!empty($_REQUEST['rpp'])) {
1564 $count = $_REQUEST['rpp'];
1565 } elseif (!empty($_REQUEST['count'])) {
1566 $count = $_REQUEST['count'];
1569 $since_id = $_REQUEST['since_id'] ?? 0;
1570 $max_id = $_REQUEST['max_id'] ?? 0;
1571 $page = $_REQUEST['page'] ?? 1;
1573 $start = max(0, ($page - 1) * $count);
1575 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1576 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1577 $searchTerm = $matches[1];
1578 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1579 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1581 while ($tag = DBA::fetch($tags)) {
1582 $uriids[] = $tag['uri-id'];
1586 if (empty($uriids)) {
1587 return api_format_data('statuses', $type, $data);
1590 $condition = ['uri-id' => $uriids];
1591 if ($exclude_replies) {
1592 $condition['gravity'] = GRAVITY_PARENT;
1595 $params['group_by'] = ['uri-id'];
1597 $condition = ["`id` > ?
1598 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1599 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1600 AND `body` LIKE CONCAT('%',?,'%')",
1601 $since_id, api_user(), $_REQUEST['q']];
1603 $condition[0] .= ' AND `id` <= ?';
1604 $condition[] = $max_id;
1610 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1611 $id = Item::fetchByLink($searchTerm, api_user());
1614 $id = Item::fetchByLink($searchTerm);
1618 $statuses = Post::select([], ['id' => $id]);
1622 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1624 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1626 bindComments($data['status']);
1628 return api_format_data('statuses', $type, $data);
1631 /// @TODO move to top of file or somewhere better
1632 api_register_func('api/search/tweets', 'api_search', true);
1633 api_register_func('api/search', 'api_search', true);
1636 * Returns the most recent statuses posted by the user and the users they follow.
1638 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1640 * @param string $type Return type (atom, rss, xml, json)
1642 * @return array|string
1643 * @throws BadRequestException
1644 * @throws ForbiddenException
1645 * @throws ImagickException
1646 * @throws InternalServerErrorException
1647 * @throws UnauthorizedException
1648 * @todo Optional parameters
1649 * @todo Add reply info
1651 function api_statuses_home_timeline($type)
1654 $user_info = api_get_user($a);
1656 if (api_user() === false || $user_info === false) {
1657 throw new ForbiddenException();
1660 unset($_REQUEST["user_id"]);
1661 unset($_GET["user_id"]);
1663 unset($_REQUEST["screen_name"]);
1664 unset($_GET["screen_name"]);
1666 // get last network messages
1669 $count = $_REQUEST['count'] ?? 20;
1670 $page = $_REQUEST['page']?? 0;
1671 $since_id = $_REQUEST['since_id'] ?? 0;
1672 $max_id = $_REQUEST['max_id'] ?? 0;
1673 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1674 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1676 $start = max(0, ($page - 1) * $count);
1678 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1679 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1682 $condition[0] .= " AND `id` <= ?";
1683 $condition[] = $max_id;
1685 if ($exclude_replies) {
1686 $condition[0] .= ' AND `gravity` = ?';
1687 $condition[] = GRAVITY_PARENT;
1689 if ($conversation_id > 0) {
1690 $condition[0] .= " AND `parent` = ?";
1691 $condition[] = $conversation_id;
1694 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1695 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1697 $items = Post::toArray($statuses);
1699 $ret = api_format_items($items, $user_info, false, $type);
1701 // Set all posts from the query above to seen
1703 foreach ($items as $item) {
1704 $idarray[] = intval($item["id"]);
1707 if (!empty($idarray)) {
1708 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1710 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1716 $data = ['status' => $ret];
1721 $data = api_rss_extra($a, $data, $user_info);
1725 return api_format_data("statuses", $type, $data);
1729 /// @TODO move to top of file or somewhere better
1730 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1731 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1734 * Returns the most recent statuses from public users.
1736 * @param string $type Return type (atom, rss, xml, json)
1738 * @return array|string
1739 * @throws BadRequestException
1740 * @throws ForbiddenException
1741 * @throws ImagickException
1742 * @throws InternalServerErrorException
1743 * @throws UnauthorizedException
1745 function api_statuses_public_timeline($type)
1748 $user_info = api_get_user($a);
1750 if (api_user() === false || $user_info === false) {
1751 throw new ForbiddenException();
1754 // get last network messages
1757 $count = $_REQUEST['count'] ?? 20;
1758 $page = $_REQUEST['page'] ?? 1;
1759 $since_id = $_REQUEST['since_id'] ?? 0;
1760 $max_id = $_REQUEST['max_id'] ?? 0;
1761 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1762 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1764 $start = max(0, ($page - 1) * $count);
1766 if ($exclude_replies && !$conversation_id) {
1767 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1768 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1771 $condition[0] .= " AND `id` <= ?";
1772 $condition[] = $max_id;
1775 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1776 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1778 $r = Post::toArray($statuses);
1780 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1781 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1784 $condition[0] .= " AND `id` <= ?";
1785 $condition[] = $max_id;
1787 if ($conversation_id > 0) {
1788 $condition[0] .= " AND `parent` = ?";
1789 $condition[] = $conversation_id;
1792 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1793 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1795 $r = Post::toArray($statuses);
1798 $ret = api_format_items($r, $user_info, false, $type);
1802 $data = ['status' => $ret];
1807 $data = api_rss_extra($a, $data, $user_info);
1811 return api_format_data("statuses", $type, $data);
1814 /// @TODO move to top of file or somewhere better
1815 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1818 * Returns the most recent statuses posted by users this node knows about.
1820 * @param string $type Return format: json, xml, atom, rss
1821 * @return array|string
1822 * @throws BadRequestException
1823 * @throws ForbiddenException
1824 * @throws ImagickException
1825 * @throws InternalServerErrorException
1826 * @throws UnauthorizedException
1828 function api_statuses_networkpublic_timeline($type)
1831 $user_info = api_get_user($a);
1833 if (api_user() === false || $user_info === false) {
1834 throw new ForbiddenException();
1837 $since_id = $_REQUEST['since_id'] ?? 0;
1838 $max_id = $_REQUEST['max_id'] ?? 0;
1841 $count = $_REQUEST['count'] ?? 20;
1842 $page = $_REQUEST['page'] ?? 1;
1844 $start = max(0, ($page - 1) * $count);
1846 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1847 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1850 $condition[0] .= " AND `id` <= ?";
1851 $condition[] = $max_id;
1854 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1855 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1857 $ret = api_format_items($statuses, $user_info, false, $type);
1861 $data = ['status' => $ret];
1866 $data = api_rss_extra($a, $data, $user_info);
1870 return api_format_data("statuses", $type, $data);
1873 /// @TODO move to top of file or somewhere better
1874 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1877 * Returns a single status.
1879 * @param string $type Return type (atom, rss, xml, json)
1881 * @return array|string
1882 * @throws BadRequestException
1883 * @throws ForbiddenException
1884 * @throws ImagickException
1885 * @throws InternalServerErrorException
1886 * @throws UnauthorizedException
1887 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1889 function api_statuses_show($type)
1892 $user_info = api_get_user($a);
1894 if (api_user() === false || $user_info === false) {
1895 throw new ForbiddenException();
1899 $id = intval($a->argv[3] ?? 0);
1902 $id = intval($_REQUEST['id'] ?? 0);
1907 $id = intval($a->argv[4] ?? 0);
1910 Logger::log('API: api_statuses_show: ' . $id);
1912 $conversation = !empty($_REQUEST['conversation']);
1914 // try to fetch the item for the local user - or the public item, if there is no local one
1915 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1916 if (!DBA::isResult($uri_item)) {
1917 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1920 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1921 if (!DBA::isResult($item)) {
1922 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1927 if ($conversation) {
1928 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1929 $params = ['order' => ['id' => true]];
1931 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1935 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1937 /// @TODO How about copying this to above methods which don't check $r ?
1938 if (!DBA::isResult($statuses)) {
1939 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1942 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1944 if ($conversation) {
1945 $data = ['status' => $ret];
1946 return api_format_data("statuses", $type, $data);
1948 $data = ['status' => $ret[0]];
1949 return api_format_data("status", $type, $data);
1953 /// @TODO move to top of file or somewhere better
1954 api_register_func('api/statuses/show', 'api_statuses_show', true);
1958 * @param string $type Return type (atom, rss, xml, json)
1960 * @return array|string
1961 * @throws BadRequestException
1962 * @throws ForbiddenException
1963 * @throws ImagickException
1964 * @throws InternalServerErrorException
1965 * @throws UnauthorizedException
1966 * @todo nothing to say?
1968 function api_conversation_show($type)
1971 $user_info = api_get_user($a);
1973 if (api_user() === false || $user_info === false) {
1974 throw new ForbiddenException();
1978 $id = intval($a->argv[3] ?? 0);
1979 $since_id = intval($_REQUEST['since_id'] ?? 0);
1980 $max_id = intval($_REQUEST['max_id'] ?? 0);
1981 $count = intval($_REQUEST['count'] ?? 20);
1982 $page = intval($_REQUEST['page'] ?? 1);
1984 $start = max(0, ($page - 1) * $count);
1987 $id = intval($_REQUEST['id'] ?? 0);
1992 $id = intval($a->argv[4] ?? 0);
1995 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1997 // try to fetch the item for the local user - or the public item, if there is no local one
1998 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1999 if (!DBA::isResult($item)) {
2000 throw new BadRequestException("There is no status with this id.");
2003 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
2004 if (!DBA::isResult($parent)) {
2005 throw new BadRequestException("There is no status with this id.");
2008 $id = $parent['id'];
2010 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
2011 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2014 $condition[0] .= " AND `id` <= ?";
2015 $condition[] = $max_id;
2018 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2019 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2021 if (!DBA::isResult($statuses)) {
2022 throw new BadRequestException("There is no status with id $id.");
2025 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2027 $data = ['status' => $ret];
2028 return api_format_data("statuses", $type, $data);
2031 /// @TODO move to top of file or somewhere better
2032 api_register_func('api/conversation/show', 'api_conversation_show', true);
2033 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2038 * @param string $type Return type (atom, rss, xml, json)
2040 * @return array|string
2041 * @throws BadRequestException
2042 * @throws ForbiddenException
2043 * @throws ImagickException
2044 * @throws InternalServerErrorException
2045 * @throws UnauthorizedException
2046 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2048 function api_statuses_repeat($type)
2054 if (api_user() === false) {
2055 throw new ForbiddenException();
2061 $id = intval($a->argv[3] ?? 0);
2064 $id = intval($_REQUEST['id'] ?? 0);
2069 $id = intval($a->argv[4] ?? 0);
2072 Logger::log('API: api_statuses_repeat: '.$id);
2074 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2075 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2077 if (DBA::isResult($item) && !empty($item['body'])) {
2078 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2079 if (!Item::performActivity($id, 'announce', local_user())) {
2080 throw new InternalServerErrorException();
2085 if (strpos($item['body'], "[/share]") !== false) {
2086 $pos = strpos($item['body'], "[share");
2087 $post = substr($item['body'], $pos);
2089 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2091 if (!empty($item['title'])) {
2092 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2095 $post .= $item['body'];
2096 $post .= "[/share]";
2098 $_REQUEST['body'] = $post;
2099 $_REQUEST['profile_uid'] = api_user();
2100 $_REQUEST['api_source'] = true;
2102 if (empty($_REQUEST['source'])) {
2103 $_REQUEST["source"] = api_source();
2106 $item_id = item_post($a);
2109 throw new ForbiddenException();
2112 // output the post that we just posted.
2114 return api_status_show($type, $item_id);
2117 /// @TODO move to top of file or somewhere better
2118 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2121 * Destroys a specific status.
2123 * @param string $type Return type (atom, rss, xml, json)
2125 * @return array|string
2126 * @throws BadRequestException
2127 * @throws ForbiddenException
2128 * @throws ImagickException
2129 * @throws InternalServerErrorException
2130 * @throws UnauthorizedException
2131 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2133 function api_statuses_destroy($type)
2137 if (api_user() === false) {
2138 throw new ForbiddenException();
2144 $id = intval($a->argv[3] ?? 0);
2147 $id = intval($_REQUEST['id'] ?? 0);
2152 $id = intval($a->argv[4] ?? 0);
2155 Logger::log('API: api_statuses_destroy: '.$id);
2157 $ret = api_statuses_show($type);
2159 Item::deleteForUser(['id' => $id], api_user());
2164 /// @TODO move to top of file or somewhere better
2165 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2168 * Returns the most recent mentions.
2170 * @param string $type Return type (atom, rss, xml, json)
2172 * @return array|string
2173 * @throws BadRequestException
2174 * @throws ForbiddenException
2175 * @throws ImagickException
2176 * @throws InternalServerErrorException
2177 * @throws UnauthorizedException
2178 * @see http://developer.twitter.com/doc/get/statuses/mentions
2180 function api_statuses_mentions($type)
2183 $user_info = api_get_user($a);
2185 if (api_user() === false || $user_info === false) {
2186 throw new ForbiddenException();
2189 unset($_REQUEST["user_id"]);
2190 unset($_GET["user_id"]);
2192 unset($_REQUEST["screen_name"]);
2193 unset($_GET["screen_name"]);
2195 // get last network messages
2198 $since_id = intval($_REQUEST['since_id'] ?? 0);
2199 $max_id = intval($_REQUEST['max_id'] ?? 0);
2200 $count = intval($_REQUEST['count'] ?? 20);
2201 $page = intval($_REQUEST['page'] ?? 1);
2203 $start = max(0, ($page - 1) * $count);
2205 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2206 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2207 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2209 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2210 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2211 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2212 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2213 api_user(), $since_id];
2216 $query .= " AND `id` <= ?";
2217 $condition[] = $max_id;
2220 array_unshift($condition, $query);
2222 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2223 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2225 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2227 $data = ['status' => $ret];
2232 $data = api_rss_extra($a, $data, $user_info);
2236 return api_format_data("statuses", $type, $data);
2239 /// @TODO move to top of file or somewhere better
2240 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2241 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2244 * Returns the most recent statuses posted by the user.
2246 * @param string $type Either "json" or "xml"
2247 * @return string|array
2248 * @throws BadRequestException
2249 * @throws ForbiddenException
2250 * @throws ImagickException
2251 * @throws InternalServerErrorException
2252 * @throws UnauthorizedException
2253 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2255 function api_statuses_user_timeline($type)
2258 $user_info = api_get_user($a);
2260 if (api_user() === false || $user_info === false) {
2261 throw new ForbiddenException();
2264 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2266 $since_id = $_REQUEST['since_id'] ?? 0;
2267 $max_id = $_REQUEST['max_id'] ?? 0;
2268 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2269 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2272 $count = $_REQUEST['count'] ?? 20;
2273 $page = $_REQUEST['page'] ?? 1;
2275 $start = max(0, ($page - 1) * $count);
2277 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2278 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2280 if ($user_info['self'] == 1) {
2281 $condition[0] .= ' AND `wall` ';
2284 if ($exclude_replies) {
2285 $condition[0] .= ' AND `gravity` = ?';
2286 $condition[] = GRAVITY_PARENT;
2289 if ($conversation_id > 0) {
2290 $condition[0] .= " AND `parent` = ?";
2291 $condition[] = $conversation_id;
2295 $condition[0] .= " AND `id` <= ?";
2296 $condition[] = $max_id;
2298 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2299 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2301 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2305 $data = ['status' => $ret];
2310 $data = api_rss_extra($a, $data, $user_info);
2314 return api_format_data("statuses", $type, $data);
2317 /// @TODO move to top of file or somewhere better
2318 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2321 * Star/unstar an item.
2322 * param: id : id of the item
2324 * @param string $type Return type (atom, rss, xml, json)
2326 * @return array|string
2327 * @throws BadRequestException
2328 * @throws ForbiddenException
2329 * @throws ImagickException
2330 * @throws InternalServerErrorException
2331 * @throws UnauthorizedException
2332 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2334 function api_favorites_create_destroy($type)
2338 if (api_user() === false) {
2339 throw new ForbiddenException();
2342 // for versioned api.
2343 /// @TODO We need a better global soluton
2344 $action_argv_id = 2;
2345 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2346 $action_argv_id = 3;
2349 if ($a->argc <= $action_argv_id) {
2350 throw new BadRequestException("Invalid request.");
2352 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2353 if ($a->argc == $action_argv_id + 2) {
2354 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2356 $itemid = intval($_REQUEST['id'] ?? 0);
2359 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2361 if (!DBA::isResult($item)) {
2362 throw new BadRequestException("Invalid item.");
2367 $item['starred'] = 1;
2370 $item['starred'] = 0;
2373 throw new BadRequestException("Invalid action ".$action);
2376 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2379 throw new InternalServerErrorException("DB error");
2383 $user_info = api_get_user($a);
2384 $rets = api_format_items([$item], $user_info, false, $type);
2387 $data = ['status' => $ret];
2392 $data = api_rss_extra($a, $data, $user_info);
2396 return api_format_data("status", $type, $data);
2399 /// @TODO move to top of file or somewhere better
2400 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2401 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2404 * Returns the most recent favorite statuses.
2406 * @param string $type Return type (atom, rss, xml, json)
2408 * @return string|array
2409 * @throws BadRequestException
2410 * @throws ForbiddenException
2411 * @throws ImagickException
2412 * @throws InternalServerErrorException
2413 * @throws UnauthorizedException
2415 function api_favorites($type)
2420 $user_info = api_get_user($a);
2422 if (api_user() === false || $user_info === false) {
2423 throw new ForbiddenException();
2428 // in friendica starred item are private
2429 // return favorites only for self
2430 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2432 if ($user_info['self'] == 0) {
2436 $since_id = $_REQUEST['since_id'] ?? 0;
2437 $max_id = $_REQUEST['max_id'] ?? 0;
2438 $count = $_GET['count'] ?? 20;
2439 $page = $_REQUEST['page'] ?? 1;
2441 $start = max(0, ($page - 1) * $count);
2443 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2444 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2446 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2449 $condition[0] .= " AND `id` <= ?";
2450 $condition[] = $max_id;
2453 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2455 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2460 $data = ['status' => $ret];
2465 $data = api_rss_extra($a, $data, $user_info);
2469 return api_format_data("statuses", $type, $data);
2472 /// @TODO move to top of file or somewhere better
2473 api_register_func('api/favorites', 'api_favorites', true);
2477 * @param array $item
2478 * @param array $recipient
2479 * @param array $sender
2482 * @throws InternalServerErrorException
2484 function api_format_messages($item, $recipient, $sender)
2486 // standard meta information
2488 'id' => $item['id'],
2489 'sender_id' => $sender['id'],
2491 'recipient_id' => $recipient['id'],
2492 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2493 'sender_screen_name' => $sender['screen_name'],
2494 'recipient_screen_name' => $recipient['screen_name'],
2495 'sender' => $sender,
2496 'recipient' => $recipient,
2498 'friendica_seen' => $item['seen'] ?? 0,
2499 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2502 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2503 if (isset($ret['sender']['uid'])) {
2504 unset($ret['sender']['uid']);
2506 if (isset($ret['sender']['self'])) {
2507 unset($ret['sender']['self']);
2509 if (isset($ret['recipient']['uid'])) {
2510 unset($ret['recipient']['uid']);
2512 if (isset($ret['recipient']['self'])) {
2513 unset($ret['recipient']['self']);
2516 //don't send title to regular StatusNET requests to avoid confusing these apps
2517 if (!empty($_GET['getText'])) {
2518 $ret['title'] = $item['title'];
2519 if ($_GET['getText'] == 'html') {
2520 $ret['text'] = BBCode::convert($item['body'], false);
2521 } elseif ($_GET['getText'] == 'plain') {
2522 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2525 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2527 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2528 unset($ret['sender']);
2529 unset($ret['recipient']);
2537 * @param array $item
2540 * @throws InternalServerErrorException
2542 function api_convert_item($item)
2544 $body = api_add_attachments_to_body($item);
2546 $entities = api_get_entitities($statustext, $body);
2548 // Add pictures to the attachment array and remove them from the body
2549 $attachments = api_get_attachments($body);
2551 // Workaround for ostatus messages where the title is identically to the body
2552 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2553 $statusbody = trim(HTML::toPlaintext($html, 0));
2555 // handle data: images
2556 $statusbody = api_format_items_embeded_images($item, $statusbody);
2558 $statustitle = trim($item['title']);
2560 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2561 $statustext = trim($statusbody);
2563 $statustext = trim($statustitle."\n\n".$statusbody);
2566 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2567 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2570 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false, BBCode::API, true);
2572 // Workaround for clients with limited HTML parser functionality
2573 $search = ["<br>", "<blockquote>", "</blockquote>",
2574 "<h1>", "</h1>", "<h2>", "</h2>",
2575 "<h3>", "</h3>", "<h4>", "</h4>",
2576 "<h5>", "</h5>", "<h6>", "</h6>"];
2577 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2578 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2579 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2580 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2581 $statushtml = str_replace($search, $replace, $statushtml);
2583 if ($item['title'] != "") {
2584 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2588 $oldtext = $statushtml;
2589 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2590 } while ($oldtext != $statushtml);
2592 if (substr($statushtml, 0, 4) == '<br>') {
2593 $statushtml = substr($statushtml, 4);
2596 if (substr($statushtml, 0, -4) == '<br>') {
2597 $statushtml = substr($statushtml, -4);
2600 // feeds without body should contain the link
2601 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2602 $statushtml .= BBCode::convert($item['plink']);
2606 "text" => $statustext,
2607 "html" => $statushtml,
2608 "attachments" => $attachments,
2609 "entities" => $entities
2614 * Add media attachments to the body
2616 * @param array $item
2617 * @return string body with added media
2619 function api_add_attachments_to_body(array $item)
2621 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2623 if (strpos($body, '[/img]') !== false) {
2627 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2628 if (!empty($media['preview'])) {
2629 $description = $media['description'] ?: $media['name'];
2630 if (!empty($description)) {
2631 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2633 $body .= "\n[img]" . $media['preview'] .'[/img]';
2643 * @param string $body
2646 * @throws InternalServerErrorException
2648 function api_get_attachments(&$body)
2650 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2651 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2653 $URLSearchString = "^\[\]";
2654 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2658 // Remove all embedded pictures, since they are added as attachments
2659 foreach ($images[0] as $orig) {
2660 $body = str_replace($orig, '', $body);
2665 foreach ($images[1] as $image) {
2666 $imagedata = Images::getInfoFromURLCached($image);
2669 if (DI::config()->get("system", "proxy_disabled")) {
2670 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2672 $attachments[] = ["url" => ProxyUtils::proxifyUrl($image, false), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2677 return $attachments;
2682 * @param string $text
2683 * @param string $bbcode
2686 * @throws InternalServerErrorException
2687 * @todo Links at the first character of the post
2689 function api_get_entitities(&$text, $bbcode)
2691 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2693 if ($include_entities != "true") {
2694 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2696 foreach ($images[1] as $image) {
2697 $replace = ProxyUtils::proxifyUrl($image, false);
2698 $text = str_replace($image, $replace, $text);
2703 $bbcode = BBCode::cleanPictureLinks($bbcode);
2705 // Change pure links in text to bbcode uris
2706 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2709 $entities["hashtags"] = [];
2710 $entities["symbols"] = [];
2711 $entities["urls"] = [];
2712 $entities["user_mentions"] = [];
2714 $URLSearchString = "^\[\]";
2716 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2718 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2719 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2721 $bbcode = preg_replace(
2722 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2723 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2726 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2728 $bbcode = preg_replace(
2729 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2730 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2733 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2735 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2737 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2740 foreach ($urls[1] as $id => $url) {
2741 $start = iconv_strpos($text, $url, 0, "UTF-8");
2742 if (!($start === false)) {
2743 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2747 ksort($ordered_urls);
2751 foreach ($ordered_urls as $url) {
2752 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2753 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2755 $display_url = $url["title"];
2757 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2758 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2760 if (strlen($display_url) > 26) {
2761 $display_url = substr($display_url, 0, 25)."…";
2765 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2766 if (!($start === false)) {
2767 $entities["urls"][] = ["url" => $url["url"],
2768 "expanded_url" => $url["url"],
2769 "display_url" => $display_url,
2770 "indices" => [$start, $start+strlen($url["url"])]];
2771 $offset = $start + 1;
2775 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2776 $ordered_images = [];
2777 foreach ($images as $image) {
2778 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2779 if (!($start === false)) {
2780 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2784 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2785 foreach ($images[1] as $image) {
2786 $start = iconv_strpos($text, $image, 0, "UTF-8");
2787 if (!($start === false)) {
2788 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2794 foreach ($ordered_images as $image) {
2795 $url = $image['url'];
2796 $ext_alt_text = $image['alt'];
2798 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2799 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2801 if (strlen($display_url) > 26) {
2802 $display_url = substr($display_url, 0, 25)."…";
2805 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2806 if (!($start === false)) {
2807 $image = Images::getInfoFromURLCached($url);
2809 // If image cache is activated, then use the following sizes:
2810 // thumb (150), small (340), medium (600) and large (1024)
2811 if (!DI::config()->get("system", "proxy_disabled")) {
2812 $media_url = ProxyUtils::proxifyUrl($url, false);
2815 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2816 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2818 if (($image[0] > 150) || ($image[1] > 150)) {
2819 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2820 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2823 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2824 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2826 if (($image[0] > 600) || ($image[1] > 600)) {
2827 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2828 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2832 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2835 $entities["media"][] = [
2837 "id_str" => (string) ($start + 1),
2838 "indices" => [$start, $start+strlen($url)],
2839 "media_url" => Strings::normaliseLink($media_url),
2840 "media_url_https" => $media_url,
2842 "display_url" => $display_url,
2843 "expanded_url" => $url,
2844 "ext_alt_text" => $ext_alt_text,
2848 $offset = $start + 1;
2857 * @param array $item
2858 * @param string $text
2862 function api_format_items_embeded_images($item, $text)
2864 $text = preg_replace_callback(
2865 '|data:image/([^;]+)[^=]+=*|m',
2866 function () use ($item) {
2867 return DI::baseUrl() . '/display/' . $item['guid'];
2875 * return <a href='url'>name</a> as array
2877 * @param string $txt text
2882 function api_contactlink_to_array($txt)
2885 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2886 if ($r && count($match)==3) {
2888 'name' => $match[2],
2902 * return likes, dislikes and attend status for item
2904 * @param array $item array
2905 * @param string $type Return type (atom, rss, xml, json)
2908 * likes => int count,
2909 * dislikes => int count
2910 * @throws BadRequestException
2911 * @throws ImagickException
2912 * @throws InternalServerErrorException
2913 * @throws UnauthorizedException
2915 function api_format_items_activities($item, $type = "json")
2924 'attendmaybe' => [],
2928 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2929 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2931 while ($parent_item = Post::fetch($ret)) {
2932 // not used as result should be structured like other user data
2933 //builtin_activity_puller($i, $activities);
2935 // get user data and add it to the array of the activity
2936 $user = api_get_user($a, $parent_item['author-id']);
2937 switch ($parent_item['verb']) {
2938 case Activity::LIKE:
2939 $activities['like'][] = $user;
2941 case Activity::DISLIKE:
2942 $activities['dislike'][] = $user;
2944 case Activity::ATTEND:
2945 $activities['attendyes'][] = $user;
2947 case Activity::ATTENDNO:
2948 $activities['attendno'][] = $user;
2950 case Activity::ATTENDMAYBE:
2951 $activities['attendmaybe'][] = $user;
2953 case Activity::ANNOUNCE:
2954 $activities['announce'][] = $user;
2963 if ($type == "xml") {
2964 $xml_activities = [];
2965 foreach ($activities as $k => $v) {
2966 // change xml element from "like" to "friendica:like"
2967 $xml_activities["friendica:".$k] = $v;
2968 // add user data into xml output
2970 foreach ($v as $user) {
2971 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2974 $activities = $xml_activities;
2981 * format items to be returned by api
2983 * @param array $items array of items
2984 * @param array $user_info
2985 * @param bool $filter_user filter items by $user_info
2986 * @param string $type Return type (atom, rss, xml, json)
2988 * @throws BadRequestException
2989 * @throws ImagickException
2990 * @throws InternalServerErrorException
2991 * @throws UnauthorizedException
2993 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2995 $a = Friendica\DI::app();
2999 if (empty($items)) {
3003 foreach ((array)$items as $item) {
3004 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3006 // Look if the posts are matching if they should be filtered by user id
3007 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3011 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3020 * @param array $item Item record
3021 * @param string $type Return format (atom, rss, xml, json)
3022 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3023 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3024 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3025 * @return array API-formatted status
3026 * @throws BadRequestException
3027 * @throws ImagickException
3028 * @throws InternalServerErrorException
3029 * @throws UnauthorizedException
3031 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3033 $a = Friendica\DI::app();
3035 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3036 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3039 localize_item($item);
3041 $in_reply_to = api_in_reply_to($item);
3043 $converted = api_convert_item($item);
3045 if ($type == "xml") {
3046 $geo = "georss:point";
3052 'text' => $converted["text"],
3053 'truncated' => false,
3054 'created_at'=> api_date($item['created']),
3055 'in_reply_to_status_id' => $in_reply_to['status_id'],
3056 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3057 'source' => (($item['app']) ? $item['app'] : 'web'),
3058 'id' => intval($item['id']),
3059 'id_str' => (string) intval($item['id']),
3060 'in_reply_to_user_id' => $in_reply_to['user_id'],
3061 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3062 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3064 'favorited' => $item['starred'] ? true : false,
3065 'user' => $status_user,
3066 'friendica_author' => $author_user,
3067 'friendica_owner' => $owner_user,
3068 'friendica_private' => $item['private'] == Item::PRIVATE,
3069 //'entities' => NULL,
3070 'statusnet_html' => $converted["html"],
3071 'statusnet_conversation_id' => $item['parent'],
3072 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3073 'friendica_activities' => api_format_items_activities($item, $type),
3074 'friendica_title' => $item['title'],
3075 'friendica_html' => BBCode::convert($item['body'], false)
3078 if (count($converted["attachments"]) > 0) {
3079 $status["attachments"] = $converted["attachments"];
3082 if (count($converted["entities"]) > 0) {
3083 $status["entities"] = $converted["entities"];
3086 if ($status["source"] == 'web') {
3087 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3088 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3089 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3092 $retweeted_item = [];
3095 if ($item['gravity'] == GRAVITY_PARENT) {
3096 $body = $item['body'];
3097 $retweeted_item = api_share_as_retweet($item);
3098 if ($body != $item['body']) {
3099 $quoted_item = $retweeted_item;
3100 $retweeted_item = [];
3104 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3105 $announce = api_get_announce($item);
3106 if (!empty($announce)) {
3107 $retweeted_item = $item;
3109 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3113 if (!empty($quoted_item)) {
3114 if ($quoted_item['id'] != $item['id']) {
3115 $quoted_status = api_format_item($quoted_item);
3116 /// @todo Only remove the attachments that are also contained in the quotes status
3117 unset($status['attachments']);
3118 unset($status['entities']);
3120 $conv_quoted = api_convert_item($quoted_item);
3121 $quoted_status = $status;
3122 unset($quoted_status['attachments']);
3123 unset($quoted_status['entities']);
3124 unset($quoted_status['statusnet_conversation_id']);
3125 $quoted_status['text'] = $conv_quoted['text'];
3126 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3128 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3129 } catch (BadRequestException $e) {
3130 // user not found. should be found?
3131 /// @todo check if the user should be always found
3132 $quoted_status["user"] = [];
3135 unset($quoted_status['friendica_author']);
3136 unset($quoted_status['friendica_owner']);
3137 unset($quoted_status['friendica_activities']);
3138 unset($quoted_status['friendica_private']);
3141 if (!empty($retweeted_item)) {
3142 $retweeted_status = $status;
3143 unset($retweeted_status['friendica_author']);
3144 unset($retweeted_status['friendica_owner']);
3145 unset($retweeted_status['friendica_activities']);
3146 unset($retweeted_status['friendica_private']);
3147 unset($retweeted_status['statusnet_conversation_id']);
3148 $status['user'] = $status['friendica_owner'];
3150 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3151 } catch (BadRequestException $e) {
3152 // user not found. should be found?
3153 /// @todo check if the user should be always found
3154 $retweeted_status["user"] = [];
3157 $rt_converted = api_convert_item($retweeted_item);
3159 $retweeted_status['text'] = $rt_converted["text"];
3160 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3161 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3163 if (!empty($quoted_status)) {
3164 $retweeted_status['quoted_status'] = $quoted_status;
3167 $status['friendica_author'] = $retweeted_status['user'];
3168 $status['retweeted_status'] = $retweeted_status;
3169 } elseif (!empty($quoted_status)) {
3170 $root_status = api_convert_item($item);
3172 $status['text'] = $root_status["text"];
3173 $status['statusnet_html'] = $root_status["html"];
3174 $status['quoted_status'] = $quoted_status;
3177 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3178 unset($status["user"]["uid"]);
3179 unset($status["user"]["self"]);
3181 if ($item["coord"] != "") {
3182 $coords = explode(' ', $item["coord"]);
3183 if (count($coords) == 2) {
3184 if ($type == "json") {
3185 $status["geo"] = ['type' => 'Point',
3186 'coordinates' => [(float) $coords[0],
3187 (float) $coords[1]]];
3188 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3189 $status["georss:point"] = $item["coord"];
3198 * Returns the remaining number of API requests available to the user before the API limit is reached.
3200 * @param string $type Return type (atom, rss, xml, json)
3202 * @return array|string
3205 function api_account_rate_limit_status($type)
3207 if ($type == "xml") {
3209 'remaining-hits' => '150',
3210 '@attributes' => ["type" => "integer"],
3211 'hourly-limit' => '150',
3212 '@attributes2' => ["type" => "integer"],
3213 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3214 '@attributes3' => ["type" => "datetime"],
3215 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3216 '@attributes4' => ["type" => "integer"],
3220 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3221 'remaining_hits' => '150',
3222 'hourly_limit' => '150',
3223 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3227 return api_format_data('hash', $type, ['hash' => $hash]);
3230 /// @TODO move to top of file or somewhere better
3231 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3234 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3236 * @param string $type Return type (atom, rss, xml, json)
3238 * @return array|string
3240 function api_help_test($type)
3242 if ($type == 'xml') {
3248 return api_format_data('ok', $type, ["ok" => $ok]);
3251 /// @TODO move to top of file or somewhere better
3252 api_register_func('api/help/test', 'api_help_test', false);
3255 * Returns all lists the user subscribes to.
3257 * @param string $type Return type (atom, rss, xml, json)
3259 * @return array|string
3260 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3262 function api_lists_list($type)
3265 /// @TODO $ret is not filled here?
3266 return api_format_data('lists', $type, ["lists_list" => $ret]);
3269 /// @TODO move to top of file or somewhere better
3270 api_register_func('api/lists/list', 'api_lists_list', true);
3271 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3274 * Returns all groups the user owns.
3276 * @param string $type Return type (atom, rss, xml, json)
3278 * @return array|string
3279 * @throws BadRequestException
3280 * @throws ForbiddenException
3281 * @throws ImagickException
3282 * @throws InternalServerErrorException
3283 * @throws UnauthorizedException
3284 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3286 function api_lists_ownerships($type)
3290 if (api_user() === false) {
3291 throw new ForbiddenException();
3295 $user_info = api_get_user($a);
3296 $uid = $user_info['uid'];
3298 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3300 // loop through all groups
3302 foreach ($groups as $group) {
3303 if ($group['visible']) {
3309 'name' => $group['name'],
3310 'id' => intval($group['id']),
3311 'id_str' => (string) $group['id'],
3312 'user' => $user_info,
3316 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3319 /// @TODO move to top of file or somewhere better
3320 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3323 * Returns recent statuses from users in the specified group.
3325 * @param string $type Return type (atom, rss, xml, json)
3327 * @return array|string
3328 * @throws BadRequestException
3329 * @throws ForbiddenException
3330 * @throws ImagickException
3331 * @throws InternalServerErrorException
3332 * @throws UnauthorizedException
3333 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3335 function api_lists_statuses($type)
3339 $user_info = api_get_user($a);
3340 if (api_user() === false || $user_info === false) {
3341 throw new ForbiddenException();
3344 unset($_REQUEST["user_id"]);
3345 unset($_GET["user_id"]);
3347 unset($_REQUEST["screen_name"]);
3348 unset($_GET["screen_name"]);
3350 if (empty($_REQUEST['list_id'])) {
3351 throw new BadRequestException('list_id not specified');
3355 $count = $_REQUEST['count'] ?? 20;
3356 $page = $_REQUEST['page'] ?? 1;
3357 $since_id = $_REQUEST['since_id'] ?? 0;
3358 $max_id = $_REQUEST['max_id'] ?? 0;
3359 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3360 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3362 $start = max(0, ($page - 1) * $count);
3364 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3365 $gids = array_column($groups, 'contact-id');
3366 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3367 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3370 $condition[0] .= " AND `id` <= ?";
3371 $condition[] = $max_id;
3373 if ($exclude_replies > 0) {
3374 $condition[0] .= ' AND `gravity` = ?';
3375 $condition[] = GRAVITY_PARENT;
3377 if ($conversation_id > 0) {
3378 $condition[0] .= " AND `parent` = ?";
3379 $condition[] = $conversation_id;
3382 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3383 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3385 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3387 $data = ['status' => $items];
3392 $data = api_rss_extra($a, $data, $user_info);
3396 return api_format_data("statuses", $type, $data);
3399 /// @TODO move to top of file or somewhere better
3400 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3403 * Returns either the friends of the follower list
3405 * Considers friends and followers lists to be private and won't return
3406 * anything if any user_id parameter is passed.
3408 * @param string $qtype Either "friends" or "followers"
3409 * @return boolean|array
3410 * @throws BadRequestException
3411 * @throws ForbiddenException
3412 * @throws ImagickException
3413 * @throws InternalServerErrorException
3414 * @throws UnauthorizedException
3416 function api_statuses_f($qtype)
3420 if (api_user() === false) {
3421 throw new ForbiddenException();
3425 $count = $_GET['count'] ?? 20;
3426 $page = $_GET['page'] ?? 1;
3428 $start = max(0, ($page - 1) * $count);
3430 $user_info = api_get_user($a);
3432 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3433 /* this is to stop Hotot to load friends multiple times
3434 * I'm not sure if I'm missing return something or
3435 * is a bug in hotot. Workaround, meantime
3439 return array('$users' => $ret);*/
3444 if ($qtype == 'friends') {
3445 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3446 } elseif ($qtype == 'followers') {
3447 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3450 // friends and followers only for self
3451 if ($user_info['self'] == 0) {
3452 $sql_extra = " AND false ";
3455 if ($qtype == 'blocks') {
3456 $sql_filter = 'AND `blocked` AND NOT `pending`';
3457 } elseif ($qtype == 'incoming') {
3458 $sql_filter = 'AND `pending`';
3460 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3478 foreach ($r as $cid) {
3479 $user = api_get_user($a, $cid['nurl']);
3480 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3481 unset($user["uid"]);
3482 unset($user["self"]);
3489 return ['user' => $ret];
3494 * Returns the list of friends of the provided user
3496 * @deprecated By Twitter API in favor of friends/list
3498 * @param string $type Either "json" or "xml"
3499 * @return boolean|string|array
3500 * @throws BadRequestException
3501 * @throws ForbiddenException
3503 function api_statuses_friends($type)
3505 $data = api_statuses_f("friends");
3506 if ($data === false) {
3509 return api_format_data("users", $type, $data);
3513 * Returns the list of followers of the provided user
3515 * @deprecated By Twitter API in favor of friends/list
3517 * @param string $type Either "json" or "xml"
3518 * @return boolean|string|array
3519 * @throws BadRequestException
3520 * @throws ForbiddenException
3522 function api_statuses_followers($type)
3524 $data = api_statuses_f("followers");
3525 if ($data === false) {
3528 return api_format_data("users", $type, $data);
3531 /// @TODO move to top of file or somewhere better
3532 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3533 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3536 * Returns the list of blocked users
3538 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3540 * @param string $type Either "json" or "xml"
3542 * @return boolean|string|array
3543 * @throws BadRequestException
3544 * @throws ForbiddenException
3546 function api_blocks_list($type)
3548 $data = api_statuses_f('blocks');
3549 if ($data === false) {
3552 return api_format_data("users", $type, $data);
3555 /// @TODO move to top of file or somewhere better
3556 api_register_func('api/blocks/list', 'api_blocks_list', true);
3559 * Returns the list of pending users IDs
3561 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3563 * @param string $type Either "json" or "xml"
3565 * @return boolean|string|array
3566 * @throws BadRequestException
3567 * @throws ForbiddenException
3569 function api_friendships_incoming($type)
3571 $data = api_statuses_f('incoming');
3572 if ($data === false) {
3577 foreach ($data['user'] as $user) {
3578 $ids[] = $user['id'];
3581 return api_format_data("ids", $type, ['id' => $ids]);
3584 /// @TODO move to top of file or somewhere better
3585 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3588 * Returns the instance's configuration information.
3590 * @param string $type Return type (atom, rss, xml, json)
3592 * @return array|string
3593 * @throws InternalServerErrorException
3595 function api_statusnet_config($type)
3597 $name = DI::config()->get('config', 'sitename');
3598 $server = DI::baseUrl()->getHostname();
3599 $logo = DI::baseUrl() . '/images/friendica-64.png';
3600 $email = DI::config()->get('config', 'admin_email');
3601 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3602 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3603 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3604 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3605 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3608 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3609 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3610 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3611 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3612 'shorturllength' => '30',
3614 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3615 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3616 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3617 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3622 return api_format_data('config', $type, ['config' => $config]);
3625 /// @TODO move to top of file or somewhere better
3626 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3627 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3631 * @param string $type Return type (atom, rss, xml, json)
3633 * @return array|string
3635 function api_statusnet_version($type)
3638 $fake_statusnet_version = "0.9.7";
3640 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3643 /// @TODO move to top of file or somewhere better
3644 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3645 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3648 * Sends a new direct message.
3650 * @param string $type Return type (atom, rss, xml, json)
3652 * @return array|string
3653 * @throws BadRequestException
3654 * @throws ForbiddenException
3655 * @throws ImagickException
3656 * @throws InternalServerErrorException
3657 * @throws NotFoundException
3658 * @throws UnauthorizedException
3659 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3661 function api_direct_messages_new($type)
3665 if (api_user() === false) {
3666 throw new ForbiddenException();
3669 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3673 $sender = api_get_user($a);
3676 if (!empty($_POST['screen_name'])) {
3678 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3680 DBA::escape($_POST['screen_name'])
3683 if (DBA::isResult($r)) {
3684 // Selecting the id by priority, friendica first
3685 api_best_nickname($r);
3687 $recipient = api_get_user($a, $r[0]['nurl']);
3690 $recipient = api_get_user($a, $_POST['user_id']);
3693 if (empty($recipient)) {
3694 throw new NotFoundException('Recipient not found');
3698 if (!empty($_REQUEST['replyto'])) {
3700 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3702 intval($_REQUEST['replyto'])
3704 $replyto = $r[0]['parent-uri'];
3705 $sub = $r[0]['title'];
3707 if (!empty($_REQUEST['title'])) {
3708 $sub = $_REQUEST['title'];
3710 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3714 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3717 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3718 $ret = api_format_messages($r[0], $recipient, $sender);
3720 $ret = ["error"=>$id];
3723 $data = ['direct_message'=>$ret];
3729 $data = api_rss_extra($a, $data, $sender);
3733 return api_format_data("direct-messages", $type, $data);
3736 /// @TODO move to top of file or somewhere better
3737 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3740 * delete a direct_message from mail table through api
3742 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3743 * @return string|array
3744 * @throws BadRequestException
3745 * @throws ForbiddenException
3746 * @throws ImagickException
3747 * @throws InternalServerErrorException
3748 * @throws UnauthorizedException
3749 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3751 function api_direct_messages_destroy($type)
3755 if (api_user() === false) {
3756 throw new ForbiddenException();
3760 $user_info = api_get_user($a);
3762 $id = $_REQUEST['id'] ?? 0;
3764 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3765 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3766 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3768 $uid = $user_info['uid'];
3769 // error if no id or parenturi specified (for clients posting parent-uri as well)
3770 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3771 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3772 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3775 // BadRequestException if no id specified (for clients using Twitter API)
3777 throw new BadRequestException('Message id not specified');
3780 // add parent-uri to sql command if specified by calling app
3781 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3783 // get data of the specified message id
3785 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3790 // error message if specified id is not in database
3791 if (!DBA::isResult($r)) {
3792 if ($verbose == "true") {
3793 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3794 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3796 /// @todo BadRequestException ok for Twitter API clients?
3797 throw new BadRequestException('message id not in database');
3802 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3807 if ($verbose == "true") {
3810 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3811 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3813 $answer = ['result' => 'error', 'message' => 'unknown error'];
3814 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3817 /// @todo return JSON data like Twitter API not yet implemented
3820 /// @TODO move to top of file or somewhere better
3821 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3826 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3827 * @return string|array
3828 * @throws BadRequestException
3829 * @throws ForbiddenException
3830 * @throws ImagickException
3831 * @throws InternalServerErrorException
3832 * @throws NotFoundException
3833 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3835 function api_friendships_destroy($type)
3839 if ($uid === false) {
3840 throw new ForbiddenException();
3843 $contact_id = $_REQUEST['user_id'] ?? 0;
3845 if (empty($contact_id)) {
3846 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3847 throw new BadRequestException("no user_id specified");
3850 // Get Contact by given id
3851 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3853 if(!DBA::isResult($contact)) {
3854 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3855 throw new NotFoundException("no contact found to given ID");
3858 $url = $contact["url"];
3860 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3861 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3862 Strings::normaliseLink($url), $url];
3863 $contact = DBA::selectFirst('contact', [], $condition);
3865 if (!DBA::isResult($contact)) {
3866 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3867 throw new NotFoundException("Not following Contact");
3870 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3871 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3872 throw new ExpectationFailedException("Not supported");
3875 $dissolve = ($contact['rel'] == Contact::SHARING);
3877 $owner = User::getOwnerDataById($uid);
3879 Contact::terminateFriendship($owner, $contact, $dissolve);
3882 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3883 throw new NotFoundException("Error Processing Request");
3886 // Sharing-only contacts get deleted as there no relationship any more
3888 Contact::remove($contact['id']);
3890 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3893 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3894 unset($contact["uid"]);
3895 unset($contact["self"]);
3897 // Set screen_name since Twidere requests it
3898 $contact["screen_name"] = $contact["nick"];
3900 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3902 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3906 * @param string $type Return type (atom, rss, xml, json)
3907 * @param string $box
3908 * @param string $verbose
3910 * @return array|string
3911 * @throws BadRequestException
3912 * @throws ForbiddenException
3913 * @throws ImagickException
3914 * @throws InternalServerErrorException
3915 * @throws UnauthorizedException
3917 function api_direct_messages_box($type, $box, $verbose)
3920 if (api_user() === false) {
3921 throw new ForbiddenException();
3924 $count = $_GET['count'] ?? 20;
3925 $page = $_REQUEST['page'] ?? 1;
3927 $since_id = $_REQUEST['since_id'] ?? 0;
3928 $max_id = $_REQUEST['max_id'] ?? 0;
3930 $user_id = $_REQUEST['user_id'] ?? '';
3931 $screen_name = $_REQUEST['screen_name'] ?? '';
3934 unset($_REQUEST["user_id"]);
3935 unset($_GET["user_id"]);
3937 unset($_REQUEST["screen_name"]);
3938 unset($_GET["screen_name"]);
3940 $user_info = api_get_user($a);
3941 if ($user_info === false) {
3942 throw new ForbiddenException();
3944 $profile_url = $user_info["url"];
3947 $start = max(0, ($page - 1) * $count);
3952 if ($box=="sentbox") {
3953 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3954 } elseif ($box == "conversation") {
3955 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3956 } elseif ($box == "all") {
3957 $sql_extra = "true";
3958 } elseif ($box == "inbox") {
3959 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3963 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3966 if ($user_id != "") {
3967 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3968 } elseif ($screen_name !="") {
3969 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3973 "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",
3979 if ($verbose == "true" && !DBA::isResult($r)) {
3980 $answer = ['result' => 'error', 'message' => 'no mails available'];
3981 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3985 foreach ($r as $item) {
3986 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3987 $recipient = $user_info;
3988 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3989 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3990 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3991 $sender = $user_info;
3994 if (isset($recipient) && isset($sender)) {
3995 $ret[] = api_format_messages($item, $recipient, $sender);
4000 $data = ['direct_message' => $ret];
4005 $data = api_rss_extra($a, $data, $user_info);
4009 return api_format_data("direct-messages", $type, $data);
4013 * Returns the most recent direct messages sent by the user.
4015 * @param string $type Return type (atom, rss, xml, json)
4017 * @return array|string
4018 * @throws BadRequestException
4019 * @throws ForbiddenException
4020 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4022 function api_direct_messages_sentbox($type)
4024 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4025 return api_direct_messages_box($type, "sentbox", $verbose);
4029 * Returns the most recent direct messages sent to the user.
4031 * @param string $type Return type (atom, rss, xml, json)
4033 * @return array|string
4034 * @throws BadRequestException
4035 * @throws ForbiddenException
4036 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4038 function api_direct_messages_inbox($type)
4040 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4041 return api_direct_messages_box($type, "inbox", $verbose);
4046 * @param string $type Return type (atom, rss, xml, json)
4048 * @return array|string
4049 * @throws BadRequestException
4050 * @throws ForbiddenException
4052 function api_direct_messages_all($type)
4054 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4055 return api_direct_messages_box($type, "all", $verbose);
4060 * @param string $type Return type (atom, rss, xml, json)
4062 * @return array|string
4063 * @throws BadRequestException
4064 * @throws ForbiddenException
4066 function api_direct_messages_conversation($type)
4068 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4069 return api_direct_messages_box($type, "conversation", $verbose);
4072 /// @TODO move to top of file or somewhere better
4073 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4074 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4075 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4076 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4079 * Returns an OAuth Request Token.
4081 * @see https://oauth.net/core/1.0/#auth_step1
4083 function api_oauth_request_token()
4085 $oauth1 = new FKOAuth1();
4087 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4088 } catch (Exception $e) {
4089 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4097 * Returns an OAuth Access Token.
4099 * @return array|string
4100 * @see https://oauth.net/core/1.0/#auth_step3
4102 function api_oauth_access_token()
4104 $oauth1 = new FKOAuth1();
4106 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4107 } catch (Exception $e) {
4108 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4115 /// @TODO move to top of file or somewhere better
4116 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4117 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4121 * delete a complete photoalbum with all containing photos from database through api
4123 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4124 * @return string|array
4125 * @throws BadRequestException
4126 * @throws ForbiddenException
4127 * @throws InternalServerErrorException
4129 function api_fr_photoalbum_delete($type)
4131 if (api_user() === false) {
4132 throw new ForbiddenException();
4135 $album = $_REQUEST['album'] ?? '';
4137 // we do not allow calls without album string
4139 throw new BadRequestException("no albumname specified");
4141 // check if album is existing
4143 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4144 if (!DBA::isResult($photos)) {
4145 throw new BadRequestException("album not available");
4148 $resourceIds = array_column($photos, 'resource-id');
4150 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4151 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4152 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4153 Item::deleteForUser($condition, api_user());
4155 // now let's delete all photos from the album
4156 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4158 // return success of deletion or error message
4160 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4161 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4163 throw new InternalServerErrorException("unknown error - deleting from database failed");
4168 * update the name of the album for all photos of an album
4170 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4171 * @return string|array
4172 * @throws BadRequestException
4173 * @throws ForbiddenException
4174 * @throws InternalServerErrorException
4176 function api_fr_photoalbum_update($type)
4178 if (api_user() === false) {
4179 throw new ForbiddenException();
4182 $album = $_REQUEST['album'] ?? '';
4183 $album_new = $_REQUEST['album_new'] ?? '';
4185 // we do not allow calls without album string
4187 throw new BadRequestException("no albumname specified");
4189 if ($album_new == "") {
4190 throw new BadRequestException("no new albumname specified");
4192 // check if album is existing
4193 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4194 throw new BadRequestException("album not available");
4196 // now let's update all photos to the albumname
4197 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4199 // return success of updating or error message
4201 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4202 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4204 throw new InternalServerErrorException("unknown error - updating in database failed");
4210 * list all photos of the authenticated user
4212 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4213 * @return string|array
4214 * @throws ForbiddenException
4215 * @throws InternalServerErrorException
4217 function api_fr_photos_list($type)
4219 if (api_user() === false) {
4220 throw new ForbiddenException();
4223 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4224 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4225 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4226 intval(local_user())
4229 'image/jpeg' => 'jpg',
4230 'image/png' => 'png',
4231 'image/gif' => 'gif'
4233 $data = ['photo'=>[]];
4234 if (DBA::isResult($r)) {
4235 foreach ($r as $rr) {
4237 $photo['id'] = $rr['resource-id'];
4238 $photo['album'] = $rr['album'];
4239 $photo['filename'] = $rr['filename'];
4240 $photo['type'] = $rr['type'];
4241 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4242 $photo['created'] = $rr['created'];
4243 $photo['edited'] = $rr['edited'];
4244 $photo['desc'] = $rr['desc'];
4246 if ($type == "xml") {
4247 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4249 $photo['thumb'] = $thumb;
4250 $data['photo'][] = $photo;
4254 return api_format_data("photos", $type, $data);
4258 * upload a new photo or change an existing photo
4260 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4261 * @return string|array
4262 * @throws BadRequestException
4263 * @throws ForbiddenException
4264 * @throws ImagickException
4265 * @throws InternalServerErrorException
4266 * @throws NotFoundException
4268 function api_fr_photo_create_update($type)
4270 if (api_user() === false) {
4271 throw new ForbiddenException();
4274 $photo_id = $_REQUEST['photo_id'] ?? null;
4275 $desc = $_REQUEST['desc'] ?? null;
4276 $album = $_REQUEST['album'] ?? null;
4277 $album_new = $_REQUEST['album_new'] ?? null;
4278 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4279 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4280 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4281 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4282 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4284 // do several checks on input parameters
4285 // we do not allow calls without album string
4286 if ($album == null) {
4287 throw new BadRequestException("no albumname specified");
4289 // if photo_id == null --> we are uploading a new photo
4290 if ($photo_id == null) {
4293 // error if no media posted in create-mode
4294 if (empty($_FILES['media'])) {
4296 throw new BadRequestException("no media data submitted");
4299 // album_new will be ignored in create-mode
4304 // check if photo is existing in databasei
4305 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4306 throw new BadRequestException("photo not available");
4310 // checks on acl strings provided by clients
4311 $acl_input_error = false;
4312 $acl_input_error |= check_acl_input($allow_cid);
4313 $acl_input_error |= check_acl_input($deny_cid);
4314 $acl_input_error |= check_acl_input($allow_gid);
4315 $acl_input_error |= check_acl_input($deny_gid);
4316 if ($acl_input_error) {
4317 throw new BadRequestException("acl data invalid");
4319 // now let's upload the new media in create-mode
4320 if ($mode == "create") {
4321 $media = $_FILES['media'];
4322 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4324 // return success of updating or error message
4325 if (!is_null($data)) {
4326 return api_format_data("photo_create", $type, $data);
4328 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4332 // now let's do the changes in update-mode
4333 if ($mode == "update") {
4334 $updated_fields = [];
4336 if (!is_null($desc)) {
4337 $updated_fields['desc'] = $desc;
4340 if (!is_null($album_new)) {
4341 $updated_fields['album'] = $album_new;
4344 if (!is_null($allow_cid)) {
4345 $allow_cid = trim($allow_cid);
4346 $updated_fields['allow_cid'] = $allow_cid;
4349 if (!is_null($deny_cid)) {
4350 $deny_cid = trim($deny_cid);
4351 $updated_fields['deny_cid'] = $deny_cid;
4354 if (!is_null($allow_gid)) {
4355 $allow_gid = trim($allow_gid);
4356 $updated_fields['allow_gid'] = $allow_gid;
4359 if (!is_null($deny_gid)) {
4360 $deny_gid = trim($deny_gid);
4361 $updated_fields['deny_gid'] = $deny_gid;
4365 if (count($updated_fields) > 0) {
4366 $nothingtodo = false;
4367 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4369 $nothingtodo = true;
4372 if (!empty($_FILES['media'])) {
4373 $nothingtodo = false;
4374 $media = $_FILES['media'];
4375 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4376 if (!is_null($data)) {
4377 return api_format_data("photo_update", $type, $data);
4381 // return success of updating or error message
4383 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4384 return api_format_data("photo_update", $type, ['$result' => $answer]);
4387 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4388 return api_format_data("photo_update", $type, ['$result' => $answer]);
4390 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4393 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4397 * delete a single photo from the database through api
4399 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4400 * @return string|array
4401 * @throws BadRequestException
4402 * @throws ForbiddenException
4403 * @throws InternalServerErrorException
4405 function api_fr_photo_delete($type)
4407 if (api_user() === false) {
4408 throw new ForbiddenException();
4412 $photo_id = $_REQUEST['photo_id'] ?? null;
4414 // do several checks on input parameters
4415 // we do not allow calls without photo id
4416 if ($photo_id == null) {
4417 throw new BadRequestException("no photo_id specified");
4420 // check if photo is existing in database
4421 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4422 throw new BadRequestException("photo not available");
4425 // now we can perform on the deletion of the photo
4426 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4428 // return success of deletion or error message
4430 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4431 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4432 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4433 Item::deleteForUser($condition, api_user());
4435 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4436 return api_format_data("photo_delete", $type, ['$result' => $result]);
4438 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4444 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4446 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4447 * @return string|array
4448 * @throws BadRequestException
4449 * @throws ForbiddenException
4450 * @throws InternalServerErrorException
4451 * @throws NotFoundException
4453 function api_fr_photo_detail($type)
4455 if (api_user() === false) {
4456 throw new ForbiddenException();
4458 if (empty($_REQUEST['photo_id'])) {
4459 throw new BadRequestException("No photo id.");
4462 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4463 $photo_id = $_REQUEST['photo_id'];
4465 // prepare json/xml output with data from database for the requested photo
4466 $data = prepare_photo_data($type, $scale, $photo_id);
4468 return api_format_data("photo_detail", $type, $data);
4473 * updates the profile image for the user (either a specified profile or the default profile)
4475 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4477 * @return string|array
4478 * @throws BadRequestException
4479 * @throws ForbiddenException
4480 * @throws ImagickException
4481 * @throws InternalServerErrorException
4482 * @throws NotFoundException
4483 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4485 function api_account_update_profile_image($type)
4487 if (api_user() === false) {
4488 throw new ForbiddenException();
4491 $profile_id = $_REQUEST['profile_id'] ?? 0;
4493 // error if image data is missing
4494 if (empty($_FILES['image'])) {
4495 throw new BadRequestException("no media data submitted");
4498 // check if specified profile id is valid
4499 if ($profile_id != 0) {
4500 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4501 // error message if specified profile id is not in database
4502 if (!DBA::isResult($profile)) {
4503 throw new BadRequestException("profile_id not available");
4505 $is_default_profile = $profile['is-default'];
4507 $is_default_profile = 1;
4510 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4512 if (!empty($_FILES['image'])) {
4513 $media = $_FILES['image'];
4514 } elseif (!empty($_FILES['media'])) {
4515 $media = $_FILES['media'];
4517 // save new profile image
4518 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4521 if (is_array($media['type'])) {
4522 $filetype = $media['type'][0];
4524 $filetype = $media['type'];
4526 if ($filetype == "image/jpeg") {
4528 } elseif ($filetype == "image/png") {
4531 throw new InternalServerErrorException('Unsupported filetype');
4534 // change specified profile or all profiles to the new resource-id
4535 if ($is_default_profile) {
4536 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4537 Photo::update(['profile' => false], $condition);
4539 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4540 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4541 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4544 Contact::updateSelfFromUserID(api_user(), true);
4546 // Update global directory in background
4547 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4548 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4549 Worker::add(PRIORITY_LOW, "Directory", $url);
4552 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4554 // output for client
4556 return api_account_verify_credentials($type);
4558 // SaveMediaToDatabase failed for some reason
4559 throw new InternalServerErrorException("image upload failed");
4563 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4564 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4565 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4566 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4567 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4568 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4569 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4570 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4571 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4574 * Update user profile
4576 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4578 * @return array|string
4579 * @throws BadRequestException
4580 * @throws ForbiddenException
4581 * @throws ImagickException
4582 * @throws InternalServerErrorException
4583 * @throws UnauthorizedException
4585 function api_account_update_profile($type)
4587 $local_user = api_user();
4588 $api_user = api_get_user(DI::app());
4590 if (!empty($_POST['name'])) {
4591 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4592 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4593 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4594 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4597 if (isset($_POST['description'])) {
4598 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4599 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4600 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4603 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4604 // Update global directory in background
4605 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4606 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4609 return api_account_verify_credentials($type);
4612 /// @TODO move to top of file or somewhere better
4613 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4617 * @param string $acl_string
4621 function check_acl_input($acl_string)
4623 if (empty($acl_string)) {
4627 $contact_not_found = false;
4629 // split <x><y><z> into array of cid's
4630 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4632 // check for each cid if it is available on server
4633 $cid_array = $array[0];
4634 foreach ($cid_array as $cid) {
4635 $cid = str_replace("<", "", $cid);
4636 $cid = str_replace(">", "", $cid);
4637 $condition = ['id' => $cid, 'uid' => api_user()];
4638 $contact_not_found |= !DBA::exists('contact', $condition);
4640 return $contact_not_found;
4644 * @param string $mediatype
4645 * @param array $media
4646 * @param string $type
4647 * @param string $album
4648 * @param string $allow_cid
4649 * @param string $deny_cid
4650 * @param string $allow_gid
4651 * @param string $deny_gid
4652 * @param string $desc
4653 * @param integer $profile
4654 * @param boolean $visibility
4655 * @param string $photo_id
4657 * @throws BadRequestException
4658 * @throws ForbiddenException
4659 * @throws ImagickException
4660 * @throws InternalServerErrorException
4661 * @throws NotFoundException
4662 * @throws UnauthorizedException
4664 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
4672 if (is_array($media)) {
4673 if (is_array($media['tmp_name'])) {
4674 $src = $media['tmp_name'][0];
4676 $src = $media['tmp_name'];
4678 if (is_array($media['name'])) {
4679 $filename = basename($media['name'][0]);
4681 $filename = basename($media['name']);
4683 if (is_array($media['size'])) {
4684 $filesize = intval($media['size'][0]);
4686 $filesize = intval($media['size']);
4688 if (is_array($media['type'])) {
4689 $filetype = $media['type'][0];
4691 $filetype = $media['type'];
4695 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4698 "File upload src: " . $src . " - filename: " . $filename .
4699 " - size: " . $filesize . " - type: " . $filetype,
4703 // check if there was a php upload error
4704 if ($filesize == 0 && $media['error'] == 1) {
4705 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4707 // check against max upload size within Friendica instance
4708 $maximagesize = DI::config()->get('system', 'maximagesize');
4709 if ($maximagesize && ($filesize > $maximagesize)) {
4710 $formattedBytes = Strings::formatBytes($maximagesize);
4711 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4714 // create Photo instance with the data of the image
4715 $imagedata = @file_get_contents($src);
4716 $Image = new Image($imagedata, $filetype);
4717 if (!$Image->isValid()) {
4718 throw new InternalServerErrorException("unable to process image data");
4721 // check orientation of image
4722 $Image->orient($src);
4725 // check max length of images on server
4726 $max_length = DI::config()->get('system', 'max_image_length');
4728 $max_length = MAX_IMAGE_LENGTH;
4730 if ($max_length > 0) {
4731 $Image->scaleDown($max_length);
4732 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4734 $width = $Image->getWidth();
4735 $height = $Image->getHeight();
4737 // create a new resource-id if not already provided
4738 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4740 if ($mediatype == "photo") {
4741 // upload normal image (scales 0, 1, 2)
4742 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4744 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4746 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4748 if ($width > 640 || $height > 640) {
4749 $Image->scaleDown(640);
4750 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4752 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4756 if ($width > 320 || $height > 320) {
4757 $Image->scaleDown(320);
4758 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4760 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4763 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4764 } elseif ($mediatype == "profileimage") {
4765 // upload profile image (scales 4, 5, 6)
4766 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4768 if ($width > 300 || $height > 300) {
4769 $Image->scaleDown(300);
4770 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4772 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4776 if ($width > 80 || $height > 80) {
4777 $Image->scaleDown(80);
4778 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4780 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4784 if ($width > 48 || $height > 48) {
4785 $Image->scaleDown(48);
4786 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4788 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4791 $Image->__destruct();
4792 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4796 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4797 if ($photo_id == null && $mediatype == "photo") {
4798 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4800 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4801 return prepare_photo_data($type, false, $resource_id);
4803 throw new InternalServerErrorException("image upload failed");
4809 * @param string $hash
4810 * @param string $allow_cid
4811 * @param string $deny_cid
4812 * @param string $allow_gid
4813 * @param string $deny_gid
4814 * @param string $filetype
4815 * @param boolean $visibility
4816 * @throws InternalServerErrorException
4818 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4820 // get data about the api authenticated user
4821 $uri = Item::newURI(intval(api_user()));
4822 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4825 $arr['guid'] = System::createUUID();
4826 $arr['uid'] = intval(api_user());
4828 $arr['type'] = 'photo';
4830 $arr['resource-id'] = $hash;
4831 $arr['contact-id'] = $owner_record['id'];
4832 $arr['owner-name'] = $owner_record['name'];
4833 $arr['owner-link'] = $owner_record['url'];
4834 $arr['owner-avatar'] = $owner_record['thumb'];
4835 $arr['author-name'] = $owner_record['name'];
4836 $arr['author-link'] = $owner_record['url'];
4837 $arr['author-avatar'] = $owner_record['thumb'];
4839 $arr['allow_cid'] = $allow_cid;
4840 $arr['allow_gid'] = $allow_gid;
4841 $arr['deny_cid'] = $deny_cid;
4842 $arr['deny_gid'] = $deny_gid;
4843 $arr['visible'] = $visibility;
4847 'image/jpeg' => 'jpg',
4848 'image/png' => 'png',
4849 'image/gif' => 'gif'
4852 // adds link to the thumbnail scale photo
4853 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4854 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4857 // do the magic for storing the item in the database and trigger the federation to other contacts
4863 * @param string $type
4865 * @param string $photo_id
4868 * @throws BadRequestException
4869 * @throws ForbiddenException
4870 * @throws ImagickException
4871 * @throws InternalServerErrorException
4872 * @throws NotFoundException
4873 * @throws UnauthorizedException
4875 function prepare_photo_data($type, $scale, $photo_id)
4878 $user_info = api_get_user($a);
4880 if ($user_info === false) {
4881 throw new ForbiddenException();
4884 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4885 $data_sql = ($scale === false ? "" : "data, ");
4887 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4888 // clients needs to convert this in their way for further processing
4890 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4891 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4892 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4893 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4894 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4895 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4897 intval(local_user()),
4898 DBA::escape($photo_id),
4903 'image/jpeg' => 'jpg',
4904 'image/png' => 'png',
4905 'image/gif' => 'gif'
4908 // prepare output data for photo
4909 if (DBA::isResult($r)) {
4910 $data = ['photo' => $r[0]];
4911 $data['photo']['id'] = $data['photo']['resource-id'];
4912 if ($scale !== false) {
4913 $data['photo']['data'] = base64_encode($data['photo']['data']);
4915 unset($data['photo']['datasize']); //needed only with scale param
4917 if ($type == "xml") {
4918 $data['photo']['links'] = [];
4919 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4920 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4922 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4925 $data['photo']['link'] = [];
4926 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4928 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4929 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4933 unset($data['photo']['resource-id']);
4934 unset($data['photo']['minscale']);
4935 unset($data['photo']['maxscale']);
4937 throw new NotFoundException();
4940 // retrieve item element for getting activities (like, dislike etc.) related to photo
4941 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4942 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4943 if (!DBA::isResult($item)) {
4944 throw new NotFoundException('Photo-related item not found.');
4947 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4949 // retrieve comments on photo
4950 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4951 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4953 $statuses = Post::selectForUser(api_user(), [], $condition);
4955 // prepare output of comments
4956 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4958 if ($type == "xml") {
4960 foreach ($commentData as $comment) {
4961 $comments[$k++ . ":comment"] = $comment;
4964 foreach ($commentData as $comment) {
4965 $comments[] = $comment;
4968 $data['photo']['friendica_comments'] = $comments;
4970 // include info if rights on photo and rights on item are mismatching
4971 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4972 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4973 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4974 $data['photo']['deny_gid'] != $item['deny_gid'];
4975 $data['photo']['rights_mismatch'] = $rights_mismatch;
4982 * Similar as /mod/redir.php
4983 * redirect to 'url' after dfrn auth
4985 * Why this when there is mod/redir.php already?
4986 * This use api_user() and api_login()
4989 * c_url: url of remote contact to auth to
4990 * url: string, url to redirect after auth
4992 function api_friendica_remoteauth()
4994 $url = $_GET['url'] ?? '';
4995 $c_url = $_GET['c_url'] ?? '';
4997 if ($url === '' || $c_url === '') {
4998 throw new BadRequestException("Wrong parameters.");
5001 $c_url = Strings::normaliseLink($c_url);
5005 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5006 if (!DBA::isResult($contact)) {
5007 throw new BadRequestException("Unknown contact");
5010 $cid = $contact['id'];
5012 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5014 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5015 System::externalRedirect($url ?: $c_url);
5018 if ($contact['duplex'] && $contact['issued-id']) {
5019 $orig_id = $contact['issued-id'];
5020 $dfrn_id = '1:' . $orig_id;
5022 if ($contact['duplex'] && $contact['dfrn-id']) {
5023 $orig_id = $contact['dfrn-id'];
5024 $dfrn_id = '0:' . $orig_id;
5027 $sec = Strings::getRandomHex();
5029 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5030 'sec' => $sec, 'expire' => time() + 45];
5031 DBA::insert('profile_check', $fields);
5033 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5034 $dest = ($url ? '&destination_url=' . $url : '');
5036 System::externalRedirect(
5037 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5038 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5039 . '&type=profile&sec=' . $sec . $dest
5042 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5045 * Return an item with announcer data if it had been announced
5047 * @param array $item Item array
5048 * @return array Item array with announce data
5050 function api_get_announce($item)
5052 // Quit if the item already has got a different owner and author
5053 if ($item['owner-id'] != $item['author-id']) {
5057 // Don't change original or Diaspora posts
5058 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5062 // Quit if we do now the original author and it had been a post from a native network
5063 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5067 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5068 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5069 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5070 if (!DBA::isResult($announce)) {
5074 return array_merge($item, $announce);
5078 * Return the item shared, if the item contains only the [share] tag
5080 * @param array $item Sharer item
5081 * @return array|false Shared item or false if not a reshare
5082 * @throws ImagickException
5083 * @throws InternalServerErrorException
5085 function api_share_as_retweet(&$item)
5087 $body = trim($item["body"]);
5089 if (Diaspora::isReshare($body, false) === false) {
5090 if ($item['author-id'] == $item['owner-id']) {
5093 // Reshares from OStatus, ActivityPub and Twitter
5094 $reshared_item = $item;
5095 $reshared_item['owner-id'] = $reshared_item['author-id'];
5096 $reshared_item['owner-link'] = $reshared_item['author-link'];
5097 $reshared_item['owner-name'] = $reshared_item['author-name'];
5098 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5099 return $reshared_item;
5103 $reshared = Item::getShareArray($item);
5104 if (empty($reshared)) {
5108 $reshared_item = $item;
5110 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5114 if (!empty($reshared['comment'])) {
5115 $item['body'] = $reshared['comment'];
5118 $reshared_item["share-pre-body"] = $reshared['comment'];
5119 $reshared_item["body"] = $reshared['shared'];
5120 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5121 $reshared_item["author-name"] = $reshared['author'];
5122 $reshared_item["author-link"] = $reshared['profile'];
5123 $reshared_item["author-avatar"] = $reshared['avatar'];
5124 $reshared_item["plink"] = $reshared['link'] ?? '';
5125 $reshared_item["created"] = $reshared['posted'];
5126 $reshared_item["edited"] = $reshared['posted'];
5128 // Try to fetch the original item
5129 if (!empty($reshared['guid'])) {
5130 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5131 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5132 $condition = ['id' => $original_id];
5137 if (!empty($condition)) {
5138 $original_item = Post::selectFirst([], $condition);
5139 if (DBA::isResult($original_item)) {
5140 $reshared_item = array_merge($reshared_item, $original_item);
5144 return $reshared_item;
5149 * @param array $item
5154 function api_in_reply_to($item)
5158 $in_reply_to['status_id'] = null;
5159 $in_reply_to['user_id'] = null;
5160 $in_reply_to['status_id_str'] = null;
5161 $in_reply_to['user_id_str'] = null;
5162 $in_reply_to['screen_name'] = null;
5164 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5165 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5166 if (DBA::isResult($parent)) {
5167 $in_reply_to['status_id'] = intval($parent['id']);
5169 $in_reply_to['status_id'] = intval($item['parent']);
5172 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5174 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5175 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5177 if (DBA::isResult($parent)) {
5178 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5179 $in_reply_to['user_id'] = intval($parent['author-id']);
5180 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5183 // There seems to be situation, where both fields are identical:
5184 // https://github.com/friendica/friendica/issues/1010
5185 // This is a bugfix for that.
5186 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5187 Logger::warning(API_LOG_PREFIX . 'ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5188 $in_reply_to['status_id'] = null;
5189 $in_reply_to['user_id'] = null;
5190 $in_reply_to['status_id_str'] = null;
5191 $in_reply_to['user_id_str'] = null;
5192 $in_reply_to['screen_name'] = null;
5196 return $in_reply_to;
5201 * @param string $text
5204 * @throws InternalServerErrorException
5206 function api_clean_plain_items($text)
5208 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5210 $text = BBCode::cleanPictureLinks($text);
5211 $URLSearchString = "^\[\]";
5213 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5215 if ($include_entities == "true") {
5216 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5219 // Simplify "attachment" element
5220 $text = BBCode::removeAttachment($text);
5227 * @param array $contacts
5231 function api_best_nickname(&$contacts)
5235 if (count($contacts) == 0) {
5239 foreach ($contacts as $contact) {
5240 if ($contact["network"] == "") {
5241 $contact["network"] = "dfrn";
5242 $best_contact = [$contact];
5246 if (sizeof($best_contact) == 0) {
5247 foreach ($contacts as $contact) {
5248 if ($contact["network"] == "dfrn") {
5249 $best_contact = [$contact];
5254 if (sizeof($best_contact) == 0) {
5255 foreach ($contacts as $contact) {
5256 if ($contact["network"] == "dspr") {
5257 $best_contact = [$contact];
5262 if (sizeof($best_contact) == 0) {
5263 foreach ($contacts as $contact) {
5264 if ($contact["network"] == "stat") {
5265 $best_contact = [$contact];
5270 if (sizeof($best_contact) == 0) {
5271 foreach ($contacts as $contact) {
5272 if ($contact["network"] == "pump") {
5273 $best_contact = [$contact];
5278 if (sizeof($best_contact) == 0) {
5279 foreach ($contacts as $contact) {
5280 if ($contact["network"] == "twit") {
5281 $best_contact = [$contact];
5286 if (sizeof($best_contact) == 1) {
5287 $contacts = $best_contact;
5289 $contacts = [$contacts[0]];
5294 * Return all or a specified group of the user with the containing contacts.
5296 * @param string $type Return type (atom, rss, xml, json)
5298 * @return array|string
5299 * @throws BadRequestException
5300 * @throws ForbiddenException
5301 * @throws ImagickException
5302 * @throws InternalServerErrorException
5303 * @throws UnauthorizedException
5305 function api_friendica_group_show($type)
5309 if (api_user() === false) {
5310 throw new ForbiddenException();
5314 $user_info = api_get_user($a);
5315 $gid = $_REQUEST['gid'] ?? 0;
5316 $uid = $user_info['uid'];
5318 // get data of the specified group id or all groups if not specified
5321 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5325 // error message if specified gid is not in database
5326 if (!DBA::isResult($r)) {
5327 throw new BadRequestException("gid not available");
5331 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5336 // loop through all groups and retrieve all members for adding data in the user array
5338 foreach ($r as $rr) {
5339 $members = Contact\Group::getById($rr['id']);
5342 if ($type == "xml") {
5343 $user_element = "users";
5345 foreach ($members as $member) {
5346 $user = api_get_user($a, $member['nurl']);
5347 $users[$k++.":user"] = $user;
5350 $user_element = "user";
5351 foreach ($members as $member) {
5352 $user = api_get_user($a, $member['nurl']);
5356 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5358 return api_format_data("groups", $type, ['group' => $grps]);
5360 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5364 * Delete the specified group of the user.
5366 * @param string $type Return type (atom, rss, xml, json)
5368 * @return array|string
5369 * @throws BadRequestException
5370 * @throws ForbiddenException
5371 * @throws ImagickException
5372 * @throws InternalServerErrorException
5373 * @throws UnauthorizedException
5375 function api_friendica_group_delete($type)
5379 if (api_user() === false) {
5380 throw new ForbiddenException();
5384 $user_info = api_get_user($a);
5385 $gid = $_REQUEST['gid'] ?? 0;
5386 $name = $_REQUEST['name'] ?? '';
5387 $uid = $user_info['uid'];
5389 // error if no gid specified
5390 if ($gid == 0 || $name == "") {
5391 throw new BadRequestException('gid or name not specified');
5394 // get data of the specified group id
5396 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5400 // error message if specified gid is not in database
5401 if (!DBA::isResult($r)) {
5402 throw new BadRequestException('gid not available');
5405 // get data of the specified group id and group name
5407 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5412 // error message if specified gid is not in database
5413 if (!DBA::isResult($rname)) {
5414 throw new BadRequestException('wrong group name');
5418 $ret = Group::removeByName($uid, $name);
5421 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5422 return api_format_data("group_delete", $type, ['result' => $success]);
5424 throw new BadRequestException('other API error');
5427 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5432 * @param string $type Return type (atom, rss, xml, json)
5434 * @return array|string
5435 * @throws BadRequestException
5436 * @throws ForbiddenException
5437 * @throws ImagickException
5438 * @throws InternalServerErrorException
5439 * @throws UnauthorizedException
5440 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5442 function api_lists_destroy($type)
5446 if (api_user() === false) {
5447 throw new ForbiddenException();
5451 $user_info = api_get_user($a);
5452 $gid = $_REQUEST['list_id'] ?? 0;
5453 $uid = $user_info['uid'];
5455 // error if no gid specified
5457 throw new BadRequestException('gid not specified');
5460 // get data of the specified group id
5461 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5462 // error message if specified gid is not in database
5464 throw new BadRequestException('gid not available');
5467 if (Group::remove($gid)) {
5469 'name' => $group['name'],
5470 'id' => intval($gid),
5471 'id_str' => (string) $gid,
5472 'user' => $user_info
5475 return api_format_data("lists", $type, ['lists' => $list]);
5478 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5481 * Add a new group to the database.
5483 * @param string $name Group name
5484 * @param int $uid User ID
5485 * @param array $users List of users to add to the group
5488 * @throws BadRequestException
5490 function group_create($name, $uid, $users = [])
5492 // error if no name specified
5494 throw new BadRequestException('group name not specified');
5497 // get data of the specified group name
5499 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5503 // error message if specified group name already exists
5504 if (DBA::isResult($rname)) {
5505 throw new BadRequestException('group name already exists');
5508 // check if specified group name is a deleted group
5510 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5514 // error message if specified group name already exists
5515 if (DBA::isResult($rname)) {
5516 $reactivate_group = true;
5520 $ret = Group::create($uid, $name);
5522 $gid = Group::getIdByName($uid, $name);
5524 throw new BadRequestException('other API error');
5528 $erroraddinguser = false;
5530 foreach ($users as $user) {
5531 $cid = $user['cid'];
5532 // check if user really exists as contact
5534 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5538 if (count($contact)) {
5539 Group::addMember($gid, $cid);
5541 $erroraddinguser = true;
5542 $errorusers[] = $cid;
5546 // return success message incl. missing users in array
5547 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5549 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5553 * Create the specified group with the posted array of contacts.
5555 * @param string $type Return type (atom, rss, xml, json)
5557 * @return array|string
5558 * @throws BadRequestException
5559 * @throws ForbiddenException
5560 * @throws ImagickException
5561 * @throws InternalServerErrorException
5562 * @throws UnauthorizedException
5564 function api_friendica_group_create($type)
5568 if (api_user() === false) {
5569 throw new ForbiddenException();
5573 $user_info = api_get_user($a);
5574 $name = $_REQUEST['name'] ?? '';
5575 $uid = $user_info['uid'];
5576 $json = json_decode($_POST['json'], true);
5577 $users = $json['user'];
5579 $success = group_create($name, $uid, $users);
5581 return api_format_data("group_create", $type, ['result' => $success]);
5583 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5586 * Create a new group.
5588 * @param string $type Return type (atom, rss, xml, json)
5590 * @return array|string
5591 * @throws BadRequestException
5592 * @throws ForbiddenException
5593 * @throws ImagickException
5594 * @throws InternalServerErrorException
5595 * @throws UnauthorizedException
5596 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5598 function api_lists_create($type)
5602 if (api_user() === false) {
5603 throw new ForbiddenException();
5607 $user_info = api_get_user($a);
5608 $name = $_REQUEST['name'] ?? '';
5609 $uid = $user_info['uid'];
5611 $success = group_create($name, $uid);
5612 if ($success['success']) {
5614 'name' => $success['name'],
5615 'id' => intval($success['gid']),
5616 'id_str' => (string) $success['gid'],
5617 'user' => $user_info
5620 return api_format_data("lists", $type, ['lists'=>$grp]);
5623 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5626 * Update the specified group with the posted array of contacts.
5628 * @param string $type Return type (atom, rss, xml, json)
5630 * @return array|string
5631 * @throws BadRequestException
5632 * @throws ForbiddenException
5633 * @throws ImagickException
5634 * @throws InternalServerErrorException
5635 * @throws UnauthorizedException
5637 function api_friendica_group_update($type)
5641 if (api_user() === false) {
5642 throw new ForbiddenException();
5646 $user_info = api_get_user($a);
5647 $uid = $user_info['uid'];
5648 $gid = $_REQUEST['gid'] ?? 0;
5649 $name = $_REQUEST['name'] ?? '';
5650 $json = json_decode($_POST['json'], true);
5651 $users = $json['user'];
5653 // error if no name specified
5655 throw new BadRequestException('group name not specified');
5658 // error if no gid specified
5660 throw new BadRequestException('gid not specified');
5664 $members = Contact\Group::getById($gid);
5665 foreach ($members as $member) {
5666 $cid = $member['id'];
5667 foreach ($users as $user) {
5668 $found = ($user['cid'] == $cid ? true : false);
5670 if (!isset($found) || !$found) {
5671 Group::removeMemberByName($uid, $name, $cid);
5676 $erroraddinguser = false;
5678 foreach ($users as $user) {
5679 $cid = $user['cid'];
5680 // check if user really exists as contact
5682 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5687 if (count($contact)) {
5688 Group::addMember($gid, $cid);
5690 $erroraddinguser = true;
5691 $errorusers[] = $cid;
5695 // return success message incl. missing users in array
5696 $status = ($erroraddinguser ? "missing user" : "ok");
5697 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5698 return api_format_data("group_update", $type, ['result' => $success]);
5701 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5704 * Update information about a group.
5706 * @param string $type Return type (atom, rss, xml, json)
5708 * @return array|string
5709 * @throws BadRequestException
5710 * @throws ForbiddenException
5711 * @throws ImagickException
5712 * @throws InternalServerErrorException
5713 * @throws UnauthorizedException
5714 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5716 function api_lists_update($type)
5720 if (api_user() === false) {
5721 throw new ForbiddenException();
5725 $user_info = api_get_user($a);
5726 $gid = $_REQUEST['list_id'] ?? 0;
5727 $name = $_REQUEST['name'] ?? '';
5728 $uid = $user_info['uid'];
5730 // error if no gid specified
5732 throw new BadRequestException('gid not specified');
5735 // get data of the specified group id
5736 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5737 // error message if specified gid is not in database
5739 throw new BadRequestException('gid not available');
5742 if (Group::update($gid, $name)) {
5745 'id' => intval($gid),
5746 'id_str' => (string) $gid,
5747 'user' => $user_info
5750 return api_format_data("lists", $type, ['lists' => $list]);
5754 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5758 * @param string $type Return type (atom, rss, xml, json)
5760 * @return array|string
5761 * @throws BadRequestException
5762 * @throws ForbiddenException
5763 * @throws ImagickException
5764 * @throws InternalServerErrorException
5766 function api_friendica_activity($type)
5770 if (api_user() === false) {
5771 throw new ForbiddenException();
5773 $verb = strtolower($a->argv[3]);
5774 $verb = preg_replace("|\..*$|", "", $verb);
5776 $id = $_REQUEST['id'] ?? 0;
5778 $res = Item::performActivity($id, $verb, api_user());
5781 if ($type == "xml") {
5786 return api_format_data('ok', $type, ['ok' => $ok]);
5788 throw new BadRequestException('Error adding activity');
5792 /// @TODO move to top of file or somewhere better
5793 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5794 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5795 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5796 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5797 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5798 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5799 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5800 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5801 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5802 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5805 * Returns notifications
5807 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5809 * @return string|array
5810 * @throws ForbiddenException
5811 * @throws BadRequestException
5814 function api_friendica_notification($type)
5818 if (api_user() === false) {
5819 throw new ForbiddenException();
5822 throw new BadRequestException("Invalid argument count");
5825 $notifications = DI::notification()->getApiList(local_user());
5827 if ($type == "xml") {
5829 if (!empty($notifications)) {
5830 foreach ($notifications as $notification) {
5831 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5835 $result = $xmlnotes;
5836 } elseif (count($notifications) > 0) {
5837 $result = $notifications->getArrayCopy();
5842 return api_format_data("notes", $type, ['note' => $result]);
5846 * Set notification as seen and returns associated item (if possible)
5848 * POST request with 'id' param as notification id
5850 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5851 * @return string|array
5852 * @throws BadRequestException
5853 * @throws ForbiddenException
5854 * @throws ImagickException
5855 * @throws InternalServerErrorException
5856 * @throws UnauthorizedException
5858 function api_friendica_notification_seen($type)
5861 $user_info = api_get_user($a);
5863 if (api_user() === false || $user_info === false) {
5864 throw new ForbiddenException();
5866 if ($a->argc !== 4) {
5867 throw new BadRequestException("Invalid argument count");
5870 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5873 $notify = DI::notify()->getByID($id, api_user());
5874 DI::notify()->setSeen(true, $notify);
5876 if ($notify->otype === Notification\ObjectType::ITEM) {
5877 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5878 if (DBA::isResult($item)) {
5879 // we found the item, return it to the user
5880 $ret = api_format_items([$item], $user_info, false, $type);
5881 $data = ['status' => $ret];
5882 return api_format_data("status", $type, $data);
5884 // the item can't be found, but we set the notification as seen, so we count this as a success
5886 return api_format_data('result', $type, ['result' => "success"]);
5887 } catch (NotFoundException $e) {
5888 throw new BadRequestException('Invalid argument', $e);
5889 } catch (Exception $e) {
5890 throw new InternalServerErrorException('Internal Server exception', $e);
5894 /// @TODO move to top of file or somewhere better
5895 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5896 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5899 * update a direct_message to seen state
5901 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5902 * @return string|array (success result=ok, error result=error with error message)
5903 * @throws BadRequestException
5904 * @throws ForbiddenException
5905 * @throws ImagickException
5906 * @throws InternalServerErrorException
5907 * @throws UnauthorizedException
5909 function api_friendica_direct_messages_setseen($type)
5912 if (api_user() === false) {
5913 throw new ForbiddenException();
5917 $user_info = api_get_user($a);
5918 $uid = $user_info['uid'];
5919 $id = $_REQUEST['id'] ?? 0;
5921 // return error if id is zero
5923 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5924 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5927 // error message if specified id is not in database
5928 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5929 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5930 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5933 // update seen indicator
5934 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5938 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5939 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5941 $answer = ['result' => 'error', 'message' => 'unknown error'];
5942 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5946 /// @TODO move to top of file or somewhere better
5947 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5950 * search for direct_messages containing a searchstring through api
5952 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5953 * @param string $box
5954 * @return string|array (success: success=true if found and search_result contains found messages,
5955 * success=false if nothing was found, search_result='nothing found',
5956 * error: result=error with error message)
5957 * @throws BadRequestException
5958 * @throws ForbiddenException
5959 * @throws ImagickException
5960 * @throws InternalServerErrorException
5961 * @throws UnauthorizedException
5963 function api_friendica_direct_messages_search($type, $box = "")
5967 if (api_user() === false) {
5968 throw new ForbiddenException();
5972 $user_info = api_get_user($a);
5973 $searchstring = $_REQUEST['searchstring'] ?? '';
5974 $uid = $user_info['uid'];
5976 // error if no searchstring specified
5977 if ($searchstring == "") {
5978 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5979 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5982 // get data for the specified searchstring
5984 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
5986 DBA::escape('%'.$searchstring.'%')
5989 $profile_url = $user_info["url"];
5991 // message if nothing was found
5992 if (!DBA::isResult($r)) {
5993 $success = ['success' => false, 'search_results' => 'problem with query'];
5994 } elseif (count($r) == 0) {
5995 $success = ['success' => false, 'search_results' => 'nothing found'];
5998 foreach ($r as $item) {
5999 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6000 $recipient = $user_info;
6001 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6002 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6003 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6004 $sender = $user_info;
6007 if (isset($recipient) && isset($sender)) {
6008 $ret[] = api_format_messages($item, $recipient, $sender);
6011 $success = ['success' => true, 'search_results' => $ret];
6014 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6017 /// @TODO move to top of file or somewhere better
6018 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6021 * Returns a list of saved searches.
6023 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6025 * @param string $type Return format: json or xml
6027 * @return string|array
6030 function api_saved_searches_list($type)
6032 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6035 while ($term = DBA::fetch($terms)) {
6037 'created_at' => api_date(time()),
6038 'id' => intval($term['id']),
6039 'id_str' => $term['id'],
6040 'name' => $term['term'],
6042 'query' => $term['term']
6048 return api_format_data("terms", $type, ['terms' => $result]);
6051 /// @TODO move to top of file or somewhere better
6052 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6055 * Number of comments
6057 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6059 * @param object $data [Status, Status]
6063 function bindComments(&$data)
6065 if (count($data) == 0) {
6071 foreach ($data as $item) {
6072 $ids[] = $item['id'];
6075 $idStr = DBA::escape(implode(', ', $ids));
6076 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6077 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6078 $itemsData = DBA::toArray($items);
6080 foreach ($itemsData as $item) {
6081 $comments[$item['parent']] = $item['comments'];
6084 foreach ($data as $idx => $item) {
6086 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6091 @TODO Maybe open to implement?
6093 [pagename] => api/1.1/statuses/lookup.json
6094 [id] => 605138389168451584
6095 [include_cards] => true
6096 [cards_platform] => Android-12
6097 [include_entities] => true
6098 [include_my_retweet] => 1
6100 [include_reply_count] => true
6101 [include_descendent_reply_count] => true
6105 Not implemented by now:
6106 statuses/retweets_of_me
6111 account/update_location
6112 account/update_profile_background_image
6115 friendica/profile/update
6116 friendica/profile/create
6117 friendica/profile/delete
6119 Not implemented in status.net:
6120 statuses/retweeted_to_me
6121 statuses/retweeted_by_me
6122 direct_messages/destroy
6124 account/update_delivery_device
6125 notifications/follow