3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\User;
46 use Friendica\Model\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'] && count($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 (!empty($_FILES['media'])) {
1161 // upload the image if we have one
1162 $picture = wall_upload_post($a, false);
1163 if (is_array($picture)) {
1164 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1168 if (requestdata('media_ids')) {
1169 $ids = explode(',', requestdata('media_ids'));
1170 foreach ($ids as $id) {
1172 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1176 if (DBA::isResult($r)) {
1177 $phototypes = Images::supportedTypes();
1178 $ext = $phototypes[$r[0]['type']];
1179 $description = $r[0]['desc'] ?? '';
1180 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1181 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1186 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1188 $_REQUEST['api_source'] = true;
1190 if (empty($_REQUEST['source'])) {
1191 $_REQUEST["source"] = api_source();
1194 // call out normal post function
1195 $item_id = item_post($a);
1197 // output the post that we just posted.
1198 return api_status_show($type, $item_id);
1201 /// @TODO move to top of file or somewhere better
1202 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1203 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1206 * Uploads an image to Friendica.
1209 * @throws BadRequestException
1210 * @throws ForbiddenException
1211 * @throws ImagickException
1212 * @throws InternalServerErrorException
1213 * @throws UnauthorizedException
1214 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1216 function api_media_upload()
1220 if (api_user() === false) {
1221 Logger::log('no user');
1222 throw new ForbiddenException();
1227 if (empty($_FILES['media'])) {
1229 throw new BadRequestException("No media.");
1232 $media = wall_upload_post($a, false);
1235 throw new InternalServerErrorException();
1239 $returndata["media_id"] = $media["id"];
1240 $returndata["media_id_string"] = (string)$media["id"];
1241 $returndata["size"] = $media["size"];
1242 $returndata["image"] = ["w" => $media["width"],
1243 "h" => $media["height"],
1244 "image_type" => $media["type"],
1245 "friendica_preview_url" => $media["preview"]];
1247 Logger::info('Media uploaded', ['return' => $returndata]);
1249 return ["media" => $returndata];
1252 /// @TODO move to top of file or somewhere better
1253 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1256 * Updates media meta data (picture descriptions)
1258 * @param string $type Return type (atom, rss, xml, json)
1260 * @return array|string
1261 * @throws BadRequestException
1262 * @throws ForbiddenException
1263 * @throws ImagickException
1264 * @throws InternalServerErrorException
1265 * @throws TooManyRequestsException
1266 * @throws UnauthorizedException
1267 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1269 * @todo Compare the corresponding Twitter function for correct return values
1271 function api_media_metadata_create($type)
1275 if (api_user() === false) {
1276 Logger::info('no user');
1277 throw new ForbiddenException();
1282 $postdata = Network::postdata();
1284 if (empty($postdata)) {
1285 throw new BadRequestException("No post data");
1288 $data = json_decode($postdata, true);
1290 throw new BadRequestException("Invalid post data");
1293 if (empty($data['media_id']) || empty($data['alt_text'])) {
1294 throw new BadRequestException("Missing post data values");
1297 if (empty($data['alt_text']['text'])) {
1298 throw new BadRequestException("No alt text.");
1301 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1303 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1304 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1305 if (!DBA::isResult($photo)) {
1306 throw new BadRequestException("Metadata not found.");
1309 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1312 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1315 * @param string $type Return format (atom, rss, xml, json)
1316 * @param int $item_id
1317 * @return array|string
1320 function api_status_show($type, $item_id)
1322 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1326 $item = api_get_item(['id' => $item_id]);
1327 if (!empty($item)) {
1328 $status_info = api_format_item($item, $type);
1331 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1333 return api_format_data('statuses', $type, ['status' => $status_info]);
1337 * Retrieves the last public status of the provided user info
1339 * @param int $ownerId Public contact Id
1340 * @param int $uid User Id
1344 function api_get_last_status($ownerId, $uid)
1347 'author-id'=> $ownerId,
1349 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1350 'private' => [Item::PUBLIC, Item::UNLISTED]
1353 $item = api_get_item($condition);
1359 * Retrieves a single item record based on the provided condition and converts it for API use.
1361 * @param array $condition Item table condition array
1365 function api_get_item(array $condition)
1367 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1373 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1374 * The author's most recent status will be returned inline.
1376 * @param string $type Return type (atom, rss, xml, json)
1377 * @return array|string
1378 * @throws BadRequestException
1379 * @throws ImagickException
1380 * @throws InternalServerErrorException
1381 * @throws UnauthorizedException
1382 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1384 function api_users_show($type)
1386 $a = Friendica\DI::app();
1388 $user_info = api_get_user($a);
1390 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1391 if (!empty($item)) {
1392 $user_info['status'] = api_format_item($item, $type);
1395 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1396 unset($user_info['uid']);
1397 unset($user_info['self']);
1399 return api_format_data('user', $type, ['user' => $user_info]);
1402 /// @TODO move to top of file or somewhere better
1403 api_register_func('api/users/show', 'api_users_show');
1404 api_register_func('api/externalprofile/show', 'api_users_show');
1407 * Search a public user account.
1409 * @param string $type Return type (atom, rss, xml, json)
1411 * @return array|string
1412 * @throws BadRequestException
1413 * @throws ImagickException
1414 * @throws InternalServerErrorException
1415 * @throws UnauthorizedException
1416 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1418 function api_users_search($type)
1424 if (!empty($_GET['q'])) {
1425 $contacts = Contact::selectToArray(
1428 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1436 if (DBA::isResult($contacts)) {
1438 foreach ($contacts as $contact) {
1439 $user_info = api_get_user($a, $contact['id']);
1441 if ($type == 'xml') {
1442 $userlist[$k++ . ':user'] = $user_info;
1444 $userlist[] = $user_info;
1447 $userlist = ['users' => $userlist];
1449 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1452 throw new BadRequestException('No search term specified.');
1455 return api_format_data('users', $type, $userlist);
1458 /// @TODO move to top of file or somewhere better
1459 api_register_func('api/users/search', 'api_users_search');
1462 * Return user objects
1464 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1466 * @param string $type Return format: json or xml
1468 * @return array|string
1469 * @throws BadRequestException
1470 * @throws ImagickException
1471 * @throws InternalServerErrorException
1472 * @throws NotFoundException if the results are empty.
1473 * @throws UnauthorizedException
1475 function api_users_lookup($type)
1479 if (!empty($_REQUEST['user_id'])) {
1480 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1482 $users[] = api_get_user(DI::app(), $id);
1487 if (empty($users)) {
1488 throw new NotFoundException;
1491 return api_format_data("users", $type, ['users' => $users]);
1494 /// @TODO move to top of file or somewhere better
1495 api_register_func('api/users/lookup', 'api_users_lookup', true);
1498 * Returns statuses that match a specified query.
1500 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1502 * @param string $type Return format: json, xml, atom, rss
1504 * @return array|string
1505 * @throws BadRequestException if the "q" parameter is missing.
1506 * @throws ForbiddenException
1507 * @throws ImagickException
1508 * @throws InternalServerErrorException
1509 * @throws UnauthorizedException
1511 function api_search($type)
1514 $user_info = api_get_user($a);
1516 if (api_user() === false || $user_info === false) {
1517 throw new ForbiddenException();
1520 if (empty($_REQUEST['q'])) {
1521 throw new BadRequestException('q parameter is required.');
1524 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1527 $data['status'] = [];
1529 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1530 if (!empty($_REQUEST['rpp'])) {
1531 $count = $_REQUEST['rpp'];
1532 } elseif (!empty($_REQUEST['count'])) {
1533 $count = $_REQUEST['count'];
1536 $since_id = $_REQUEST['since_id'] ?? 0;
1537 $max_id = $_REQUEST['max_id'] ?? 0;
1538 $page = $_REQUEST['page'] ?? 1;
1540 $start = max(0, ($page - 1) * $count);
1542 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1543 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1544 $searchTerm = $matches[1];
1545 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1546 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1548 while ($tag = DBA::fetch($tags)) {
1549 $uriids[] = $tag['uri-id'];
1553 if (empty($uriids)) {
1554 return api_format_data('statuses', $type, $data);
1557 $condition = ['uri-id' => $uriids];
1558 if ($exclude_replies) {
1559 $condition['gravity'] = GRAVITY_PARENT;
1562 $params['group_by'] = ['uri-id'];
1564 $condition = ["`id` > ?
1565 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1566 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1567 AND `body` LIKE CONCAT('%',?,'%')",
1568 $since_id, api_user(), $_REQUEST['q']];
1570 $condition[0] .= ' AND `id` <= ?';
1571 $condition[] = $max_id;
1577 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1578 $id = Item::fetchByLink($searchTerm, api_user());
1581 $id = Item::fetchByLink($searchTerm);
1585 $statuses = Post::select([], ['id' => $id]);
1589 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1591 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1593 bindComments($data['status']);
1595 return api_format_data('statuses', $type, $data);
1598 /// @TODO move to top of file or somewhere better
1599 api_register_func('api/search/tweets', 'api_search', true);
1600 api_register_func('api/search', 'api_search', true);
1603 * Returns the most recent statuses posted by the user and the users they follow.
1605 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1607 * @param string $type Return type (atom, rss, xml, json)
1609 * @return array|string
1610 * @throws BadRequestException
1611 * @throws ForbiddenException
1612 * @throws ImagickException
1613 * @throws InternalServerErrorException
1614 * @throws UnauthorizedException
1615 * @todo Optional parameters
1616 * @todo Add reply info
1618 function api_statuses_home_timeline($type)
1621 $user_info = api_get_user($a);
1623 if (api_user() === false || $user_info === false) {
1624 throw new ForbiddenException();
1627 unset($_REQUEST["user_id"]);
1628 unset($_GET["user_id"]);
1630 unset($_REQUEST["screen_name"]);
1631 unset($_GET["screen_name"]);
1633 // get last network messages
1636 $count = $_REQUEST['count'] ?? 20;
1637 $page = $_REQUEST['page']?? 0;
1638 $since_id = $_REQUEST['since_id'] ?? 0;
1639 $max_id = $_REQUEST['max_id'] ?? 0;
1640 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1641 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1643 $start = max(0, ($page - 1) * $count);
1645 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1646 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1649 $condition[0] .= " AND `id` <= ?";
1650 $condition[] = $max_id;
1652 if ($exclude_replies) {
1653 $condition[0] .= ' AND `gravity` = ?';
1654 $condition[] = GRAVITY_PARENT;
1656 if ($conversation_id > 0) {
1657 $condition[0] .= " AND `parent` = ?";
1658 $condition[] = $conversation_id;
1661 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1662 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1664 $items = Post::toArray($statuses);
1666 $ret = api_format_items($items, $user_info, false, $type);
1668 // Set all posts from the query above to seen
1670 foreach ($items as $item) {
1671 $idarray[] = intval($item["id"]);
1674 if (!empty($idarray)) {
1675 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1677 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1683 $data = ['status' => $ret];
1688 $data = api_rss_extra($a, $data, $user_info);
1692 return api_format_data("statuses", $type, $data);
1696 /// @TODO move to top of file or somewhere better
1697 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1698 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1701 * Returns the most recent statuses from public users.
1703 * @param string $type Return type (atom, rss, xml, json)
1705 * @return array|string
1706 * @throws BadRequestException
1707 * @throws ForbiddenException
1708 * @throws ImagickException
1709 * @throws InternalServerErrorException
1710 * @throws UnauthorizedException
1712 function api_statuses_public_timeline($type)
1715 $user_info = api_get_user($a);
1717 if (api_user() === false || $user_info === false) {
1718 throw new ForbiddenException();
1721 // get last network messages
1724 $count = $_REQUEST['count'] ?? 20;
1725 $page = $_REQUEST['page'] ?? 1;
1726 $since_id = $_REQUEST['since_id'] ?? 0;
1727 $max_id = $_REQUEST['max_id'] ?? 0;
1728 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1729 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1731 $start = max(0, ($page - 1) * $count);
1733 if ($exclude_replies && !$conversation_id) {
1734 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1735 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1738 $condition[0] .= " AND `iid` <= ?";
1739 $condition[] = $max_id;
1742 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1743 $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1745 $r = Post::toArray($statuses);
1747 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1748 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1751 $condition[0] .= " AND `id` <= ?";
1752 $condition[] = $max_id;
1754 if ($conversation_id > 0) {
1755 $condition[0] .= " AND `parent` = ?";
1756 $condition[] = $conversation_id;
1759 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1760 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1762 $r = Post::toArray($statuses);
1765 $ret = api_format_items($r, $user_info, false, $type);
1769 $data = ['status' => $ret];
1774 $data = api_rss_extra($a, $data, $user_info);
1778 return api_format_data("statuses", $type, $data);
1781 /// @TODO move to top of file or somewhere better
1782 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1785 * Returns the most recent statuses posted by users this node knows about.
1787 * @param string $type Return format: json, xml, atom, rss
1788 * @return array|string
1789 * @throws BadRequestException
1790 * @throws ForbiddenException
1791 * @throws ImagickException
1792 * @throws InternalServerErrorException
1793 * @throws UnauthorizedException
1795 function api_statuses_networkpublic_timeline($type)
1798 $user_info = api_get_user($a);
1800 if (api_user() === false || $user_info === false) {
1801 throw new ForbiddenException();
1804 $since_id = $_REQUEST['since_id'] ?? 0;
1805 $max_id = $_REQUEST['max_id'] ?? 0;
1808 $count = $_REQUEST['count'] ?? 20;
1809 $page = $_REQUEST['page'] ?? 1;
1811 $start = max(0, ($page - 1) * $count);
1813 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `iid` > ? AND `private` = ?",
1814 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1817 $condition[0] .= " AND `iid` <= ?";
1818 $condition[] = $max_id;
1821 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1822 $statuses = Post::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1824 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1828 $data = ['status' => $ret];
1833 $data = api_rss_extra($a, $data, $user_info);
1837 return api_format_data("statuses", $type, $data);
1840 /// @TODO move to top of file or somewhere better
1841 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1844 * Returns a single status.
1846 * @param string $type Return type (atom, rss, xml, json)
1848 * @return array|string
1849 * @throws BadRequestException
1850 * @throws ForbiddenException
1851 * @throws ImagickException
1852 * @throws InternalServerErrorException
1853 * @throws UnauthorizedException
1854 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1856 function api_statuses_show($type)
1859 $user_info = api_get_user($a);
1861 if (api_user() === false || $user_info === false) {
1862 throw new ForbiddenException();
1866 $id = intval($a->argv[3] ?? 0);
1869 $id = intval($_REQUEST['id'] ?? 0);
1874 $id = intval($a->argv[4] ?? 0);
1877 Logger::log('API: api_statuses_show: ' . $id);
1879 $conversation = !empty($_REQUEST['conversation']);
1881 // try to fetch the item for the local user - or the public item, if there is no local one
1882 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1883 if (!DBA::isResult($uri_item)) {
1884 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1887 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1888 if (!DBA::isResult($item)) {
1889 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1894 if ($conversation) {
1895 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1896 $params = ['order' => ['id' => true]];
1898 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1902 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1904 /// @TODO How about copying this to above methods which don't check $r ?
1905 if (!DBA::isResult($statuses)) {
1906 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1909 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1911 if ($conversation) {
1912 $data = ['status' => $ret];
1913 return api_format_data("statuses", $type, $data);
1915 $data = ['status' => $ret[0]];
1916 return api_format_data("status", $type, $data);
1920 /// @TODO move to top of file or somewhere better
1921 api_register_func('api/statuses/show', 'api_statuses_show', true);
1925 * @param string $type Return type (atom, rss, xml, json)
1927 * @return array|string
1928 * @throws BadRequestException
1929 * @throws ForbiddenException
1930 * @throws ImagickException
1931 * @throws InternalServerErrorException
1932 * @throws UnauthorizedException
1933 * @todo nothing to say?
1935 function api_conversation_show($type)
1938 $user_info = api_get_user($a);
1940 if (api_user() === false || $user_info === false) {
1941 throw new ForbiddenException();
1945 $id = intval($a->argv[3] ?? 0);
1946 $since_id = intval($_REQUEST['since_id'] ?? 0);
1947 $max_id = intval($_REQUEST['max_id'] ?? 0);
1948 $count = intval($_REQUEST['count'] ?? 20);
1949 $page = intval($_REQUEST['page'] ?? 1);
1951 $start = max(0, ($page - 1) * $count);
1954 $id = intval($_REQUEST['id'] ?? 0);
1959 $id = intval($a->argv[4] ?? 0);
1962 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1964 // try to fetch the item for the local user - or the public item, if there is no local one
1965 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1966 if (!DBA::isResult($item)) {
1967 throw new BadRequestException("There is no status with this id.");
1970 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1971 if (!DBA::isResult($parent)) {
1972 throw new BadRequestException("There is no status with this id.");
1975 $id = $parent['id'];
1977 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1978 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1981 $condition[0] .= " AND `id` <= ?";
1982 $condition[] = $max_id;
1985 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1986 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1988 if (!DBA::isResult($statuses)) {
1989 throw new BadRequestException("There is no status with id $id.");
1992 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1994 $data = ['status' => $ret];
1995 return api_format_data("statuses", $type, $data);
1998 /// @TODO move to top of file or somewhere better
1999 api_register_func('api/conversation/show', 'api_conversation_show', true);
2000 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2005 * @param string $type Return type (atom, rss, xml, json)
2007 * @return array|string
2008 * @throws BadRequestException
2009 * @throws ForbiddenException
2010 * @throws ImagickException
2011 * @throws InternalServerErrorException
2012 * @throws UnauthorizedException
2013 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2015 function api_statuses_repeat($type)
2021 if (api_user() === false) {
2022 throw new ForbiddenException();
2028 $id = intval($a->argv[3] ?? 0);
2031 $id = intval($_REQUEST['id'] ?? 0);
2036 $id = intval($a->argv[4] ?? 0);
2039 Logger::log('API: api_statuses_repeat: '.$id);
2041 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2042 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2044 if (DBA::isResult($item) && !empty($item['body'])) {
2045 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2046 if (!Item::performActivity($id, 'announce', local_user())) {
2047 throw new InternalServerErrorException();
2052 if (strpos($item['body'], "[/share]") !== false) {
2053 $pos = strpos($item['body'], "[share");
2054 $post = substr($item['body'], $pos);
2056 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2058 if (!empty($item['title'])) {
2059 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2062 $post .= $item['body'];
2063 $post .= "[/share]";
2065 $_REQUEST['body'] = $post;
2066 $_REQUEST['profile_uid'] = api_user();
2067 $_REQUEST['api_source'] = true;
2069 if (empty($_REQUEST['source'])) {
2070 $_REQUEST["source"] = api_source();
2073 $item_id = item_post($a);
2076 throw new ForbiddenException();
2079 // output the post that we just posted.
2081 return api_status_show($type, $item_id);
2084 /// @TODO move to top of file or somewhere better
2085 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2088 * Destroys a specific status.
2090 * @param string $type Return type (atom, rss, xml, json)
2092 * @return array|string
2093 * @throws BadRequestException
2094 * @throws ForbiddenException
2095 * @throws ImagickException
2096 * @throws InternalServerErrorException
2097 * @throws UnauthorizedException
2098 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2100 function api_statuses_destroy($type)
2104 if (api_user() === false) {
2105 throw new ForbiddenException();
2111 $id = intval($a->argv[3] ?? 0);
2114 $id = intval($_REQUEST['id'] ?? 0);
2119 $id = intval($a->argv[4] ?? 0);
2122 Logger::log('API: api_statuses_destroy: '.$id);
2124 $ret = api_statuses_show($type);
2126 Item::deleteForUser(['id' => $id], api_user());
2131 /// @TODO move to top of file or somewhere better
2132 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2135 * Returns the most recent mentions.
2137 * @param string $type Return type (atom, rss, xml, json)
2139 * @return array|string
2140 * @throws BadRequestException
2141 * @throws ForbiddenException
2142 * @throws ImagickException
2143 * @throws InternalServerErrorException
2144 * @throws UnauthorizedException
2145 * @see http://developer.twitter.com/doc/get/statuses/mentions
2147 function api_statuses_mentions($type)
2150 $user_info = api_get_user($a);
2152 if (api_user() === false || $user_info === false) {
2153 throw new ForbiddenException();
2156 unset($_REQUEST["user_id"]);
2157 unset($_GET["user_id"]);
2159 unset($_REQUEST["screen_name"]);
2160 unset($_GET["screen_name"]);
2162 // get last network messages
2165 $since_id = intval($_REQUEST['since_id'] ?? 0);
2166 $max_id = intval($_REQUEST['max_id'] ?? 0);
2167 $count = intval($_REQUEST['count'] ?? 20);
2168 $page = intval($_REQUEST['page'] ?? 1);
2170 $start = max(0, ($page - 1) * $count);
2172 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2173 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2174 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2176 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2177 Post\UserNotification::NOTIF_EXPLICIT_TAGGED | Post\UserNotification::NOTIF_IMPLICIT_TAGGED |
2178 Post\UserNotification::NOTIF_THREAD_COMMENT | Post\UserNotification::NOTIF_DIRECT_COMMENT |
2179 Post\UserNotification::NOTIF_DIRECT_THREAD_COMMENT,
2180 api_user(), $since_id];
2183 $query .= " AND `id` <= ?";
2184 $condition[] = $max_id;
2187 array_unshift($condition, $query);
2189 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2190 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2192 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2194 $data = ['status' => $ret];
2199 $data = api_rss_extra($a, $data, $user_info);
2203 return api_format_data("statuses", $type, $data);
2206 /// @TODO move to top of file or somewhere better
2207 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2208 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2211 * Returns the most recent statuses posted by the user.
2213 * @param string $type Either "json" or "xml"
2214 * @return string|array
2215 * @throws BadRequestException
2216 * @throws ForbiddenException
2217 * @throws ImagickException
2218 * @throws InternalServerErrorException
2219 * @throws UnauthorizedException
2220 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2222 function api_statuses_user_timeline($type)
2225 $user_info = api_get_user($a);
2227 if (api_user() === false || $user_info === false) {
2228 throw new ForbiddenException();
2231 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2233 $since_id = $_REQUEST['since_id'] ?? 0;
2234 $max_id = $_REQUEST['max_id'] ?? 0;
2235 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2236 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2239 $count = $_REQUEST['count'] ?? 20;
2240 $page = $_REQUEST['page'] ?? 1;
2242 $start = max(0, ($page - 1) * $count);
2244 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2245 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2247 if ($user_info['self'] == 1) {
2248 $condition[0] .= ' AND `wall` ';
2251 if ($exclude_replies) {
2252 $condition[0] .= ' AND `gravity` = ?';
2253 $condition[] = GRAVITY_PARENT;
2256 if ($conversation_id > 0) {
2257 $condition[0] .= " AND `parent` = ?";
2258 $condition[] = $conversation_id;
2262 $condition[0] .= " AND `id` <= ?";
2263 $condition[] = $max_id;
2266 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2267 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2269 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2273 $data = ['status' => $ret];
2278 $data = api_rss_extra($a, $data, $user_info);
2282 return api_format_data("statuses", $type, $data);
2285 /// @TODO move to top of file or somewhere better
2286 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2289 * Star/unstar an item.
2290 * param: id : id of the item
2292 * @param string $type Return type (atom, rss, xml, json)
2294 * @return array|string
2295 * @throws BadRequestException
2296 * @throws ForbiddenException
2297 * @throws ImagickException
2298 * @throws InternalServerErrorException
2299 * @throws UnauthorizedException
2300 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2302 function api_favorites_create_destroy($type)
2306 if (api_user() === false) {
2307 throw new ForbiddenException();
2310 // for versioned api.
2311 /// @TODO We need a better global soluton
2312 $action_argv_id = 2;
2313 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2314 $action_argv_id = 3;
2317 if ($a->argc <= $action_argv_id) {
2318 throw new BadRequestException("Invalid request.");
2320 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2321 if ($a->argc == $action_argv_id + 2) {
2322 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2324 $itemid = intval($_REQUEST['id'] ?? 0);
2327 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2329 if (!DBA::isResult($item)) {
2330 throw new BadRequestException("Invalid item.");
2335 $item['starred'] = 1;
2338 $item['starred'] = 0;
2341 throw new BadRequestException("Invalid action ".$action);
2344 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2347 throw new InternalServerErrorException("DB error");
2351 $user_info = api_get_user($a);
2352 $rets = api_format_items([$item], $user_info, false, $type);
2355 $data = ['status' => $ret];
2360 $data = api_rss_extra($a, $data, $user_info);
2364 return api_format_data("status", $type, $data);
2367 /// @TODO move to top of file or somewhere better
2368 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2369 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2372 * Returns the most recent favorite statuses.
2374 * @param string $type Return type (atom, rss, xml, json)
2376 * @return string|array
2377 * @throws BadRequestException
2378 * @throws ForbiddenException
2379 * @throws ImagickException
2380 * @throws InternalServerErrorException
2381 * @throws UnauthorizedException
2383 function api_favorites($type)
2388 $user_info = api_get_user($a);
2390 if (api_user() === false || $user_info === false) {
2391 throw new ForbiddenException();
2396 // in friendica starred item are private
2397 // return favorites only for self
2398 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2400 if ($user_info['self'] == 0) {
2404 $since_id = $_REQUEST['since_id'] ?? 0;
2405 $max_id = $_REQUEST['max_id'] ?? 0;
2406 $count = $_GET['count'] ?? 20;
2407 $page = $_REQUEST['page'] ?? 1;
2409 $start = max(0, ($page - 1) * $count);
2411 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2412 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2414 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2417 $condition[0] .= " AND `id` <= ?";
2418 $condition[] = $max_id;
2421 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2423 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2428 $data = ['status' => $ret];
2433 $data = api_rss_extra($a, $data, $user_info);
2437 return api_format_data("statuses", $type, $data);
2440 /// @TODO move to top of file or somewhere better
2441 api_register_func('api/favorites', 'api_favorites', true);
2445 * @param array $item
2446 * @param array $recipient
2447 * @param array $sender
2450 * @throws InternalServerErrorException
2452 function api_format_messages($item, $recipient, $sender)
2454 // standard meta information
2456 'id' => $item['id'],
2457 'sender_id' => $sender['id'],
2459 'recipient_id' => $recipient['id'],
2460 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2461 'sender_screen_name' => $sender['screen_name'],
2462 'recipient_screen_name' => $recipient['screen_name'],
2463 'sender' => $sender,
2464 'recipient' => $recipient,
2466 'friendica_seen' => $item['seen'] ?? 0,
2467 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2470 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2471 if (isset($ret['sender']['uid'])) {
2472 unset($ret['sender']['uid']);
2474 if (isset($ret['sender']['self'])) {
2475 unset($ret['sender']['self']);
2477 if (isset($ret['recipient']['uid'])) {
2478 unset($ret['recipient']['uid']);
2480 if (isset($ret['recipient']['self'])) {
2481 unset($ret['recipient']['self']);
2484 //don't send title to regular StatusNET requests to avoid confusing these apps
2485 if (!empty($_GET['getText'])) {
2486 $ret['title'] = $item['title'];
2487 if ($_GET['getText'] == 'html') {
2488 $ret['text'] = BBCode::convert($item['body'], false);
2489 } elseif ($_GET['getText'] == 'plain') {
2490 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2493 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2495 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2496 unset($ret['sender']);
2497 unset($ret['recipient']);
2505 * @param array $item
2508 * @throws InternalServerErrorException
2510 function api_convert_item($item)
2512 $body = $item['body'];
2513 $entities = api_get_entitities($statustext, $body);
2515 // Add pictures to the attachment array and remove them from the body
2516 $attachments = api_get_attachments($body);
2518 // Workaround for ostatus messages where the title is identically to the body
2519 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2520 $statusbody = trim(HTML::toPlaintext($html, 0));
2522 // handle data: images
2523 $statusbody = api_format_items_embeded_images($item, $statusbody);
2525 $statustitle = trim($item['title']);
2527 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2528 $statustext = trim($statusbody);
2530 $statustext = trim($statustitle."\n\n".$statusbody);
2533 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2534 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2537 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2539 // Workaround for clients with limited HTML parser functionality
2540 $search = ["<br>", "<blockquote>", "</blockquote>",
2541 "<h1>", "</h1>", "<h2>", "</h2>",
2542 "<h3>", "</h3>", "<h4>", "</h4>",
2543 "<h5>", "</h5>", "<h6>", "</h6>"];
2544 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2545 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2546 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2547 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2548 $statushtml = str_replace($search, $replace, $statushtml);
2550 if ($item['title'] != "") {
2551 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2555 $oldtext = $statushtml;
2556 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2557 } while ($oldtext != $statushtml);
2559 if (substr($statushtml, 0, 4) == '<br>') {
2560 $statushtml = substr($statushtml, 4);
2563 if (substr($statushtml, 0, -4) == '<br>') {
2564 $statushtml = substr($statushtml, -4);
2567 // feeds without body should contain the link
2568 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2569 $statushtml .= BBCode::convert($item['plink']);
2573 "text" => $statustext,
2574 "html" => $statushtml,
2575 "attachments" => $attachments,
2576 "entities" => $entities
2582 * @param string $body
2585 * @throws InternalServerErrorException
2587 function api_get_attachments(&$body)
2589 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2590 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2592 $URLSearchString = "^\[\]";
2593 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2597 // Remove all embedded pictures, since they are added as attachments
2598 foreach ($images[0] as $orig) {
2599 $body = str_replace($orig, '', $body);
2604 foreach ($images[1] as $image) {
2605 $imagedata = Images::getInfoFromURLCached($image);
2608 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2612 return $attachments;
2617 * @param string $text
2618 * @param string $bbcode
2621 * @throws InternalServerErrorException
2622 * @todo Links at the first character of the post
2624 function api_get_entitities(&$text, $bbcode)
2626 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2628 if ($include_entities != "true") {
2629 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2631 foreach ($images[1] as $image) {
2632 $replace = ProxyUtils::proxifyUrl($image);
2633 $text = str_replace($image, $replace, $text);
2638 $bbcode = BBCode::cleanPictureLinks($bbcode);
2640 // Change pure links in text to bbcode uris
2641 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2644 $entities["hashtags"] = [];
2645 $entities["symbols"] = [];
2646 $entities["urls"] = [];
2647 $entities["user_mentions"] = [];
2649 $URLSearchString = "^\[\]";
2651 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2653 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2654 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2656 $bbcode = preg_replace(
2657 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2658 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2661 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2663 $bbcode = preg_replace(
2664 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2665 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2668 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2670 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2672 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2675 foreach ($urls[1] as $id => $url) {
2676 $start = iconv_strpos($text, $url, 0, "UTF-8");
2677 if (!($start === false)) {
2678 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2682 ksort($ordered_urls);
2686 foreach ($ordered_urls as $url) {
2687 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2688 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2690 $display_url = $url["title"];
2692 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2693 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2695 if (strlen($display_url) > 26) {
2696 $display_url = substr($display_url, 0, 25)."…";
2700 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2701 if (!($start === false)) {
2702 $entities["urls"][] = ["url" => $url["url"],
2703 "expanded_url" => $url["url"],
2704 "display_url" => $display_url,
2705 "indices" => [$start, $start+strlen($url["url"])]];
2706 $offset = $start + 1;
2710 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2711 $ordered_images = [];
2712 foreach ($images as $image) {
2713 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2714 if (!($start === false)) {
2715 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2719 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2720 foreach ($images[1] as $image) {
2721 $start = iconv_strpos($text, $image, 0, "UTF-8");
2722 if (!($start === false)) {
2723 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2729 foreach ($ordered_images as $image) {
2730 $url = $image['url'];
2731 $ext_alt_text = $image['alt'];
2733 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2734 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2736 if (strlen($display_url) > 26) {
2737 $display_url = substr($display_url, 0, 25)."…";
2740 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2741 if (!($start === false)) {
2742 $image = Images::getInfoFromURLCached($url);
2744 // If image cache is activated, then use the following sizes:
2745 // thumb (150), small (340), medium (600) and large (1024)
2746 if (!DI::config()->get("system", "proxy_disabled")) {
2747 $media_url = ProxyUtils::proxifyUrl($url);
2750 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2751 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2753 if (($image[0] > 150) || ($image[1] > 150)) {
2754 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2755 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2758 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2759 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2761 if (($image[0] > 600) || ($image[1] > 600)) {
2762 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2763 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2767 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2770 $entities["media"][] = [
2772 "id_str" => (string) ($start + 1),
2773 "indices" => [$start, $start+strlen($url)],
2774 "media_url" => Strings::normaliseLink($media_url),
2775 "media_url_https" => $media_url,
2777 "display_url" => $display_url,
2778 "expanded_url" => $url,
2779 "ext_alt_text" => $ext_alt_text,
2783 $offset = $start + 1;
2792 * @param array $item
2793 * @param string $text
2797 function api_format_items_embeded_images($item, $text)
2799 $text = preg_replace_callback(
2800 '|data:image/([^;]+)[^=]+=*|m',
2801 function () use ($item) {
2802 return DI::baseUrl() . '/display/' . $item['guid'];
2810 * return <a href='url'>name</a> as array
2812 * @param string $txt text
2817 function api_contactlink_to_array($txt)
2820 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2821 if ($r && count($match)==3) {
2823 'name' => $match[2],
2837 * return likes, dislikes and attend status for item
2839 * @param array $item array
2840 * @param string $type Return type (atom, rss, xml, json)
2843 * likes => int count,
2844 * dislikes => int count
2845 * @throws BadRequestException
2846 * @throws ImagickException
2847 * @throws InternalServerErrorException
2848 * @throws UnauthorizedException
2850 function api_format_items_activities($item, $type = "json")
2859 'attendmaybe' => [],
2863 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2864 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2866 while ($parent_item = Post::fetch($ret)) {
2867 // not used as result should be structured like other user data
2868 //builtin_activity_puller($i, $activities);
2870 // get user data and add it to the array of the activity
2871 $user = api_get_user($a, $parent_item['author-id']);
2872 switch ($parent_item['verb']) {
2873 case Activity::LIKE:
2874 $activities['like'][] = $user;
2876 case Activity::DISLIKE:
2877 $activities['dislike'][] = $user;
2879 case Activity::ATTEND:
2880 $activities['attendyes'][] = $user;
2882 case Activity::ATTENDNO:
2883 $activities['attendno'][] = $user;
2885 case Activity::ATTENDMAYBE:
2886 $activities['attendmaybe'][] = $user;
2888 case Activity::ANNOUNCE:
2889 $activities['announce'][] = $user;
2898 if ($type == "xml") {
2899 $xml_activities = [];
2900 foreach ($activities as $k => $v) {
2901 // change xml element from "like" to "friendica:like"
2902 $xml_activities["friendica:".$k] = $v;
2903 // add user data into xml output
2905 foreach ($v as $user) {
2906 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2909 $activities = $xml_activities;
2916 * format items to be returned by api
2918 * @param array $items array of items
2919 * @param array $user_info
2920 * @param bool $filter_user filter items by $user_info
2921 * @param string $type Return type (atom, rss, xml, json)
2923 * @throws BadRequestException
2924 * @throws ImagickException
2925 * @throws InternalServerErrorException
2926 * @throws UnauthorizedException
2928 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2930 $a = Friendica\DI::app();
2934 foreach ((array)$items as $item) {
2935 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2937 // Look if the posts are matching if they should be filtered by user id
2938 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2942 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2951 * @param array $item Item record
2952 * @param string $type Return format (atom, rss, xml, json)
2953 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2954 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2955 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2956 * @return array API-formatted status
2957 * @throws BadRequestException
2958 * @throws ImagickException
2959 * @throws InternalServerErrorException
2960 * @throws UnauthorizedException
2962 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2964 $a = Friendica\DI::app();
2966 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2967 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2970 localize_item($item);
2972 $in_reply_to = api_in_reply_to($item);
2974 $converted = api_convert_item($item);
2976 if ($type == "xml") {
2977 $geo = "georss:point";
2983 'text' => $converted["text"],
2984 'truncated' => false,
2985 'created_at'=> api_date($item['created']),
2986 'in_reply_to_status_id' => $in_reply_to['status_id'],
2987 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2988 'source' => (($item['app']) ? $item['app'] : 'web'),
2989 'id' => intval($item['id']),
2990 'id_str' => (string) intval($item['id']),
2991 'in_reply_to_user_id' => $in_reply_to['user_id'],
2992 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2993 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2995 'favorited' => $item['starred'] ? true : false,
2996 'user' => $status_user,
2997 'friendica_author' => $author_user,
2998 'friendica_owner' => $owner_user,
2999 'friendica_private' => $item['private'] == Item::PRIVATE,
3000 //'entities' => NULL,
3001 'statusnet_html' => $converted["html"],
3002 'statusnet_conversation_id' => $item['parent'],
3003 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3004 'friendica_activities' => api_format_items_activities($item, $type),
3005 'friendica_title' => $item['title'],
3006 'friendica_html' => BBCode::convert($item['body'], false)
3009 if (count($converted["attachments"]) > 0) {
3010 $status["attachments"] = $converted["attachments"];
3013 if (count($converted["entities"]) > 0) {
3014 $status["entities"] = $converted["entities"];
3017 if ($status["source"] == 'web') {
3018 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3019 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3020 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3023 $retweeted_item = [];
3026 if ($item['gravity'] == GRAVITY_PARENT) {
3027 $body = $item['body'];
3028 $retweeted_item = api_share_as_retweet($item);
3029 if ($body != $item['body']) {
3030 $quoted_item = $retweeted_item;
3031 $retweeted_item = [];
3035 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3036 $announce = api_get_announce($item);
3037 if (!empty($announce)) {
3038 $retweeted_item = $item;
3040 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3044 if (!empty($quoted_item)) {
3045 if ($quoted_item['id'] != $item['id']) {
3046 $quoted_status = api_format_item($quoted_item);
3047 /// @todo Only remove the attachments that are also contained in the quotes status
3048 unset($status['attachments']);
3049 unset($status['entities']);
3051 $conv_quoted = api_convert_item($quoted_item);
3052 $quoted_status = $status;
3053 unset($quoted_status['attachments']);
3054 unset($quoted_status['entities']);
3055 unset($quoted_status['statusnet_conversation_id']);
3056 $quoted_status['text'] = $conv_quoted['text'];
3057 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3059 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3060 } catch (BadRequestException $e) {
3061 // user not found. should be found?
3062 /// @todo check if the user should be always found
3063 $quoted_status["user"] = [];
3066 unset($quoted_status['friendica_author']);
3067 unset($quoted_status['friendica_owner']);
3068 unset($quoted_status['friendica_activities']);
3069 unset($quoted_status['friendica_private']);
3072 if (!empty($retweeted_item)) {
3073 $retweeted_status = $status;
3074 unset($retweeted_status['friendica_author']);
3075 unset($retweeted_status['friendica_owner']);
3076 unset($retweeted_status['friendica_activities']);
3077 unset($retweeted_status['friendica_private']);
3078 unset($retweeted_status['statusnet_conversation_id']);
3079 $status['user'] = $status['friendica_owner'];
3081 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3082 } catch (BadRequestException $e) {
3083 // user not found. should be found?
3084 /// @todo check if the user should be always found
3085 $retweeted_status["user"] = [];
3088 $rt_converted = api_convert_item($retweeted_item);
3090 $retweeted_status['text'] = $rt_converted["text"];
3091 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3092 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3094 if (!empty($quoted_status)) {
3095 $retweeted_status['quoted_status'] = $quoted_status;
3098 $status['friendica_author'] = $retweeted_status['user'];
3099 $status['retweeted_status'] = $retweeted_status;
3100 } elseif (!empty($quoted_status)) {
3101 $root_status = api_convert_item($item);
3103 $status['text'] = $root_status["text"];
3104 $status['statusnet_html'] = $root_status["html"];
3105 $status['quoted_status'] = $quoted_status;
3108 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3109 unset($status["user"]["uid"]);
3110 unset($status["user"]["self"]);
3112 if ($item["coord"] != "") {
3113 $coords = explode(' ', $item["coord"]);
3114 if (count($coords) == 2) {
3115 if ($type == "json") {
3116 $status["geo"] = ['type' => 'Point',
3117 'coordinates' => [(float) $coords[0],
3118 (float) $coords[1]]];
3119 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3120 $status["georss:point"] = $item["coord"];
3129 * Returns the remaining number of API requests available to the user before the API limit is reached.
3131 * @param string $type Return type (atom, rss, xml, json)
3133 * @return array|string
3136 function api_account_rate_limit_status($type)
3138 if ($type == "xml") {
3140 'remaining-hits' => '150',
3141 '@attributes' => ["type" => "integer"],
3142 'hourly-limit' => '150',
3143 '@attributes2' => ["type" => "integer"],
3144 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3145 '@attributes3' => ["type" => "datetime"],
3146 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3147 '@attributes4' => ["type" => "integer"],
3151 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3152 'remaining_hits' => '150',
3153 'hourly_limit' => '150',
3154 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3158 return api_format_data('hash', $type, ['hash' => $hash]);
3161 /// @TODO move to top of file or somewhere better
3162 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3165 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3167 * @param string $type Return type (atom, rss, xml, json)
3169 * @return array|string
3171 function api_help_test($type)
3173 if ($type == 'xml') {
3179 return api_format_data('ok', $type, ["ok" => $ok]);
3182 /// @TODO move to top of file or somewhere better
3183 api_register_func('api/help/test', 'api_help_test', false);
3186 * Returns all lists the user subscribes to.
3188 * @param string $type Return type (atom, rss, xml, json)
3190 * @return array|string
3191 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3193 function api_lists_list($type)
3196 /// @TODO $ret is not filled here?
3197 return api_format_data('lists', $type, ["lists_list" => $ret]);
3200 /// @TODO move to top of file or somewhere better
3201 api_register_func('api/lists/list', 'api_lists_list', true);
3202 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3205 * Returns all groups the user owns.
3207 * @param string $type Return type (atom, rss, xml, json)
3209 * @return array|string
3210 * @throws BadRequestException
3211 * @throws ForbiddenException
3212 * @throws ImagickException
3213 * @throws InternalServerErrorException
3214 * @throws UnauthorizedException
3215 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3217 function api_lists_ownerships($type)
3221 if (api_user() === false) {
3222 throw new ForbiddenException();
3226 $user_info = api_get_user($a);
3227 $uid = $user_info['uid'];
3229 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3231 // loop through all groups
3233 foreach ($groups as $group) {
3234 if ($group['visible']) {
3240 'name' => $group['name'],
3241 'id' => intval($group['id']),
3242 'id_str' => (string) $group['id'],
3243 'user' => $user_info,
3247 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3250 /// @TODO move to top of file or somewhere better
3251 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3254 * Returns recent statuses from users in the specified group.
3256 * @param string $type Return type (atom, rss, xml, json)
3258 * @return array|string
3259 * @throws BadRequestException
3260 * @throws ForbiddenException
3261 * @throws ImagickException
3262 * @throws InternalServerErrorException
3263 * @throws UnauthorizedException
3264 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3266 function api_lists_statuses($type)
3270 $user_info = api_get_user($a);
3271 if (api_user() === false || $user_info === false) {
3272 throw new ForbiddenException();
3275 unset($_REQUEST["user_id"]);
3276 unset($_GET["user_id"]);
3278 unset($_REQUEST["screen_name"]);
3279 unset($_GET["screen_name"]);
3281 if (empty($_REQUEST['list_id'])) {
3282 throw new BadRequestException('list_id not specified');
3286 $count = $_REQUEST['count'] ?? 20;
3287 $page = $_REQUEST['page'] ?? 1;
3288 $since_id = $_REQUEST['since_id'] ?? 0;
3289 $max_id = $_REQUEST['max_id'] ?? 0;
3290 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3291 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3293 $start = max(0, ($page - 1) * $count);
3295 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3296 $gids = array_column($groups, 'contact-id');
3297 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3298 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3301 $condition[0] .= " AND `id` <= ?";
3302 $condition[] = $max_id;
3304 if ($exclude_replies > 0) {
3305 $condition[0] .= ' AND `gravity` = ?';
3306 $condition[] = GRAVITY_PARENT;
3308 if ($conversation_id > 0) {
3309 $condition[0] .= " AND `parent` = ?";
3310 $condition[] = $conversation_id;
3313 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3314 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3316 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3318 $data = ['status' => $items];
3323 $data = api_rss_extra($a, $data, $user_info);
3327 return api_format_data("statuses", $type, $data);
3330 /// @TODO move to top of file or somewhere better
3331 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3334 * Returns either the friends of the follower list
3336 * Considers friends and followers lists to be private and won't return
3337 * anything if any user_id parameter is passed.
3339 * @param string $qtype Either "friends" or "followers"
3340 * @return boolean|array
3341 * @throws BadRequestException
3342 * @throws ForbiddenException
3343 * @throws ImagickException
3344 * @throws InternalServerErrorException
3345 * @throws UnauthorizedException
3347 function api_statuses_f($qtype)
3351 if (api_user() === false) {
3352 throw new ForbiddenException();
3356 $count = $_GET['count'] ?? 20;
3357 $page = $_GET['page'] ?? 1;
3359 $start = max(0, ($page - 1) * $count);
3361 $user_info = api_get_user($a);
3363 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3364 /* this is to stop Hotot to load friends multiple times
3365 * I'm not sure if I'm missing return something or
3366 * is a bug in hotot. Workaround, meantime
3370 return array('$users' => $ret);*/
3375 if ($qtype == 'friends') {
3376 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3377 } elseif ($qtype == 'followers') {
3378 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3381 // friends and followers only for self
3382 if ($user_info['self'] == 0) {
3383 $sql_extra = " AND false ";
3386 if ($qtype == 'blocks') {
3387 $sql_filter = 'AND `blocked` AND NOT `pending`';
3388 } elseif ($qtype == 'incoming') {
3389 $sql_filter = 'AND `pending`';
3391 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3409 foreach ($r as $cid) {
3410 $user = api_get_user($a, $cid['nurl']);
3411 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3412 unset($user["uid"]);
3413 unset($user["self"]);
3420 return ['user' => $ret];
3425 * Returns the list of friends of the provided user
3427 * @deprecated By Twitter API in favor of friends/list
3429 * @param string $type Either "json" or "xml"
3430 * @return boolean|string|array
3431 * @throws BadRequestException
3432 * @throws ForbiddenException
3434 function api_statuses_friends($type)
3436 $data = api_statuses_f("friends");
3437 if ($data === false) {
3440 return api_format_data("users", $type, $data);
3444 * Returns the list of followers of the provided user
3446 * @deprecated By Twitter API in favor of friends/list
3448 * @param string $type Either "json" or "xml"
3449 * @return boolean|string|array
3450 * @throws BadRequestException
3451 * @throws ForbiddenException
3453 function api_statuses_followers($type)
3455 $data = api_statuses_f("followers");
3456 if ($data === false) {
3459 return api_format_data("users", $type, $data);
3462 /// @TODO move to top of file or somewhere better
3463 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3464 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3467 * Returns the list of blocked users
3469 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3471 * @param string $type Either "json" or "xml"
3473 * @return boolean|string|array
3474 * @throws BadRequestException
3475 * @throws ForbiddenException
3477 function api_blocks_list($type)
3479 $data = api_statuses_f('blocks');
3480 if ($data === false) {
3483 return api_format_data("users", $type, $data);
3486 /// @TODO move to top of file or somewhere better
3487 api_register_func('api/blocks/list', 'api_blocks_list', true);
3490 * Returns the list of pending users IDs
3492 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3494 * @param string $type Either "json" or "xml"
3496 * @return boolean|string|array
3497 * @throws BadRequestException
3498 * @throws ForbiddenException
3500 function api_friendships_incoming($type)
3502 $data = api_statuses_f('incoming');
3503 if ($data === false) {
3508 foreach ($data['user'] as $user) {
3509 $ids[] = $user['id'];
3512 return api_format_data("ids", $type, ['id' => $ids]);
3515 /// @TODO move to top of file or somewhere better
3516 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3519 * Returns the instance's configuration information.
3521 * @param string $type Return type (atom, rss, xml, json)
3523 * @return array|string
3524 * @throws InternalServerErrorException
3526 function api_statusnet_config($type)
3528 $name = DI::config()->get('config', 'sitename');
3529 $server = DI::baseUrl()->getHostname();
3530 $logo = DI::baseUrl() . '/images/friendica-64.png';
3531 $email = DI::config()->get('config', 'admin_email');
3532 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3533 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3534 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3535 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3536 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3539 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3540 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3541 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3542 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3543 'shorturllength' => '30',
3545 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3546 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3547 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3548 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3553 return api_format_data('config', $type, ['config' => $config]);
3556 /// @TODO move to top of file or somewhere better
3557 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3558 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3562 * @param string $type Return type (atom, rss, xml, json)
3564 * @return array|string
3566 function api_statusnet_version($type)
3569 $fake_statusnet_version = "0.9.7";
3571 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3574 /// @TODO move to top of file or somewhere better
3575 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3576 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3579 * Sends a new direct message.
3581 * @param string $type Return type (atom, rss, xml, json)
3583 * @return array|string
3584 * @throws BadRequestException
3585 * @throws ForbiddenException
3586 * @throws ImagickException
3587 * @throws InternalServerErrorException
3588 * @throws NotFoundException
3589 * @throws UnauthorizedException
3590 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3592 function api_direct_messages_new($type)
3596 if (api_user() === false) {
3597 throw new ForbiddenException();
3600 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3604 $sender = api_get_user($a);
3607 if (!empty($_POST['screen_name'])) {
3609 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3611 DBA::escape($_POST['screen_name'])
3614 if (DBA::isResult($r)) {
3615 // Selecting the id by priority, friendica first
3616 api_best_nickname($r);
3618 $recipient = api_get_user($a, $r[0]['nurl']);
3621 $recipient = api_get_user($a, $_POST['user_id']);
3624 if (empty($recipient)) {
3625 throw new NotFoundException('Recipient not found');
3629 if (!empty($_REQUEST['replyto'])) {
3631 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3633 intval($_REQUEST['replyto'])
3635 $replyto = $r[0]['parent-uri'];
3636 $sub = $r[0]['title'];
3638 if (!empty($_REQUEST['title'])) {
3639 $sub = $_REQUEST['title'];
3641 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3645 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3648 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3649 $ret = api_format_messages($r[0], $recipient, $sender);
3651 $ret = ["error"=>$id];
3654 $data = ['direct_message'=>$ret];
3660 $data = api_rss_extra($a, $data, $sender);
3664 return api_format_data("direct-messages", $type, $data);
3667 /// @TODO move to top of file or somewhere better
3668 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3671 * delete a direct_message from mail table through api
3673 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3674 * @return string|array
3675 * @throws BadRequestException
3676 * @throws ForbiddenException
3677 * @throws ImagickException
3678 * @throws InternalServerErrorException
3679 * @throws UnauthorizedException
3680 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3682 function api_direct_messages_destroy($type)
3686 if (api_user() === false) {
3687 throw new ForbiddenException();
3691 $user_info = api_get_user($a);
3693 $id = $_REQUEST['id'] ?? 0;
3695 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3696 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3697 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3699 $uid = $user_info['uid'];
3700 // error if no id or parenturi specified (for clients posting parent-uri as well)
3701 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3702 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3703 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3706 // BadRequestException if no id specified (for clients using Twitter API)
3708 throw new BadRequestException('Message id not specified');
3711 // add parent-uri to sql command if specified by calling app
3712 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3714 // get data of the specified message id
3716 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3721 // error message if specified id is not in database
3722 if (!DBA::isResult($r)) {
3723 if ($verbose == "true") {
3724 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3725 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3727 /// @todo BadRequestException ok for Twitter API clients?
3728 throw new BadRequestException('message id not in database');
3733 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3738 if ($verbose == "true") {
3741 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3742 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3744 $answer = ['result' => 'error', 'message' => 'unknown error'];
3745 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3748 /// @todo return JSON data like Twitter API not yet implemented
3751 /// @TODO move to top of file or somewhere better
3752 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3757 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3758 * @return string|array
3759 * @throws BadRequestException
3760 * @throws ForbiddenException
3761 * @throws ImagickException
3762 * @throws InternalServerErrorException
3763 * @throws NotFoundException
3764 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3766 function api_friendships_destroy($type)
3770 if ($uid === false) {
3771 throw new ForbiddenException();
3774 $contact_id = $_REQUEST['user_id'] ?? 0;
3776 if (empty($contact_id)) {
3777 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3778 throw new BadRequestException("no user_id specified");
3781 // Get Contact by given id
3782 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3784 if(!DBA::isResult($contact)) {
3785 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3786 throw new NotFoundException("no contact found to given ID");
3789 $url = $contact["url"];
3791 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3792 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3793 Strings::normaliseLink($url), $url];
3794 $contact = DBA::selectFirst('contact', [], $condition);
3796 if (!DBA::isResult($contact)) {
3797 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3798 throw new NotFoundException("Not following Contact");
3801 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3802 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3803 throw new ExpectationFailedException("Not supported");
3806 $dissolve = ($contact['rel'] == Contact::SHARING);
3808 $owner = User::getOwnerDataById($uid);
3810 Contact::terminateFriendship($owner, $contact, $dissolve);
3813 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3814 throw new NotFoundException("Error Processing Request");
3817 // Sharing-only contacts get deleted as there no relationship any more
3819 Contact::remove($contact['id']);
3821 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3824 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3825 unset($contact["uid"]);
3826 unset($contact["self"]);
3828 // Set screen_name since Twidere requests it
3829 $contact["screen_name"] = $contact["nick"];
3831 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3833 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3837 * @param string $type Return type (atom, rss, xml, json)
3838 * @param string $box
3839 * @param string $verbose
3841 * @return array|string
3842 * @throws BadRequestException
3843 * @throws ForbiddenException
3844 * @throws ImagickException
3845 * @throws InternalServerErrorException
3846 * @throws UnauthorizedException
3848 function api_direct_messages_box($type, $box, $verbose)
3851 if (api_user() === false) {
3852 throw new ForbiddenException();
3855 $count = $_GET['count'] ?? 20;
3856 $page = $_REQUEST['page'] ?? 1;
3858 $since_id = $_REQUEST['since_id'] ?? 0;
3859 $max_id = $_REQUEST['max_id'] ?? 0;
3861 $user_id = $_REQUEST['user_id'] ?? '';
3862 $screen_name = $_REQUEST['screen_name'] ?? '';
3865 unset($_REQUEST["user_id"]);
3866 unset($_GET["user_id"]);
3868 unset($_REQUEST["screen_name"]);
3869 unset($_GET["screen_name"]);
3871 $user_info = api_get_user($a);
3872 if ($user_info === false) {
3873 throw new ForbiddenException();
3875 $profile_url = $user_info["url"];
3878 $start = max(0, ($page - 1) * $count);
3883 if ($box=="sentbox") {
3884 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3885 } elseif ($box == "conversation") {
3886 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3887 } elseif ($box == "all") {
3888 $sql_extra = "true";
3889 } elseif ($box == "inbox") {
3890 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3894 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3897 if ($user_id != "") {
3898 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3899 } elseif ($screen_name !="") {
3900 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3904 "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",
3910 if ($verbose == "true" && !DBA::isResult($r)) {
3911 $answer = ['result' => 'error', 'message' => 'no mails available'];
3912 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3916 foreach ($r as $item) {
3917 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3918 $recipient = $user_info;
3919 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3920 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3921 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3922 $sender = $user_info;
3925 if (isset($recipient) && isset($sender)) {
3926 $ret[] = api_format_messages($item, $recipient, $sender);
3931 $data = ['direct_message' => $ret];
3936 $data = api_rss_extra($a, $data, $user_info);
3940 return api_format_data("direct-messages", $type, $data);
3944 * Returns the most recent direct messages sent by the user.
3946 * @param string $type Return type (atom, rss, xml, json)
3948 * @return array|string
3949 * @throws BadRequestException
3950 * @throws ForbiddenException
3951 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3953 function api_direct_messages_sentbox($type)
3955 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3956 return api_direct_messages_box($type, "sentbox", $verbose);
3960 * Returns the most recent direct messages sent to the user.
3962 * @param string $type Return type (atom, rss, xml, json)
3964 * @return array|string
3965 * @throws BadRequestException
3966 * @throws ForbiddenException
3967 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3969 function api_direct_messages_inbox($type)
3971 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3972 return api_direct_messages_box($type, "inbox", $verbose);
3977 * @param string $type Return type (atom, rss, xml, json)
3979 * @return array|string
3980 * @throws BadRequestException
3981 * @throws ForbiddenException
3983 function api_direct_messages_all($type)
3985 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3986 return api_direct_messages_box($type, "all", $verbose);
3991 * @param string $type Return type (atom, rss, xml, json)
3993 * @return array|string
3994 * @throws BadRequestException
3995 * @throws ForbiddenException
3997 function api_direct_messages_conversation($type)
3999 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4000 return api_direct_messages_box($type, "conversation", $verbose);
4003 /// @TODO move to top of file or somewhere better
4004 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4005 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4006 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4007 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4010 * Returns an OAuth Request Token.
4012 * @see https://oauth.net/core/1.0/#auth_step1
4014 function api_oauth_request_token()
4016 $oauth1 = new FKOAuth1();
4018 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4019 } catch (Exception $e) {
4020 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4028 * Returns an OAuth Access Token.
4030 * @return array|string
4031 * @see https://oauth.net/core/1.0/#auth_step3
4033 function api_oauth_access_token()
4035 $oauth1 = new FKOAuth1();
4037 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4038 } catch (Exception $e) {
4039 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4046 /// @TODO move to top of file or somewhere better
4047 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4048 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4052 * delete a complete photoalbum with all containing photos from database through api
4054 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4055 * @return string|array
4056 * @throws BadRequestException
4057 * @throws ForbiddenException
4058 * @throws InternalServerErrorException
4060 function api_fr_photoalbum_delete($type)
4062 if (api_user() === false) {
4063 throw new ForbiddenException();
4066 $album = $_REQUEST['album'] ?? '';
4068 // we do not allow calls without album string
4070 throw new BadRequestException("no albumname specified");
4072 // check if album is existing
4074 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4075 if (!DBA::isResult($photos)) {
4076 throw new BadRequestException("album not available");
4079 $resourceIds = array_column($photos, 'resource-id');
4081 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4082 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4083 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4084 Item::deleteForUser($condition, api_user());
4086 // now let's delete all photos from the album
4087 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4089 // return success of deletion or error message
4091 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4092 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4094 throw new InternalServerErrorException("unknown error - deleting from database failed");
4099 * update the name of the album for all photos of an album
4101 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4102 * @return string|array
4103 * @throws BadRequestException
4104 * @throws ForbiddenException
4105 * @throws InternalServerErrorException
4107 function api_fr_photoalbum_update($type)
4109 if (api_user() === false) {
4110 throw new ForbiddenException();
4113 $album = $_REQUEST['album'] ?? '';
4114 $album_new = $_REQUEST['album_new'] ?? '';
4116 // we do not allow calls without album string
4118 throw new BadRequestException("no albumname specified");
4120 if ($album_new == "") {
4121 throw new BadRequestException("no new albumname specified");
4123 // check if album is existing
4124 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4125 throw new BadRequestException("album not available");
4127 // now let's update all photos to the albumname
4128 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4130 // return success of updating or error message
4132 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4133 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4135 throw new InternalServerErrorException("unknown error - updating in database failed");
4141 * list all photos of the authenticated user
4143 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4144 * @return string|array
4145 * @throws ForbiddenException
4146 * @throws InternalServerErrorException
4148 function api_fr_photos_list($type)
4150 if (api_user() === false) {
4151 throw new ForbiddenException();
4154 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4155 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4156 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4157 intval(local_user())
4160 'image/jpeg' => 'jpg',
4161 'image/png' => 'png',
4162 'image/gif' => 'gif'
4164 $data = ['photo'=>[]];
4165 if (DBA::isResult($r)) {
4166 foreach ($r as $rr) {
4168 $photo['id'] = $rr['resource-id'];
4169 $photo['album'] = $rr['album'];
4170 $photo['filename'] = $rr['filename'];
4171 $photo['type'] = $rr['type'];
4172 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4173 $photo['created'] = $rr['created'];
4174 $photo['edited'] = $rr['edited'];
4175 $photo['desc'] = $rr['desc'];
4177 if ($type == "xml") {
4178 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4180 $photo['thumb'] = $thumb;
4181 $data['photo'][] = $photo;
4185 return api_format_data("photos", $type, $data);
4189 * upload a new photo or change an existing photo
4191 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4192 * @return string|array
4193 * @throws BadRequestException
4194 * @throws ForbiddenException
4195 * @throws ImagickException
4196 * @throws InternalServerErrorException
4197 * @throws NotFoundException
4199 function api_fr_photo_create_update($type)
4201 if (api_user() === false) {
4202 throw new ForbiddenException();
4205 $photo_id = $_REQUEST['photo_id'] ?? null;
4206 $desc = $_REQUEST['desc'] ?? null;
4207 $album = $_REQUEST['album'] ?? null;
4208 $album_new = $_REQUEST['album_new'] ?? null;
4209 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4210 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4211 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4212 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4213 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4215 // do several checks on input parameters
4216 // we do not allow calls without album string
4217 if ($album == null) {
4218 throw new BadRequestException("no albumname specified");
4220 // if photo_id == null --> we are uploading a new photo
4221 if ($photo_id == null) {
4224 // error if no media posted in create-mode
4225 if (empty($_FILES['media'])) {
4227 throw new BadRequestException("no media data submitted");
4230 // album_new will be ignored in create-mode
4235 // check if photo is existing in databasei
4236 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4237 throw new BadRequestException("photo not available");
4241 // checks on acl strings provided by clients
4242 $acl_input_error = false;
4243 $acl_input_error |= check_acl_input($allow_cid);
4244 $acl_input_error |= check_acl_input($deny_cid);
4245 $acl_input_error |= check_acl_input($allow_gid);
4246 $acl_input_error |= check_acl_input($deny_gid);
4247 if ($acl_input_error) {
4248 throw new BadRequestException("acl data invalid");
4250 // now let's upload the new media in create-mode
4251 if ($mode == "create") {
4252 $media = $_FILES['media'];
4253 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4255 // return success of updating or error message
4256 if (!is_null($data)) {
4257 return api_format_data("photo_create", $type, $data);
4259 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4263 // now let's do the changes in update-mode
4264 if ($mode == "update") {
4265 $updated_fields = [];
4267 if (!is_null($desc)) {
4268 $updated_fields['desc'] = $desc;
4271 if (!is_null($album_new)) {
4272 $updated_fields['album'] = $album_new;
4275 if (!is_null($allow_cid)) {
4276 $allow_cid = trim($allow_cid);
4277 $updated_fields['allow_cid'] = $allow_cid;
4280 if (!is_null($deny_cid)) {
4281 $deny_cid = trim($deny_cid);
4282 $updated_fields['deny_cid'] = $deny_cid;
4285 if (!is_null($allow_gid)) {
4286 $allow_gid = trim($allow_gid);
4287 $updated_fields['allow_gid'] = $allow_gid;
4290 if (!is_null($deny_gid)) {
4291 $deny_gid = trim($deny_gid);
4292 $updated_fields['deny_gid'] = $deny_gid;
4296 if (count($updated_fields) > 0) {
4297 $nothingtodo = false;
4298 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4300 $nothingtodo = true;
4303 if (!empty($_FILES['media'])) {
4304 $nothingtodo = false;
4305 $media = $_FILES['media'];
4306 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4307 if (!is_null($data)) {
4308 return api_format_data("photo_update", $type, $data);
4312 // return success of updating or error message
4314 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4315 return api_format_data("photo_update", $type, ['$result' => $answer]);
4318 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4319 return api_format_data("photo_update", $type, ['$result' => $answer]);
4321 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4324 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4328 * delete a single photo from the database through api
4330 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4331 * @return string|array
4332 * @throws BadRequestException
4333 * @throws ForbiddenException
4334 * @throws InternalServerErrorException
4336 function api_fr_photo_delete($type)
4338 if (api_user() === false) {
4339 throw new ForbiddenException();
4343 $photo_id = $_REQUEST['photo_id'] ?? null;
4345 // do several checks on input parameters
4346 // we do not allow calls without photo id
4347 if ($photo_id == null) {
4348 throw new BadRequestException("no photo_id specified");
4351 // check if photo is existing in database
4352 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4353 throw new BadRequestException("photo not available");
4356 // now we can perform on the deletion of the photo
4357 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4359 // return success of deletion or error message
4361 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4362 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4363 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4364 Item::deleteForUser($condition, api_user());
4366 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4367 return api_format_data("photo_delete", $type, ['$result' => $result]);
4369 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4375 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4377 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4378 * @return string|array
4379 * @throws BadRequestException
4380 * @throws ForbiddenException
4381 * @throws InternalServerErrorException
4382 * @throws NotFoundException
4384 function api_fr_photo_detail($type)
4386 if (api_user() === false) {
4387 throw new ForbiddenException();
4389 if (empty($_REQUEST['photo_id'])) {
4390 throw new BadRequestException("No photo id.");
4393 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4394 $photo_id = $_REQUEST['photo_id'];
4396 // prepare json/xml output with data from database for the requested photo
4397 $data = prepare_photo_data($type, $scale, $photo_id);
4399 return api_format_data("photo_detail", $type, $data);
4404 * updates the profile image for the user (either a specified profile or the default profile)
4406 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4408 * @return string|array
4409 * @throws BadRequestException
4410 * @throws ForbiddenException
4411 * @throws ImagickException
4412 * @throws InternalServerErrorException
4413 * @throws NotFoundException
4414 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4416 function api_account_update_profile_image($type)
4418 if (api_user() === false) {
4419 throw new ForbiddenException();
4422 $profile_id = $_REQUEST['profile_id'] ?? 0;
4424 // error if image data is missing
4425 if (empty($_FILES['image'])) {
4426 throw new BadRequestException("no media data submitted");
4429 // check if specified profile id is valid
4430 if ($profile_id != 0) {
4431 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4432 // error message if specified profile id is not in database
4433 if (!DBA::isResult($profile)) {
4434 throw new BadRequestException("profile_id not available");
4436 $is_default_profile = $profile['is-default'];
4438 $is_default_profile = 1;
4441 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4443 if (!empty($_FILES['image'])) {
4444 $media = $_FILES['image'];
4445 } elseif (!empty($_FILES['media'])) {
4446 $media = $_FILES['media'];
4448 // save new profile image
4449 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4452 if (is_array($media['type'])) {
4453 $filetype = $media['type'][0];
4455 $filetype = $media['type'];
4457 if ($filetype == "image/jpeg") {
4459 } elseif ($filetype == "image/png") {
4462 throw new InternalServerErrorException('Unsupported filetype');
4465 // change specified profile or all profiles to the new resource-id
4466 if ($is_default_profile) {
4467 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4468 Photo::update(['profile' => false], $condition);
4470 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4471 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4472 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4475 Contact::updateSelfFromUserID(api_user(), true);
4477 // Update global directory in background
4478 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4479 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4480 Worker::add(PRIORITY_LOW, "Directory", $url);
4483 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4485 // output for client
4487 return api_account_verify_credentials($type);
4489 // SaveMediaToDatabase failed for some reason
4490 throw new InternalServerErrorException("image upload failed");
4494 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4495 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4496 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4497 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4498 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4499 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4500 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4501 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4502 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4505 * Update user profile
4507 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4509 * @return array|string
4510 * @throws BadRequestException
4511 * @throws ForbiddenException
4512 * @throws ImagickException
4513 * @throws InternalServerErrorException
4514 * @throws UnauthorizedException
4516 function api_account_update_profile($type)
4518 $local_user = api_user();
4519 $api_user = api_get_user(DI::app());
4521 if (!empty($_POST['name'])) {
4522 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4523 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4524 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4525 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4528 if (isset($_POST['description'])) {
4529 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4530 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4531 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4534 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4535 // Update global directory in background
4536 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4537 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4540 return api_account_verify_credentials($type);
4543 /// @TODO move to top of file or somewhere better
4544 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4548 * @param string $acl_string
4552 function check_acl_input($acl_string)
4554 if (empty($acl_string)) {
4558 $contact_not_found = false;
4560 // split <x><y><z> into array of cid's
4561 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4563 // check for each cid if it is available on server
4564 $cid_array = $array[0];
4565 foreach ($cid_array as $cid) {
4566 $cid = str_replace("<", "", $cid);
4567 $cid = str_replace(">", "", $cid);
4568 $condition = ['id' => $cid, 'uid' => api_user()];
4569 $contact_not_found |= !DBA::exists('contact', $condition);
4571 return $contact_not_found;
4575 * @param string $mediatype
4576 * @param array $media
4577 * @param string $type
4578 * @param string $album
4579 * @param string $allow_cid
4580 * @param string $deny_cid
4581 * @param string $allow_gid
4582 * @param string $deny_gid
4583 * @param string $desc
4584 * @param integer $profile
4585 * @param boolean $visibility
4586 * @param string $photo_id
4588 * @throws BadRequestException
4589 * @throws ForbiddenException
4590 * @throws ImagickException
4591 * @throws InternalServerErrorException
4592 * @throws NotFoundException
4593 * @throws UnauthorizedException
4595 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)
4603 if (is_array($media)) {
4604 if (is_array($media['tmp_name'])) {
4605 $src = $media['tmp_name'][0];
4607 $src = $media['tmp_name'];
4609 if (is_array($media['name'])) {
4610 $filename = basename($media['name'][0]);
4612 $filename = basename($media['name']);
4614 if (is_array($media['size'])) {
4615 $filesize = intval($media['size'][0]);
4617 $filesize = intval($media['size']);
4619 if (is_array($media['type'])) {
4620 $filetype = $media['type'][0];
4622 $filetype = $media['type'];
4626 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4629 "File upload src: " . $src . " - filename: " . $filename .
4630 " - size: " . $filesize . " - type: " . $filetype,
4634 // check if there was a php upload error
4635 if ($filesize == 0 && $media['error'] == 1) {
4636 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4638 // check against max upload size within Friendica instance
4639 $maximagesize = DI::config()->get('system', 'maximagesize');
4640 if ($maximagesize && ($filesize > $maximagesize)) {
4641 $formattedBytes = Strings::formatBytes($maximagesize);
4642 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4645 // create Photo instance with the data of the image
4646 $imagedata = @file_get_contents($src);
4647 $Image = new Image($imagedata, $filetype);
4648 if (!$Image->isValid()) {
4649 throw new InternalServerErrorException("unable to process image data");
4652 // check orientation of image
4653 $Image->orient($src);
4656 // check max length of images on server
4657 $max_length = DI::config()->get('system', 'max_image_length');
4659 $max_length = MAX_IMAGE_LENGTH;
4661 if ($max_length > 0) {
4662 $Image->scaleDown($max_length);
4663 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4665 $width = $Image->getWidth();
4666 $height = $Image->getHeight();
4668 // create a new resource-id if not already provided
4669 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4671 if ($mediatype == "photo") {
4672 // upload normal image (scales 0, 1, 2)
4673 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4675 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4677 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4679 if ($width > 640 || $height > 640) {
4680 $Image->scaleDown(640);
4681 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4683 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4687 if ($width > 320 || $height > 320) {
4688 $Image->scaleDown(320);
4689 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4691 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4694 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4695 } elseif ($mediatype == "profileimage") {
4696 // upload profile image (scales 4, 5, 6)
4697 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4699 if ($width > 300 || $height > 300) {
4700 $Image->scaleDown(300);
4701 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4703 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4707 if ($width > 80 || $height > 80) {
4708 $Image->scaleDown(80);
4709 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4711 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4715 if ($width > 48 || $height > 48) {
4716 $Image->scaleDown(48);
4717 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4719 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4722 $Image->__destruct();
4723 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4727 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4728 if ($photo_id == null && $mediatype == "photo") {
4729 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4731 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4732 return prepare_photo_data($type, false, $resource_id);
4734 throw new InternalServerErrorException("image upload failed");
4740 * @param string $hash
4741 * @param string $allow_cid
4742 * @param string $deny_cid
4743 * @param string $allow_gid
4744 * @param string $deny_gid
4745 * @param string $filetype
4746 * @param boolean $visibility
4747 * @throws InternalServerErrorException
4749 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4751 // get data about the api authenticated user
4752 $uri = Item::newURI(intval(api_user()));
4753 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4756 $arr['guid'] = System::createUUID();
4757 $arr['uid'] = intval(api_user());
4759 $arr['type'] = 'photo';
4761 $arr['resource-id'] = $hash;
4762 $arr['contact-id'] = $owner_record['id'];
4763 $arr['owner-name'] = $owner_record['name'];
4764 $arr['owner-link'] = $owner_record['url'];
4765 $arr['owner-avatar'] = $owner_record['thumb'];
4766 $arr['author-name'] = $owner_record['name'];
4767 $arr['author-link'] = $owner_record['url'];
4768 $arr['author-avatar'] = $owner_record['thumb'];
4770 $arr['allow_cid'] = $allow_cid;
4771 $arr['allow_gid'] = $allow_gid;
4772 $arr['deny_cid'] = $deny_cid;
4773 $arr['deny_gid'] = $deny_gid;
4774 $arr['visible'] = $visibility;
4778 'image/jpeg' => 'jpg',
4779 'image/png' => 'png',
4780 'image/gif' => 'gif'
4783 // adds link to the thumbnail scale photo
4784 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4785 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4788 // do the magic for storing the item in the database and trigger the federation to other contacts
4794 * @param string $type
4796 * @param string $photo_id
4799 * @throws BadRequestException
4800 * @throws ForbiddenException
4801 * @throws ImagickException
4802 * @throws InternalServerErrorException
4803 * @throws NotFoundException
4804 * @throws UnauthorizedException
4806 function prepare_photo_data($type, $scale, $photo_id)
4809 $user_info = api_get_user($a);
4811 if ($user_info === false) {
4812 throw new ForbiddenException();
4815 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4816 $data_sql = ($scale === false ? "" : "data, ");
4818 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4819 // clients needs to convert this in their way for further processing
4821 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4822 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4823 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4824 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4825 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4826 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4828 intval(local_user()),
4829 DBA::escape($photo_id),
4834 'image/jpeg' => 'jpg',
4835 'image/png' => 'png',
4836 'image/gif' => 'gif'
4839 // prepare output data for photo
4840 if (DBA::isResult($r)) {
4841 $data = ['photo' => $r[0]];
4842 $data['photo']['id'] = $data['photo']['resource-id'];
4843 if ($scale !== false) {
4844 $data['photo']['data'] = base64_encode($data['photo']['data']);
4846 unset($data['photo']['datasize']); //needed only with scale param
4848 if ($type == "xml") {
4849 $data['photo']['links'] = [];
4850 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4851 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4853 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4856 $data['photo']['link'] = [];
4857 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4859 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4860 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4864 unset($data['photo']['resource-id']);
4865 unset($data['photo']['minscale']);
4866 unset($data['photo']['maxscale']);
4868 throw new NotFoundException();
4871 // retrieve item element for getting activities (like, dislike etc.) related to photo
4872 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4873 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4874 if (!DBA::isResult($item)) {
4875 throw new NotFoundException('Photo-related item not found.');
4878 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4880 // retrieve comments on photo
4881 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4882 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4884 $statuses = Post::selectForUser(api_user(), [], $condition);
4886 // prepare output of comments
4887 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4889 if ($type == "xml") {
4891 foreach ($commentData as $comment) {
4892 $comments[$k++ . ":comment"] = $comment;
4895 foreach ($commentData as $comment) {
4896 $comments[] = $comment;
4899 $data['photo']['friendica_comments'] = $comments;
4901 // include info if rights on photo and rights on item are mismatching
4902 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4903 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4904 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4905 $data['photo']['deny_gid'] != $item['deny_gid'];
4906 $data['photo']['rights_mismatch'] = $rights_mismatch;
4913 * Similar as /mod/redir.php
4914 * redirect to 'url' after dfrn auth
4916 * Why this when there is mod/redir.php already?
4917 * This use api_user() and api_login()
4920 * c_url: url of remote contact to auth to
4921 * url: string, url to redirect after auth
4923 function api_friendica_remoteauth()
4925 $url = $_GET['url'] ?? '';
4926 $c_url = $_GET['c_url'] ?? '';
4928 if ($url === '' || $c_url === '') {
4929 throw new BadRequestException("Wrong parameters.");
4932 $c_url = Strings::normaliseLink($c_url);
4936 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4937 if (!DBA::isResult($contact)) {
4938 throw new BadRequestException("Unknown contact");
4941 $cid = $contact['id'];
4943 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
4945 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
4946 System::externalRedirect($url ?: $c_url);
4949 if ($contact['duplex'] && $contact['issued-id']) {
4950 $orig_id = $contact['issued-id'];
4951 $dfrn_id = '1:' . $orig_id;
4953 if ($contact['duplex'] && $contact['dfrn-id']) {
4954 $orig_id = $contact['dfrn-id'];
4955 $dfrn_id = '0:' . $orig_id;
4958 $sec = Strings::getRandomHex();
4960 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4961 'sec' => $sec, 'expire' => time() + 45];
4962 DBA::insert('profile_check', $fields);
4964 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4965 $dest = ($url ? '&destination_url=' . $url : '');
4967 System::externalRedirect(
4968 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4969 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4970 . '&type=profile&sec=' . $sec . $dest
4973 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4976 * Return an item with announcer data if it had been announced
4978 * @param array $item Item array
4979 * @return array Item array with announce data
4981 function api_get_announce($item)
4983 // Quit if the item already has got a different owner and author
4984 if ($item['owner-id'] != $item['author-id']) {
4988 // Don't change original or Diaspora posts
4989 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4993 // Quit if we do now the original author and it had been a post from a native network
4994 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4998 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4999 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5000 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5001 if (!DBA::isResult($announce)) {
5005 return array_merge($item, $announce);
5009 * Return the item shared, if the item contains only the [share] tag
5011 * @param array $item Sharer item
5012 * @return array|false Shared item or false if not a reshare
5013 * @throws ImagickException
5014 * @throws InternalServerErrorException
5016 function api_share_as_retweet(&$item)
5018 $body = trim($item["body"]);
5020 if (Diaspora::isReshare($body, false) === false) {
5021 if ($item['author-id'] == $item['owner-id']) {
5024 // Reshares from OStatus, ActivityPub and Twitter
5025 $reshared_item = $item;
5026 $reshared_item['owner-id'] = $reshared_item['author-id'];
5027 $reshared_item['owner-link'] = $reshared_item['author-link'];
5028 $reshared_item['owner-name'] = $reshared_item['author-name'];
5029 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5030 return $reshared_item;
5034 $reshared = Item::getShareArray($item);
5035 if (empty($reshared)) {
5039 $reshared_item = $item;
5041 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5045 if (!empty($reshared['comment'])) {
5046 $item['body'] = $reshared['comment'];
5049 $reshared_item["share-pre-body"] = $reshared['comment'];
5050 $reshared_item["body"] = $reshared['shared'];
5051 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, false);
5052 $reshared_item["author-name"] = $reshared['author'];
5053 $reshared_item["author-link"] = $reshared['profile'];
5054 $reshared_item["author-avatar"] = $reshared['avatar'];
5055 $reshared_item["plink"] = $reshared['link'] ?? '';
5056 $reshared_item["created"] = $reshared['posted'];
5057 $reshared_item["edited"] = $reshared['posted'];
5059 // Try to fetch the original item
5060 if (!empty($reshared['guid'])) {
5061 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5062 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5063 $condition = ['id' => $original_id];
5068 if (!empty($condition)) {
5069 $original_item = Post::selectFirst([], $condition);
5070 if (DBA::isResult($original_item)) {
5071 $reshared_item = array_merge($reshared_item, $original_item);
5075 return $reshared_item;
5080 * @param array $item
5085 function api_in_reply_to($item)
5089 $in_reply_to['status_id'] = null;
5090 $in_reply_to['user_id'] = null;
5091 $in_reply_to['status_id_str'] = null;
5092 $in_reply_to['user_id_str'] = null;
5093 $in_reply_to['screen_name'] = null;
5095 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5096 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5097 if (DBA::isResult($parent)) {
5098 $in_reply_to['status_id'] = intval($parent['id']);
5100 $in_reply_to['status_id'] = intval($item['parent']);
5103 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5105 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5106 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5108 if (DBA::isResult($parent)) {
5109 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5110 $in_reply_to['user_id'] = intval($parent['author-id']);
5111 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5114 // There seems to be situation, where both fields are identical:
5115 // https://github.com/friendica/friendica/issues/1010
5116 // This is a bugfix for that.
5117 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5118 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']]);
5119 $in_reply_to['status_id'] = null;
5120 $in_reply_to['user_id'] = null;
5121 $in_reply_to['status_id_str'] = null;
5122 $in_reply_to['user_id_str'] = null;
5123 $in_reply_to['screen_name'] = null;
5127 return $in_reply_to;
5132 * @param string $text
5135 * @throws InternalServerErrorException
5137 function api_clean_plain_items($text)
5139 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5141 $text = BBCode::cleanPictureLinks($text);
5142 $URLSearchString = "^\[\]";
5144 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5146 if ($include_entities == "true") {
5147 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5150 // Simplify "attachment" element
5151 $text = BBCode::removeAttachment($text);
5158 * @param array $contacts
5162 function api_best_nickname(&$contacts)
5166 if (count($contacts) == 0) {
5170 foreach ($contacts as $contact) {
5171 if ($contact["network"] == "") {
5172 $contact["network"] = "dfrn";
5173 $best_contact = [$contact];
5177 if (sizeof($best_contact) == 0) {
5178 foreach ($contacts as $contact) {
5179 if ($contact["network"] == "dfrn") {
5180 $best_contact = [$contact];
5185 if (sizeof($best_contact) == 0) {
5186 foreach ($contacts as $contact) {
5187 if ($contact["network"] == "dspr") {
5188 $best_contact = [$contact];
5193 if (sizeof($best_contact) == 0) {
5194 foreach ($contacts as $contact) {
5195 if ($contact["network"] == "stat") {
5196 $best_contact = [$contact];
5201 if (sizeof($best_contact) == 0) {
5202 foreach ($contacts as $contact) {
5203 if ($contact["network"] == "pump") {
5204 $best_contact = [$contact];
5209 if (sizeof($best_contact) == 0) {
5210 foreach ($contacts as $contact) {
5211 if ($contact["network"] == "twit") {
5212 $best_contact = [$contact];
5217 if (sizeof($best_contact) == 1) {
5218 $contacts = $best_contact;
5220 $contacts = [$contacts[0]];
5225 * Return all or a specified group of the user with the containing contacts.
5227 * @param string $type Return type (atom, rss, xml, json)
5229 * @return array|string
5230 * @throws BadRequestException
5231 * @throws ForbiddenException
5232 * @throws ImagickException
5233 * @throws InternalServerErrorException
5234 * @throws UnauthorizedException
5236 function api_friendica_group_show($type)
5240 if (api_user() === false) {
5241 throw new ForbiddenException();
5245 $user_info = api_get_user($a);
5246 $gid = $_REQUEST['gid'] ?? 0;
5247 $uid = $user_info['uid'];
5249 // get data of the specified group id or all groups if not specified
5252 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5256 // error message if specified gid is not in database
5257 if (!DBA::isResult($r)) {
5258 throw new BadRequestException("gid not available");
5262 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5267 // loop through all groups and retrieve all members for adding data in the user array
5269 foreach ($r as $rr) {
5270 $members = Contact\Group::getById($rr['id']);
5273 if ($type == "xml") {
5274 $user_element = "users";
5276 foreach ($members as $member) {
5277 $user = api_get_user($a, $member['nurl']);
5278 $users[$k++.":user"] = $user;
5281 $user_element = "user";
5282 foreach ($members as $member) {
5283 $user = api_get_user($a, $member['nurl']);
5287 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5289 return api_format_data("groups", $type, ['group' => $grps]);
5291 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5295 * Delete the specified group of the user.
5297 * @param string $type Return type (atom, rss, xml, json)
5299 * @return array|string
5300 * @throws BadRequestException
5301 * @throws ForbiddenException
5302 * @throws ImagickException
5303 * @throws InternalServerErrorException
5304 * @throws UnauthorizedException
5306 function api_friendica_group_delete($type)
5310 if (api_user() === false) {
5311 throw new ForbiddenException();
5315 $user_info = api_get_user($a);
5316 $gid = $_REQUEST['gid'] ?? 0;
5317 $name = $_REQUEST['name'] ?? '';
5318 $uid = $user_info['uid'];
5320 // error if no gid specified
5321 if ($gid == 0 || $name == "") {
5322 throw new BadRequestException('gid or name not specified');
5325 // get data of the specified group id
5327 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5331 // error message if specified gid is not in database
5332 if (!DBA::isResult($r)) {
5333 throw new BadRequestException('gid not available');
5336 // get data of the specified group id and group name
5338 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5343 // error message if specified gid is not in database
5344 if (!DBA::isResult($rname)) {
5345 throw new BadRequestException('wrong group name');
5349 $ret = Group::removeByName($uid, $name);
5352 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5353 return api_format_data("group_delete", $type, ['result' => $success]);
5355 throw new BadRequestException('other API error');
5358 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5363 * @param string $type Return type (atom, rss, xml, json)
5365 * @return array|string
5366 * @throws BadRequestException
5367 * @throws ForbiddenException
5368 * @throws ImagickException
5369 * @throws InternalServerErrorException
5370 * @throws UnauthorizedException
5371 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5373 function api_lists_destroy($type)
5377 if (api_user() === false) {
5378 throw new ForbiddenException();
5382 $user_info = api_get_user($a);
5383 $gid = $_REQUEST['list_id'] ?? 0;
5384 $uid = $user_info['uid'];
5386 // error if no gid specified
5388 throw new BadRequestException('gid not specified');
5391 // get data of the specified group id
5392 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5393 // error message if specified gid is not in database
5395 throw new BadRequestException('gid not available');
5398 if (Group::remove($gid)) {
5400 'name' => $group['name'],
5401 'id' => intval($gid),
5402 'id_str' => (string) $gid,
5403 'user' => $user_info
5406 return api_format_data("lists", $type, ['lists' => $list]);
5409 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5412 * Add a new group to the database.
5414 * @param string $name Group name
5415 * @param int $uid User ID
5416 * @param array $users List of users to add to the group
5419 * @throws BadRequestException
5421 function group_create($name, $uid, $users = [])
5423 // error if no name specified
5425 throw new BadRequestException('group name not specified');
5428 // get data of the specified group name
5430 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5434 // error message if specified group name already exists
5435 if (DBA::isResult($rname)) {
5436 throw new BadRequestException('group name already exists');
5439 // check if specified group name is a deleted group
5441 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5445 // error message if specified group name already exists
5446 if (DBA::isResult($rname)) {
5447 $reactivate_group = true;
5451 $ret = Group::create($uid, $name);
5453 $gid = Group::getIdByName($uid, $name);
5455 throw new BadRequestException('other API error');
5459 $erroraddinguser = false;
5461 foreach ($users as $user) {
5462 $cid = $user['cid'];
5463 // check if user really exists as contact
5465 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5469 if (count($contact)) {
5470 Group::addMember($gid, $cid);
5472 $erroraddinguser = true;
5473 $errorusers[] = $cid;
5477 // return success message incl. missing users in array
5478 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5480 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5484 * Create the specified group with the posted array of contacts.
5486 * @param string $type Return type (atom, rss, xml, json)
5488 * @return array|string
5489 * @throws BadRequestException
5490 * @throws ForbiddenException
5491 * @throws ImagickException
5492 * @throws InternalServerErrorException
5493 * @throws UnauthorizedException
5495 function api_friendica_group_create($type)
5499 if (api_user() === false) {
5500 throw new ForbiddenException();
5504 $user_info = api_get_user($a);
5505 $name = $_REQUEST['name'] ?? '';
5506 $uid = $user_info['uid'];
5507 $json = json_decode($_POST['json'], true);
5508 $users = $json['user'];
5510 $success = group_create($name, $uid, $users);
5512 return api_format_data("group_create", $type, ['result' => $success]);
5514 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5517 * Create a new group.
5519 * @param string $type Return type (atom, rss, xml, json)
5521 * @return array|string
5522 * @throws BadRequestException
5523 * @throws ForbiddenException
5524 * @throws ImagickException
5525 * @throws InternalServerErrorException
5526 * @throws UnauthorizedException
5527 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5529 function api_lists_create($type)
5533 if (api_user() === false) {
5534 throw new ForbiddenException();
5538 $user_info = api_get_user($a);
5539 $name = $_REQUEST['name'] ?? '';
5540 $uid = $user_info['uid'];
5542 $success = group_create($name, $uid);
5543 if ($success['success']) {
5545 'name' => $success['name'],
5546 'id' => intval($success['gid']),
5547 'id_str' => (string) $success['gid'],
5548 'user' => $user_info
5551 return api_format_data("lists", $type, ['lists'=>$grp]);
5554 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5557 * Update the specified group with the posted array of contacts.
5559 * @param string $type Return type (atom, rss, xml, json)
5561 * @return array|string
5562 * @throws BadRequestException
5563 * @throws ForbiddenException
5564 * @throws ImagickException
5565 * @throws InternalServerErrorException
5566 * @throws UnauthorizedException
5568 function api_friendica_group_update($type)
5572 if (api_user() === false) {
5573 throw new ForbiddenException();
5577 $user_info = api_get_user($a);
5578 $uid = $user_info['uid'];
5579 $gid = $_REQUEST['gid'] ?? 0;
5580 $name = $_REQUEST['name'] ?? '';
5581 $json = json_decode($_POST['json'], true);
5582 $users = $json['user'];
5584 // error if no name specified
5586 throw new BadRequestException('group name not specified');
5589 // error if no gid specified
5591 throw new BadRequestException('gid not specified');
5595 $members = Contact\Group::getById($gid);
5596 foreach ($members as $member) {
5597 $cid = $member['id'];
5598 foreach ($users as $user) {
5599 $found = ($user['cid'] == $cid ? true : false);
5601 if (!isset($found) || !$found) {
5602 Group::removeMemberByName($uid, $name, $cid);
5607 $erroraddinguser = false;
5609 foreach ($users as $user) {
5610 $cid = $user['cid'];
5611 // check if user really exists as contact
5613 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5618 if (count($contact)) {
5619 Group::addMember($gid, $cid);
5621 $erroraddinguser = true;
5622 $errorusers[] = $cid;
5626 // return success message incl. missing users in array
5627 $status = ($erroraddinguser ? "missing user" : "ok");
5628 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5629 return api_format_data("group_update", $type, ['result' => $success]);
5632 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5635 * Update information about a group.
5637 * @param string $type Return type (atom, rss, xml, json)
5639 * @return array|string
5640 * @throws BadRequestException
5641 * @throws ForbiddenException
5642 * @throws ImagickException
5643 * @throws InternalServerErrorException
5644 * @throws UnauthorizedException
5645 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5647 function api_lists_update($type)
5651 if (api_user() === false) {
5652 throw new ForbiddenException();
5656 $user_info = api_get_user($a);
5657 $gid = $_REQUEST['list_id'] ?? 0;
5658 $name = $_REQUEST['name'] ?? '';
5659 $uid = $user_info['uid'];
5661 // error if no gid specified
5663 throw new BadRequestException('gid not specified');
5666 // get data of the specified group id
5667 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5668 // error message if specified gid is not in database
5670 throw new BadRequestException('gid not available');
5673 if (Group::update($gid, $name)) {
5676 'id' => intval($gid),
5677 'id_str' => (string) $gid,
5678 'user' => $user_info
5681 return api_format_data("lists", $type, ['lists' => $list]);
5685 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5689 * @param string $type Return type (atom, rss, xml, json)
5691 * @return array|string
5692 * @throws BadRequestException
5693 * @throws ForbiddenException
5694 * @throws ImagickException
5695 * @throws InternalServerErrorException
5697 function api_friendica_activity($type)
5701 if (api_user() === false) {
5702 throw new ForbiddenException();
5704 $verb = strtolower($a->argv[3]);
5705 $verb = preg_replace("|\..*$|", "", $verb);
5707 $id = $_REQUEST['id'] ?? 0;
5709 $res = Item::performActivity($id, $verb, api_user());
5712 if ($type == "xml") {
5717 return api_format_data('ok', $type, ['ok' => $ok]);
5719 throw new BadRequestException('Error adding activity');
5723 /// @TODO move to top of file or somewhere better
5724 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5725 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5726 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5727 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5728 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5729 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5730 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5731 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5732 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5733 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5736 * Returns notifications
5738 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5740 * @return string|array
5741 * @throws ForbiddenException
5742 * @throws BadRequestException
5745 function api_friendica_notification($type)
5749 if (api_user() === false) {
5750 throw new ForbiddenException();
5753 throw new BadRequestException("Invalid argument count");
5756 $notifications = DI::notification()->getApiList(local_user());
5758 if ($type == "xml") {
5760 if (!empty($notifications)) {
5761 foreach ($notifications as $notification) {
5762 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5766 $result = $xmlnotes;
5767 } elseif (count($notifications) > 0) {
5768 $result = $notifications->getArrayCopy();
5773 return api_format_data("notes", $type, ['note' => $result]);
5777 * Set notification as seen and returns associated item (if possible)
5779 * POST request with 'id' param as notification id
5781 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5782 * @return string|array
5783 * @throws BadRequestException
5784 * @throws ForbiddenException
5785 * @throws ImagickException
5786 * @throws InternalServerErrorException
5787 * @throws UnauthorizedException
5789 function api_friendica_notification_seen($type)
5792 $user_info = api_get_user($a);
5794 if (api_user() === false || $user_info === false) {
5795 throw new ForbiddenException();
5797 if ($a->argc !== 4) {
5798 throw new BadRequestException("Invalid argument count");
5801 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5804 $notify = DI::notify()->getByID($id, api_user());
5805 DI::notify()->setSeen(true, $notify);
5807 if ($notify->otype === Notification\ObjectType::ITEM) {
5808 $item = Post::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5809 if (DBA::isResult($item)) {
5810 // we found the item, return it to the user
5811 $ret = api_format_items([$item], $user_info, false, $type);
5812 $data = ['status' => $ret];
5813 return api_format_data("status", $type, $data);
5815 // the item can't be found, but we set the notification as seen, so we count this as a success
5817 return api_format_data('result', $type, ['result' => "success"]);
5818 } catch (NotFoundException $e) {
5819 throw new BadRequestException('Invalid argument', $e);
5820 } catch (Exception $e) {
5821 throw new InternalServerErrorException('Internal Server exception', $e);
5825 /// @TODO move to top of file or somewhere better
5826 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5827 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5830 * update a direct_message to seen state
5832 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5833 * @return string|array (success result=ok, error result=error with error message)
5834 * @throws BadRequestException
5835 * @throws ForbiddenException
5836 * @throws ImagickException
5837 * @throws InternalServerErrorException
5838 * @throws UnauthorizedException
5840 function api_friendica_direct_messages_setseen($type)
5843 if (api_user() === false) {
5844 throw new ForbiddenException();
5848 $user_info = api_get_user($a);
5849 $uid = $user_info['uid'];
5850 $id = $_REQUEST['id'] ?? 0;
5852 // return error if id is zero
5854 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5855 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5858 // error message if specified id is not in database
5859 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5860 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5861 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5864 // update seen indicator
5865 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5869 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5870 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5872 $answer = ['result' => 'error', 'message' => 'unknown error'];
5873 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5877 /// @TODO move to top of file or somewhere better
5878 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5881 * search for direct_messages containing a searchstring through api
5883 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5884 * @param string $box
5885 * @return string|array (success: success=true if found and search_result contains found messages,
5886 * success=false if nothing was found, search_result='nothing found',
5887 * error: result=error with error message)
5888 * @throws BadRequestException
5889 * @throws ForbiddenException
5890 * @throws ImagickException
5891 * @throws InternalServerErrorException
5892 * @throws UnauthorizedException
5894 function api_friendica_direct_messages_search($type, $box = "")
5898 if (api_user() === false) {
5899 throw new ForbiddenException();
5903 $user_info = api_get_user($a);
5904 $searchstring = $_REQUEST['searchstring'] ?? '';
5905 $uid = $user_info['uid'];
5907 // error if no searchstring specified
5908 if ($searchstring == "") {
5909 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5910 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5913 // get data for the specified searchstring
5915 "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",
5917 DBA::escape('%'.$searchstring.'%')
5920 $profile_url = $user_info["url"];
5922 // message if nothing was found
5923 if (!DBA::isResult($r)) {
5924 $success = ['success' => false, 'search_results' => 'problem with query'];
5925 } elseif (count($r) == 0) {
5926 $success = ['success' => false, 'search_results' => 'nothing found'];
5929 foreach ($r as $item) {
5930 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5931 $recipient = $user_info;
5932 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5933 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5934 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5935 $sender = $user_info;
5938 if (isset($recipient) && isset($sender)) {
5939 $ret[] = api_format_messages($item, $recipient, $sender);
5942 $success = ['success' => true, 'search_results' => $ret];
5945 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5948 /// @TODO move to top of file or somewhere better
5949 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5952 * Returns a list of saved searches.
5954 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5956 * @param string $type Return format: json or xml
5958 * @return string|array
5961 function api_saved_searches_list($type)
5963 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5966 while ($term = DBA::fetch($terms)) {
5968 'created_at' => api_date(time()),
5969 'id' => intval($term['id']),
5970 'id_str' => $term['id'],
5971 'name' => $term['term'],
5973 'query' => $term['term']
5979 return api_format_data("terms", $type, ['terms' => $result]);
5982 /// @TODO move to top of file or somewhere better
5983 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5986 * Number of comments
5988 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5990 * @param object $data [Status, Status]
5994 function bindComments(&$data)
5996 if (count($data) == 0) {
6002 foreach ($data as $item) {
6003 $ids[] = $item['id'];
6006 $idStr = DBA::escape(implode(', ', $ids));
6007 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6008 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6009 $itemsData = DBA::toArray($items);
6011 foreach ($itemsData as $item) {
6012 $comments[$item['parent']] = $item['comments'];
6015 foreach ($data as $idx => $item) {
6017 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6022 @TODO Maybe open to implement?
6024 [pagename] => api/1.1/statuses/lookup.json
6025 [id] => 605138389168451584
6026 [include_cards] => true
6027 [cards_platform] => Android-12
6028 [include_entities] => true
6029 [include_my_retweet] => 1
6031 [include_reply_count] => true
6032 [include_descendent_reply_count] => true
6036 Not implemented by now:
6037 statuses/retweets_of_me
6042 account/update_location
6043 account/update_profile_background_image
6046 friendica/profile/update
6047 friendica/profile/create
6048 friendica/profile/delete
6050 Not implemented in status.net:
6051 statuses/retweeted_to_me
6052 statuses/retweeted_by_me
6053 direct_messages/destroy
6055 account/update_delivery_device
6056 notifications/follow