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\Notify;
43 use Friendica\Model\Photo;
44 use Friendica\Model\User;
45 use Friendica\Model\UserItem;
46 use Friendica\Model\Verb;
47 use Friendica\Network\FKOAuth1;
48 use Friendica\Network\HTTPException;
49 use Friendica\Network\HTTPException\BadRequestException;
50 use Friendica\Network\HTTPException\ExpectationFailedException;
51 use Friendica\Network\HTTPException\ForbiddenException;
52 use Friendica\Network\HTTPException\InternalServerErrorException;
53 use Friendica\Network\HTTPException\MethodNotAllowedException;
54 use Friendica\Network\HTTPException\NotFoundException;
55 use Friendica\Network\HTTPException\NotImplementedException;
56 use Friendica\Network\HTTPException\TooManyRequestsException;
57 use Friendica\Network\HTTPException\UnauthorizedException;
58 use Friendica\Object\Image;
59 use Friendica\Protocol\Activity;
60 use Friendica\Protocol\Diaspora;
61 use Friendica\Util\DateTimeFormat;
62 use Friendica\Util\Images;
63 use Friendica\Util\Network;
64 use Friendica\Util\Proxy as ProxyUtils;
65 use Friendica\Util\Strings;
66 use Friendica\Util\XML;
68 require_once __DIR__ . '/../mod/share.php';
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->getQueryString(), ".xml") > 0) {
317 if (strpos($args->getQueryString(), ".json") > 0) {
320 if (strpos($args->getQueryString(), ".rss") > 0) {
323 if (strpos($args->getQueryString(), ".atom") > 0) {
328 foreach ($API as $p => $info) {
329 if (strpos($args->getQueryString(), $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) {
340 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 . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], '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 NotImplementedException();
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(), true),
658 'pid' => Contact::getIdForURL($contact["url"], 0, true),
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, true);
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, true),
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 = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1122 $posts_day = DBA::count('thread', $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 = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1136 $posts_week = DBA::count('thread', $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 = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1150 $posts_month = DBA::count('thread', $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::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
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 = Item::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 = Item::select([], ['id' => $id]);
1589 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1591 $data['status'] = api_format_items(Item::inArray($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 `item`.`id` > ?",
1646 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1649 $condition[0] .= " AND `item`.`id` <= ?";
1650 $condition[] = $max_id;
1652 if ($exclude_replies) {
1653 $condition[0] .= ' AND `item`.`gravity` = ?';
1654 $condition[] = GRAVITY_PARENT;
1656 if ($conversation_id > 0) {
1657 $condition[0] .= " AND `item`.`parent` = ?";
1658 $condition[] = $conversation_id;
1661 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1662 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1664 $items = Item::inArray($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 = Item::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 `thread`.`iid` <= ?";
1739 $condition[] = $max_id;
1742 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1743 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1745 $r = Item::inArray($statuses);
1747 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
1748 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1751 $condition[0] .= " AND `item`.`id` <= ?";
1752 $condition[] = $max_id;
1754 if ($conversation_id > 0) {
1755 $condition[0] .= " AND `item`.`parent` = ?";
1756 $condition[] = $conversation_id;
1759 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1760 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1762 $r = Item::inArray($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 `thread`.`iid` > ? AND `private` = ?",
1814 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1817 $condition[0] .= " AND `thread`.`iid` <= ?";
1818 $condition[] = $max_id;
1821 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1822 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1824 $ret = api_format_items(Item::inArray($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 = Item::selectFirst(['uri'], ['id' => $id]);
1883 if (!DBA::isResult($uri_item)) {
1884 throw new BadRequestException("There is no status with this id.");
1887 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1888 if (!DBA::isResult($item)) {
1889 throw new BadRequestException("There is no status with this 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 = Item::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("There is no status with this id.");
1909 $ret = api_format_items(Item::inArray($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 = Item::selectFirst(['parent-uri'], ['id' => $id]);
1966 if (!DBA::isResult($item)) {
1967 throw new BadRequestException("There is no status with this id.");
1970 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], '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 `item`.`id` > ?",
1978 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1981 $condition[0] .= " AND `item`.`id` <= ?";
1982 $condition[] = $max_id;
1985 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1986 $statuses = Item::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(Item::inArray($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', 'body', 'title', 'attach', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2042 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2044 if (DBA::isResult($item) && $item['body'] != "") {
2045 if (strpos($item['body'], "[/share]") !== false) {
2046 $pos = strpos($item['body'], "[share");
2047 $post = substr($item['body'], $pos);
2049 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2051 if (!empty($item['title'])) {
2052 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2055 $post .= $item['body'];
2056 $post .= "[/share]";
2058 $_REQUEST['body'] = $post;
2059 $_REQUEST['attach'] = $item['attach'];
2060 $_REQUEST['profile_uid'] = api_user();
2061 $_REQUEST['api_source'] = true;
2063 if (empty($_REQUEST['source'])) {
2064 $_REQUEST["source"] = api_source();
2067 $item_id = item_post($a);
2069 /// @todo Copy tags from the original post to the new one
2071 throw new ForbiddenException();
2074 // output the post that we just posted.
2076 return api_status_show($type, $item_id);
2079 /// @TODO move to top of file or somewhere better
2080 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2083 * Destroys a specific status.
2085 * @param string $type Return type (atom, rss, xml, json)
2087 * @return array|string
2088 * @throws BadRequestException
2089 * @throws ForbiddenException
2090 * @throws ImagickException
2091 * @throws InternalServerErrorException
2092 * @throws UnauthorizedException
2093 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2095 function api_statuses_destroy($type)
2099 if (api_user() === false) {
2100 throw new ForbiddenException();
2106 $id = intval($a->argv[3] ?? 0);
2109 $id = intval($_REQUEST['id'] ?? 0);
2114 $id = intval($a->argv[4] ?? 0);
2117 Logger::log('API: api_statuses_destroy: '.$id);
2119 $ret = api_statuses_show($type);
2121 Item::deleteForUser(['id' => $id], api_user());
2126 /// @TODO move to top of file or somewhere better
2127 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2130 * Returns the most recent mentions.
2132 * @param string $type Return type (atom, rss, xml, json)
2134 * @return array|string
2135 * @throws BadRequestException
2136 * @throws ForbiddenException
2137 * @throws ImagickException
2138 * @throws InternalServerErrorException
2139 * @throws UnauthorizedException
2140 * @see http://developer.twitter.com/doc/get/statuses/mentions
2142 function api_statuses_mentions($type)
2145 $user_info = api_get_user($a);
2147 if (api_user() === false || $user_info === false) {
2148 throw new ForbiddenException();
2151 unset($_REQUEST["user_id"]);
2152 unset($_GET["user_id"]);
2154 unset($_REQUEST["screen_name"]);
2155 unset($_GET["screen_name"]);
2157 // get last network messages
2160 $since_id = $_REQUEST['since_id'] ?? 0;
2161 $max_id = $_REQUEST['max_id'] ?? 0;
2162 $count = $_REQUEST['count'] ?? 20;
2163 $page = $_REQUEST['page'] ?? 1;
2165 $start = max(0, ($page - 1) * $count);
2167 $query = "SELECT `item`.`id` FROM `user-item`
2168 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2169 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2170 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2171 AND `user-item`.`iid` > ?";
2172 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2173 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2174 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2175 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2179 $query .= " AND `item`.`id` <= ?";
2180 $condition[] = $max_id;
2183 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2184 $condition[] = $start;
2185 $condition[] = $count;
2187 $useritems = DBA::p($query, $condition);
2189 while ($useritem = DBA::fetch($useritems)) {
2190 $itemids[] = $useritem['id'];
2192 DBA::close($useritems);
2194 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2195 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2197 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2199 $data = ['status' => $ret];
2204 $data = api_rss_extra($a, $data, $user_info);
2208 return api_format_data("statuses", $type, $data);
2211 /// @TODO move to top of file or somewhere better
2212 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2213 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2216 * Returns the most recent statuses posted by the user.
2218 * @param string $type Either "json" or "xml"
2219 * @return string|array
2220 * @throws BadRequestException
2221 * @throws ForbiddenException
2222 * @throws ImagickException
2223 * @throws InternalServerErrorException
2224 * @throws UnauthorizedException
2225 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2227 function api_statuses_user_timeline($type)
2230 $user_info = api_get_user($a);
2232 if (api_user() === false || $user_info === false) {
2233 throw new ForbiddenException();
2237 "api_statuses_user_timeline: api_user: ". api_user() .
2238 "\nuser_info: ".print_r($user_info, true) .
2239 "\n_REQUEST: ".print_r($_REQUEST, true),
2243 $since_id = $_REQUEST['since_id'] ?? 0;
2244 $max_id = $_REQUEST['max_id'] ?? 0;
2245 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2246 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2249 $count = $_REQUEST['count'] ?? 20;
2250 $page = $_REQUEST['page'] ?? 1;
2252 $start = max(0, ($page - 1) * $count);
2254 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2255 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2257 if ($user_info['self'] == 1) {
2258 $condition[0] .= ' AND `item`.`wall` ';
2261 if ($exclude_replies) {
2262 $condition[0] .= ' AND `item`.`gravity` = ?';
2263 $condition[] = GRAVITY_PARENT;
2266 if ($conversation_id > 0) {
2267 $condition[0] .= " AND `item`.`parent` = ?";
2268 $condition[] = $conversation_id;
2272 $condition[0] .= " AND `item`.`id` <= ?";
2273 $condition[] = $max_id;
2276 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2277 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2279 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2283 $data = ['status' => $ret];
2288 $data = api_rss_extra($a, $data, $user_info);
2292 return api_format_data("statuses", $type, $data);
2295 /// @TODO move to top of file or somewhere better
2296 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2299 * Star/unstar an item.
2300 * param: id : id of the item
2302 * @param string $type Return type (atom, rss, xml, json)
2304 * @return array|string
2305 * @throws BadRequestException
2306 * @throws ForbiddenException
2307 * @throws ImagickException
2308 * @throws InternalServerErrorException
2309 * @throws UnauthorizedException
2310 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2312 function api_favorites_create_destroy($type)
2316 if (api_user() === false) {
2317 throw new ForbiddenException();
2320 // for versioned api.
2321 /// @TODO We need a better global soluton
2322 $action_argv_id = 2;
2323 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2324 $action_argv_id = 3;
2327 if ($a->argc <= $action_argv_id) {
2328 throw new BadRequestException("Invalid request.");
2330 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2331 if ($a->argc == $action_argv_id + 2) {
2332 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2334 $itemid = intval($_REQUEST['id'] ?? 0);
2337 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2339 if (!DBA::isResult($item)) {
2340 throw new BadRequestException("Invalid item.");
2345 $item['starred'] = 1;
2348 $item['starred'] = 0;
2351 throw new BadRequestException("Invalid action ".$action);
2354 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2357 throw new InternalServerErrorException("DB error");
2361 $user_info = api_get_user($a);
2362 $rets = api_format_items([$item], $user_info, false, $type);
2365 $data = ['status' => $ret];
2370 $data = api_rss_extra($a, $data, $user_info);
2374 return api_format_data("status", $type, $data);
2377 /// @TODO move to top of file or somewhere better
2378 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2379 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2382 * Returns the most recent favorite statuses.
2384 * @param string $type Return type (atom, rss, xml, json)
2386 * @return string|array
2387 * @throws BadRequestException
2388 * @throws ForbiddenException
2389 * @throws ImagickException
2390 * @throws InternalServerErrorException
2391 * @throws UnauthorizedException
2393 function api_favorites($type)
2398 $user_info = api_get_user($a);
2400 if (api_user() === false || $user_info === false) {
2401 throw new ForbiddenException();
2406 // in friendica starred item are private
2407 // return favorites only for self
2408 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2410 if ($user_info['self'] == 0) {
2414 $since_id = $_REQUEST['since_id'] ?? 0;
2415 $max_id = $_REQUEST['max_id'] ?? 0;
2416 $count = $_GET['count'] ?? 20;
2417 $page = $_REQUEST['page'] ?? 1;
2419 $start = max(0, ($page - 1) * $count);
2421 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2422 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2424 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2427 $condition[0] .= " AND `item`.`id` <= ?";
2428 $condition[] = $max_id;
2431 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2433 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2438 $data = ['status' => $ret];
2443 $data = api_rss_extra($a, $data, $user_info);
2447 return api_format_data("statuses", $type, $data);
2450 /// @TODO move to top of file or somewhere better
2451 api_register_func('api/favorites', 'api_favorites', true);
2455 * @param array $item
2456 * @param array $recipient
2457 * @param array $sender
2460 * @throws InternalServerErrorException
2462 function api_format_messages($item, $recipient, $sender)
2464 // standard meta information
2466 'id' => $item['id'],
2467 'sender_id' => $sender['id'],
2469 'recipient_id' => $recipient['id'],
2470 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2471 'sender_screen_name' => $sender['screen_name'],
2472 'recipient_screen_name' => $recipient['screen_name'],
2473 'sender' => $sender,
2474 'recipient' => $recipient,
2476 'friendica_seen' => $item['seen'] ?? 0,
2477 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2480 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2481 if (isset($ret['sender']['uid'])) {
2482 unset($ret['sender']['uid']);
2484 if (isset($ret['sender']['self'])) {
2485 unset($ret['sender']['self']);
2487 if (isset($ret['recipient']['uid'])) {
2488 unset($ret['recipient']['uid']);
2490 if (isset($ret['recipient']['self'])) {
2491 unset($ret['recipient']['self']);
2494 //don't send title to regular StatusNET requests to avoid confusing these apps
2495 if (!empty($_GET['getText'])) {
2496 $ret['title'] = $item['title'];
2497 if ($_GET['getText'] == 'html') {
2498 $ret['text'] = BBCode::convert($item['body'], false);
2499 } elseif ($_GET['getText'] == 'plain') {
2500 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2503 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2505 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2506 unset($ret['sender']);
2507 unset($ret['recipient']);
2515 * @param array $item
2518 * @throws InternalServerErrorException
2520 function api_convert_item($item)
2522 $body = $item['body'];
2523 $entities = api_get_entitities($statustext, $body);
2525 // Add pictures to the attachment array and remove them from the body
2526 $attachments = api_get_attachments($body);
2528 // Workaround for ostatus messages where the title is identically to the body
2529 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2530 $statusbody = trim(HTML::toPlaintext($html, 0));
2532 // handle data: images
2533 $statusbody = api_format_items_embeded_images($item, $statusbody);
2535 $statustitle = trim($item['title']);
2537 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2538 $statustext = trim($statusbody);
2540 $statustext = trim($statustitle."\n\n".$statusbody);
2543 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2544 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2547 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2549 // Workaround for clients with limited HTML parser functionality
2550 $search = ["<br>", "<blockquote>", "</blockquote>",
2551 "<h1>", "</h1>", "<h2>", "</h2>",
2552 "<h3>", "</h3>", "<h4>", "</h4>",
2553 "<h5>", "</h5>", "<h6>", "</h6>"];
2554 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2555 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2556 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2557 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2558 $statushtml = str_replace($search, $replace, $statushtml);
2560 if ($item['title'] != "") {
2561 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2565 $oldtext = $statushtml;
2566 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2567 } while ($oldtext != $statushtml);
2569 if (substr($statushtml, 0, 4) == '<br>') {
2570 $statushtml = substr($statushtml, 4);
2573 if (substr($statushtml, 0, -4) == '<br>') {
2574 $statushtml = substr($statushtml, -4);
2577 // feeds without body should contain the link
2578 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2579 $statushtml .= BBCode::convert($item['plink']);
2583 "text" => $statustext,
2584 "html" => $statushtml,
2585 "attachments" => $attachments,
2586 "entities" => $entities
2592 * @param string $body
2595 * @throws InternalServerErrorException
2597 function api_get_attachments(&$body)
2599 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2600 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2602 $URLSearchString = "^\[\]";
2603 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2607 // Remove all embedded pictures, since they are added as attachments
2608 foreach ($images[0] as $orig) {
2609 $body = str_replace($orig, '', $body);
2614 foreach ($images[1] as $image) {
2615 $imagedata = Images::getInfoFromURLCached($image);
2618 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2622 return $attachments;
2627 * @param string $text
2628 * @param string $bbcode
2631 * @throws InternalServerErrorException
2632 * @todo Links at the first character of the post
2634 function api_get_entitities(&$text, $bbcode)
2636 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2638 if ($include_entities != "true") {
2639 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2641 foreach ($images[1] as $image) {
2642 $replace = ProxyUtils::proxifyUrl($image);
2643 $text = str_replace($image, $replace, $text);
2648 $bbcode = BBCode::cleanPictureLinks($bbcode);
2650 // Change pure links in text to bbcode uris
2651 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2654 $entities["hashtags"] = [];
2655 $entities["symbols"] = [];
2656 $entities["urls"] = [];
2657 $entities["user_mentions"] = [];
2659 $URLSearchString = "^\[\]";
2661 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2663 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2664 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2666 $bbcode = preg_replace(
2667 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2668 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2671 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2673 $bbcode = preg_replace(
2674 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2675 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2678 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2680 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2682 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2685 foreach ($urls[1] as $id => $url) {
2686 $start = iconv_strpos($text, $url, 0, "UTF-8");
2687 if (!($start === false)) {
2688 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2692 ksort($ordered_urls);
2696 foreach ($ordered_urls as $url) {
2697 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2698 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2700 $display_url = $url["title"];
2702 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2703 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2705 if (strlen($display_url) > 26) {
2706 $display_url = substr($display_url, 0, 25)."…";
2710 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2711 if (!($start === false)) {
2712 $entities["urls"][] = ["url" => $url["url"],
2713 "expanded_url" => $url["url"],
2714 "display_url" => $display_url,
2715 "indices" => [$start, $start+strlen($url["url"])]];
2716 $offset = $start + 1;
2720 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2721 $ordered_images = [];
2722 foreach ($images as $image) {
2723 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2724 if (!($start === false)) {
2725 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2729 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2730 foreach ($images[1] as $image) {
2731 $start = iconv_strpos($text, $image, 0, "UTF-8");
2732 if (!($start === false)) {
2733 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2739 foreach ($ordered_images as $image) {
2740 $url = $image['url'];
2741 $ext_alt_text = $image['alt'];
2743 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2744 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2746 if (strlen($display_url) > 26) {
2747 $display_url = substr($display_url, 0, 25)."…";
2750 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2751 if (!($start === false)) {
2752 $image = Images::getInfoFromURLCached($url);
2754 // If image cache is activated, then use the following sizes:
2755 // thumb (150), small (340), medium (600) and large (1024)
2756 if (!DI::config()->get("system", "proxy_disabled")) {
2757 $media_url = ProxyUtils::proxifyUrl($url);
2760 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2761 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2763 if (($image[0] > 150) || ($image[1] > 150)) {
2764 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2765 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2768 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2769 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2771 if (($image[0] > 600) || ($image[1] > 600)) {
2772 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2773 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2777 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2780 $entities["media"][] = [
2782 "id_str" => (string) ($start + 1),
2783 "indices" => [$start, $start+strlen($url)],
2784 "media_url" => Strings::normaliseLink($media_url),
2785 "media_url_https" => $media_url,
2787 "display_url" => $display_url,
2788 "expanded_url" => $url,
2789 "ext_alt_text" => $ext_alt_text,
2793 $offset = $start + 1;
2802 * @param array $item
2803 * @param string $text
2807 function api_format_items_embeded_images($item, $text)
2809 $text = preg_replace_callback(
2810 '|data:image/([^;]+)[^=]+=*|m',
2811 function () use ($item) {
2812 return DI::baseUrl() . '/display/' . $item['guid'];
2820 * return <a href='url'>name</a> as array
2822 * @param string $txt text
2827 function api_contactlink_to_array($txt)
2830 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2831 if ($r && count($match)==3) {
2833 'name' => $match[2],
2847 * return likes, dislikes and attend status for item
2849 * @param array $item array
2850 * @param string $type Return type (atom, rss, xml, json)
2853 * likes => int count,
2854 * dislikes => int count
2855 * @throws BadRequestException
2856 * @throws ImagickException
2857 * @throws InternalServerErrorException
2858 * @throws UnauthorizedException
2860 function api_format_items_activities($item, $type = "json")
2869 'attendmaybe' => [],
2873 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2874 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2876 while ($parent_item = Item::fetch($ret)) {
2877 // not used as result should be structured like other user data
2878 //builtin_activity_puller($i, $activities);
2880 // get user data and add it to the array of the activity
2881 $user = api_get_user($a, $parent_item['author-id']);
2882 switch ($parent_item['verb']) {
2883 case Activity::LIKE:
2884 $activities['like'][] = $user;
2886 case Activity::DISLIKE:
2887 $activities['dislike'][] = $user;
2889 case Activity::ATTEND:
2890 $activities['attendyes'][] = $user;
2892 case Activity::ATTENDNO:
2893 $activities['attendno'][] = $user;
2895 case Activity::ATTENDMAYBE:
2896 $activities['attendmaybe'][] = $user;
2898 case Activity::ANNOUNCE:
2899 $activities['announce'][] = $user;
2908 if ($type == "xml") {
2909 $xml_activities = [];
2910 foreach ($activities as $k => $v) {
2911 // change xml element from "like" to "friendica:like"
2912 $xml_activities["friendica:".$k] = $v;
2913 // add user data into xml output
2915 foreach ($v as $user) {
2916 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2919 $activities = $xml_activities;
2926 * format items to be returned by api
2928 * @param array $items array of items
2929 * @param array $user_info
2930 * @param bool $filter_user filter items by $user_info
2931 * @param string $type Return type (atom, rss, xml, json)
2933 * @throws BadRequestException
2934 * @throws ImagickException
2935 * @throws InternalServerErrorException
2936 * @throws UnauthorizedException
2938 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2940 $a = Friendica\DI::app();
2944 foreach ((array)$items as $item) {
2945 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2947 // Look if the posts are matching if they should be filtered by user id
2948 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2952 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2961 * @param array $item Item record
2962 * @param string $type Return format (atom, rss, xml, json)
2963 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2964 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2965 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2966 * @return array API-formatted status
2967 * @throws BadRequestException
2968 * @throws ImagickException
2969 * @throws InternalServerErrorException
2970 * @throws UnauthorizedException
2972 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2974 $a = Friendica\DI::app();
2976 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2977 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2980 localize_item($item);
2982 $in_reply_to = api_in_reply_to($item);
2984 $converted = api_convert_item($item);
2986 if ($type == "xml") {
2987 $geo = "georss:point";
2993 'text' => $converted["text"],
2994 'truncated' => false,
2995 'created_at'=> api_date($item['created']),
2996 'in_reply_to_status_id' => $in_reply_to['status_id'],
2997 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2998 'source' => (($item['app']) ? $item['app'] : 'web'),
2999 'id' => intval($item['id']),
3000 'id_str' => (string) intval($item['id']),
3001 'in_reply_to_user_id' => $in_reply_to['user_id'],
3002 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3003 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3005 'favorited' => $item['starred'] ? true : false,
3006 'user' => $status_user,
3007 'friendica_author' => $author_user,
3008 'friendica_owner' => $owner_user,
3009 'friendica_private' => $item['private'] == Item::PRIVATE,
3010 //'entities' => NULL,
3011 'statusnet_html' => $converted["html"],
3012 'statusnet_conversation_id' => $item['parent'],
3013 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3014 'friendica_activities' => api_format_items_activities($item, $type),
3015 'friendica_title' => $item['title'],
3016 'friendica_html' => BBCode::convert($item['body'], false)
3019 if (count($converted["attachments"]) > 0) {
3020 $status["attachments"] = $converted["attachments"];
3023 if (count($converted["entities"]) > 0) {
3024 $status["entities"] = $converted["entities"];
3027 if ($status["source"] == 'web') {
3028 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3029 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3030 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3033 $retweeted_item = [];
3036 if ($item['gravity'] == GRAVITY_PARENT) {
3037 $body = $item['body'];
3038 $retweeted_item = api_share_as_retweet($item);
3039 if ($body != $item['body']) {
3040 $quoted_item = $retweeted_item;
3041 $retweeted_item = [];
3045 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3046 $announce = api_get_announce($item);
3047 if (!empty($announce)) {
3048 $retweeted_item = $item;
3050 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3054 if (!empty($quoted_item)) {
3055 if ($quoted_item['id'] != $item['id']) {
3056 $quoted_status = api_format_item($quoted_item);
3057 /// @todo Only remove the attachments that are also contained in the quotes status
3058 unset($status['attachments']);
3059 unset($status['entities']);
3061 $conv_quoted = api_convert_item($quoted_item);
3062 $quoted_status = $status;
3063 unset($quoted_status['attachments']);
3064 unset($quoted_status['entities']);
3065 unset($quoted_status['statusnet_conversation_id']);
3066 $quoted_status['text'] = $conv_quoted['text'];
3067 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3069 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3070 } catch (BadRequestException $e) {
3071 // user not found. should be found?
3072 /// @todo check if the user should be always found
3073 $quoted_status["user"] = [];
3076 unset($quoted_status['friendica_author']);
3077 unset($quoted_status['friendica_owner']);
3078 unset($quoted_status['friendica_activities']);
3079 unset($quoted_status['friendica_private']);
3082 if (!empty($retweeted_item)) {
3083 $retweeted_status = $status;
3084 unset($retweeted_status['friendica_author']);
3085 unset($retweeted_status['friendica_owner']);
3086 unset($retweeted_status['friendica_activities']);
3087 unset($retweeted_status['friendica_private']);
3088 unset($retweeted_status['statusnet_conversation_id']);
3089 $status['user'] = $status['friendica_owner'];
3091 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3092 } catch (BadRequestException $e) {
3093 // user not found. should be found?
3094 /// @todo check if the user should be always found
3095 $retweeted_status["user"] = [];
3098 $rt_converted = api_convert_item($retweeted_item);
3100 $retweeted_status['text'] = $rt_converted["text"];
3101 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3102 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3104 if (!empty($quoted_status)) {
3105 $retweeted_status['quoted_status'] = $quoted_status;
3108 $status['friendica_author'] = $retweeted_status['user'];
3109 $status['retweeted_status'] = $retweeted_status;
3110 } elseif (!empty($quoted_status)) {
3111 $root_status = api_convert_item($item);
3113 $status['text'] = $root_status["text"];
3114 $status['statusnet_html'] = $root_status["html"];
3115 $status['quoted_status'] = $quoted_status;
3118 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3119 unset($status["user"]["uid"]);
3120 unset($status["user"]["self"]);
3122 if ($item["coord"] != "") {
3123 $coords = explode(' ', $item["coord"]);
3124 if (count($coords) == 2) {
3125 if ($type == "json") {
3126 $status["geo"] = ['type' => 'Point',
3127 'coordinates' => [(float) $coords[0],
3128 (float) $coords[1]]];
3129 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3130 $status["georss:point"] = $item["coord"];
3139 * Returns the remaining number of API requests available to the user before the API limit is reached.
3141 * @param string $type Return type (atom, rss, xml, json)
3143 * @return array|string
3146 function api_account_rate_limit_status($type)
3148 if ($type == "xml") {
3150 'remaining-hits' => '150',
3151 '@attributes' => ["type" => "integer"],
3152 'hourly-limit' => '150',
3153 '@attributes2' => ["type" => "integer"],
3154 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3155 '@attributes3' => ["type" => "datetime"],
3156 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3157 '@attributes4' => ["type" => "integer"],
3161 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3162 'remaining_hits' => '150',
3163 'hourly_limit' => '150',
3164 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3168 return api_format_data('hash', $type, ['hash' => $hash]);
3171 /// @TODO move to top of file or somewhere better
3172 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3175 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3177 * @param string $type Return type (atom, rss, xml, json)
3179 * @return array|string
3181 function api_help_test($type)
3183 if ($type == 'xml') {
3189 return api_format_data('ok', $type, ["ok" => $ok]);
3192 /// @TODO move to top of file or somewhere better
3193 api_register_func('api/help/test', 'api_help_test', false);
3196 * Returns all lists the user subscribes to.
3198 * @param string $type Return type (atom, rss, xml, json)
3200 * @return array|string
3201 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3203 function api_lists_list($type)
3206 /// @TODO $ret is not filled here?
3207 return api_format_data('lists', $type, ["lists_list" => $ret]);
3210 /// @TODO move to top of file or somewhere better
3211 api_register_func('api/lists/list', 'api_lists_list', true);
3212 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3215 * Returns all groups the user owns.
3217 * @param string $type Return type (atom, rss, xml, json)
3219 * @return array|string
3220 * @throws BadRequestException
3221 * @throws ForbiddenException
3222 * @throws ImagickException
3223 * @throws InternalServerErrorException
3224 * @throws UnauthorizedException
3225 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3227 function api_lists_ownerships($type)
3231 if (api_user() === false) {
3232 throw new ForbiddenException();
3236 $user_info = api_get_user($a);
3237 $uid = $user_info['uid'];
3239 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3241 // loop through all groups
3243 foreach ($groups as $group) {
3244 if ($group['visible']) {
3250 'name' => $group['name'],
3251 'id' => intval($group['id']),
3252 'id_str' => (string) $group['id'],
3253 'user' => $user_info,
3257 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3260 /// @TODO move to top of file or somewhere better
3261 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3264 * Returns recent statuses from users in the specified group.
3266 * @param string $type Return type (atom, rss, xml, json)
3268 * @return array|string
3269 * @throws BadRequestException
3270 * @throws ForbiddenException
3271 * @throws ImagickException
3272 * @throws InternalServerErrorException
3273 * @throws UnauthorizedException
3274 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3276 function api_lists_statuses($type)
3280 $user_info = api_get_user($a);
3281 if (api_user() === false || $user_info === false) {
3282 throw new ForbiddenException();
3285 unset($_REQUEST["user_id"]);
3286 unset($_GET["user_id"]);
3288 unset($_REQUEST["screen_name"]);
3289 unset($_GET["screen_name"]);
3291 if (empty($_REQUEST['list_id'])) {
3292 throw new BadRequestException('list_id not specified');
3296 $count = $_REQUEST['count'] ?? 20;
3297 $page = $_REQUEST['page'] ?? 1;
3298 $since_id = $_REQUEST['since_id'] ?? 0;
3299 $max_id = $_REQUEST['max_id'] ?? 0;
3300 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3301 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3303 $start = max(0, ($page - 1) * $count);
3305 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3306 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3309 $condition[0] .= " AND `item`.`id` <= ?";
3310 $condition[] = $max_id;
3312 if ($exclude_replies > 0) {
3313 $condition[0] .= ' AND `item`.`gravity` = ?';
3314 $condition[] = GRAVITY_PARENT;
3316 if ($conversation_id > 0) {
3317 $condition[0] .= " AND `item`.`parent` = ?";
3318 $condition[] = $conversation_id;
3321 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3322 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3324 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3326 $data = ['status' => $items];
3331 $data = api_rss_extra($a, $data, $user_info);
3335 return api_format_data("statuses", $type, $data);
3338 /// @TODO move to top of file or somewhere better
3339 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3342 * Returns either the friends of the follower list
3344 * Considers friends and followers lists to be private and won't return
3345 * anything if any user_id parameter is passed.
3347 * @param string $qtype Either "friends" or "followers"
3348 * @return boolean|array
3349 * @throws BadRequestException
3350 * @throws ForbiddenException
3351 * @throws ImagickException
3352 * @throws InternalServerErrorException
3353 * @throws UnauthorizedException
3355 function api_statuses_f($qtype)
3359 if (api_user() === false) {
3360 throw new ForbiddenException();
3364 $count = $_GET['count'] ?? 20;
3365 $page = $_GET['page'] ?? 1;
3367 $start = max(0, ($page - 1) * $count);
3369 $user_info = api_get_user($a);
3371 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3372 /* this is to stop Hotot to load friends multiple times
3373 * I'm not sure if I'm missing return something or
3374 * is a bug in hotot. Workaround, meantime
3378 return array('$users' => $ret);*/
3383 if ($qtype == 'friends') {
3384 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3385 } elseif ($qtype == 'followers') {
3386 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3389 // friends and followers only for self
3390 if ($user_info['self'] == 0) {
3391 $sql_extra = " AND false ";
3394 if ($qtype == 'blocks') {
3395 $sql_filter = 'AND `blocked` AND NOT `pending`';
3396 } elseif ($qtype == 'incoming') {
3397 $sql_filter = 'AND `pending`';
3399 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3417 foreach ($r as $cid) {
3418 $user = api_get_user($a, $cid['nurl']);
3419 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3420 unset($user["uid"]);
3421 unset($user["self"]);
3428 return ['user' => $ret];
3433 * Returns the list of friends of the provided user
3435 * @deprecated By Twitter API in favor of friends/list
3437 * @param string $type Either "json" or "xml"
3438 * @return boolean|string|array
3439 * @throws BadRequestException
3440 * @throws ForbiddenException
3442 function api_statuses_friends($type)
3444 $data = api_statuses_f("friends");
3445 if ($data === false) {
3448 return api_format_data("users", $type, $data);
3452 * Returns the list of followers of the provided user
3454 * @deprecated By Twitter API in favor of friends/list
3456 * @param string $type Either "json" or "xml"
3457 * @return boolean|string|array
3458 * @throws BadRequestException
3459 * @throws ForbiddenException
3461 function api_statuses_followers($type)
3463 $data = api_statuses_f("followers");
3464 if ($data === false) {
3467 return api_format_data("users", $type, $data);
3470 /// @TODO move to top of file or somewhere better
3471 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3472 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3475 * Returns the list of blocked users
3477 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3479 * @param string $type Either "json" or "xml"
3481 * @return boolean|string|array
3482 * @throws BadRequestException
3483 * @throws ForbiddenException
3485 function api_blocks_list($type)
3487 $data = api_statuses_f('blocks');
3488 if ($data === false) {
3491 return api_format_data("users", $type, $data);
3494 /// @TODO move to top of file or somewhere better
3495 api_register_func('api/blocks/list', 'api_blocks_list', true);
3498 * Returns the list of pending users IDs
3500 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3502 * @param string $type Either "json" or "xml"
3504 * @return boolean|string|array
3505 * @throws BadRequestException
3506 * @throws ForbiddenException
3508 function api_friendships_incoming($type)
3510 $data = api_statuses_f('incoming');
3511 if ($data === false) {
3516 foreach ($data['user'] as $user) {
3517 $ids[] = $user['id'];
3520 return api_format_data("ids", $type, ['id' => $ids]);
3523 /// @TODO move to top of file or somewhere better
3524 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3527 * Returns the instance's configuration information.
3529 * @param string $type Return type (atom, rss, xml, json)
3531 * @return array|string
3532 * @throws InternalServerErrorException
3534 function api_statusnet_config($type)
3536 $name = DI::config()->get('config', 'sitename');
3537 $server = DI::baseUrl()->getHostname();
3538 $logo = DI::baseUrl() . '/images/friendica-64.png';
3539 $email = DI::config()->get('config', 'admin_email');
3540 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3541 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3542 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3543 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3544 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3547 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3548 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3549 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3550 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3551 'shorturllength' => '30',
3553 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3554 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3555 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3556 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3561 return api_format_data('config', $type, ['config' => $config]);
3564 /// @TODO move to top of file or somewhere better
3565 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3566 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3570 * @param string $type Return type (atom, rss, xml, json)
3572 * @return array|string
3574 function api_statusnet_version($type)
3577 $fake_statusnet_version = "0.9.7";
3579 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3582 /// @TODO move to top of file or somewhere better
3583 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3584 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3587 * Sends a new direct message.
3589 * @param string $type Return type (atom, rss, xml, json)
3591 * @return array|string
3592 * @throws BadRequestException
3593 * @throws ForbiddenException
3594 * @throws ImagickException
3595 * @throws InternalServerErrorException
3596 * @throws NotFoundException
3597 * @throws UnauthorizedException
3598 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3600 function api_direct_messages_new($type)
3604 if (api_user() === false) {
3605 throw new ForbiddenException();
3608 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3612 $sender = api_get_user($a);
3615 if (!empty($_POST['screen_name'])) {
3617 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3619 DBA::escape($_POST['screen_name'])
3622 if (DBA::isResult($r)) {
3623 // Selecting the id by priority, friendica first
3624 api_best_nickname($r);
3626 $recipient = api_get_user($a, $r[0]['nurl']);
3629 $recipient = api_get_user($a, $_POST['user_id']);
3632 if (empty($recipient)) {
3633 throw new NotFoundException('Recipient not found');
3637 if (!empty($_REQUEST['replyto'])) {
3639 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3641 intval($_REQUEST['replyto'])
3643 $replyto = $r[0]['parent-uri'];
3644 $sub = $r[0]['title'];
3646 if (!empty($_REQUEST['title'])) {
3647 $sub = $_REQUEST['title'];
3649 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3653 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3656 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3657 $ret = api_format_messages($r[0], $recipient, $sender);
3659 $ret = ["error"=>$id];
3662 $data = ['direct_message'=>$ret];
3668 $data = api_rss_extra($a, $data, $sender);
3672 return api_format_data("direct-messages", $type, $data);
3675 /// @TODO move to top of file or somewhere better
3676 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3679 * delete a direct_message from mail table through api
3681 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3682 * @return string|array
3683 * @throws BadRequestException
3684 * @throws ForbiddenException
3685 * @throws ImagickException
3686 * @throws InternalServerErrorException
3687 * @throws UnauthorizedException
3688 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3690 function api_direct_messages_destroy($type)
3694 if (api_user() === false) {
3695 throw new ForbiddenException();
3699 $user_info = api_get_user($a);
3701 $id = $_REQUEST['id'] ?? 0;
3703 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3704 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3705 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3707 $uid = $user_info['uid'];
3708 // error if no id or parenturi specified (for clients posting parent-uri as well)
3709 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3710 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3711 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3714 // BadRequestException if no id specified (for clients using Twitter API)
3716 throw new BadRequestException('Message id not specified');
3719 // add parent-uri to sql command if specified by calling app
3720 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3722 // get data of the specified message id
3724 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3729 // error message if specified id is not in database
3730 if (!DBA::isResult($r)) {
3731 if ($verbose == "true") {
3732 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3733 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3735 /// @todo BadRequestException ok for Twitter API clients?
3736 throw new BadRequestException('message id not in database');
3741 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3746 if ($verbose == "true") {
3749 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3750 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3752 $answer = ['result' => 'error', 'message' => 'unknown error'];
3753 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3756 /// @todo return JSON data like Twitter API not yet implemented
3759 /// @TODO move to top of file or somewhere better
3760 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3765 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3766 * @return string|array
3767 * @throws BadRequestException
3768 * @throws ForbiddenException
3769 * @throws ImagickException
3770 * @throws InternalServerErrorException
3771 * @throws NotFoundException
3772 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3774 function api_friendships_destroy($type)
3778 if ($uid === false) {
3779 throw new ForbiddenException();
3782 $contact_id = $_REQUEST['user_id'] ?? 0;
3784 if (empty($contact_id)) {
3785 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3786 throw new BadRequestException("no user_id specified");
3789 // Get Contact by given id
3790 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3792 if(!DBA::isResult($contact)) {
3793 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3794 throw new NotFoundException("no contact found to given ID");
3797 $url = $contact["url"];
3799 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3800 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3801 Strings::normaliseLink($url), $url];
3802 $contact = DBA::selectFirst('contact', [], $condition);
3804 if (!DBA::isResult($contact)) {
3805 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3806 throw new NotFoundException("Not following Contact");
3809 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3810 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3811 throw new ExpectationFailedException("Not supported");
3814 $dissolve = ($contact['rel'] == Contact::SHARING);
3816 $owner = User::getOwnerDataById($uid);
3818 Contact::terminateFriendship($owner, $contact, $dissolve);
3821 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3822 throw new NotFoundException("Error Processing Request");
3825 // Sharing-only contacts get deleted as there no relationship any more
3827 Contact::remove($contact['id']);
3829 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3832 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3833 unset($contact["uid"]);
3834 unset($contact["self"]);
3836 // Set screen_name since Twidere requests it
3837 $contact["screen_name"] = $contact["nick"];
3839 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3841 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3845 * @param string $type Return type (atom, rss, xml, json)
3846 * @param string $box
3847 * @param string $verbose
3849 * @return array|string
3850 * @throws BadRequestException
3851 * @throws ForbiddenException
3852 * @throws ImagickException
3853 * @throws InternalServerErrorException
3854 * @throws UnauthorizedException
3856 function api_direct_messages_box($type, $box, $verbose)
3859 if (api_user() === false) {
3860 throw new ForbiddenException();
3863 $count = $_GET['count'] ?? 20;
3864 $page = $_REQUEST['page'] ?? 1;
3866 $since_id = $_REQUEST['since_id'] ?? 0;
3867 $max_id = $_REQUEST['max_id'] ?? 0;
3869 $user_id = $_REQUEST['user_id'] ?? '';
3870 $screen_name = $_REQUEST['screen_name'] ?? '';
3873 unset($_REQUEST["user_id"]);
3874 unset($_GET["user_id"]);
3876 unset($_REQUEST["screen_name"]);
3877 unset($_GET["screen_name"]);
3879 $user_info = api_get_user($a);
3880 if ($user_info === false) {
3881 throw new ForbiddenException();
3883 $profile_url = $user_info["url"];
3886 $start = max(0, ($page - 1) * $count);
3891 if ($box=="sentbox") {
3892 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3893 } elseif ($box == "conversation") {
3894 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3895 } elseif ($box == "all") {
3896 $sql_extra = "true";
3897 } elseif ($box == "inbox") {
3898 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3902 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3905 if ($user_id != "") {
3906 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3907 } elseif ($screen_name !="") {
3908 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3912 "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",
3918 if ($verbose == "true" && !DBA::isResult($r)) {
3919 $answer = ['result' => 'error', 'message' => 'no mails available'];
3920 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3924 foreach ($r as $item) {
3925 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3926 $recipient = $user_info;
3927 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3928 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3929 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3930 $sender = $user_info;
3933 if (isset($recipient) && isset($sender)) {
3934 $ret[] = api_format_messages($item, $recipient, $sender);
3939 $data = ['direct_message' => $ret];
3944 $data = api_rss_extra($a, $data, $user_info);
3948 return api_format_data("direct-messages", $type, $data);
3952 * Returns the most recent direct messages sent by the user.
3954 * @param string $type Return type (atom, rss, xml, json)
3956 * @return array|string
3957 * @throws BadRequestException
3958 * @throws ForbiddenException
3959 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3961 function api_direct_messages_sentbox($type)
3963 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3964 return api_direct_messages_box($type, "sentbox", $verbose);
3968 * Returns the most recent direct messages sent to the user.
3970 * @param string $type Return type (atom, rss, xml, json)
3972 * @return array|string
3973 * @throws BadRequestException
3974 * @throws ForbiddenException
3975 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3977 function api_direct_messages_inbox($type)
3979 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3980 return api_direct_messages_box($type, "inbox", $verbose);
3985 * @param string $type Return type (atom, rss, xml, json)
3987 * @return array|string
3988 * @throws BadRequestException
3989 * @throws ForbiddenException
3991 function api_direct_messages_all($type)
3993 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3994 return api_direct_messages_box($type, "all", $verbose);
3999 * @param string $type Return type (atom, rss, xml, json)
4001 * @return array|string
4002 * @throws BadRequestException
4003 * @throws ForbiddenException
4005 function api_direct_messages_conversation($type)
4007 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4008 return api_direct_messages_box($type, "conversation", $verbose);
4011 /// @TODO move to top of file or somewhere better
4012 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4013 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4014 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4015 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4018 * Returns an OAuth Request Token.
4020 * @see https://oauth.net/core/1.0/#auth_step1
4022 function api_oauth_request_token()
4024 $oauth1 = new FKOAuth1();
4026 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4027 } catch (Exception $e) {
4028 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4036 * Returns an OAuth Access Token.
4038 * @return array|string
4039 * @see https://oauth.net/core/1.0/#auth_step3
4041 function api_oauth_access_token()
4043 $oauth1 = new FKOAuth1();
4045 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4046 } catch (Exception $e) {
4047 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4054 /// @TODO move to top of file or somewhere better
4055 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4056 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4060 * delete a complete photoalbum with all containing photos from database through api
4062 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4063 * @return string|array
4064 * @throws BadRequestException
4065 * @throws ForbiddenException
4066 * @throws InternalServerErrorException
4068 function api_fr_photoalbum_delete($type)
4070 if (api_user() === false) {
4071 throw new ForbiddenException();
4074 $album = $_REQUEST['album'] ?? '';
4076 // we do not allow calls without album string
4078 throw new BadRequestException("no albumname specified");
4080 // check if album is existing
4082 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album]);
4083 if (!DBA::isResult($photos)) {
4084 throw new BadRequestException("album not available");
4087 $resourceIds = array_unique(array_column($photos, 'resource-id'));
4089 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4090 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4091 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4092 Item::deleteForUser($condition, api_user());
4094 // now let's delete all photos from the album
4095 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4097 // return success of deletion or error message
4099 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4100 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4102 throw new InternalServerErrorException("unknown error - deleting from database failed");
4107 * update the name of the album for all photos of an album
4109 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4110 * @return string|array
4111 * @throws BadRequestException
4112 * @throws ForbiddenException
4113 * @throws InternalServerErrorException
4115 function api_fr_photoalbum_update($type)
4117 if (api_user() === false) {
4118 throw new ForbiddenException();
4121 $album = $_REQUEST['album'] ?? '';
4122 $album_new = $_REQUEST['album_new'] ?? '';
4124 // we do not allow calls without album string
4126 throw new BadRequestException("no albumname specified");
4128 if ($album_new == "") {
4129 throw new BadRequestException("no new albumname specified");
4131 // check if album is existing
4132 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4133 throw new BadRequestException("album not available");
4135 // now let's update all photos to the albumname
4136 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4138 // return success of updating or error message
4140 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4141 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4143 throw new InternalServerErrorException("unknown error - updating in database failed");
4149 * list all photos of the authenticated user
4151 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4152 * @return string|array
4153 * @throws ForbiddenException
4154 * @throws InternalServerErrorException
4156 function api_fr_photos_list($type)
4158 if (api_user() === false) {
4159 throw new ForbiddenException();
4162 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4163 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4164 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4165 intval(local_user())
4168 'image/jpeg' => 'jpg',
4169 'image/png' => 'png',
4170 'image/gif' => 'gif'
4172 $data = ['photo'=>[]];
4173 if (DBA::isResult($r)) {
4174 foreach ($r as $rr) {
4176 $photo['id'] = $rr['resource-id'];
4177 $photo['album'] = $rr['album'];
4178 $photo['filename'] = $rr['filename'];
4179 $photo['type'] = $rr['type'];
4180 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4181 $photo['created'] = $rr['created'];
4182 $photo['edited'] = $rr['edited'];
4183 $photo['desc'] = $rr['desc'];
4185 if ($type == "xml") {
4186 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4188 $photo['thumb'] = $thumb;
4189 $data['photo'][] = $photo;
4193 return api_format_data("photos", $type, $data);
4197 * upload a new photo or change an existing photo
4199 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4200 * @return string|array
4201 * @throws BadRequestException
4202 * @throws ForbiddenException
4203 * @throws ImagickException
4204 * @throws InternalServerErrorException
4205 * @throws NotFoundException
4207 function api_fr_photo_create_update($type)
4209 if (api_user() === false) {
4210 throw new ForbiddenException();
4213 $photo_id = $_REQUEST['photo_id'] ?? null;
4214 $desc = $_REQUEST['desc'] ?? null;
4215 $album = $_REQUEST['album'] ?? null;
4216 $album_new = $_REQUEST['album_new'] ?? null;
4217 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4218 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4219 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4220 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4221 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4223 // do several checks on input parameters
4224 // we do not allow calls without album string
4225 if ($album == null) {
4226 throw new BadRequestException("no albumname specified");
4228 // if photo_id == null --> we are uploading a new photo
4229 if ($photo_id == null) {
4232 // error if no media posted in create-mode
4233 if (empty($_FILES['media'])) {
4235 throw new BadRequestException("no media data submitted");
4238 // album_new will be ignored in create-mode
4243 // check if photo is existing in databasei
4244 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4245 throw new BadRequestException("photo not available");
4249 // checks on acl strings provided by clients
4250 $acl_input_error = false;
4251 $acl_input_error |= check_acl_input($allow_cid);
4252 $acl_input_error |= check_acl_input($deny_cid);
4253 $acl_input_error |= check_acl_input($allow_gid);
4254 $acl_input_error |= check_acl_input($deny_gid);
4255 if ($acl_input_error) {
4256 throw new BadRequestException("acl data invalid");
4258 // now let's upload the new media in create-mode
4259 if ($mode == "create") {
4260 $media = $_FILES['media'];
4261 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4263 // return success of updating or error message
4264 if (!is_null($data)) {
4265 return api_format_data("photo_create", $type, $data);
4267 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4271 // now let's do the changes in update-mode
4272 if ($mode == "update") {
4273 $updated_fields = [];
4275 if (!is_null($desc)) {
4276 $updated_fields['desc'] = $desc;
4279 if (!is_null($album_new)) {
4280 $updated_fields['album'] = $album_new;
4283 if (!is_null($allow_cid)) {
4284 $allow_cid = trim($allow_cid);
4285 $updated_fields['allow_cid'] = $allow_cid;
4288 if (!is_null($deny_cid)) {
4289 $deny_cid = trim($deny_cid);
4290 $updated_fields['deny_cid'] = $deny_cid;
4293 if (!is_null($allow_gid)) {
4294 $allow_gid = trim($allow_gid);
4295 $updated_fields['allow_gid'] = $allow_gid;
4298 if (!is_null($deny_gid)) {
4299 $deny_gid = trim($deny_gid);
4300 $updated_fields['deny_gid'] = $deny_gid;
4304 if (count($updated_fields) > 0) {
4305 $nothingtodo = false;
4306 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4308 $nothingtodo = true;
4311 if (!empty($_FILES['media'])) {
4312 $nothingtodo = false;
4313 $media = $_FILES['media'];
4314 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4315 if (!is_null($data)) {
4316 return api_format_data("photo_update", $type, $data);
4320 // return success of updating or error message
4322 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4323 return api_format_data("photo_update", $type, ['$result' => $answer]);
4326 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4327 return api_format_data("photo_update", $type, ['$result' => $answer]);
4329 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4332 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4336 * delete a single photo from the database through api
4338 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4339 * @return string|array
4340 * @throws BadRequestException
4341 * @throws ForbiddenException
4342 * @throws InternalServerErrorException
4344 function api_fr_photo_delete($type)
4346 if (api_user() === false) {
4347 throw new ForbiddenException();
4351 $photo_id = $_REQUEST['photo_id'] ?? null;
4353 // do several checks on input parameters
4354 // we do not allow calls without photo id
4355 if ($photo_id == null) {
4356 throw new BadRequestException("no photo_id specified");
4359 // check if photo is existing in database
4360 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4361 throw new BadRequestException("photo not available");
4364 // now we can perform on the deletion of the photo
4365 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4367 // return success of deletion or error message
4369 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4370 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4371 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4372 Item::deleteForUser($condition, api_user());
4374 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4375 return api_format_data("photo_delete", $type, ['$result' => $result]);
4377 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4383 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4385 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4386 * @return string|array
4387 * @throws BadRequestException
4388 * @throws ForbiddenException
4389 * @throws InternalServerErrorException
4390 * @throws NotFoundException
4392 function api_fr_photo_detail($type)
4394 if (api_user() === false) {
4395 throw new ForbiddenException();
4397 if (empty($_REQUEST['photo_id'])) {
4398 throw new BadRequestException("No photo id.");
4401 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4402 $photo_id = $_REQUEST['photo_id'];
4404 // prepare json/xml output with data from database for the requested photo
4405 $data = prepare_photo_data($type, $scale, $photo_id);
4407 return api_format_data("photo_detail", $type, $data);
4412 * updates the profile image for the user (either a specified profile or the default profile)
4414 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4416 * @return string|array
4417 * @throws BadRequestException
4418 * @throws ForbiddenException
4419 * @throws ImagickException
4420 * @throws InternalServerErrorException
4421 * @throws NotFoundException
4422 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4424 function api_account_update_profile_image($type)
4426 if (api_user() === false) {
4427 throw new ForbiddenException();
4430 $profile_id = $_REQUEST['profile_id'] ?? 0;
4432 // error if image data is missing
4433 if (empty($_FILES['image'])) {
4434 throw new BadRequestException("no media data submitted");
4437 // check if specified profile id is valid
4438 if ($profile_id != 0) {
4439 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4440 // error message if specified profile id is not in database
4441 if (!DBA::isResult($profile)) {
4442 throw new BadRequestException("profile_id not available");
4444 $is_default_profile = $profile['is-default'];
4446 $is_default_profile = 1;
4449 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4451 if (!empty($_FILES['image'])) {
4452 $media = $_FILES['image'];
4453 } elseif (!empty($_FILES['media'])) {
4454 $media = $_FILES['media'];
4456 // save new profile image
4457 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4460 if (is_array($media['type'])) {
4461 $filetype = $media['type'][0];
4463 $filetype = $media['type'];
4465 if ($filetype == "image/jpeg") {
4467 } elseif ($filetype == "image/png") {
4470 throw new InternalServerErrorException('Unsupported filetype');
4473 // change specified profile or all profiles to the new resource-id
4474 if ($is_default_profile) {
4475 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4476 Photo::update(['profile' => false], $condition);
4478 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4479 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4480 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4483 Contact::updateSelfFromUserID(api_user(), true);
4485 // Update global directory in background
4486 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4487 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4488 Worker::add(PRIORITY_LOW, "Directory", $url);
4491 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4493 // output for client
4495 return api_account_verify_credentials($type);
4497 // SaveMediaToDatabase failed for some reason
4498 throw new InternalServerErrorException("image upload failed");
4502 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4503 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4504 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4505 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4506 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4507 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4508 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4509 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4510 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4513 * Update user profile
4515 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4517 * @return array|string
4518 * @throws BadRequestException
4519 * @throws ForbiddenException
4520 * @throws ImagickException
4521 * @throws InternalServerErrorException
4522 * @throws UnauthorizedException
4524 function api_account_update_profile($type)
4526 $local_user = api_user();
4527 $api_user = api_get_user(DI::app());
4529 if (!empty($_POST['name'])) {
4530 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4531 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4532 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4533 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4536 if (isset($_POST['description'])) {
4537 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4538 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4539 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4542 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4543 // Update global directory in background
4544 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4545 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4548 return api_account_verify_credentials($type);
4551 /// @TODO move to top of file or somewhere better
4552 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4556 * @param string $acl_string
4560 function check_acl_input($acl_string)
4562 if (empty($acl_string)) {
4566 $contact_not_found = false;
4568 // split <x><y><z> into array of cid's
4569 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4571 // check for each cid if it is available on server
4572 $cid_array = $array[0];
4573 foreach ($cid_array as $cid) {
4574 $cid = str_replace("<", "", $cid);
4575 $cid = str_replace(">", "", $cid);
4576 $condition = ['id' => $cid, 'uid' => api_user()];
4577 $contact_not_found |= !DBA::exists('contact', $condition);
4579 return $contact_not_found;
4583 * @param string $mediatype
4584 * @param array $media
4585 * @param string $type
4586 * @param string $album
4587 * @param string $allow_cid
4588 * @param string $deny_cid
4589 * @param string $allow_gid
4590 * @param string $deny_gid
4591 * @param string $desc
4592 * @param integer $profile
4593 * @param boolean $visibility
4594 * @param string $photo_id
4596 * @throws BadRequestException
4597 * @throws ForbiddenException
4598 * @throws ImagickException
4599 * @throws InternalServerErrorException
4600 * @throws NotFoundException
4601 * @throws UnauthorizedException
4603 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)
4611 if (is_array($media)) {
4612 if (is_array($media['tmp_name'])) {
4613 $src = $media['tmp_name'][0];
4615 $src = $media['tmp_name'];
4617 if (is_array($media['name'])) {
4618 $filename = basename($media['name'][0]);
4620 $filename = basename($media['name']);
4622 if (is_array($media['size'])) {
4623 $filesize = intval($media['size'][0]);
4625 $filesize = intval($media['size']);
4627 if (is_array($media['type'])) {
4628 $filetype = $media['type'][0];
4630 $filetype = $media['type'];
4634 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4637 "File upload src: " . $src . " - filename: " . $filename .
4638 " - size: " . $filesize . " - type: " . $filetype,
4642 // check if there was a php upload error
4643 if ($filesize == 0 && $media['error'] == 1) {
4644 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4646 // check against max upload size within Friendica instance
4647 $maximagesize = DI::config()->get('system', 'maximagesize');
4648 if ($maximagesize && ($filesize > $maximagesize)) {
4649 $formattedBytes = Strings::formatBytes($maximagesize);
4650 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4653 // create Photo instance with the data of the image
4654 $imagedata = @file_get_contents($src);
4655 $Image = new Image($imagedata, $filetype);
4656 if (!$Image->isValid()) {
4657 throw new InternalServerErrorException("unable to process image data");
4660 // check orientation of image
4661 $Image->orient($src);
4664 // check max length of images on server
4665 $max_length = DI::config()->get('system', 'max_image_length');
4667 $max_length = MAX_IMAGE_LENGTH;
4669 if ($max_length > 0) {
4670 $Image->scaleDown($max_length);
4671 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4673 $width = $Image->getWidth();
4674 $height = $Image->getHeight();
4676 // create a new resource-id if not already provided
4677 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4679 if ($mediatype == "photo") {
4680 // upload normal image (scales 0, 1, 2)
4681 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4683 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4685 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4687 if ($width > 640 || $height > 640) {
4688 $Image->scaleDown(640);
4689 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4691 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4695 if ($width > 320 || $height > 320) {
4696 $Image->scaleDown(320);
4697 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4699 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4702 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4703 } elseif ($mediatype == "profileimage") {
4704 // upload profile image (scales 4, 5, 6)
4705 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4707 if ($width > 300 || $height > 300) {
4708 $Image->scaleDown(300);
4709 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4711 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4715 if ($width > 80 || $height > 80) {
4716 $Image->scaleDown(80);
4717 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4719 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4723 if ($width > 48 || $height > 48) {
4724 $Image->scaleDown(48);
4725 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4727 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4730 $Image->__destruct();
4731 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4735 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4736 if ($photo_id == null && $mediatype == "photo") {
4737 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4739 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4740 return prepare_photo_data($type, false, $resource_id);
4742 throw new InternalServerErrorException("image upload failed");
4748 * @param string $hash
4749 * @param string $allow_cid
4750 * @param string $deny_cid
4751 * @param string $allow_gid
4752 * @param string $deny_gid
4753 * @param string $filetype
4754 * @param boolean $visibility
4755 * @throws InternalServerErrorException
4757 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4759 // get data about the api authenticated user
4760 $uri = Item::newURI(intval(api_user()));
4761 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4764 $arr['guid'] = System::createUUID();
4765 $arr['uid'] = intval(api_user());
4767 $arr['parent-uri'] = $uri;
4768 $arr['type'] = 'photo';
4770 $arr['resource-id'] = $hash;
4771 $arr['contact-id'] = $owner_record['id'];
4772 $arr['owner-name'] = $owner_record['name'];
4773 $arr['owner-link'] = $owner_record['url'];
4774 $arr['owner-avatar'] = $owner_record['thumb'];
4775 $arr['author-name'] = $owner_record['name'];
4776 $arr['author-link'] = $owner_record['url'];
4777 $arr['author-avatar'] = $owner_record['thumb'];
4779 $arr['allow_cid'] = $allow_cid;
4780 $arr['allow_gid'] = $allow_gid;
4781 $arr['deny_cid'] = $deny_cid;
4782 $arr['deny_gid'] = $deny_gid;
4783 $arr['visible'] = $visibility;
4787 'image/jpeg' => 'jpg',
4788 'image/png' => 'png',
4789 'image/gif' => 'gif'
4792 // adds link to the thumbnail scale photo
4793 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4794 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4797 // do the magic for storing the item in the database and trigger the federation to other contacts
4803 * @param string $type
4805 * @param string $photo_id
4808 * @throws BadRequestException
4809 * @throws ForbiddenException
4810 * @throws ImagickException
4811 * @throws InternalServerErrorException
4812 * @throws NotFoundException
4813 * @throws UnauthorizedException
4815 function prepare_photo_data($type, $scale, $photo_id)
4818 $user_info = api_get_user($a);
4820 if ($user_info === false) {
4821 throw new ForbiddenException();
4824 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4825 $data_sql = ($scale === false ? "" : "data, ");
4827 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4828 // clients needs to convert this in their way for further processing
4830 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4831 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4832 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4833 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4834 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4835 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4837 intval(local_user()),
4838 DBA::escape($photo_id),
4843 'image/jpeg' => 'jpg',
4844 'image/png' => 'png',
4845 'image/gif' => 'gif'
4848 // prepare output data for photo
4849 if (DBA::isResult($r)) {
4850 $data = ['photo' => $r[0]];
4851 $data['photo']['id'] = $data['photo']['resource-id'];
4852 if ($scale !== false) {
4853 $data['photo']['data'] = base64_encode($data['photo']['data']);
4855 unset($data['photo']['datasize']); //needed only with scale param
4857 if ($type == "xml") {
4858 $data['photo']['links'] = [];
4859 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4860 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4862 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4865 $data['photo']['link'] = [];
4866 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4868 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4869 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4873 unset($data['photo']['resource-id']);
4874 unset($data['photo']['minscale']);
4875 unset($data['photo']['maxscale']);
4877 throw new NotFoundException();
4880 // retrieve item element for getting activities (like, dislike etc.) related to photo
4881 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4882 $item = Item::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4883 if (!DBA::isResult($item)) {
4884 throw new NotFoundException('Photo-related item not found.');
4887 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4889 // retrieve comments on photo
4890 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4891 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4893 $statuses = Item::selectForUser(api_user(), [], $condition);
4895 // prepare output of comments
4896 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4898 if ($type == "xml") {
4900 foreach ($commentData as $comment) {
4901 $comments[$k++ . ":comment"] = $comment;
4904 foreach ($commentData as $comment) {
4905 $comments[] = $comment;
4908 $data['photo']['friendica_comments'] = $comments;
4910 // include info if rights on photo and rights on item are mismatching
4911 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4912 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4913 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4914 $data['photo']['deny_gid'] != $item['deny_gid'];
4915 $data['photo']['rights_mismatch'] = $rights_mismatch;
4922 * Similar as /mod/redir.php
4923 * redirect to 'url' after dfrn auth
4925 * Why this when there is mod/redir.php already?
4926 * This use api_user() and api_login()
4929 * c_url: url of remote contact to auth to
4930 * url: string, url to redirect after auth
4932 function api_friendica_remoteauth()
4934 $url = $_GET['url'] ?? '';
4935 $c_url = $_GET['c_url'] ?? '';
4937 if ($url === '' || $c_url === '') {
4938 throw new BadRequestException("Wrong parameters.");
4941 $c_url = Strings::normaliseLink($c_url);
4945 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
4946 if (!DBA::isResult($contact)) {
4947 throw new BadRequestException("Unknown contact");
4950 $cid = $contact['id'];
4952 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
4954 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
4955 System::externalRedirect($url ?: $c_url);
4958 if ($contact['duplex'] && $contact['issued-id']) {
4959 $orig_id = $contact['issued-id'];
4960 $dfrn_id = '1:' . $orig_id;
4962 if ($contact['duplex'] && $contact['dfrn-id']) {
4963 $orig_id = $contact['dfrn-id'];
4964 $dfrn_id = '0:' . $orig_id;
4967 $sec = Strings::getRandomHex();
4969 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
4970 'sec' => $sec, 'expire' => time() + 45];
4971 DBA::insert('profile_check', $fields);
4973 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
4974 $dest = ($url ? '&destination_url=' . $url : '');
4976 System::externalRedirect(
4977 $contact['poll'] . '?dfrn_id=' . $dfrn_id
4978 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
4979 . '&type=profile&sec=' . $sec . $dest
4982 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
4985 * Return an item with announcer data if it had been announced
4987 * @param array $item Item array
4988 * @return array Item array with announce data
4990 function api_get_announce($item)
4992 // Quit if the item already has got a different owner and author
4993 if ($item['owner-id'] != $item['author-id']) {
4997 // Don't change original or Diaspora posts
4998 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5002 // Quit if we do now the original author and it had been a post from a native network
5003 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5007 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5008 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5009 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5010 if (!DBA::isResult($announce)) {
5014 return array_merge($item, $announce);
5018 * Return the item shared, if the item contains only the [share] tag
5020 * @param array $item Sharer item
5021 * @return array|false Shared item or false if not a reshare
5022 * @throws ImagickException
5023 * @throws InternalServerErrorException
5025 function api_share_as_retweet(&$item)
5027 $body = trim($item["body"]);
5029 if (Diaspora::isReshare($body, false) === false) {
5030 if ($item['author-id'] == $item['owner-id']) {
5033 // Reshares from OStatus, ActivityPub and Twitter
5034 $reshared_item = $item;
5035 $reshared_item['owner-id'] = $reshared_item['author-id'];
5036 $reshared_item['owner-link'] = $reshared_item['author-link'];
5037 $reshared_item['owner-name'] = $reshared_item['author-name'];
5038 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5039 return $reshared_item;
5043 $reshared = Item::getShareArray($item);
5044 if (empty($reshared)) {
5048 $reshared_item = $item;
5050 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5054 if (!empty($reshared['comment'])) {
5055 $item['body'] = $reshared['comment'];
5058 $reshared_item["share-pre-body"] = $reshared['comment'];
5059 $reshared_item["body"] = $reshared['shared'];
5060 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5061 $reshared_item["author-name"] = $reshared['author'];
5062 $reshared_item["author-link"] = $reshared['profile'];
5063 $reshared_item["author-avatar"] = $reshared['avatar'];
5064 $reshared_item["plink"] = $reshared['link'] ?? '';
5065 $reshared_item["created"] = $reshared['posted'];
5066 $reshared_item["edited"] = $reshared['posted'];
5068 // Try to fetch the original item
5069 if (!empty($reshared['guid'])) {
5070 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5071 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5072 $condition = ['id' => $original_id];
5077 if (!empty($condition)) {
5078 $original_item = Item::selectFirst([], $condition);
5079 if (DBA::isResult($original_item)) {
5080 $reshared_item = array_merge($reshared_item, $original_item);
5084 return $reshared_item;
5089 * @param array $item
5094 function api_in_reply_to($item)
5098 $in_reply_to['status_id'] = null;
5099 $in_reply_to['user_id'] = null;
5100 $in_reply_to['status_id_str'] = null;
5101 $in_reply_to['user_id_str'] = null;
5102 $in_reply_to['screen_name'] = null;
5104 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
5105 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5106 if (DBA::isResult($parent)) {
5107 $in_reply_to['status_id'] = intval($parent['id']);
5109 $in_reply_to['status_id'] = intval($item['parent']);
5112 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5114 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5115 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5117 if (DBA::isResult($parent)) {
5118 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5119 $in_reply_to['user_id'] = intval($parent['author-id']);
5120 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5123 // There seems to be situation, where both fields are identical:
5124 // https://github.com/friendica/friendica/issues/1010
5125 // This is a bugfix for that.
5126 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5127 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']]);
5128 $in_reply_to['status_id'] = null;
5129 $in_reply_to['user_id'] = null;
5130 $in_reply_to['status_id_str'] = null;
5131 $in_reply_to['user_id_str'] = null;
5132 $in_reply_to['screen_name'] = null;
5136 return $in_reply_to;
5141 * @param string $text
5144 * @throws InternalServerErrorException
5146 function api_clean_plain_items($text)
5148 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5150 $text = BBCode::cleanPictureLinks($text);
5151 $URLSearchString = "^\[\]";
5153 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5155 if ($include_entities == "true") {
5156 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5159 // Simplify "attachment" element
5160 $text = BBCode::removeAttachment($text);
5167 * @param array $contacts
5171 function api_best_nickname(&$contacts)
5175 if (count($contacts) == 0) {
5179 foreach ($contacts as $contact) {
5180 if ($contact["network"] == "") {
5181 $contact["network"] = "dfrn";
5182 $best_contact = [$contact];
5186 if (sizeof($best_contact) == 0) {
5187 foreach ($contacts as $contact) {
5188 if ($contact["network"] == "dfrn") {
5189 $best_contact = [$contact];
5194 if (sizeof($best_contact) == 0) {
5195 foreach ($contacts as $contact) {
5196 if ($contact["network"] == "dspr") {
5197 $best_contact = [$contact];
5202 if (sizeof($best_contact) == 0) {
5203 foreach ($contacts as $contact) {
5204 if ($contact["network"] == "stat") {
5205 $best_contact = [$contact];
5210 if (sizeof($best_contact) == 0) {
5211 foreach ($contacts as $contact) {
5212 if ($contact["network"] == "pump") {
5213 $best_contact = [$contact];
5218 if (sizeof($best_contact) == 0) {
5219 foreach ($contacts as $contact) {
5220 if ($contact["network"] == "twit") {
5221 $best_contact = [$contact];
5226 if (sizeof($best_contact) == 1) {
5227 $contacts = $best_contact;
5229 $contacts = [$contacts[0]];
5234 * Return all or a specified group of the user with the containing contacts.
5236 * @param string $type Return type (atom, rss, xml, json)
5238 * @return array|string
5239 * @throws BadRequestException
5240 * @throws ForbiddenException
5241 * @throws ImagickException
5242 * @throws InternalServerErrorException
5243 * @throws UnauthorizedException
5245 function api_friendica_group_show($type)
5249 if (api_user() === false) {
5250 throw new ForbiddenException();
5254 $user_info = api_get_user($a);
5255 $gid = $_REQUEST['gid'] ?? 0;
5256 $uid = $user_info['uid'];
5258 // get data of the specified group id or all groups if not specified
5261 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5265 // error message if specified gid is not in database
5266 if (!DBA::isResult($r)) {
5267 throw new BadRequestException("gid not available");
5271 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5276 // loop through all groups and retrieve all members for adding data in the user array
5278 foreach ($r as $rr) {
5279 $members = Contact::getByGroupId($rr['id']);
5282 if ($type == "xml") {
5283 $user_element = "users";
5285 foreach ($members as $member) {
5286 $user = api_get_user($a, $member['nurl']);
5287 $users[$k++.":user"] = $user;
5290 $user_element = "user";
5291 foreach ($members as $member) {
5292 $user = api_get_user($a, $member['nurl']);
5296 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5298 return api_format_data("groups", $type, ['group' => $grps]);
5300 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5304 * Delete the specified group of the user.
5306 * @param string $type Return type (atom, rss, xml, json)
5308 * @return array|string
5309 * @throws BadRequestException
5310 * @throws ForbiddenException
5311 * @throws ImagickException
5312 * @throws InternalServerErrorException
5313 * @throws UnauthorizedException
5315 function api_friendica_group_delete($type)
5319 if (api_user() === false) {
5320 throw new ForbiddenException();
5324 $user_info = api_get_user($a);
5325 $gid = $_REQUEST['gid'] ?? 0;
5326 $name = $_REQUEST['name'] ?? '';
5327 $uid = $user_info['uid'];
5329 // error if no gid specified
5330 if ($gid == 0 || $name == "") {
5331 throw new BadRequestException('gid or name not specified');
5334 // get data of the specified group id
5336 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5340 // error message if specified gid is not in database
5341 if (!DBA::isResult($r)) {
5342 throw new BadRequestException('gid not available');
5345 // get data of the specified group id and group name
5347 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5352 // error message if specified gid is not in database
5353 if (!DBA::isResult($rname)) {
5354 throw new BadRequestException('wrong group name');
5358 $ret = Group::removeByName($uid, $name);
5361 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5362 return api_format_data("group_delete", $type, ['result' => $success]);
5364 throw new BadRequestException('other API error');
5367 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5372 * @param string $type Return type (atom, rss, xml, json)
5374 * @return array|string
5375 * @throws BadRequestException
5376 * @throws ForbiddenException
5377 * @throws ImagickException
5378 * @throws InternalServerErrorException
5379 * @throws UnauthorizedException
5380 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5382 function api_lists_destroy($type)
5386 if (api_user() === false) {
5387 throw new ForbiddenException();
5391 $user_info = api_get_user($a);
5392 $gid = $_REQUEST['list_id'] ?? 0;
5393 $uid = $user_info['uid'];
5395 // error if no gid specified
5397 throw new BadRequestException('gid not specified');
5400 // get data of the specified group id
5401 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5402 // error message if specified gid is not in database
5404 throw new BadRequestException('gid not available');
5407 if (Group::remove($gid)) {
5409 'name' => $group['name'],
5410 'id' => intval($gid),
5411 'id_str' => (string) $gid,
5412 'user' => $user_info
5415 return api_format_data("lists", $type, ['lists' => $list]);
5418 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5421 * Add a new group to the database.
5423 * @param string $name Group name
5424 * @param int $uid User ID
5425 * @param array $users List of users to add to the group
5428 * @throws BadRequestException
5430 function group_create($name, $uid, $users = [])
5432 // error if no name specified
5434 throw new BadRequestException('group name not specified');
5437 // get data of the specified group name
5439 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5443 // error message if specified group name already exists
5444 if (DBA::isResult($rname)) {
5445 throw new BadRequestException('group name already exists');
5448 // check if specified group name is a deleted group
5450 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5454 // error message if specified group name already exists
5455 if (DBA::isResult($rname)) {
5456 $reactivate_group = true;
5460 $ret = Group::create($uid, $name);
5462 $gid = Group::getIdByName($uid, $name);
5464 throw new BadRequestException('other API error');
5468 $erroraddinguser = false;
5470 foreach ($users as $user) {
5471 $cid = $user['cid'];
5472 // check if user really exists as contact
5474 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5478 if (count($contact)) {
5479 Group::addMember($gid, $cid);
5481 $erroraddinguser = true;
5482 $errorusers[] = $cid;
5486 // return success message incl. missing users in array
5487 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5489 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5493 * Create the specified group with the posted array of contacts.
5495 * @param string $type Return type (atom, rss, xml, json)
5497 * @return array|string
5498 * @throws BadRequestException
5499 * @throws ForbiddenException
5500 * @throws ImagickException
5501 * @throws InternalServerErrorException
5502 * @throws UnauthorizedException
5504 function api_friendica_group_create($type)
5508 if (api_user() === false) {
5509 throw new ForbiddenException();
5513 $user_info = api_get_user($a);
5514 $name = $_REQUEST['name'] ?? '';
5515 $uid = $user_info['uid'];
5516 $json = json_decode($_POST['json'], true);
5517 $users = $json['user'];
5519 $success = group_create($name, $uid, $users);
5521 return api_format_data("group_create", $type, ['result' => $success]);
5523 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5526 * Create a new group.
5528 * @param string $type Return type (atom, rss, xml, json)
5530 * @return array|string
5531 * @throws BadRequestException
5532 * @throws ForbiddenException
5533 * @throws ImagickException
5534 * @throws InternalServerErrorException
5535 * @throws UnauthorizedException
5536 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5538 function api_lists_create($type)
5542 if (api_user() === false) {
5543 throw new ForbiddenException();
5547 $user_info = api_get_user($a);
5548 $name = $_REQUEST['name'] ?? '';
5549 $uid = $user_info['uid'];
5551 $success = group_create($name, $uid);
5552 if ($success['success']) {
5554 'name' => $success['name'],
5555 'id' => intval($success['gid']),
5556 'id_str' => (string) $success['gid'],
5557 'user' => $user_info
5560 return api_format_data("lists", $type, ['lists'=>$grp]);
5563 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5566 * Update the specified group with the posted array of contacts.
5568 * @param string $type Return type (atom, rss, xml, json)
5570 * @return array|string
5571 * @throws BadRequestException
5572 * @throws ForbiddenException
5573 * @throws ImagickException
5574 * @throws InternalServerErrorException
5575 * @throws UnauthorizedException
5577 function api_friendica_group_update($type)
5581 if (api_user() === false) {
5582 throw new ForbiddenException();
5586 $user_info = api_get_user($a);
5587 $uid = $user_info['uid'];
5588 $gid = $_REQUEST['gid'] ?? 0;
5589 $name = $_REQUEST['name'] ?? '';
5590 $json = json_decode($_POST['json'], true);
5591 $users = $json['user'];
5593 // error if no name specified
5595 throw new BadRequestException('group name not specified');
5598 // error if no gid specified
5600 throw new BadRequestException('gid not specified');
5604 $members = Contact::getByGroupId($gid);
5605 foreach ($members as $member) {
5606 $cid = $member['id'];
5607 foreach ($users as $user) {
5608 $found = ($user['cid'] == $cid ? true : false);
5610 if (!isset($found) || !$found) {
5611 Group::removeMemberByName($uid, $name, $cid);
5616 $erroraddinguser = false;
5618 foreach ($users as $user) {
5619 $cid = $user['cid'];
5620 // check if user really exists as contact
5622 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5627 if (count($contact)) {
5628 Group::addMember($gid, $cid);
5630 $erroraddinguser = true;
5631 $errorusers[] = $cid;
5635 // return success message incl. missing users in array
5636 $status = ($erroraddinguser ? "missing user" : "ok");
5637 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5638 return api_format_data("group_update", $type, ['result' => $success]);
5641 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5644 * Update information about a group.
5646 * @param string $type Return type (atom, rss, xml, json)
5648 * @return array|string
5649 * @throws BadRequestException
5650 * @throws ForbiddenException
5651 * @throws ImagickException
5652 * @throws InternalServerErrorException
5653 * @throws UnauthorizedException
5654 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5656 function api_lists_update($type)
5660 if (api_user() === false) {
5661 throw new ForbiddenException();
5665 $user_info = api_get_user($a);
5666 $gid = $_REQUEST['list_id'] ?? 0;
5667 $name = $_REQUEST['name'] ?? '';
5668 $uid = $user_info['uid'];
5670 // error if no gid specified
5672 throw new BadRequestException('gid not specified');
5675 // get data of the specified group id
5676 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5677 // error message if specified gid is not in database
5679 throw new BadRequestException('gid not available');
5682 if (Group::update($gid, $name)) {
5685 'id' => intval($gid),
5686 'id_str' => (string) $gid,
5687 'user' => $user_info
5690 return api_format_data("lists", $type, ['lists' => $list]);
5694 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5698 * @param string $type Return type (atom, rss, xml, json)
5700 * @return array|string
5701 * @throws BadRequestException
5702 * @throws ForbiddenException
5703 * @throws ImagickException
5704 * @throws InternalServerErrorException
5706 function api_friendica_activity($type)
5710 if (api_user() === false) {
5711 throw new ForbiddenException();
5713 $verb = strtolower($a->argv[3]);
5714 $verb = preg_replace("|\..*$|", "", $verb);
5716 $id = $_REQUEST['id'] ?? 0;
5718 $res = Item::performActivity($id, $verb);
5721 if ($type == "xml") {
5726 return api_format_data('ok', $type, ['ok' => $ok]);
5728 throw new BadRequestException('Error adding activity');
5732 /// @TODO move to top of file or somewhere better
5733 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5734 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5735 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5736 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5737 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5738 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5739 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5740 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5741 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5742 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5745 * Returns notifications
5747 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5749 * @return string|array
5750 * @throws ForbiddenException
5751 * @throws BadRequestException
5754 function api_friendica_notification($type)
5758 if (api_user() === false) {
5759 throw new ForbiddenException();
5762 throw new BadRequestException("Invalid argument count");
5765 $notifications = DI::notification()->getApiList(local_user());
5767 if ($type == "xml") {
5769 if (!empty($notifications)) {
5770 foreach ($notifications as $notification) {
5771 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5775 $result = $xmlnotes;
5776 } elseif (count($notifications) > 0) {
5777 $result = $notifications->getArrayCopy();
5782 return api_format_data("notes", $type, ['note' => $result]);
5786 * Set notification as seen and returns associated item (if possible)
5788 * POST request with 'id' param as notification id
5790 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5791 * @return string|array
5792 * @throws BadRequestException
5793 * @throws ForbiddenException
5794 * @throws ImagickException
5795 * @throws InternalServerErrorException
5796 * @throws UnauthorizedException
5798 function api_friendica_notification_seen($type)
5801 $user_info = api_get_user($a);
5803 if (api_user() === false || $user_info === false) {
5804 throw new ForbiddenException();
5806 if ($a->argc !== 4) {
5807 throw new BadRequestException("Invalid argument count");
5810 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5813 $notify = DI::notify()->getByID($id, api_user());
5814 DI::notify()->setSeen(true, $notify);
5816 if ($notify->otype === Notify\ObjectType::ITEM) {
5817 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5818 if (DBA::isResult($item)) {
5819 // we found the item, return it to the user
5820 $ret = api_format_items([$item], $user_info, false, $type);
5821 $data = ['status' => $ret];
5822 return api_format_data("status", $type, $data);
5824 // the item can't be found, but we set the notification as seen, so we count this as a success
5826 return api_format_data('result', $type, ['result' => "success"]);
5827 } catch (NotFoundException $e) {
5828 throw new BadRequestException('Invalid argument', $e);
5829 } catch (Exception $e) {
5830 throw new InternalServerErrorException('Internal Server exception', $e);
5834 /// @TODO move to top of file or somewhere better
5835 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5836 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5839 * update a direct_message to seen state
5841 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5842 * @return string|array (success result=ok, error result=error with error message)
5843 * @throws BadRequestException
5844 * @throws ForbiddenException
5845 * @throws ImagickException
5846 * @throws InternalServerErrorException
5847 * @throws UnauthorizedException
5849 function api_friendica_direct_messages_setseen($type)
5852 if (api_user() === false) {
5853 throw new ForbiddenException();
5857 $user_info = api_get_user($a);
5858 $uid = $user_info['uid'];
5859 $id = $_REQUEST['id'] ?? 0;
5861 // return error if id is zero
5863 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5864 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5867 // error message if specified id is not in database
5868 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5869 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5870 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5873 // update seen indicator
5874 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5878 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5879 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5881 $answer = ['result' => 'error', 'message' => 'unknown error'];
5882 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5886 /// @TODO move to top of file or somewhere better
5887 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5890 * search for direct_messages containing a searchstring through api
5892 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5893 * @param string $box
5894 * @return string|array (success: success=true if found and search_result contains found messages,
5895 * success=false if nothing was found, search_result='nothing found',
5896 * error: result=error with error message)
5897 * @throws BadRequestException
5898 * @throws ForbiddenException
5899 * @throws ImagickException
5900 * @throws InternalServerErrorException
5901 * @throws UnauthorizedException
5903 function api_friendica_direct_messages_search($type, $box = "")
5907 if (api_user() === false) {
5908 throw new ForbiddenException();
5912 $user_info = api_get_user($a);
5913 $searchstring = $_REQUEST['searchstring'] ?? '';
5914 $uid = $user_info['uid'];
5916 // error if no searchstring specified
5917 if ($searchstring == "") {
5918 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5919 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5922 // get data for the specified searchstring
5924 "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",
5926 DBA::escape('%'.$searchstring.'%')
5929 $profile_url = $user_info["url"];
5931 // message if nothing was found
5932 if (!DBA::isResult($r)) {
5933 $success = ['success' => false, 'search_results' => 'problem with query'];
5934 } elseif (count($r) == 0) {
5935 $success = ['success' => false, 'search_results' => 'nothing found'];
5938 foreach ($r as $item) {
5939 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5940 $recipient = $user_info;
5941 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5942 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5943 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5944 $sender = $user_info;
5947 if (isset($recipient) && isset($sender)) {
5948 $ret[] = api_format_messages($item, $recipient, $sender);
5951 $success = ['success' => true, 'search_results' => $ret];
5954 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5957 /// @TODO move to top of file or somewhere better
5958 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5961 * Returns a list of saved searches.
5963 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5965 * @param string $type Return format: json or xml
5967 * @return string|array
5970 function api_saved_searches_list($type)
5972 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5975 while ($term = DBA::fetch($terms)) {
5977 'created_at' => api_date(time()),
5978 'id' => intval($term['id']),
5979 'id_str' => $term['id'],
5980 'name' => $term['term'],
5982 'query' => $term['term']
5988 return api_format_data("terms", $type, ['terms' => $result]);
5991 /// @TODO move to top of file or somewhere better
5992 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5995 * Number of comments
5997 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5999 * @param object $data [Status, Status]
6003 function bindComments(&$data)
6005 if (count($data) == 0) {
6011 foreach ($data as $item) {
6012 $ids[] = $item['id'];
6015 $idStr = DBA::escape(implode(', ', $ids));
6016 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6017 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6018 $itemsData = DBA::toArray($items);
6020 foreach ($itemsData as $item) {
6021 $comments[$item['parent']] = $item['comments'];
6024 foreach ($data as $idx => $item) {
6026 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6031 @TODO Maybe open to implement?
6033 [pagename] => api/1.1/statuses/lookup.json
6034 [id] => 605138389168451584
6035 [include_cards] => true
6036 [cards_platform] => Android-12
6037 [include_entities] => true
6038 [include_my_retweet] => 1
6040 [include_reply_count] => true
6041 [include_descendent_reply_count] => true
6045 Not implemented by now:
6046 statuses/retweets_of_me
6051 account/update_location
6052 account/update_profile_background_image
6055 friendica/profile/update
6056 friendica/profile/create
6057 friendica/profile/delete
6059 Not implemented in status.net:
6060 statuses/retweeted_to_me
6061 statuses/retweeted_by_me
6062 direct_messages/destroy
6064 account/update_delivery_device
6065 notifications/follow