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 DI::auth()->setForUser($a, $record);
269 $_SESSION["allow_api"] = true;
271 Hook::callAll('logged_in', $a->user);
275 * Check HTTP method of called API
277 * API endpoints can define which HTTP method to accept when called.
278 * This function check the current HTTP method agains endpoint
281 * @param string $method Required methods, uppercase, separated by comma
284 function api_check_method($method)
286 if ($method == "*") {
289 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
293 * Main API entry point
295 * Authenticate user, call registered API function, set HTTP headers
298 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
299 * @return string|array API call result
302 function api_call(App $a, App\Arguments $args = null)
304 global $API, $called_api;
311 if (strpos($args->getQueryString(), ".xml") > 0) {
314 if (strpos($args->getQueryString(), ".json") > 0) {
317 if (strpos($args->getQueryString(), ".rss") > 0) {
320 if (strpos($args->getQueryString(), ".atom") > 0) {
325 foreach ($API as $p => $info) {
326 if (strpos($args->getQueryString(), $p) === 0) {
327 if (!api_check_method($info['method'])) {
328 throw new MethodNotAllowedException();
331 $called_api = explode("/", $p);
333 if (!empty($info['auth']) && api_user() === false) {
337 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
338 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
340 $stamp = microtime(true);
341 $return = call_user_func($info['func'], $type);
342 $duration = floatval(microtime(true) - $stamp);
344 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
346 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
348 if (false === $return) {
350 * api function returned false withour throw an
351 * exception. This should not happend, throw a 500
353 throw new InternalServerErrorException();
358 header("Content-Type: text/xml");
361 header("Content-Type: application/json");
362 if (!empty($return)) {
363 $json = json_encode(end($return));
364 if (!empty($_GET['callback'])) {
365 $json = $_GET['callback'] . "(" . $json . ")";
371 header("Content-Type: application/rss+xml");
372 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
375 header("Content-Type: application/atom+xml");
376 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
383 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
384 throw new NotImplementedException();
385 } catch (HTTPException $e) {
386 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
387 return api_error($type, $e, $args);
392 * Format API error string
394 * @param string $type Return type (xml, json, rss, as)
395 * @param object $e HTTPException Error object
396 * @param App\Arguments $args The App arguments
397 * @return string|array error message formatted as $type
399 function api_error($type, $e, App\Arguments $args)
401 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
402 /// @TODO: https://dev.twitter.com/overview/api/response-codes
404 $error = ["error" => $error,
405 "code" => $e->getCode() . " " . $e->httpdesc,
406 "request" => $args->getQueryString()];
408 $return = api_format_data('status', $type, ['status' => $error]);
412 header("Content-Type: text/xml");
415 header("Content-Type: application/json");
416 $return = json_encode($return);
419 header("Content-Type: application/rss+xml");
422 header("Content-Type: application/atom+xml");
430 * Set values for RSS template
433 * @param array $arr Array to be passed to template
434 * @param array $user_info User info
436 * @throws BadRequestException
437 * @throws ImagickException
438 * @throws InternalServerErrorException
439 * @throws UnauthorizedException
440 * @todo find proper type-hints
442 function api_rss_extra(App $a, $arr, $user_info)
444 if (is_null($user_info)) {
445 $user_info = api_get_user($a);
448 $arr['$user'] = $user_info;
450 'alternate' => $user_info['url'],
451 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
452 'base' => DI::baseUrl(),
453 'updated' => api_date(null),
454 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
455 'language' => $user_info['lang'],
456 'logo' => DI::baseUrl() . "/images/friendica-32.png",
464 * Unique contact to contact url.
466 * @param int $id Contact id
467 * @return bool|string
468 * Contact url or False if contact id is unknown
471 function api_unique_id_to_nurl($id)
473 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
475 if (DBA::isResult($r)) {
483 * Get user info array.
486 * @param int|string $contact_id Contact ID or URL
488 * @throws BadRequestException
489 * @throws ImagickException
490 * @throws InternalServerErrorException
491 * @throws UnauthorizedException
493 function api_get_user(App $a, $contact_id = null)
501 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
503 // Searching for contact URL
504 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
505 $user = DBA::escape(Strings::normaliseLink($contact_id));
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 // Searching for contact id with uid = 0
514 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
515 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
518 throw new BadRequestException("User ID ".$contact_id." not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && !empty($_GET['user_id'])) {
529 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
532 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 if (is_null($user) && !empty($_GET['screen_name'])) {
542 $user = DBA::escape($_GET['screen_name']);
543 $extra_query = "AND `contact`.`nick` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 if (is_null($user) && !empty($_GET['profileurl'])) {
550 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
551 $extra_query = "AND `contact`.`nurl` = '%s' ";
552 if (api_user() !== false) {
553 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
557 // $called_api is the API path exploded on / and is expected to have at least 2 elements
558 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
559 $argid = count($called_api);
560 if (!empty($a->argv[$argid])) {
561 $data = explode(".", $a->argv[$argid]);
562 if (count($data) > 1) {
563 list($user, $null) = $data;
566 if (is_numeric($user)) {
567 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
571 $extra_query = "AND `contact`.`nurl` = '%s' ";
572 if (api_user() !== false) {
573 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
577 $user = DBA::escape($user);
578 $extra_query = "AND `contact`.`nick` = '%s' ";
579 if (api_user() !== false) {
580 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
585 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
588 if (api_user() === false) {
592 $user = $_SESSION['uid'];
593 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
597 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
601 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
607 // Selecting the id by priority, friendica first
608 if (is_array($uinfo)) {
609 api_best_nickname($uinfo);
612 // if the contact wasn't found, fetch it from the contacts with uid = 0
613 if (!DBA::isResult($uinfo)) {
615 throw new BadRequestException("User not found.");
618 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
620 if (DBA::isResult($contact)) {
622 'id' => $contact["id"],
623 'id_str' => (string) $contact["id"],
624 'name' => $contact["name"],
625 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
626 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
627 'description' => BBCode::toPlaintext($contact["about"]),
628 'profile_image_url' => $contact["micro"],
629 'profile_image_url_https' => $contact["micro"],
630 'profile_image_url_profile_size' => $contact["thumb"],
631 'profile_image_url_large' => $contact["photo"],
632 'url' => $contact["url"],
633 'protected' => false,
634 'followers_count' => 0,
635 'friends_count' => 0,
637 'created_at' => api_date($contact["created"]),
638 'favourites_count' => 0,
640 'time_zone' => 'UTC',
641 'geo_enabled' => false,
643 'statuses_count' => 0,
645 'contributors_enabled' => false,
646 'is_translator' => false,
647 'is_translation_enabled' => false,
648 'following' => false,
649 'follow_request_sent' => false,
650 'statusnet_blocking' => false,
651 'notifications' => false,
652 'statusnet_profile_url' => $contact["url"],
654 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
655 'pid' => Contact::getIdForURL($contact["url"], 0, true),
657 'network' => $contact["network"],
662 throw new BadRequestException("User ".$url." not found.");
666 if ($uinfo[0]['self']) {
667 if ($uinfo[0]['network'] == "") {
668 $uinfo[0]['network'] = Protocol::DFRN;
671 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
672 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
679 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
681 if (!empty($profile['about'])) {
682 $description = $profile['about'];
684 $description = $uinfo[0]["about"];
687 if (!empty($usr['default-location'])) {
688 $location = $usr['default-location'];
689 } elseif (!empty($uinfo[0]["location"])) {
690 $location = $uinfo[0]["location"];
692 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
696 'id' => intval($pcontact_id),
697 'id_str' => (string) intval($pcontact_id),
698 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
699 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
700 'location' => $location,
701 'description' => BBCode::toPlaintext($description),
702 'profile_image_url' => $uinfo[0]['micro'],
703 'profile_image_url_https' => $uinfo[0]['micro'],
704 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
705 'profile_image_url_large' => $uinfo[0]["photo"],
706 'url' => $uinfo[0]['url'],
707 'protected' => false,
708 'followers_count' => intval($countfollowers),
709 'friends_count' => intval($countfriends),
711 'created_at' => api_date($uinfo[0]['created']),
712 'favourites_count' => intval($starred),
714 'time_zone' => 'UTC',
715 'geo_enabled' => false,
717 'statuses_count' => intval($countitems),
719 'contributors_enabled' => false,
720 'is_translator' => false,
721 'is_translation_enabled' => false,
722 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
723 'follow_request_sent' => false,
724 'statusnet_blocking' => false,
725 'notifications' => false,
727 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
728 'statusnet_profile_url' => $uinfo[0]['url'],
729 'uid' => intval($uinfo[0]['uid']),
730 'cid' => intval($uinfo[0]['cid']),
731 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
732 'self' => $uinfo[0]['self'],
733 'network' => $uinfo[0]['network'],
736 // If this is a local user and it uses Frio, we can get its color preferences.
738 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
739 if ($theme_info['theme'] === 'frio') {
740 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
742 if ($schema && ($schema != '---')) {
743 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
744 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
745 require_once $schemefile;
748 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
749 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
750 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
752 if (empty($nav_bg)) {
755 if (empty($link_color)) {
756 $link_color = "#6fdbe8";
758 if (empty($bgcolor)) {
759 $bgcolor = "#ededed";
762 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
763 $ret['profile_link_color'] = str_replace('#', '', $link_color);
764 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
772 * return api-formatted array for item's author and owner
775 * @param array $item item from db
776 * @return array(array:author, array:owner)
777 * @throws BadRequestException
778 * @throws ImagickException
779 * @throws InternalServerErrorException
780 * @throws UnauthorizedException
782 function api_item_get_user(App $a, $item)
784 $status_user = api_get_user($a, $item['author-id'] ?? null);
786 $author_user = $status_user;
788 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
790 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
791 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
793 $owner_user = $author_user;
796 return ([$status_user, $author_user, $owner_user]);
800 * walks recursively through an array with the possibility to change value and key
802 * @param array $array The array to walk through
803 * @param callable $callback The callback function
805 * @return array the transformed array
807 function api_walk_recursive(array &$array, callable $callback)
811 foreach ($array as $k => $v) {
813 if ($callback($v, $k)) {
814 $new_array[$k] = api_walk_recursive($v, $callback);
817 if ($callback($v, $k)) {
828 * Callback function to transform the array in an array that can be transformed in a XML file
830 * @param mixed $item Array item value
831 * @param string $key Array key
833 * @return boolean Should the array item be deleted?
835 function api_reformat_xml(&$item, &$key)
837 if (is_bool($item)) {
838 $item = ($item ? "true" : "false");
841 if (substr($key, 0, 10) == "statusnet_") {
842 $key = "statusnet:".substr($key, 10);
843 } elseif (substr($key, 0, 10) == "friendica_") {
844 $key = "friendica:".substr($key, 10);
846 /// @TODO old-lost code?
848 // $key = "default:".$key;
854 * Creates the XML from a JSON style array
856 * @param array $data JSON style array
857 * @param string $root_element Name of the root element
859 * @return string The XML data
861 function api_create_xml(array $data, $root_element)
863 $childname = key($data);
864 $data2 = array_pop($data);
866 $namespaces = ["" => "http://api.twitter.com",
867 "statusnet" => "http://status.net/schema/api/1/",
868 "friendica" => "http://friendi.ca/schema/api/1/",
869 "georss" => "http://www.georss.org/georss"];
871 /// @todo Auto detection of needed namespaces
872 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
876 if (is_array($data2)) {
878 api_walk_recursive($data2, "api_reformat_xml");
884 foreach ($data2 as $item) {
885 $data4[$i++ . ":" . $childname] = $item;
892 $data3 = [$root_element => $data2];
894 $ret = XML::fromArray($data3, $xml, false, $namespaces);
899 * Formats the data according to the data type
901 * @param string $root_element Name of the root element
902 * @param string $type Return type (atom, rss, xml, json)
903 * @param array $data JSON style array
905 * @return array|string (string|array) XML data or JSON data
907 function api_format_data($root_element, $type, $data)
913 $ret = api_create_xml($data, $root_element);
928 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
929 * returns a 401 status code and an error message if not.
931 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
933 * @param string $type Return type (atom, rss, xml, json)
934 * @return array|string
935 * @throws BadRequestException
936 * @throws ForbiddenException
937 * @throws ImagickException
938 * @throws InternalServerErrorException
939 * @throws UnauthorizedException
941 function api_account_verify_credentials($type)
945 if (api_user() === false) {
946 throw new ForbiddenException();
949 unset($_REQUEST["user_id"]);
950 unset($_GET["user_id"]);
952 unset($_REQUEST["screen_name"]);
953 unset($_GET["screen_name"]);
955 $skip_status = $_REQUEST['skip_status'] ?? false;
957 $user_info = api_get_user($a);
959 // "verified" isn't used here in the standard
960 unset($user_info["verified"]);
962 // - Adding last status
964 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
966 $user_info['status'] = api_format_item($item, $type);
970 // "uid" and "self" are only needed for some internal stuff, so remove it from here
971 unset($user_info["uid"]);
972 unset($user_info["self"]);
974 return api_format_data("user", $type, ['user' => $user_info]);
977 /// @TODO move to top of file or somewhere better
978 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
981 * Get data from $_POST or $_GET
986 function requestdata($k)
988 if (!empty($_POST[$k])) {
991 if (!empty($_GET[$k])) {
998 * Deprecated function to upload media.
1000 * @param string $type Return type (atom, rss, xml, json)
1002 * @return array|string
1003 * @throws BadRequestException
1004 * @throws ForbiddenException
1005 * @throws ImagickException
1006 * @throws InternalServerErrorException
1007 * @throws UnauthorizedException
1009 function api_statuses_mediap($type)
1013 if (api_user() === false) {
1014 Logger::log('api_statuses_update: no user');
1015 throw new ForbiddenException();
1017 $user_info = api_get_user($a);
1019 $_REQUEST['profile_uid'] = api_user();
1020 $_REQUEST['api_source'] = true;
1021 $txt = requestdata('status');
1022 /// @TODO old-lost code?
1023 //$txt = urldecode(requestdata('status'));
1025 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1026 $txt = HTML::toBBCodeVideo($txt);
1027 $config = HTMLPurifier_Config::createDefault();
1028 $config->set('Cache.DefinitionImpl', null);
1029 $purifier = new HTMLPurifier($config);
1030 $txt = $purifier->purify($txt);
1032 $txt = HTML::toBBCode($txt);
1034 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1036 $picture = wall_upload_post($a, false);
1038 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1039 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1040 $item_id = item_post($a);
1042 // output the post that we just posted.
1043 return api_status_show($type, $item_id);
1046 /// @TODO move this to top of file or somewhere better!
1047 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1050 * Updates the user’s current status.
1052 * @param string $type Return type (atom, rss, xml, json)
1054 * @return array|string
1055 * @throws BadRequestException
1056 * @throws ForbiddenException
1057 * @throws ImagickException
1058 * @throws InternalServerErrorException
1059 * @throws TooManyRequestsException
1060 * @throws UnauthorizedException
1061 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1063 function api_statuses_update($type)
1067 if (api_user() === false) {
1068 Logger::log('api_statuses_update: no user');
1069 throw new ForbiddenException();
1074 // convert $_POST array items to the form we use for web posts.
1075 if (requestdata('htmlstatus')) {
1076 $txt = requestdata('htmlstatus');
1077 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1078 $txt = HTML::toBBCodeVideo($txt);
1080 $config = HTMLPurifier_Config::createDefault();
1081 $config->set('Cache.DefinitionImpl', null);
1083 $purifier = new HTMLPurifier($config);
1084 $txt = $purifier->purify($txt);
1086 $_REQUEST['body'] = HTML::toBBCode($txt);
1089 $_REQUEST['body'] = requestdata('status');
1092 $_REQUEST['title'] = requestdata('title');
1094 $parent = requestdata('in_reply_to_status_id');
1096 // Twidere sends "-1" if it is no reply ...
1097 if ($parent == -1) {
1101 if (ctype_digit($parent)) {
1102 $_REQUEST['parent'] = $parent;
1104 $_REQUEST['parent_uri'] = $parent;
1107 if (requestdata('lat') && requestdata('long')) {
1108 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1110 $_REQUEST['profile_uid'] = api_user();
1113 // Check for throttling (maximum posts per day, week and month)
1114 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1115 if ($throttle_day > 0) {
1116 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1118 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1119 $posts_day = DBA::count('thread', $condition);
1121 if ($posts_day > $throttle_day) {
1122 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1123 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1124 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));
1128 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1129 if ($throttle_week > 0) {
1130 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1132 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1133 $posts_week = DBA::count('thread', $condition);
1135 if ($posts_week > $throttle_week) {
1136 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1137 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1138 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));
1142 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1143 if ($throttle_month > 0) {
1144 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1146 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1147 $posts_month = DBA::count('thread', $condition);
1149 if ($posts_month > $throttle_month) {
1150 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1151 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1152 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));
1157 if (!empty($_FILES['media'])) {
1158 // upload the image if we have one
1159 $picture = wall_upload_post($a, false);
1160 if (is_array($picture)) {
1161 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1165 if (requestdata('media_ids')) {
1166 $ids = explode(',', requestdata('media_ids'));
1167 foreach ($ids as $id) {
1169 "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",
1173 if (DBA::isResult($r)) {
1174 $phototypes = Images::supportedTypes();
1175 $ext = $phototypes[$r[0]['type']];
1176 $description = $r[0]['desc'] ?? '';
1177 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1178 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1183 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1185 $_REQUEST['api_source'] = true;
1187 if (empty($_REQUEST['source'])) {
1188 $_REQUEST["source"] = api_source();
1191 // call out normal post function
1192 $item_id = item_post($a);
1194 // output the post that we just posted.
1195 return api_status_show($type, $item_id);
1198 /// @TODO move to top of file or somewhere better
1199 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1200 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1203 * Uploads an image to Friendica.
1206 * @throws BadRequestException
1207 * @throws ForbiddenException
1208 * @throws ImagickException
1209 * @throws InternalServerErrorException
1210 * @throws UnauthorizedException
1211 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1213 function api_media_upload()
1217 if (api_user() === false) {
1218 Logger::log('no user');
1219 throw new ForbiddenException();
1224 if (empty($_FILES['media'])) {
1226 throw new BadRequestException("No media.");
1229 $media = wall_upload_post($a, false);
1232 throw new InternalServerErrorException();
1236 $returndata["media_id"] = $media["id"];
1237 $returndata["media_id_string"] = (string)$media["id"];
1238 $returndata["size"] = $media["size"];
1239 $returndata["image"] = ["w" => $media["width"],
1240 "h" => $media["height"],
1241 "image_type" => $media["type"],
1242 "friendica_preview_url" => $media["preview"]];
1244 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1246 return ["media" => $returndata];
1249 /// @TODO move to top of file or somewhere better
1250 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1253 * Updates media meta data (picture descriptions)
1255 * @param string $type Return type (atom, rss, xml, json)
1257 * @return array|string
1258 * @throws BadRequestException
1259 * @throws ForbiddenException
1260 * @throws ImagickException
1261 * @throws InternalServerErrorException
1262 * @throws TooManyRequestsException
1263 * @throws UnauthorizedException
1264 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1266 * @todo Compare the corresponding Twitter function for correct return values
1268 function api_media_metadata_create($type)
1272 if (api_user() === false) {
1273 Logger::info('no user');
1274 throw new ForbiddenException();
1279 $postdata = Network::postdata();
1281 if (empty($postdata)) {
1282 throw new BadRequestException("No post data");
1285 $data = json_decode($postdata, true);
1287 throw new BadRequestException("Invalid post data");
1290 if (empty($data['media_id']) || empty($data['alt_text'])) {
1291 throw new BadRequestException("Missing post data values");
1294 if (empty($data['alt_text']['text'])) {
1295 throw new BadRequestException("No alt text.");
1298 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1300 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1301 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1302 if (!DBA::isResult($photo)) {
1303 throw new BadRequestException("Metadata not found.");
1306 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1309 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1312 * @param string $type Return format (atom, rss, xml, json)
1313 * @param int $item_id
1314 * @return array|string
1317 function api_status_show($type, $item_id)
1319 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1323 $item = api_get_item(['id' => $item_id]);
1324 if (!empty($item)) {
1325 $status_info = api_format_item($item, $type);
1328 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1330 return api_format_data('statuses', $type, ['status' => $status_info]);
1334 * Retrieves the last public status of the provided user info
1336 * @param int $ownerId Public contact Id
1337 * @param int $uid User Id
1341 function api_get_last_status($ownerId, $uid)
1344 'author-id'=> $ownerId,
1346 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1347 'private' => [Item::PUBLIC, Item::UNLISTED]
1350 $item = api_get_item($condition);
1356 * Retrieves a single item record based on the provided condition and converts it for API use.
1358 * @param array $condition Item table condition array
1362 function api_get_item(array $condition)
1364 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1370 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1371 * The author's most recent status will be returned inline.
1373 * @param string $type Return type (atom, rss, xml, json)
1374 * @return array|string
1375 * @throws BadRequestException
1376 * @throws ImagickException
1377 * @throws InternalServerErrorException
1378 * @throws UnauthorizedException
1379 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1381 function api_users_show($type)
1383 $a = Friendica\DI::app();
1385 $user_info = api_get_user($a);
1387 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1388 if (!empty($item)) {
1389 $user_info['status'] = api_format_item($item, $type);
1392 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1393 unset($user_info['uid']);
1394 unset($user_info['self']);
1396 return api_format_data('user', $type, ['user' => $user_info]);
1399 /// @TODO move to top of file or somewhere better
1400 api_register_func('api/users/show', 'api_users_show');
1401 api_register_func('api/externalprofile/show', 'api_users_show');
1404 * Search a public user account.
1406 * @param string $type Return type (atom, rss, xml, json)
1408 * @return array|string
1409 * @throws BadRequestException
1410 * @throws ImagickException
1411 * @throws InternalServerErrorException
1412 * @throws UnauthorizedException
1413 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1415 function api_users_search($type)
1421 if (!empty($_GET['q'])) {
1422 $contacts = Contact::selectToArray(
1425 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1433 if (DBA::isResult($contacts)) {
1435 foreach ($contacts as $contact) {
1436 $user_info = api_get_user($a, $contact['id']);
1438 if ($type == 'xml') {
1439 $userlist[$k++ . ':user'] = $user_info;
1441 $userlist[] = $user_info;
1444 $userlist = ['users' => $userlist];
1446 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1449 throw new BadRequestException('No search term specified.');
1452 return api_format_data('users', $type, $userlist);
1455 /// @TODO move to top of file or somewhere better
1456 api_register_func('api/users/search', 'api_users_search');
1459 * Return user objects
1461 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1463 * @param string $type Return format: json or xml
1465 * @return array|string
1466 * @throws BadRequestException
1467 * @throws ImagickException
1468 * @throws InternalServerErrorException
1469 * @throws NotFoundException if the results are empty.
1470 * @throws UnauthorizedException
1472 function api_users_lookup($type)
1476 if (!empty($_REQUEST['user_id'])) {
1477 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1479 $users[] = api_get_user(DI::app(), $id);
1484 if (empty($users)) {
1485 throw new NotFoundException;
1488 return api_format_data("users", $type, ['users' => $users]);
1491 /// @TODO move to top of file or somewhere better
1492 api_register_func('api/users/lookup', 'api_users_lookup', true);
1495 * Returns statuses that match a specified query.
1497 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1499 * @param string $type Return format: json, xml, atom, rss
1501 * @return array|string
1502 * @throws BadRequestException if the "q" parameter is missing.
1503 * @throws ForbiddenException
1504 * @throws ImagickException
1505 * @throws InternalServerErrorException
1506 * @throws UnauthorizedException
1508 function api_search($type)
1511 $user_info = api_get_user($a);
1513 if (api_user() === false || $user_info === false) {
1514 throw new ForbiddenException();
1517 if (empty($_REQUEST['q'])) {
1518 throw new BadRequestException('q parameter is required.');
1521 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1524 $data['status'] = [];
1526 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1527 if (!empty($_REQUEST['rpp'])) {
1528 $count = $_REQUEST['rpp'];
1529 } elseif (!empty($_REQUEST['count'])) {
1530 $count = $_REQUEST['count'];
1533 $since_id = $_REQUEST['since_id'] ?? 0;
1534 $max_id = $_REQUEST['max_id'] ?? 0;
1535 $page = $_REQUEST['page'] ?? 1;
1537 $start = max(0, ($page - 1) * $count);
1539 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1540 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1541 $searchTerm = $matches[1];
1542 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1543 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1545 while ($tag = DBA::fetch($tags)) {
1546 $uriids[] = $tag['uri-id'];
1550 if (empty($uriids)) {
1551 return api_format_data('statuses', $type, $data);
1554 $condition = ['uri-id' => $uriids];
1555 if ($exclude_replies) {
1556 $condition['gravity'] = GRAVITY_PARENT;
1559 $params['group_by'] = ['uri-id'];
1561 $condition = ["`id` > ?
1562 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1563 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1564 AND `body` LIKE CONCAT('%',?,'%')",
1565 $since_id, api_user(), $_REQUEST['q']];
1567 $condition[0] .= ' AND `id` <= ?';
1568 $condition[] = $max_id;
1574 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1575 $id = Item::fetchByLink($searchTerm, api_user());
1578 $id = Item::fetchByLink($searchTerm);
1582 $statuses = Item::select([], ['id' => $id]);
1586 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1588 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1590 bindComments($data['status']);
1592 return api_format_data('statuses', $type, $data);
1595 /// @TODO move to top of file or somewhere better
1596 api_register_func('api/search/tweets', 'api_search', true);
1597 api_register_func('api/search', 'api_search', true);
1600 * Returns the most recent statuses posted by the user and the users they follow.
1602 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1604 * @param string $type Return type (atom, rss, xml, json)
1606 * @return array|string
1607 * @throws BadRequestException
1608 * @throws ForbiddenException
1609 * @throws ImagickException
1610 * @throws InternalServerErrorException
1611 * @throws UnauthorizedException
1612 * @todo Optional parameters
1613 * @todo Add reply info
1615 function api_statuses_home_timeline($type)
1618 $user_info = api_get_user($a);
1620 if (api_user() === false || $user_info === false) {
1621 throw new ForbiddenException();
1624 unset($_REQUEST["user_id"]);
1625 unset($_GET["user_id"]);
1627 unset($_REQUEST["screen_name"]);
1628 unset($_GET["screen_name"]);
1630 // get last network messages
1633 $count = $_REQUEST['count'] ?? 20;
1634 $page = $_REQUEST['page']?? 0;
1635 $since_id = $_REQUEST['since_id'] ?? 0;
1636 $max_id = $_REQUEST['max_id'] ?? 0;
1637 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1638 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1640 $start = max(0, ($page - 1) * $count);
1642 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1643 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1646 $condition[0] .= " AND `item`.`id` <= ?";
1647 $condition[] = $max_id;
1649 if ($exclude_replies) {
1650 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1652 if ($conversation_id > 0) {
1653 $condition[0] .= " AND `item`.`parent` = ?";
1654 $condition[] = $conversation_id;
1657 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1658 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1660 $items = Item::inArray($statuses);
1662 $ret = api_format_items($items, $user_info, false, $type);
1664 // Set all posts from the query above to seen
1666 foreach ($items as $item) {
1667 $idarray[] = intval($item["id"]);
1670 if (!empty($idarray)) {
1671 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1673 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1679 $data = ['status' => $ret];
1684 $data = api_rss_extra($a, $data, $user_info);
1688 return api_format_data("statuses", $type, $data);
1692 /// @TODO move to top of file or somewhere better
1693 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1694 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1697 * Returns the most recent statuses from public users.
1699 * @param string $type Return type (atom, rss, xml, json)
1701 * @return array|string
1702 * @throws BadRequestException
1703 * @throws ForbiddenException
1704 * @throws ImagickException
1705 * @throws InternalServerErrorException
1706 * @throws UnauthorizedException
1708 function api_statuses_public_timeline($type)
1711 $user_info = api_get_user($a);
1713 if (api_user() === false || $user_info === false) {
1714 throw new ForbiddenException();
1717 // get last network messages
1720 $count = $_REQUEST['count'] ?? 20;
1721 $page = $_REQUEST['page'] ?? 1;
1722 $since_id = $_REQUEST['since_id'] ?? 0;
1723 $max_id = $_REQUEST['max_id'] ?? 0;
1724 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1725 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1727 $start = max(0, ($page - 1) * $count);
1729 if ($exclude_replies && !$conversation_id) {
1730 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
1731 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1734 $condition[0] .= " AND `thread`.`iid` <= ?";
1735 $condition[] = $max_id;
1738 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1739 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1741 $r = Item::inArray($statuses);
1743 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
1744 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1747 $condition[0] .= " AND `item`.`id` <= ?";
1748 $condition[] = $max_id;
1750 if ($conversation_id > 0) {
1751 $condition[0] .= " AND `item`.`parent` = ?";
1752 $condition[] = $conversation_id;
1755 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1756 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1758 $r = Item::inArray($statuses);
1761 $ret = api_format_items($r, $user_info, false, $type);
1765 $data = ['status' => $ret];
1770 $data = api_rss_extra($a, $data, $user_info);
1774 return api_format_data("statuses", $type, $data);
1777 /// @TODO move to top of file or somewhere better
1778 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1781 * Returns the most recent statuses posted by users this node knows about.
1783 * @param string $type Return format: json, xml, atom, rss
1784 * @return array|string
1785 * @throws BadRequestException
1786 * @throws ForbiddenException
1787 * @throws ImagickException
1788 * @throws InternalServerErrorException
1789 * @throws UnauthorizedException
1791 function api_statuses_networkpublic_timeline($type)
1794 $user_info = api_get_user($a);
1796 if (api_user() === false || $user_info === false) {
1797 throw new ForbiddenException();
1800 $since_id = $_REQUEST['since_id'] ?? 0;
1801 $max_id = $_REQUEST['max_id'] ?? 0;
1804 $count = $_REQUEST['count'] ?? 20;
1805 $page = $_REQUEST['page'] ?? 1;
1807 $start = max(0, ($page - 1) * $count);
1809 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
1810 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1813 $condition[0] .= " AND `thread`.`iid` <= ?";
1814 $condition[] = $max_id;
1817 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1818 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1820 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1824 $data = ['status' => $ret];
1829 $data = api_rss_extra($a, $data, $user_info);
1833 return api_format_data("statuses", $type, $data);
1836 /// @TODO move to top of file or somewhere better
1837 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1840 * Returns a single status.
1842 * @param string $type Return type (atom, rss, xml, json)
1844 * @return array|string
1845 * @throws BadRequestException
1846 * @throws ForbiddenException
1847 * @throws ImagickException
1848 * @throws InternalServerErrorException
1849 * @throws UnauthorizedException
1850 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1852 function api_statuses_show($type)
1855 $user_info = api_get_user($a);
1857 if (api_user() === false || $user_info === false) {
1858 throw new ForbiddenException();
1862 $id = intval($a->argv[3] ?? 0);
1865 $id = intval($_REQUEST['id'] ?? 0);
1870 $id = intval($a->argv[4] ?? 0);
1873 Logger::log('API: api_statuses_show: ' . $id);
1875 $conversation = !empty($_REQUEST['conversation']);
1877 // try to fetch the item for the local user - or the public item, if there is no local one
1878 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1879 if (!DBA::isResult($uri_item)) {
1880 throw new BadRequestException("There is no status with this id.");
1883 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1884 if (!DBA::isResult($item)) {
1885 throw new BadRequestException("There is no status with this id.");
1890 if ($conversation) {
1891 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1892 $params = ['order' => ['id' => true]];
1894 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1898 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1900 /// @TODO How about copying this to above methods which don't check $r ?
1901 if (!DBA::isResult($statuses)) {
1902 throw new BadRequestException("There is no status with this id.");
1905 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1907 if ($conversation) {
1908 $data = ['status' => $ret];
1909 return api_format_data("statuses", $type, $data);
1911 $data = ['status' => $ret[0]];
1912 return api_format_data("status", $type, $data);
1916 /// @TODO move to top of file or somewhere better
1917 api_register_func('api/statuses/show', 'api_statuses_show', true);
1921 * @param string $type Return type (atom, rss, xml, json)
1923 * @return array|string
1924 * @throws BadRequestException
1925 * @throws ForbiddenException
1926 * @throws ImagickException
1927 * @throws InternalServerErrorException
1928 * @throws UnauthorizedException
1929 * @todo nothing to say?
1931 function api_conversation_show($type)
1934 $user_info = api_get_user($a);
1936 if (api_user() === false || $user_info === false) {
1937 throw new ForbiddenException();
1941 $id = intval($a->argv[3] ?? 0);
1942 $since_id = intval($_REQUEST['since_id'] ?? 0);
1943 $max_id = intval($_REQUEST['max_id'] ?? 0);
1944 $count = intval($_REQUEST['count'] ?? 20);
1945 $page = intval($_REQUEST['page'] ?? 1);
1947 $start = max(0, ($page - 1) * $count);
1950 $id = intval($_REQUEST['id'] ?? 0);
1955 $id = intval($a->argv[4] ?? 0);
1958 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1960 // try to fetch the item for the local user - or the public item, if there is no local one
1961 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1962 if (!DBA::isResult($item)) {
1963 throw new BadRequestException("There is no status with this id.");
1966 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1967 if (!DBA::isResult($parent)) {
1968 throw new BadRequestException("There is no status with this id.");
1971 $id = $parent['id'];
1973 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1974 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1977 $condition[0] .= " AND `item`.`id` <= ?";
1978 $condition[] = $max_id;
1981 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1982 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1984 if (!DBA::isResult($statuses)) {
1985 throw new BadRequestException("There is no status with id $id.");
1988 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1990 $data = ['status' => $ret];
1991 return api_format_data("statuses", $type, $data);
1994 /// @TODO move to top of file or somewhere better
1995 api_register_func('api/conversation/show', 'api_conversation_show', true);
1996 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2001 * @param string $type Return type (atom, rss, xml, json)
2003 * @return array|string
2004 * @throws BadRequestException
2005 * @throws ForbiddenException
2006 * @throws ImagickException
2007 * @throws InternalServerErrorException
2008 * @throws UnauthorizedException
2009 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2011 function api_statuses_repeat($type)
2017 if (api_user() === false) {
2018 throw new ForbiddenException();
2024 $id = intval($a->argv[3] ?? 0);
2027 $id = intval($_REQUEST['id'] ?? 0);
2032 $id = intval($a->argv[4] ?? 0);
2035 Logger::log('API: api_statuses_repeat: '.$id);
2037 $fields = ['uri-id', 'body', 'title', 'attach', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2038 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2040 if (DBA::isResult($item) && $item['body'] != "") {
2041 if (strpos($item['body'], "[/share]") !== false) {
2042 $pos = strpos($item['body'], "[share");
2043 $post = substr($item['body'], $pos);
2045 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2047 if (!empty($item['title'])) {
2048 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2051 $post .= $item['body'];
2052 $post .= "[/share]";
2054 $_REQUEST['body'] = $post;
2055 $_REQUEST['attach'] = $item['attach'];
2056 $_REQUEST['profile_uid'] = api_user();
2057 $_REQUEST['api_source'] = true;
2059 if (empty($_REQUEST['source'])) {
2060 $_REQUEST["source"] = api_source();
2063 $item_id = item_post($a);
2065 /// @todo Copy tags from the original post to the new one
2067 throw new ForbiddenException();
2070 // output the post that we just posted.
2072 return api_status_show($type, $item_id);
2075 /// @TODO move to top of file or somewhere better
2076 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2079 * Destroys a specific status.
2081 * @param string $type Return type (atom, rss, xml, json)
2083 * @return array|string
2084 * @throws BadRequestException
2085 * @throws ForbiddenException
2086 * @throws ImagickException
2087 * @throws InternalServerErrorException
2088 * @throws UnauthorizedException
2089 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2091 function api_statuses_destroy($type)
2095 if (api_user() === false) {
2096 throw new ForbiddenException();
2102 $id = intval($a->argv[3] ?? 0);
2105 $id = intval($_REQUEST['id'] ?? 0);
2110 $id = intval($a->argv[4] ?? 0);
2113 Logger::log('API: api_statuses_destroy: '.$id);
2115 $ret = api_statuses_show($type);
2117 Item::deleteForUser(['id' => $id], api_user());
2122 /// @TODO move to top of file or somewhere better
2123 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2126 * Returns the most recent mentions.
2128 * @param string $type Return type (atom, rss, xml, json)
2130 * @return array|string
2131 * @throws BadRequestException
2132 * @throws ForbiddenException
2133 * @throws ImagickException
2134 * @throws InternalServerErrorException
2135 * @throws UnauthorizedException
2136 * @see http://developer.twitter.com/doc/get/statuses/mentions
2138 function api_statuses_mentions($type)
2141 $user_info = api_get_user($a);
2143 if (api_user() === false || $user_info === false) {
2144 throw new ForbiddenException();
2147 unset($_REQUEST["user_id"]);
2148 unset($_GET["user_id"]);
2150 unset($_REQUEST["screen_name"]);
2151 unset($_GET["screen_name"]);
2153 // get last network messages
2156 $since_id = $_REQUEST['since_id'] ?? 0;
2157 $max_id = $_REQUEST['max_id'] ?? 0;
2158 $count = $_REQUEST['count'] ?? 20;
2159 $page = $_REQUEST['page'] ?? 1;
2161 $start = max(0, ($page - 1) * $count);
2163 $query = "SELECT `item`.`id` FROM `user-item`
2164 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2165 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2166 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2167 AND `user-item`.`iid` > ?";
2168 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2169 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2170 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2171 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2175 $query .= " AND `item`.`id` <= ?";
2176 $condition[] = $max_id;
2179 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2180 $condition[] = $start;
2181 $condition[] = $count;
2183 $useritems = DBA::p($query, $condition);
2185 while ($useritem = DBA::fetch($useritems)) {
2186 $itemids[] = $useritem['id'];
2188 DBA::close($useritems);
2190 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2191 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2193 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2195 $data = ['status' => $ret];
2200 $data = api_rss_extra($a, $data, $user_info);
2204 return api_format_data("statuses", $type, $data);
2207 /// @TODO move to top of file or somewhere better
2208 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2209 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2212 * Returns the most recent statuses posted by the user.
2214 * @param string $type Either "json" or "xml"
2215 * @return string|array
2216 * @throws BadRequestException
2217 * @throws ForbiddenException
2218 * @throws ImagickException
2219 * @throws InternalServerErrorException
2220 * @throws UnauthorizedException
2221 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2223 function api_statuses_user_timeline($type)
2226 $user_info = api_get_user($a);
2228 if (api_user() === false || $user_info === false) {
2229 throw new ForbiddenException();
2233 "api_statuses_user_timeline: api_user: ". api_user() .
2234 "\nuser_info: ".print_r($user_info, true) .
2235 "\n_REQUEST: ".print_r($_REQUEST, true),
2239 $since_id = $_REQUEST['since_id'] ?? 0;
2240 $max_id = $_REQUEST['max_id'] ?? 0;
2241 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2242 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2245 $count = $_REQUEST['count'] ?? 20;
2246 $page = $_REQUEST['page'] ?? 1;
2248 $start = max(0, ($page - 1) * $count);
2250 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2251 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2253 if ($user_info['self'] == 1) {
2254 $condition[0] .= ' AND `item`.`wall` ';
2257 if ($exclude_replies) {
2258 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2261 if ($conversation_id > 0) {
2262 $condition[0] .= " AND `item`.`parent` = ?";
2263 $condition[] = $conversation_id;
2267 $condition[0] .= " AND `item`.`id` <= ?";
2268 $condition[] = $max_id;
2271 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2272 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2274 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2278 $data = ['status' => $ret];
2283 $data = api_rss_extra($a, $data, $user_info);
2287 return api_format_data("statuses", $type, $data);
2290 /// @TODO move to top of file or somewhere better
2291 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2294 * Star/unstar an item.
2295 * param: id : id of the item
2297 * @param string $type Return type (atom, rss, xml, json)
2299 * @return array|string
2300 * @throws BadRequestException
2301 * @throws ForbiddenException
2302 * @throws ImagickException
2303 * @throws InternalServerErrorException
2304 * @throws UnauthorizedException
2305 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2307 function api_favorites_create_destroy($type)
2311 if (api_user() === false) {
2312 throw new ForbiddenException();
2315 // for versioned api.
2316 /// @TODO We need a better global soluton
2317 $action_argv_id = 2;
2318 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2319 $action_argv_id = 3;
2322 if ($a->argc <= $action_argv_id) {
2323 throw new BadRequestException("Invalid request.");
2325 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2326 if ($a->argc == $action_argv_id + 2) {
2327 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2329 $itemid = intval($_REQUEST['id'] ?? 0);
2332 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2334 if (!DBA::isResult($item)) {
2335 throw new BadRequestException("Invalid item.");
2340 $item['starred'] = 1;
2343 $item['starred'] = 0;
2346 throw new BadRequestException("Invalid action ".$action);
2349 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2352 throw new InternalServerErrorException("DB error");
2356 $user_info = api_get_user($a);
2357 $rets = api_format_items([$item], $user_info, false, $type);
2360 $data = ['status' => $ret];
2365 $data = api_rss_extra($a, $data, $user_info);
2369 return api_format_data("status", $type, $data);
2372 /// @TODO move to top of file or somewhere better
2373 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2374 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2377 * Returns the most recent favorite statuses.
2379 * @param string $type Return type (atom, rss, xml, json)
2381 * @return string|array
2382 * @throws BadRequestException
2383 * @throws ForbiddenException
2384 * @throws ImagickException
2385 * @throws InternalServerErrorException
2386 * @throws UnauthorizedException
2388 function api_favorites($type)
2393 $user_info = api_get_user($a);
2395 if (api_user() === false || $user_info === false) {
2396 throw new ForbiddenException();
2401 // in friendica starred item are private
2402 // return favorites only for self
2403 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2405 if ($user_info['self'] == 0) {
2409 $since_id = $_REQUEST['since_id'] ?? 0;
2410 $max_id = $_REQUEST['max_id'] ?? 0;
2411 $count = $_GET['count'] ?? 20;
2412 $page = $_REQUEST['page'] ?? 1;
2414 $start = max(0, ($page - 1) * $count);
2416 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2417 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2419 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2422 $condition[0] .= " AND `item`.`id` <= ?";
2423 $condition[] = $max_id;
2426 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2428 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2433 $data = ['status' => $ret];
2438 $data = api_rss_extra($a, $data, $user_info);
2442 return api_format_data("statuses", $type, $data);
2445 /// @TODO move to top of file or somewhere better
2446 api_register_func('api/favorites', 'api_favorites', true);
2450 * @param array $item
2451 * @param array $recipient
2452 * @param array $sender
2455 * @throws InternalServerErrorException
2457 function api_format_messages($item, $recipient, $sender)
2459 // standard meta information
2461 'id' => $item['id'],
2462 'sender_id' => $sender['id'],
2464 'recipient_id' => $recipient['id'],
2465 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2466 'sender_screen_name' => $sender['screen_name'],
2467 'recipient_screen_name' => $recipient['screen_name'],
2468 'sender' => $sender,
2469 'recipient' => $recipient,
2471 'friendica_seen' => $item['seen'] ?? 0,
2472 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2475 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2476 if (isset($ret['sender']['uid'])) {
2477 unset($ret['sender']['uid']);
2479 if (isset($ret['sender']['self'])) {
2480 unset($ret['sender']['self']);
2482 if (isset($ret['recipient']['uid'])) {
2483 unset($ret['recipient']['uid']);
2485 if (isset($ret['recipient']['self'])) {
2486 unset($ret['recipient']['self']);
2489 //don't send title to regular StatusNET requests to avoid confusing these apps
2490 if (!empty($_GET['getText'])) {
2491 $ret['title'] = $item['title'];
2492 if ($_GET['getText'] == 'html') {
2493 $ret['text'] = BBCode::convert($item['body'], false);
2494 } elseif ($_GET['getText'] == 'plain') {
2495 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0));
2498 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, BBCode::API, true), 0);
2500 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2501 unset($ret['sender']);
2502 unset($ret['recipient']);
2510 * @param array $item
2513 * @throws InternalServerErrorException
2515 function api_convert_item($item)
2517 $body = $item['body'];
2518 $entities = api_get_entitities($statustext, $body);
2520 // Add pictures to the attachment array and remove them from the body
2521 $attachments = api_get_attachments($body);
2523 // Workaround for ostatus messages where the title is identically to the body
2524 $html = BBCode::convert(api_clean_plain_items($body), false, BBCode::API, true);
2525 $statusbody = trim(HTML::toPlaintext($html, 0));
2527 // handle data: images
2528 $statusbody = api_format_items_embeded_images($item, $statusbody);
2530 $statustitle = trim($item['title']);
2532 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2533 $statustext = trim($statusbody);
2535 $statustext = trim($statustitle."\n\n".$statusbody);
2538 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2539 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2542 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2544 // Workaround for clients with limited HTML parser functionality
2545 $search = ["<br>", "<blockquote>", "</blockquote>",
2546 "<h1>", "</h1>", "<h2>", "</h2>",
2547 "<h3>", "</h3>", "<h4>", "</h4>",
2548 "<h5>", "</h5>", "<h6>", "</h6>"];
2549 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2550 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2551 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2552 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2553 $statushtml = str_replace($search, $replace, $statushtml);
2555 if ($item['title'] != "") {
2556 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2560 $oldtext = $statushtml;
2561 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2562 } while ($oldtext != $statushtml);
2564 if (substr($statushtml, 0, 4) == '<br>') {
2565 $statushtml = substr($statushtml, 4);
2568 if (substr($statushtml, 0, -4) == '<br>') {
2569 $statushtml = substr($statushtml, -4);
2572 // feeds without body should contain the link
2573 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2574 $statushtml .= BBCode::convert($item['plink']);
2578 "text" => $statustext,
2579 "html" => $statushtml,
2580 "attachments" => $attachments,
2581 "entities" => $entities
2587 * @param string $body
2590 * @throws InternalServerErrorException
2592 function api_get_attachments(&$body)
2594 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2595 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2597 $URLSearchString = "^\[\]";
2598 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2602 // Remove all embedded pictures, since they are added as attachments
2603 foreach ($images[0] as $orig) {
2604 $body = str_replace($orig, '', $body);
2609 foreach ($images[1] as $image) {
2610 $imagedata = Images::getInfoFromURLCached($image);
2613 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2617 return $attachments;
2622 * @param string $text
2623 * @param string $bbcode
2626 * @throws InternalServerErrorException
2627 * @todo Links at the first character of the post
2629 function api_get_entitities(&$text, $bbcode)
2631 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2633 if ($include_entities != "true") {
2634 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2636 foreach ($images[1] as $image) {
2637 $replace = ProxyUtils::proxifyUrl($image);
2638 $text = str_replace($image, $replace, $text);
2643 $bbcode = BBCode::cleanPictureLinks($bbcode);
2645 // Change pure links in text to bbcode uris
2646 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2649 $entities["hashtags"] = [];
2650 $entities["symbols"] = [];
2651 $entities["urls"] = [];
2652 $entities["user_mentions"] = [];
2654 $URLSearchString = "^\[\]";
2656 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2658 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2659 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2661 $bbcode = preg_replace(
2662 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2663 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2666 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2668 $bbcode = preg_replace(
2669 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2670 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2673 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2675 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2677 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2680 foreach ($urls[1] as $id => $url) {
2681 $start = iconv_strpos($text, $url, 0, "UTF-8");
2682 if (!($start === false)) {
2683 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2687 ksort($ordered_urls);
2691 foreach ($ordered_urls as $url) {
2692 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2693 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2695 $display_url = $url["title"];
2697 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2698 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2700 if (strlen($display_url) > 26) {
2701 $display_url = substr($display_url, 0, 25)."…";
2705 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2706 if (!($start === false)) {
2707 $entities["urls"][] = ["url" => $url["url"],
2708 "expanded_url" => $url["url"],
2709 "display_url" => $display_url,
2710 "indices" => [$start, $start+strlen($url["url"])]];
2711 $offset = $start + 1;
2715 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2716 $ordered_images = [];
2717 foreach ($images as $image) {
2718 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2719 if (!($start === false)) {
2720 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2724 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2725 foreach ($images[1] as $image) {
2726 $start = iconv_strpos($text, $image, 0, "UTF-8");
2727 if (!($start === false)) {
2728 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2734 foreach ($ordered_images as $image) {
2735 $url = $image['url'];
2736 $ext_alt_text = $image['alt'];
2738 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2739 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2741 if (strlen($display_url) > 26) {
2742 $display_url = substr($display_url, 0, 25)."…";
2745 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2746 if (!($start === false)) {
2747 $image = Images::getInfoFromURLCached($url);
2749 // If image cache is activated, then use the following sizes:
2750 // thumb (150), small (340), medium (600) and large (1024)
2751 if (!DI::config()->get("system", "proxy_disabled")) {
2752 $media_url = ProxyUtils::proxifyUrl($url);
2755 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2756 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2758 if (($image[0] > 150) || ($image[1] > 150)) {
2759 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2760 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2763 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2764 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2766 if (($image[0] > 600) || ($image[1] > 600)) {
2767 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2768 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2772 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2775 $entities["media"][] = [
2777 "id_str" => (string) ($start + 1),
2778 "indices" => [$start, $start+strlen($url)],
2779 "media_url" => Strings::normaliseLink($media_url),
2780 "media_url_https" => $media_url,
2782 "display_url" => $display_url,
2783 "expanded_url" => $url,
2784 "ext_alt_text" => $ext_alt_text,
2788 $offset = $start + 1;
2797 * @param array $item
2798 * @param string $text
2802 function api_format_items_embeded_images($item, $text)
2804 $text = preg_replace_callback(
2805 '|data:image/([^;]+)[^=]+=*|m',
2806 function () use ($item) {
2807 return DI::baseUrl() . '/display/' . $item['guid'];
2815 * return <a href='url'>name</a> as array
2817 * @param string $txt text
2822 function api_contactlink_to_array($txt)
2825 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2826 if ($r && count($match)==3) {
2828 'name' => $match[2],
2842 * return likes, dislikes and attend status for item
2844 * @param array $item array
2845 * @param string $type Return type (atom, rss, xml, json)
2848 * likes => int count,
2849 * dislikes => int count
2850 * @throws BadRequestException
2851 * @throws ImagickException
2852 * @throws InternalServerErrorException
2853 * @throws UnauthorizedException
2855 function api_format_items_activities($item, $type = "json")
2864 'attendmaybe' => [],
2868 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2869 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2871 while ($parent_item = Item::fetch($ret)) {
2872 // not used as result should be structured like other user data
2873 //builtin_activity_puller($i, $activities);
2875 // get user data and add it to the array of the activity
2876 $user = api_get_user($a, $parent_item['author-id']);
2877 switch ($parent_item['verb']) {
2878 case Activity::LIKE:
2879 $activities['like'][] = $user;
2881 case Activity::DISLIKE:
2882 $activities['dislike'][] = $user;
2884 case Activity::ATTEND:
2885 $activities['attendyes'][] = $user;
2887 case Activity::ATTENDNO:
2888 $activities['attendno'][] = $user;
2890 case Activity::ATTENDMAYBE:
2891 $activities['attendmaybe'][] = $user;
2893 case Activity::ANNOUNCE:
2894 $activities['announce'][] = $user;
2903 if ($type == "xml") {
2904 $xml_activities = [];
2905 foreach ($activities as $k => $v) {
2906 // change xml element from "like" to "friendica:like"
2907 $xml_activities["friendica:".$k] = $v;
2908 // add user data into xml output
2910 foreach ($v as $user) {
2911 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2914 $activities = $xml_activities;
2921 * format items to be returned by api
2923 * @param array $items array of items
2924 * @param array $user_info
2925 * @param bool $filter_user filter items by $user_info
2926 * @param string $type Return type (atom, rss, xml, json)
2928 * @throws BadRequestException
2929 * @throws ImagickException
2930 * @throws InternalServerErrorException
2931 * @throws UnauthorizedException
2933 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2935 $a = Friendica\DI::app();
2939 foreach ((array)$items as $item) {
2940 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2942 // Look if the posts are matching if they should be filtered by user id
2943 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2947 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2956 * @param array $item Item record
2957 * @param string $type Return format (atom, rss, xml, json)
2958 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2959 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2960 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2961 * @return array API-formatted status
2962 * @throws BadRequestException
2963 * @throws ImagickException
2964 * @throws InternalServerErrorException
2965 * @throws UnauthorizedException
2967 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2969 $a = Friendica\DI::app();
2971 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2972 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2975 localize_item($item);
2977 $in_reply_to = api_in_reply_to($item);
2979 $converted = api_convert_item($item);
2981 if ($type == "xml") {
2982 $geo = "georss:point";
2988 'text' => $converted["text"],
2989 'truncated' => false,
2990 'created_at'=> api_date($item['created']),
2991 'in_reply_to_status_id' => $in_reply_to['status_id'],
2992 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2993 'source' => (($item['app']) ? $item['app'] : 'web'),
2994 'id' => intval($item['id']),
2995 'id_str' => (string) intval($item['id']),
2996 'in_reply_to_user_id' => $in_reply_to['user_id'],
2997 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2998 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3000 'favorited' => $item['starred'] ? true : false,
3001 'user' => $status_user,
3002 'friendica_author' => $author_user,
3003 'friendica_owner' => $owner_user,
3004 'friendica_private' => $item['private'] == Item::PRIVATE,
3005 //'entities' => NULL,
3006 'statusnet_html' => $converted["html"],
3007 'statusnet_conversation_id' => $item['parent'],
3008 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3009 'friendica_activities' => api_format_items_activities($item, $type),
3010 'friendica_title' => $item['title'],
3011 'friendica_html' => BBCode::convert($item['body'], false)
3014 if (count($converted["attachments"]) > 0) {
3015 $status["attachments"] = $converted["attachments"];
3018 if (count($converted["entities"]) > 0) {
3019 $status["entities"] = $converted["entities"];
3022 if ($status["source"] == 'web') {
3023 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3024 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3025 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3028 $retweeted_item = [];
3031 if ($item['gravity'] == GRAVITY_PARENT) {
3032 $body = $item['body'];
3033 $retweeted_item = api_share_as_retweet($item);
3034 if ($body != $item['body']) {
3035 $quoted_item = $retweeted_item;
3036 $retweeted_item = [];
3040 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3041 $announce = api_get_announce($item);
3042 if (!empty($announce)) {
3043 $retweeted_item = $item;
3045 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3049 if (!empty($quoted_item)) {
3050 if ($quoted_item['id'] != $item['id']) {
3051 $quoted_status = api_format_item($quoted_item);
3052 /// @todo Only remove the attachments that are also contained in the quotes status
3053 unset($status['attachments']);
3054 unset($status['entities']);
3056 $conv_quoted = api_convert_item($quoted_item);
3057 $quoted_status = $status;
3058 unset($quoted_status['attachments']);
3059 unset($quoted_status['entities']);
3060 unset($quoted_status['statusnet_conversation_id']);
3061 $quoted_status['text'] = $conv_quoted['text'];
3062 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3064 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3065 } catch (BadRequestException $e) {
3066 // user not found. should be found?
3067 /// @todo check if the user should be always found
3068 $quoted_status["user"] = [];
3071 unset($quoted_status['friendica_author']);
3072 unset($quoted_status['friendica_owner']);
3073 unset($quoted_status['friendica_activities']);
3074 unset($quoted_status['friendica_private']);
3077 if (!empty($retweeted_item)) {
3078 $retweeted_status = $status;
3079 unset($retweeted_status['friendica_author']);
3080 unset($retweeted_status['friendica_owner']);
3081 unset($retweeted_status['friendica_activities']);
3082 unset($retweeted_status['friendica_private']);
3083 unset($retweeted_status['statusnet_conversation_id']);
3084 $status['user'] = $status['friendica_owner'];
3086 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3087 } catch (BadRequestException $e) {
3088 // user not found. should be found?
3089 /// @todo check if the user should be always found
3090 $retweeted_status["user"] = [];
3093 $rt_converted = api_convert_item($retweeted_item);
3095 $retweeted_status['text'] = $rt_converted["text"];
3096 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3097 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3099 if (!empty($quoted_status)) {
3100 $retweeted_status['quoted_status'] = $quoted_status;
3103 $status['friendica_author'] = $retweeted_status['user'];
3104 $status['retweeted_status'] = $retweeted_status;
3105 } elseif (!empty($quoted_status)) {
3106 $root_status = api_convert_item($item);
3108 $status['text'] = $root_status["text"];
3109 $status['statusnet_html'] = $root_status["html"];
3110 $status['quoted_status'] = $quoted_status;
3113 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3114 unset($status["user"]["uid"]);
3115 unset($status["user"]["self"]);
3117 if ($item["coord"] != "") {
3118 $coords = explode(' ', $item["coord"]);
3119 if (count($coords) == 2) {
3120 if ($type == "json") {
3121 $status["geo"] = ['type' => 'Point',
3122 'coordinates' => [(float) $coords[0],
3123 (float) $coords[1]]];
3124 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3125 $status["georss:point"] = $item["coord"];
3134 * Returns the remaining number of API requests available to the user before the API limit is reached.
3136 * @param string $type Return type (atom, rss, xml, json)
3138 * @return array|string
3141 function api_account_rate_limit_status($type)
3143 if ($type == "xml") {
3145 'remaining-hits' => '150',
3146 '@attributes' => ["type" => "integer"],
3147 'hourly-limit' => '150',
3148 '@attributes2' => ["type" => "integer"],
3149 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3150 '@attributes3' => ["type" => "datetime"],
3151 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3152 '@attributes4' => ["type" => "integer"],
3156 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3157 'remaining_hits' => '150',
3158 'hourly_limit' => '150',
3159 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3163 return api_format_data('hash', $type, ['hash' => $hash]);
3166 /// @TODO move to top of file or somewhere better
3167 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3170 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3172 * @param string $type Return type (atom, rss, xml, json)
3174 * @return array|string
3176 function api_help_test($type)
3178 if ($type == 'xml') {
3184 return api_format_data('ok', $type, ["ok" => $ok]);
3187 /// @TODO move to top of file or somewhere better
3188 api_register_func('api/help/test', 'api_help_test', false);
3191 * Returns all lists the user subscribes to.
3193 * @param string $type Return type (atom, rss, xml, json)
3195 * @return array|string
3196 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3198 function api_lists_list($type)
3201 /// @TODO $ret is not filled here?
3202 return api_format_data('lists', $type, ["lists_list" => $ret]);
3205 /// @TODO move to top of file or somewhere better
3206 api_register_func('api/lists/list', 'api_lists_list', true);
3207 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3210 * Returns all groups the user owns.
3212 * @param string $type Return type (atom, rss, xml, json)
3214 * @return array|string
3215 * @throws BadRequestException
3216 * @throws ForbiddenException
3217 * @throws ImagickException
3218 * @throws InternalServerErrorException
3219 * @throws UnauthorizedException
3220 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3222 function api_lists_ownerships($type)
3226 if (api_user() === false) {
3227 throw new ForbiddenException();
3231 $user_info = api_get_user($a);
3232 $uid = $user_info['uid'];
3234 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3236 // loop through all groups
3238 foreach ($groups as $group) {
3239 if ($group['visible']) {
3245 'name' => $group['name'],
3246 'id' => intval($group['id']),
3247 'id_str' => (string) $group['id'],
3248 'user' => $user_info,
3252 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3255 /// @TODO move to top of file or somewhere better
3256 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3259 * Returns recent statuses from users in the specified group.
3261 * @param string $type Return type (atom, rss, xml, json)
3263 * @return array|string
3264 * @throws BadRequestException
3265 * @throws ForbiddenException
3266 * @throws ImagickException
3267 * @throws InternalServerErrorException
3268 * @throws UnauthorizedException
3269 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3271 function api_lists_statuses($type)
3275 $user_info = api_get_user($a);
3276 if (api_user() === false || $user_info === false) {
3277 throw new ForbiddenException();
3280 unset($_REQUEST["user_id"]);
3281 unset($_GET["user_id"]);
3283 unset($_REQUEST["screen_name"]);
3284 unset($_GET["screen_name"]);
3286 if (empty($_REQUEST['list_id'])) {
3287 throw new BadRequestException('list_id not specified');
3291 $count = $_REQUEST['count'] ?? 20;
3292 $page = $_REQUEST['page'] ?? 1;
3293 $since_id = $_REQUEST['since_id'] ?? 0;
3294 $max_id = $_REQUEST['max_id'] ?? 0;
3295 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3296 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3298 $start = max(0, ($page - 1) * $count);
3300 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3301 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3304 $condition[0] .= " AND `item`.`id` <= ?";
3305 $condition[] = $max_id;
3307 if ($exclude_replies > 0) {
3308 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3310 if ($conversation_id > 0) {
3311 $condition[0] .= " AND `item`.`parent` = ?";
3312 $condition[] = $conversation_id;
3315 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3316 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3318 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3320 $data = ['status' => $items];
3325 $data = api_rss_extra($a, $data, $user_info);
3329 return api_format_data("statuses", $type, $data);
3332 /// @TODO move to top of file or somewhere better
3333 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3336 * Returns either the friends of the follower list
3338 * Considers friends and followers lists to be private and won't return
3339 * anything if any user_id parameter is passed.
3341 * @param string $qtype Either "friends" or "followers"
3342 * @return boolean|array
3343 * @throws BadRequestException
3344 * @throws ForbiddenException
3345 * @throws ImagickException
3346 * @throws InternalServerErrorException
3347 * @throws UnauthorizedException
3349 function api_statuses_f($qtype)
3353 if (api_user() === false) {
3354 throw new ForbiddenException();
3358 $count = $_GET['count'] ?? 20;
3359 $page = $_GET['page'] ?? 1;
3361 $start = max(0, ($page - 1) * $count);
3363 $user_info = api_get_user($a);
3365 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3366 /* this is to stop Hotot to load friends multiple times
3367 * I'm not sure if I'm missing return something or
3368 * is a bug in hotot. Workaround, meantime
3372 return array('$users' => $ret);*/
3377 if ($qtype == 'friends') {
3378 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3379 } elseif ($qtype == 'followers') {
3380 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3383 // friends and followers only for self
3384 if ($user_info['self'] == 0) {
3385 $sql_extra = " AND false ";
3388 if ($qtype == 'blocks') {
3389 $sql_filter = 'AND `blocked` AND NOT `pending`';
3390 } elseif ($qtype == 'incoming') {
3391 $sql_filter = 'AND `pending`';
3393 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3411 foreach ($r as $cid) {
3412 $user = api_get_user($a, $cid['nurl']);
3413 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3414 unset($user["uid"]);
3415 unset($user["self"]);
3422 return ['user' => $ret];
3427 * Returns the list of friends of the provided user
3429 * @deprecated By Twitter API in favor of friends/list
3431 * @param string $type Either "json" or "xml"
3432 * @return boolean|string|array
3433 * @throws BadRequestException
3434 * @throws ForbiddenException
3436 function api_statuses_friends($type)
3438 $data = api_statuses_f("friends");
3439 if ($data === false) {
3442 return api_format_data("users", $type, $data);
3446 * Returns the list of followers of the provided user
3448 * @deprecated By Twitter API in favor of friends/list
3450 * @param string $type Either "json" or "xml"
3451 * @return boolean|string|array
3452 * @throws BadRequestException
3453 * @throws ForbiddenException
3455 function api_statuses_followers($type)
3457 $data = api_statuses_f("followers");
3458 if ($data === false) {
3461 return api_format_data("users", $type, $data);
3464 /// @TODO move to top of file or somewhere better
3465 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3466 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3469 * Returns the list of blocked users
3471 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3473 * @param string $type Either "json" or "xml"
3475 * @return boolean|string|array
3476 * @throws BadRequestException
3477 * @throws ForbiddenException
3479 function api_blocks_list($type)
3481 $data = api_statuses_f('blocks');
3482 if ($data === false) {
3485 return api_format_data("users", $type, $data);
3488 /// @TODO move to top of file or somewhere better
3489 api_register_func('api/blocks/list', 'api_blocks_list', true);
3492 * Returns the list of pending users IDs
3494 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3496 * @param string $type Either "json" or "xml"
3498 * @return boolean|string|array
3499 * @throws BadRequestException
3500 * @throws ForbiddenException
3502 function api_friendships_incoming($type)
3504 $data = api_statuses_f('incoming');
3505 if ($data === false) {
3510 foreach ($data['user'] as $user) {
3511 $ids[] = $user['id'];
3514 return api_format_data("ids", $type, ['id' => $ids]);
3517 /// @TODO move to top of file or somewhere better
3518 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3521 * Returns the instance's configuration information.
3523 * @param string $type Return type (atom, rss, xml, json)
3525 * @return array|string
3526 * @throws InternalServerErrorException
3528 function api_statusnet_config($type)
3530 $name = DI::config()->get('config', 'sitename');
3531 $server = DI::baseUrl()->getHostname();
3532 $logo = DI::baseUrl() . '/images/friendica-64.png';
3533 $email = DI::config()->get('config', 'admin_email');
3534 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3535 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3536 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3537 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3538 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3541 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3542 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3543 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3544 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3545 'shorturllength' => '30',
3547 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3548 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3549 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3550 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3555 return api_format_data('config', $type, ['config' => $config]);
3558 /// @TODO move to top of file or somewhere better
3559 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3560 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3564 * @param string $type Return type (atom, rss, xml, json)
3566 * @return array|string
3568 function api_statusnet_version($type)
3571 $fake_statusnet_version = "0.9.7";
3573 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3576 /// @TODO move to top of file or somewhere better
3577 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3578 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3582 * @param string $type Return type (atom, rss, xml, json)
3584 * @param int $rel A contact relationship constant
3585 * @return array|string|void
3586 * @throws BadRequestException
3587 * @throws ForbiddenException
3588 * @throws ImagickException
3589 * @throws InternalServerErrorException
3590 * @throws UnauthorizedException
3591 * @todo use api_format_data() to return data
3593 function api_ff_ids($type, int $rel)
3596 throw new ForbiddenException();
3603 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3605 $contacts = DBA::p("SELECT `pcontact`.`id`
3607 INNER JOIN `contact` AS `pcontact`
3608 ON `contact`.`nurl` = `pcontact`.`nurl`
3609 AND `pcontact`.`uid` = 0
3610 WHERE `contact`.`uid` = ?
3611 AND NOT `contact`.`self`
3612 AND `contact`.`rel` IN (?, ?)",
3619 foreach (DBA::toArray($contacts) as $contact) {
3620 if ($stringify_ids) {
3621 $ids[] = $contact['id'];
3623 $ids[] = intval($contact['id']);
3627 return api_format_data('ids', $type, ['id' => $ids]);
3631 * Returns the ID of every user the user is following.
3633 * @param string $type Return type (atom, rss, xml, json)
3635 * @return array|string
3636 * @throws BadRequestException
3637 * @throws ForbiddenException
3638 * @throws ImagickException
3639 * @throws InternalServerErrorException
3640 * @throws UnauthorizedException
3641 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3643 function api_friends_ids($type)
3645 return api_ff_ids($type, Contact::SHARING);
3649 * Returns the ID of every user following the user.
3651 * @param string $type Return type (atom, rss, xml, json)
3653 * @return array|string
3654 * @throws BadRequestException
3655 * @throws ForbiddenException
3656 * @throws ImagickException
3657 * @throws InternalServerErrorException
3658 * @throws UnauthorizedException
3659 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3661 function api_followers_ids($type)
3663 return api_ff_ids($type, Contact::FOLLOWER);
3666 /// @TODO move to top of file or somewhere better
3667 api_register_func('api/friends/ids', 'api_friends_ids', true);
3668 api_register_func('api/followers/ids', 'api_followers_ids', true);
3671 * Sends a new direct message.
3673 * @param string $type Return type (atom, rss, xml, json)
3675 * @return array|string
3676 * @throws BadRequestException
3677 * @throws ForbiddenException
3678 * @throws ImagickException
3679 * @throws InternalServerErrorException
3680 * @throws NotFoundException
3681 * @throws UnauthorizedException
3682 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3684 function api_direct_messages_new($type)
3688 if (api_user() === false) {
3689 throw new ForbiddenException();
3692 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3696 $sender = api_get_user($a);
3699 if (!empty($_POST['screen_name'])) {
3701 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3703 DBA::escape($_POST['screen_name'])
3706 if (DBA::isResult($r)) {
3707 // Selecting the id by priority, friendica first
3708 api_best_nickname($r);
3710 $recipient = api_get_user($a, $r[0]['nurl']);
3713 $recipient = api_get_user($a, $_POST['user_id']);
3716 if (empty($recipient)) {
3717 throw new NotFoundException('Recipient not found');
3721 if (!empty($_REQUEST['replyto'])) {
3723 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3725 intval($_REQUEST['replyto'])
3727 $replyto = $r[0]['parent-uri'];
3728 $sub = $r[0]['title'];
3730 if (!empty($_REQUEST['title'])) {
3731 $sub = $_REQUEST['title'];
3733 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3737 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3740 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3741 $ret = api_format_messages($r[0], $recipient, $sender);
3743 $ret = ["error"=>$id];
3746 $data = ['direct_message'=>$ret];
3752 $data = api_rss_extra($a, $data, $sender);
3756 return api_format_data("direct-messages", $type, $data);
3759 /// @TODO move to top of file or somewhere better
3760 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3763 * delete a direct_message from mail table through api
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 UnauthorizedException
3772 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3774 function api_direct_messages_destroy($type)
3778 if (api_user() === false) {
3779 throw new ForbiddenException();
3783 $user_info = api_get_user($a);
3785 $id = $_REQUEST['id'] ?? 0;
3787 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3788 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3789 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3791 $uid = $user_info['uid'];
3792 // error if no id or parenturi specified (for clients posting parent-uri as well)
3793 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3794 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3795 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3798 // BadRequestException if no id specified (for clients using Twitter API)
3800 throw new BadRequestException('Message id not specified');
3803 // add parent-uri to sql command if specified by calling app
3804 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3806 // get data of the specified message id
3808 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3813 // error message if specified id is not in database
3814 if (!DBA::isResult($r)) {
3815 if ($verbose == "true") {
3816 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3817 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3819 /// @todo BadRequestException ok for Twitter API clients?
3820 throw new BadRequestException('message id not in database');
3825 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3830 if ($verbose == "true") {
3833 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3834 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3836 $answer = ['result' => 'error', 'message' => 'unknown error'];
3837 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3840 /// @todo return JSON data like Twitter API not yet implemented
3843 /// @TODO move to top of file or somewhere better
3844 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3849 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3850 * @return string|array
3851 * @throws BadRequestException
3852 * @throws ForbiddenException
3853 * @throws ImagickException
3854 * @throws InternalServerErrorException
3855 * @throws NotFoundException
3856 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3858 function api_friendships_destroy($type)
3862 if ($uid === false) {
3863 throw new ForbiddenException();
3866 $contact_id = $_REQUEST['user_id'] ?? 0;
3868 if (empty($contact_id)) {
3869 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3870 throw new BadRequestException("no user_id specified");
3873 // Get Contact by given id
3874 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3876 if(!DBA::isResult($contact)) {
3877 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3878 throw new NotFoundException("no contact found to given ID");
3881 $url = $contact["url"];
3883 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3884 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3885 Strings::normaliseLink($url), $url];
3886 $contact = DBA::selectFirst('contact', [], $condition);
3888 if (!DBA::isResult($contact)) {
3889 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3890 throw new NotFoundException("Not following Contact");
3893 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3894 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3895 throw new ExpectationFailedException("Not supported");
3898 $dissolve = ($contact['rel'] == Contact::SHARING);
3900 $owner = User::getOwnerDataById($uid);
3902 Contact::terminateFriendship($owner, $contact, $dissolve);
3905 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3906 throw new NotFoundException("Error Processing Request");
3909 // Sharing-only contacts get deleted as there no relationship any more
3911 Contact::remove($contact['id']);
3913 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3916 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3917 unset($contact["uid"]);
3918 unset($contact["self"]);
3920 // Set screen_name since Twidere requests it
3921 $contact["screen_name"] = $contact["nick"];
3923 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3925 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3929 * @param string $type Return type (atom, rss, xml, json)
3930 * @param string $box
3931 * @param string $verbose
3933 * @return array|string
3934 * @throws BadRequestException
3935 * @throws ForbiddenException
3936 * @throws ImagickException
3937 * @throws InternalServerErrorException
3938 * @throws UnauthorizedException
3940 function api_direct_messages_box($type, $box, $verbose)
3943 if (api_user() === false) {
3944 throw new ForbiddenException();
3947 $count = $_GET['count'] ?? 20;
3948 $page = $_REQUEST['page'] ?? 1;
3950 $since_id = $_REQUEST['since_id'] ?? 0;
3951 $max_id = $_REQUEST['max_id'] ?? 0;
3953 $user_id = $_REQUEST['user_id'] ?? '';
3954 $screen_name = $_REQUEST['screen_name'] ?? '';
3957 unset($_REQUEST["user_id"]);
3958 unset($_GET["user_id"]);
3960 unset($_REQUEST["screen_name"]);
3961 unset($_GET["screen_name"]);
3963 $user_info = api_get_user($a);
3964 if ($user_info === false) {
3965 throw new ForbiddenException();
3967 $profile_url = $user_info["url"];
3970 $start = max(0, ($page - 1) * $count);
3975 if ($box=="sentbox") {
3976 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3977 } elseif ($box == "conversation") {
3978 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3979 } elseif ($box == "all") {
3980 $sql_extra = "true";
3981 } elseif ($box == "inbox") {
3982 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3986 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3989 if ($user_id != "") {
3990 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3991 } elseif ($screen_name !="") {
3992 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3996 "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",
4002 if ($verbose == "true" && !DBA::isResult($r)) {
4003 $answer = ['result' => 'error', 'message' => 'no mails available'];
4004 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4008 foreach ($r as $item) {
4009 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4010 $recipient = $user_info;
4011 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4012 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4013 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4014 $sender = $user_info;
4017 if (isset($recipient) && isset($sender)) {
4018 $ret[] = api_format_messages($item, $recipient, $sender);
4023 $data = ['direct_message' => $ret];
4028 $data = api_rss_extra($a, $data, $user_info);
4032 return api_format_data("direct-messages", $type, $data);
4036 * Returns the most recent direct messages sent by the user.
4038 * @param string $type Return type (atom, rss, xml, json)
4040 * @return array|string
4041 * @throws BadRequestException
4042 * @throws ForbiddenException
4043 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4045 function api_direct_messages_sentbox($type)
4047 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4048 return api_direct_messages_box($type, "sentbox", $verbose);
4052 * Returns the most recent direct messages sent to the user.
4054 * @param string $type Return type (atom, rss, xml, json)
4056 * @return array|string
4057 * @throws BadRequestException
4058 * @throws ForbiddenException
4059 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4061 function api_direct_messages_inbox($type)
4063 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4064 return api_direct_messages_box($type, "inbox", $verbose);
4069 * @param string $type Return type (atom, rss, xml, json)
4071 * @return array|string
4072 * @throws BadRequestException
4073 * @throws ForbiddenException
4075 function api_direct_messages_all($type)
4077 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4078 return api_direct_messages_box($type, "all", $verbose);
4083 * @param string $type Return type (atom, rss, xml, json)
4085 * @return array|string
4086 * @throws BadRequestException
4087 * @throws ForbiddenException
4089 function api_direct_messages_conversation($type)
4091 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4092 return api_direct_messages_box($type, "conversation", $verbose);
4095 /// @TODO move to top of file or somewhere better
4096 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4097 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4098 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4099 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4102 * Returns an OAuth Request Token.
4104 * @see https://oauth.net/core/1.0/#auth_step1
4106 function api_oauth_request_token()
4108 $oauth1 = new FKOAuth1();
4110 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4111 } catch (Exception $e) {
4112 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4120 * Returns an OAuth Access Token.
4122 * @return array|string
4123 * @see https://oauth.net/core/1.0/#auth_step3
4125 function api_oauth_access_token()
4127 $oauth1 = new FKOAuth1();
4129 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4130 } catch (Exception $e) {
4131 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4138 /// @TODO move to top of file or somewhere better
4139 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4140 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4144 * delete a complete photoalbum with all containing photos from database through api
4146 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4147 * @return string|array
4148 * @throws BadRequestException
4149 * @throws ForbiddenException
4150 * @throws InternalServerErrorException
4152 function api_fr_photoalbum_delete($type)
4154 if (api_user() === false) {
4155 throw new ForbiddenException();
4158 $album = $_REQUEST['album'] ?? '';
4160 // we do not allow calls without album string
4162 throw new BadRequestException("no albumname specified");
4164 // check if album is existing
4166 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4170 if (!DBA::isResult($r)) {
4171 throw new BadRequestException("album not available");
4174 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4175 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4176 foreach ($r as $rr) {
4177 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4178 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4180 if (!DBA::isResult($photo_item)) {
4181 throw new InternalServerErrorException("problem with deleting items occured");
4183 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4186 // now let's delete all photos from the album
4187 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4189 // return success of deletion or error message
4191 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4192 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4194 throw new InternalServerErrorException("unknown error - deleting from database failed");
4199 * update the name of the album for all photos of an album
4201 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4202 * @return string|array
4203 * @throws BadRequestException
4204 * @throws ForbiddenException
4205 * @throws InternalServerErrorException
4207 function api_fr_photoalbum_update($type)
4209 if (api_user() === false) {
4210 throw new ForbiddenException();
4213 $album = $_REQUEST['album'] ?? '';
4214 $album_new = $_REQUEST['album_new'] ?? '';
4216 // we do not allow calls without album string
4218 throw new BadRequestException("no albumname specified");
4220 if ($album_new == "") {
4221 throw new BadRequestException("no new albumname specified");
4223 // check if album is existing
4224 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4225 throw new BadRequestException("album not available");
4227 // now let's update all photos to the albumname
4228 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4230 // return success of updating or error message
4232 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4233 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4235 throw new InternalServerErrorException("unknown error - updating in database failed");
4241 * list all photos of the authenticated user
4243 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4244 * @return string|array
4245 * @throws ForbiddenException
4246 * @throws InternalServerErrorException
4248 function api_fr_photos_list($type)
4250 if (api_user() === false) {
4251 throw new ForbiddenException();
4254 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4255 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4256 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4257 intval(local_user())
4260 'image/jpeg' => 'jpg',
4261 'image/png' => 'png',
4262 'image/gif' => 'gif'
4264 $data = ['photo'=>[]];
4265 if (DBA::isResult($r)) {
4266 foreach ($r as $rr) {
4268 $photo['id'] = $rr['resource-id'];
4269 $photo['album'] = $rr['album'];
4270 $photo['filename'] = $rr['filename'];
4271 $photo['type'] = $rr['type'];
4272 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4273 $photo['created'] = $rr['created'];
4274 $photo['edited'] = $rr['edited'];
4275 $photo['desc'] = $rr['desc'];
4277 if ($type == "xml") {
4278 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4280 $photo['thumb'] = $thumb;
4281 $data['photo'][] = $photo;
4285 return api_format_data("photos", $type, $data);
4289 * upload a new photo or change an existing photo
4291 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4292 * @return string|array
4293 * @throws BadRequestException
4294 * @throws ForbiddenException
4295 * @throws ImagickException
4296 * @throws InternalServerErrorException
4297 * @throws NotFoundException
4299 function api_fr_photo_create_update($type)
4301 if (api_user() === false) {
4302 throw new ForbiddenException();
4305 $photo_id = $_REQUEST['photo_id'] ?? null;
4306 $desc = $_REQUEST['desc'] ?? null;
4307 $album = $_REQUEST['album'] ?? null;
4308 $album_new = $_REQUEST['album_new'] ?? null;
4309 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4310 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4311 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4312 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4313 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4315 // do several checks on input parameters
4316 // we do not allow calls without album string
4317 if ($album == null) {
4318 throw new BadRequestException("no albumname specified");
4320 // if photo_id == null --> we are uploading a new photo
4321 if ($photo_id == null) {
4324 // error if no media posted in create-mode
4325 if (empty($_FILES['media'])) {
4327 throw new BadRequestException("no media data submitted");
4330 // album_new will be ignored in create-mode
4335 // check if photo is existing in databasei
4336 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4337 throw new BadRequestException("photo not available");
4341 // checks on acl strings provided by clients
4342 $acl_input_error = false;
4343 $acl_input_error |= check_acl_input($allow_cid);
4344 $acl_input_error |= check_acl_input($deny_cid);
4345 $acl_input_error |= check_acl_input($allow_gid);
4346 $acl_input_error |= check_acl_input($deny_gid);
4347 if ($acl_input_error) {
4348 throw new BadRequestException("acl data invalid");
4350 // now let's upload the new media in create-mode
4351 if ($mode == "create") {
4352 $media = $_FILES['media'];
4353 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4355 // return success of updating or error message
4356 if (!is_null($data)) {
4357 return api_format_data("photo_create", $type, $data);
4359 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4363 // now let's do the changes in update-mode
4364 if ($mode == "update") {
4365 $updated_fields = [];
4367 if (!is_null($desc)) {
4368 $updated_fields['desc'] = $desc;
4371 if (!is_null($album_new)) {
4372 $updated_fields['album'] = $album_new;
4375 if (!is_null($allow_cid)) {
4376 $allow_cid = trim($allow_cid);
4377 $updated_fields['allow_cid'] = $allow_cid;
4380 if (!is_null($deny_cid)) {
4381 $deny_cid = trim($deny_cid);
4382 $updated_fields['deny_cid'] = $deny_cid;
4385 if (!is_null($allow_gid)) {
4386 $allow_gid = trim($allow_gid);
4387 $updated_fields['allow_gid'] = $allow_gid;
4390 if (!is_null($deny_gid)) {
4391 $deny_gid = trim($deny_gid);
4392 $updated_fields['deny_gid'] = $deny_gid;
4396 if (count($updated_fields) > 0) {
4397 $nothingtodo = false;
4398 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4400 $nothingtodo = true;
4403 if (!empty($_FILES['media'])) {
4404 $nothingtodo = false;
4405 $media = $_FILES['media'];
4406 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4407 if (!is_null($data)) {
4408 return api_format_data("photo_update", $type, $data);
4412 // return success of updating or error message
4414 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4415 return api_format_data("photo_update", $type, ['$result' => $answer]);
4418 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4419 return api_format_data("photo_update", $type, ['$result' => $answer]);
4421 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4424 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4428 * delete a single photo from the database through api
4430 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4431 * @return string|array
4432 * @throws BadRequestException
4433 * @throws ForbiddenException
4434 * @throws InternalServerErrorException
4436 function api_fr_photo_delete($type)
4438 if (api_user() === false) {
4439 throw new ForbiddenException();
4443 $photo_id = $_REQUEST['photo_id'] ?? null;
4445 // do several checks on input parameters
4446 // we do not allow calls without photo id
4447 if ($photo_id == null) {
4448 throw new BadRequestException("no photo_id specified");
4451 // check if photo is existing in database
4452 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4453 throw new BadRequestException("photo not available");
4456 // now we can perform on the deletion of the photo
4457 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4459 // return success of deletion or error message
4461 // retrieve the id of the parent element (the photo element)
4462 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4463 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4465 if (!DBA::isResult($photo_item)) {
4466 throw new InternalServerErrorException("problem with deleting items occured");
4468 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4469 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4470 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4472 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4473 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4475 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4481 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4483 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4484 * @return string|array
4485 * @throws BadRequestException
4486 * @throws ForbiddenException
4487 * @throws InternalServerErrorException
4488 * @throws NotFoundException
4490 function api_fr_photo_detail($type)
4492 if (api_user() === false) {
4493 throw new ForbiddenException();
4495 if (empty($_REQUEST['photo_id'])) {
4496 throw new BadRequestException("No photo id.");
4499 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4500 $photo_id = $_REQUEST['photo_id'];
4502 // prepare json/xml output with data from database for the requested photo
4503 $data = prepare_photo_data($type, $scale, $photo_id);
4505 return api_format_data("photo_detail", $type, $data);
4510 * updates the profile image for the user (either a specified profile or the default profile)
4512 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4514 * @return string|array
4515 * @throws BadRequestException
4516 * @throws ForbiddenException
4517 * @throws ImagickException
4518 * @throws InternalServerErrorException
4519 * @throws NotFoundException
4520 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4522 function api_account_update_profile_image($type)
4524 if (api_user() === false) {
4525 throw new ForbiddenException();
4528 $profile_id = $_REQUEST['profile_id'] ?? 0;
4530 // error if image data is missing
4531 if (empty($_FILES['image'])) {
4532 throw new BadRequestException("no media data submitted");
4535 // check if specified profile id is valid
4536 if ($profile_id != 0) {
4537 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4538 // error message if specified profile id is not in database
4539 if (!DBA::isResult($profile)) {
4540 throw new BadRequestException("profile_id not available");
4542 $is_default_profile = $profile['is-default'];
4544 $is_default_profile = 1;
4547 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4549 if (!empty($_FILES['image'])) {
4550 $media = $_FILES['image'];
4551 } elseif (!empty($_FILES['media'])) {
4552 $media = $_FILES['media'];
4554 // save new profile image
4555 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4558 if (is_array($media['type'])) {
4559 $filetype = $media['type'][0];
4561 $filetype = $media['type'];
4563 if ($filetype == "image/jpeg") {
4565 } elseif ($filetype == "image/png") {
4568 throw new InternalServerErrorException('Unsupported filetype');
4571 // change specified profile or all profiles to the new resource-id
4572 if ($is_default_profile) {
4573 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4574 Photo::update(['profile' => false], $condition);
4576 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4577 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4578 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4581 Contact::updateSelfFromUserID(api_user(), true);
4583 // Update global directory in background
4584 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4585 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4586 Worker::add(PRIORITY_LOW, "Directory", $url);
4589 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4591 // output for client
4593 return api_account_verify_credentials($type);
4595 // SaveMediaToDatabase failed for some reason
4596 throw new InternalServerErrorException("image upload failed");
4600 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4601 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4602 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4603 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4604 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4605 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4606 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4607 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4608 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4611 * Update user profile
4613 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4615 * @return array|string
4616 * @throws BadRequestException
4617 * @throws ForbiddenException
4618 * @throws ImagickException
4619 * @throws InternalServerErrorException
4620 * @throws UnauthorizedException
4622 function api_account_update_profile($type)
4624 $local_user = api_user();
4625 $api_user = api_get_user(DI::app());
4627 if (!empty($_POST['name'])) {
4628 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4629 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4630 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4631 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4634 if (isset($_POST['description'])) {
4635 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4636 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4637 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4640 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4641 // Update global directory in background
4642 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4643 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4646 return api_account_verify_credentials($type);
4649 /// @TODO move to top of file or somewhere better
4650 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4654 * @param string $acl_string
4658 function check_acl_input($acl_string)
4660 if (empty($acl_string)) {
4664 $contact_not_found = false;
4666 // split <x><y><z> into array of cid's
4667 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4669 // check for each cid if it is available on server
4670 $cid_array = $array[0];
4671 foreach ($cid_array as $cid) {
4672 $cid = str_replace("<", "", $cid);
4673 $cid = str_replace(">", "", $cid);
4674 $condition = ['id' => $cid, 'uid' => api_user()];
4675 $contact_not_found |= !DBA::exists('contact', $condition);
4677 return $contact_not_found;
4681 * @param string $mediatype
4682 * @param array $media
4683 * @param string $type
4684 * @param string $album
4685 * @param string $allow_cid
4686 * @param string $deny_cid
4687 * @param string $allow_gid
4688 * @param string $deny_gid
4689 * @param string $desc
4690 * @param integer $profile
4691 * @param boolean $visibility
4692 * @param string $photo_id
4694 * @throws BadRequestException
4695 * @throws ForbiddenException
4696 * @throws ImagickException
4697 * @throws InternalServerErrorException
4698 * @throws NotFoundException
4699 * @throws UnauthorizedException
4701 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)
4709 if (is_array($media)) {
4710 if (is_array($media['tmp_name'])) {
4711 $src = $media['tmp_name'][0];
4713 $src = $media['tmp_name'];
4715 if (is_array($media['name'])) {
4716 $filename = basename($media['name'][0]);
4718 $filename = basename($media['name']);
4720 if (is_array($media['size'])) {
4721 $filesize = intval($media['size'][0]);
4723 $filesize = intval($media['size']);
4725 if (is_array($media['type'])) {
4726 $filetype = $media['type'][0];
4728 $filetype = $media['type'];
4732 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4735 "File upload src: " . $src . " - filename: " . $filename .
4736 " - size: " . $filesize . " - type: " . $filetype,
4740 // check if there was a php upload error
4741 if ($filesize == 0 && $media['error'] == 1) {
4742 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4744 // check against max upload size within Friendica instance
4745 $maximagesize = DI::config()->get('system', 'maximagesize');
4746 if ($maximagesize && ($filesize > $maximagesize)) {
4747 $formattedBytes = Strings::formatBytes($maximagesize);
4748 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4751 // create Photo instance with the data of the image
4752 $imagedata = @file_get_contents($src);
4753 $Image = new Image($imagedata, $filetype);
4754 if (!$Image->isValid()) {
4755 throw new InternalServerErrorException("unable to process image data");
4758 // check orientation of image
4759 $Image->orient($src);
4762 // check max length of images on server
4763 $max_length = DI::config()->get('system', 'max_image_length');
4765 $max_length = MAX_IMAGE_LENGTH;
4767 if ($max_length > 0) {
4768 $Image->scaleDown($max_length);
4769 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4771 $width = $Image->getWidth();
4772 $height = $Image->getHeight();
4774 // create a new resource-id if not already provided
4775 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4777 if ($mediatype == "photo") {
4778 // upload normal image (scales 0, 1, 2)
4779 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4781 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4783 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4785 if ($width > 640 || $height > 640) {
4786 $Image->scaleDown(640);
4787 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4789 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4793 if ($width > 320 || $height > 320) {
4794 $Image->scaleDown(320);
4795 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4797 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4800 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4801 } elseif ($mediatype == "profileimage") {
4802 // upload profile image (scales 4, 5, 6)
4803 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4805 if ($width > 300 || $height > 300) {
4806 $Image->scaleDown(300);
4807 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4809 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4813 if ($width > 80 || $height > 80) {
4814 $Image->scaleDown(80);
4815 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4817 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4821 if ($width > 48 || $height > 48) {
4822 $Image->scaleDown(48);
4823 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4825 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4828 $Image->__destruct();
4829 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4832 if (isset($r) && $r) {
4833 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4834 if ($photo_id == null && $mediatype == "photo") {
4835 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4837 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4838 return prepare_photo_data($type, false, $resource_id);
4840 throw new InternalServerErrorException("image upload failed");
4846 * @param string $hash
4847 * @param string $allow_cid
4848 * @param string $deny_cid
4849 * @param string $allow_gid
4850 * @param string $deny_gid
4851 * @param string $filetype
4852 * @param boolean $visibility
4853 * @throws InternalServerErrorException
4855 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4857 // get data about the api authenticated user
4858 $uri = Item::newURI(intval(api_user()));
4859 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4862 $arr['guid'] = System::createUUID();
4863 $arr['uid'] = intval(api_user());
4865 $arr['parent-uri'] = $uri;
4866 $arr['type'] = 'photo';
4868 $arr['resource-id'] = $hash;
4869 $arr['contact-id'] = $owner_record['id'];
4870 $arr['owner-name'] = $owner_record['name'];
4871 $arr['owner-link'] = $owner_record['url'];
4872 $arr['owner-avatar'] = $owner_record['thumb'];
4873 $arr['author-name'] = $owner_record['name'];
4874 $arr['author-link'] = $owner_record['url'];
4875 $arr['author-avatar'] = $owner_record['thumb'];
4877 $arr['allow_cid'] = $allow_cid;
4878 $arr['allow_gid'] = $allow_gid;
4879 $arr['deny_cid'] = $deny_cid;
4880 $arr['deny_gid'] = $deny_gid;
4881 $arr['visible'] = $visibility;
4885 'image/jpeg' => 'jpg',
4886 'image/png' => 'png',
4887 'image/gif' => 'gif'
4890 // adds link to the thumbnail scale photo
4891 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4892 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4895 // do the magic for storing the item in the database and trigger the federation to other contacts
4901 * @param string $type
4903 * @param string $photo_id
4906 * @throws BadRequestException
4907 * @throws ForbiddenException
4908 * @throws ImagickException
4909 * @throws InternalServerErrorException
4910 * @throws NotFoundException
4911 * @throws UnauthorizedException
4913 function prepare_photo_data($type, $scale, $photo_id)
4916 $user_info = api_get_user($a);
4918 if ($user_info === false) {
4919 throw new ForbiddenException();
4922 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4923 $data_sql = ($scale === false ? "" : "data, ");
4925 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4926 // clients needs to convert this in their way for further processing
4928 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4929 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4930 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4931 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4932 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4933 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4935 intval(local_user()),
4936 DBA::escape($photo_id),
4941 'image/jpeg' => 'jpg',
4942 'image/png' => 'png',
4943 'image/gif' => 'gif'
4946 // prepare output data for photo
4947 if (DBA::isResult($r)) {
4948 $data = ['photo' => $r[0]];
4949 $data['photo']['id'] = $data['photo']['resource-id'];
4950 if ($scale !== false) {
4951 $data['photo']['data'] = base64_encode($data['photo']['data']);
4953 unset($data['photo']['datasize']); //needed only with scale param
4955 if ($type == "xml") {
4956 $data['photo']['links'] = [];
4957 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4958 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4960 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4963 $data['photo']['link'] = [];
4964 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4966 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4967 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4971 unset($data['photo']['resource-id']);
4972 unset($data['photo']['minscale']);
4973 unset($data['photo']['maxscale']);
4975 throw new NotFoundException();
4978 // retrieve item element for getting activities (like, dislike etc.) related to photo
4979 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4980 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4981 if (!DBA::isResult($item)) {
4982 throw new NotFoundException('Photo-related item not found.');
4985 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4987 // retrieve comments on photo
4988 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4989 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4991 $statuses = Item::selectForUser(api_user(), [], $condition);
4993 // prepare output of comments
4994 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4996 if ($type == "xml") {
4998 foreach ($commentData as $comment) {
4999 $comments[$k++ . ":comment"] = $comment;
5002 foreach ($commentData as $comment) {
5003 $comments[] = $comment;
5006 $data['photo']['friendica_comments'] = $comments;
5008 // include info if rights on photo and rights on item are mismatching
5009 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5010 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5011 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5012 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5013 $data['photo']['rights_mismatch'] = $rights_mismatch;
5020 * Similar as /mod/redir.php
5021 * redirect to 'url' after dfrn auth
5023 * Why this when there is mod/redir.php already?
5024 * This use api_user() and api_login()
5027 * c_url: url of remote contact to auth to
5028 * url: string, url to redirect after auth
5030 function api_friendica_remoteauth()
5032 $url = $_GET['url'] ?? '';
5033 $c_url = $_GET['c_url'] ?? '';
5035 if ($url === '' || $c_url === '') {
5036 throw new BadRequestException("Wrong parameters.");
5039 $c_url = Strings::normaliseLink($c_url);
5043 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5044 if (!DBA::isResult($contact)) {
5045 throw new BadRequestException("Unknown contact");
5048 $cid = $contact['id'];
5050 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5052 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5053 System::externalRedirect($url ?: $c_url);
5056 if ($contact['duplex'] && $contact['issued-id']) {
5057 $orig_id = $contact['issued-id'];
5058 $dfrn_id = '1:' . $orig_id;
5060 if ($contact['duplex'] && $contact['dfrn-id']) {
5061 $orig_id = $contact['dfrn-id'];
5062 $dfrn_id = '0:' . $orig_id;
5065 $sec = Strings::getRandomHex();
5067 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5068 'sec' => $sec, 'expire' => time() + 45];
5069 DBA::insert('profile_check', $fields);
5071 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5072 $dest = ($url ? '&destination_url=' . $url : '');
5074 System::externalRedirect(
5075 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5076 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5077 . '&type=profile&sec=' . $sec . $dest
5080 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5083 * Return an item with announcer data if it had been announced
5085 * @param array $item Item array
5086 * @return array Item array with announce data
5088 function api_get_announce($item)
5090 // Quit if the item already has got a different owner and author
5091 if ($item['owner-id'] != $item['author-id']) {
5095 // Don't change original or Diaspora posts
5096 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5100 // Quit if we do now the original author and it had been a post from a native network
5101 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5105 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5106 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
5107 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5108 if (!DBA::isResult($announce)) {
5112 return array_merge($item, $announce);
5116 * Return the item shared, if the item contains only the [share] tag
5118 * @param array $item Sharer item
5119 * @return array|false Shared item or false if not a reshare
5120 * @throws ImagickException
5121 * @throws InternalServerErrorException
5123 function api_share_as_retweet(&$item)
5125 $body = trim($item["body"]);
5127 if (Diaspora::isReshare($body, false) === false) {
5128 if ($item['author-id'] == $item['owner-id']) {
5131 // Reshares from OStatus, ActivityPub and Twitter
5132 $reshared_item = $item;
5133 $reshared_item['owner-id'] = $reshared_item['author-id'];
5134 $reshared_item['owner-link'] = $reshared_item['author-link'];
5135 $reshared_item['owner-name'] = $reshared_item['author-name'];
5136 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5137 return $reshared_item;
5141 $reshared = Item::getShareArray($item);
5142 if (empty($reshared)) {
5146 $reshared_item = $item;
5148 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5152 if (!empty($reshared['comment'])) {
5153 $item['body'] = $reshared['comment'];
5156 $reshared_item["share-pre-body"] = $reshared['comment'];
5157 $reshared_item["body"] = $reshared['shared'];
5158 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5159 $reshared_item["author-name"] = $reshared['author'];
5160 $reshared_item["author-link"] = $reshared['profile'];
5161 $reshared_item["author-avatar"] = $reshared['avatar'];
5162 $reshared_item["plink"] = $reshared['link'] ?? '';
5163 $reshared_item["created"] = $reshared['posted'];
5164 $reshared_item["edited"] = $reshared['posted'];
5166 // Try to fetch the original item
5167 if (!empty($reshared['guid'])) {
5168 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5169 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5170 $condition = ['id' => $original_id];
5175 if (!empty($condition)) {
5176 $original_item = Item::selectFirst([], $condition);
5177 if (DBA::isResult($original_item)) {
5178 $reshared_item = array_merge($reshared_item, $original_item);
5182 return $reshared_item;
5187 * @param array $item
5192 function api_in_reply_to($item)
5196 $in_reply_to['status_id'] = null;
5197 $in_reply_to['user_id'] = null;
5198 $in_reply_to['status_id_str'] = null;
5199 $in_reply_to['user_id_str'] = null;
5200 $in_reply_to['screen_name'] = null;
5202 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5203 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5204 if (DBA::isResult($parent)) {
5205 $in_reply_to['status_id'] = intval($parent['id']);
5207 $in_reply_to['status_id'] = intval($item['parent']);
5210 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5212 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5213 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5215 if (DBA::isResult($parent)) {
5216 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5217 $in_reply_to['user_id'] = intval($parent['author-id']);
5218 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5221 // There seems to be situation, where both fields are identical:
5222 // https://github.com/friendica/friendica/issues/1010
5223 // This is a bugfix for that.
5224 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5225 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']]);
5226 $in_reply_to['status_id'] = null;
5227 $in_reply_to['user_id'] = null;
5228 $in_reply_to['status_id_str'] = null;
5229 $in_reply_to['user_id_str'] = null;
5230 $in_reply_to['screen_name'] = null;
5234 return $in_reply_to;
5239 * @param string $text
5242 * @throws InternalServerErrorException
5244 function api_clean_plain_items($text)
5246 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5248 $text = BBCode::cleanPictureLinks($text);
5249 $URLSearchString = "^\[\]";
5251 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5253 if ($include_entities == "true") {
5254 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5257 // Simplify "attachment" element
5258 $text = BBCode::removeAttachment($text);
5265 * @param array $contacts
5269 function api_best_nickname(&$contacts)
5273 if (count($contacts) == 0) {
5277 foreach ($contacts as $contact) {
5278 if ($contact["network"] == "") {
5279 $contact["network"] = "dfrn";
5280 $best_contact = [$contact];
5284 if (sizeof($best_contact) == 0) {
5285 foreach ($contacts as $contact) {
5286 if ($contact["network"] == "dfrn") {
5287 $best_contact = [$contact];
5292 if (sizeof($best_contact) == 0) {
5293 foreach ($contacts as $contact) {
5294 if ($contact["network"] == "dspr") {
5295 $best_contact = [$contact];
5300 if (sizeof($best_contact) == 0) {
5301 foreach ($contacts as $contact) {
5302 if ($contact["network"] == "stat") {
5303 $best_contact = [$contact];
5308 if (sizeof($best_contact) == 0) {
5309 foreach ($contacts as $contact) {
5310 if ($contact["network"] == "pump") {
5311 $best_contact = [$contact];
5316 if (sizeof($best_contact) == 0) {
5317 foreach ($contacts as $contact) {
5318 if ($contact["network"] == "twit") {
5319 $best_contact = [$contact];
5324 if (sizeof($best_contact) == 1) {
5325 $contacts = $best_contact;
5327 $contacts = [$contacts[0]];
5332 * Return all or a specified group of the user with the containing contacts.
5334 * @param string $type Return type (atom, rss, xml, json)
5336 * @return array|string
5337 * @throws BadRequestException
5338 * @throws ForbiddenException
5339 * @throws ImagickException
5340 * @throws InternalServerErrorException
5341 * @throws UnauthorizedException
5343 function api_friendica_group_show($type)
5347 if (api_user() === false) {
5348 throw new ForbiddenException();
5352 $user_info = api_get_user($a);
5353 $gid = $_REQUEST['gid'] ?? 0;
5354 $uid = $user_info['uid'];
5356 // get data of the specified group id or all groups if not specified
5359 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5363 // error message if specified gid is not in database
5364 if (!DBA::isResult($r)) {
5365 throw new BadRequestException("gid not available");
5369 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5374 // loop through all groups and retrieve all members for adding data in the user array
5376 foreach ($r as $rr) {
5377 $members = Contact::getByGroupId($rr['id']);
5380 if ($type == "xml") {
5381 $user_element = "users";
5383 foreach ($members as $member) {
5384 $user = api_get_user($a, $member['nurl']);
5385 $users[$k++.":user"] = $user;
5388 $user_element = "user";
5389 foreach ($members as $member) {
5390 $user = api_get_user($a, $member['nurl']);
5394 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5396 return api_format_data("groups", $type, ['group' => $grps]);
5398 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5402 * Delete the specified group of the user.
5404 * @param string $type Return type (atom, rss, xml, json)
5406 * @return array|string
5407 * @throws BadRequestException
5408 * @throws ForbiddenException
5409 * @throws ImagickException
5410 * @throws InternalServerErrorException
5411 * @throws UnauthorizedException
5413 function api_friendica_group_delete($type)
5417 if (api_user() === false) {
5418 throw new ForbiddenException();
5422 $user_info = api_get_user($a);
5423 $gid = $_REQUEST['gid'] ?? 0;
5424 $name = $_REQUEST['name'] ?? '';
5425 $uid = $user_info['uid'];
5427 // error if no gid specified
5428 if ($gid == 0 || $name == "") {
5429 throw new BadRequestException('gid or name not specified');
5432 // get data of the specified group id
5434 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5438 // error message if specified gid is not in database
5439 if (!DBA::isResult($r)) {
5440 throw new BadRequestException('gid not available');
5443 // get data of the specified group id and group name
5445 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5450 // error message if specified gid is not in database
5451 if (!DBA::isResult($rname)) {
5452 throw new BadRequestException('wrong group name');
5456 $ret = Group::removeByName($uid, $name);
5459 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5460 return api_format_data("group_delete", $type, ['result' => $success]);
5462 throw new BadRequestException('other API error');
5465 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5470 * @param string $type Return type (atom, rss, xml, json)
5472 * @return array|string
5473 * @throws BadRequestException
5474 * @throws ForbiddenException
5475 * @throws ImagickException
5476 * @throws InternalServerErrorException
5477 * @throws UnauthorizedException
5478 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5480 function api_lists_destroy($type)
5484 if (api_user() === false) {
5485 throw new ForbiddenException();
5489 $user_info = api_get_user($a);
5490 $gid = $_REQUEST['list_id'] ?? 0;
5491 $uid = $user_info['uid'];
5493 // error if no gid specified
5495 throw new BadRequestException('gid not specified');
5498 // get data of the specified group id
5499 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5500 // error message if specified gid is not in database
5502 throw new BadRequestException('gid not available');
5505 if (Group::remove($gid)) {
5507 'name' => $group['name'],
5508 'id' => intval($gid),
5509 'id_str' => (string) $gid,
5510 'user' => $user_info
5513 return api_format_data("lists", $type, ['lists' => $list]);
5516 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5519 * Add a new group to the database.
5521 * @param string $name Group name
5522 * @param int $uid User ID
5523 * @param array $users List of users to add to the group
5526 * @throws BadRequestException
5528 function group_create($name, $uid, $users = [])
5530 // error if no name specified
5532 throw new BadRequestException('group name not specified');
5535 // get data of the specified group name
5537 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5541 // error message if specified group name already exists
5542 if (DBA::isResult($rname)) {
5543 throw new BadRequestException('group name already exists');
5546 // check if specified group name is a deleted group
5548 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5552 // error message if specified group name already exists
5553 if (DBA::isResult($rname)) {
5554 $reactivate_group = true;
5558 $ret = Group::create($uid, $name);
5560 $gid = Group::getIdByName($uid, $name);
5562 throw new BadRequestException('other API error');
5566 $erroraddinguser = false;
5568 foreach ($users as $user) {
5569 $cid = $user['cid'];
5570 // check if user really exists as contact
5572 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5576 if (count($contact)) {
5577 Group::addMember($gid, $cid);
5579 $erroraddinguser = true;
5580 $errorusers[] = $cid;
5584 // return success message incl. missing users in array
5585 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5587 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5591 * Create the specified group with the posted array of contacts.
5593 * @param string $type Return type (atom, rss, xml, json)
5595 * @return array|string
5596 * @throws BadRequestException
5597 * @throws ForbiddenException
5598 * @throws ImagickException
5599 * @throws InternalServerErrorException
5600 * @throws UnauthorizedException
5602 function api_friendica_group_create($type)
5606 if (api_user() === false) {
5607 throw new ForbiddenException();
5611 $user_info = api_get_user($a);
5612 $name = $_REQUEST['name'] ?? '';
5613 $uid = $user_info['uid'];
5614 $json = json_decode($_POST['json'], true);
5615 $users = $json['user'];
5617 $success = group_create($name, $uid, $users);
5619 return api_format_data("group_create", $type, ['result' => $success]);
5621 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5624 * Create a new group.
5626 * @param string $type Return type (atom, rss, xml, json)
5628 * @return array|string
5629 * @throws BadRequestException
5630 * @throws ForbiddenException
5631 * @throws ImagickException
5632 * @throws InternalServerErrorException
5633 * @throws UnauthorizedException
5634 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5636 function api_lists_create($type)
5640 if (api_user() === false) {
5641 throw new ForbiddenException();
5645 $user_info = api_get_user($a);
5646 $name = $_REQUEST['name'] ?? '';
5647 $uid = $user_info['uid'];
5649 $success = group_create($name, $uid);
5650 if ($success['success']) {
5652 'name' => $success['name'],
5653 'id' => intval($success['gid']),
5654 'id_str' => (string) $success['gid'],
5655 'user' => $user_info
5658 return api_format_data("lists", $type, ['lists'=>$grp]);
5661 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5664 * Update the specified group with the posted array of contacts.
5666 * @param string $type Return type (atom, rss, xml, json)
5668 * @return array|string
5669 * @throws BadRequestException
5670 * @throws ForbiddenException
5671 * @throws ImagickException
5672 * @throws InternalServerErrorException
5673 * @throws UnauthorizedException
5675 function api_friendica_group_update($type)
5679 if (api_user() === false) {
5680 throw new ForbiddenException();
5684 $user_info = api_get_user($a);
5685 $uid = $user_info['uid'];
5686 $gid = $_REQUEST['gid'] ?? 0;
5687 $name = $_REQUEST['name'] ?? '';
5688 $json = json_decode($_POST['json'], true);
5689 $users = $json['user'];
5691 // error if no name specified
5693 throw new BadRequestException('group name not specified');
5696 // error if no gid specified
5698 throw new BadRequestException('gid not specified');
5702 $members = Contact::getByGroupId($gid);
5703 foreach ($members as $member) {
5704 $cid = $member['id'];
5705 foreach ($users as $user) {
5706 $found = ($user['cid'] == $cid ? true : false);
5708 if (!isset($found) || !$found) {
5709 Group::removeMemberByName($uid, $name, $cid);
5714 $erroraddinguser = false;
5716 foreach ($users as $user) {
5717 $cid = $user['cid'];
5718 // check if user really exists as contact
5720 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5725 if (count($contact)) {
5726 Group::addMember($gid, $cid);
5728 $erroraddinguser = true;
5729 $errorusers[] = $cid;
5733 // return success message incl. missing users in array
5734 $status = ($erroraddinguser ? "missing user" : "ok");
5735 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5736 return api_format_data("group_update", $type, ['result' => $success]);
5739 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5742 * Update information about a group.
5744 * @param string $type Return type (atom, rss, xml, json)
5746 * @return array|string
5747 * @throws BadRequestException
5748 * @throws ForbiddenException
5749 * @throws ImagickException
5750 * @throws InternalServerErrorException
5751 * @throws UnauthorizedException
5752 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5754 function api_lists_update($type)
5758 if (api_user() === false) {
5759 throw new ForbiddenException();
5763 $user_info = api_get_user($a);
5764 $gid = $_REQUEST['list_id'] ?? 0;
5765 $name = $_REQUEST['name'] ?? '';
5766 $uid = $user_info['uid'];
5768 // error if no gid specified
5770 throw new BadRequestException('gid not specified');
5773 // get data of the specified group id
5774 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5775 // error message if specified gid is not in database
5777 throw new BadRequestException('gid not available');
5780 if (Group::update($gid, $name)) {
5783 'id' => intval($gid),
5784 'id_str' => (string) $gid,
5785 'user' => $user_info
5788 return api_format_data("lists", $type, ['lists' => $list]);
5792 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5796 * @param string $type Return type (atom, rss, xml, json)
5798 * @return array|string
5799 * @throws BadRequestException
5800 * @throws ForbiddenException
5801 * @throws ImagickException
5802 * @throws InternalServerErrorException
5804 function api_friendica_activity($type)
5808 if (api_user() === false) {
5809 throw new ForbiddenException();
5811 $verb = strtolower($a->argv[3]);
5812 $verb = preg_replace("|\..*$|", "", $verb);
5814 $id = $_REQUEST['id'] ?? 0;
5816 $res = Item::performActivity($id, $verb);
5819 if ($type == "xml") {
5824 return api_format_data('ok', $type, ['ok' => $ok]);
5826 throw new BadRequestException('Error adding activity');
5830 /// @TODO move to top of file or somewhere better
5831 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5832 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5833 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5834 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5835 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5836 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5837 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5838 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5839 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5840 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5843 * Returns notifications
5845 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5847 * @return string|array
5848 * @throws ForbiddenException
5849 * @throws BadRequestException
5852 function api_friendica_notification($type)
5856 if (api_user() === false) {
5857 throw new ForbiddenException();
5860 throw new BadRequestException("Invalid argument count");
5863 $notifications = DI::notification()->getApiList(local_user());
5865 if ($type == "xml") {
5867 if (!empty($notifications)) {
5868 foreach ($notifications as $notification) {
5869 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5873 $result = $xmlnotes;
5874 } elseif (count($notifications) > 0) {
5875 $result = $notifications->getArrayCopy();
5880 return api_format_data("notes", $type, ['note' => $result]);
5884 * Set notification as seen and returns associated item (if possible)
5886 * POST request with 'id' param as notification id
5888 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5889 * @return string|array
5890 * @throws BadRequestException
5891 * @throws ForbiddenException
5892 * @throws ImagickException
5893 * @throws InternalServerErrorException
5894 * @throws UnauthorizedException
5896 function api_friendica_notification_seen($type)
5899 $user_info = api_get_user($a);
5901 if (api_user() === false || $user_info === false) {
5902 throw new ForbiddenException();
5904 if ($a->argc !== 4) {
5905 throw new BadRequestException("Invalid argument count");
5908 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5911 $notify = DI::notify()->getByID($id, api_user());
5912 DI::notify()->setSeen(true, $notify);
5914 if ($notify->otype === Notify\ObjectType::ITEM) {
5915 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5916 if (DBA::isResult($item)) {
5917 // we found the item, return it to the user
5918 $ret = api_format_items([$item], $user_info, false, $type);
5919 $data = ['status' => $ret];
5920 return api_format_data("status", $type, $data);
5922 // the item can't be found, but we set the notification as seen, so we count this as a success
5924 return api_format_data('result', $type, ['result' => "success"]);
5925 } catch (NotFoundException $e) {
5926 throw new BadRequestException('Invalid argument', $e);
5927 } catch (Exception $e) {
5928 throw new InternalServerErrorException('Internal Server exception', $e);
5932 /// @TODO move to top of file or somewhere better
5933 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5934 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5937 * update a direct_message to seen state
5939 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5940 * @return string|array (success result=ok, error result=error with error message)
5941 * @throws BadRequestException
5942 * @throws ForbiddenException
5943 * @throws ImagickException
5944 * @throws InternalServerErrorException
5945 * @throws UnauthorizedException
5947 function api_friendica_direct_messages_setseen($type)
5950 if (api_user() === false) {
5951 throw new ForbiddenException();
5955 $user_info = api_get_user($a);
5956 $uid = $user_info['uid'];
5957 $id = $_REQUEST['id'] ?? 0;
5959 // return error if id is zero
5961 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5962 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5965 // error message if specified id is not in database
5966 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5967 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5968 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5971 // update seen indicator
5972 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5976 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5977 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5979 $answer = ['result' => 'error', 'message' => 'unknown error'];
5980 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5984 /// @TODO move to top of file or somewhere better
5985 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5988 * search for direct_messages containing a searchstring through api
5990 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5991 * @param string $box
5992 * @return string|array (success: success=true if found and search_result contains found messages,
5993 * success=false if nothing was found, search_result='nothing found',
5994 * error: result=error with error message)
5995 * @throws BadRequestException
5996 * @throws ForbiddenException
5997 * @throws ImagickException
5998 * @throws InternalServerErrorException
5999 * @throws UnauthorizedException
6001 function api_friendica_direct_messages_search($type, $box = "")
6005 if (api_user() === false) {
6006 throw new ForbiddenException();
6010 $user_info = api_get_user($a);
6011 $searchstring = $_REQUEST['searchstring'] ?? '';
6012 $uid = $user_info['uid'];
6014 // error if no searchstring specified
6015 if ($searchstring == "") {
6016 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6017 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6020 // get data for the specified searchstring
6022 "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",
6024 DBA::escape('%'.$searchstring.'%')
6027 $profile_url = $user_info["url"];
6029 // message if nothing was found
6030 if (!DBA::isResult($r)) {
6031 $success = ['success' => false, 'search_results' => 'problem with query'];
6032 } elseif (count($r) == 0) {
6033 $success = ['success' => false, 'search_results' => 'nothing found'];
6036 foreach ($r as $item) {
6037 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6038 $recipient = $user_info;
6039 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6040 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6041 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6042 $sender = $user_info;
6045 if (isset($recipient) && isset($sender)) {
6046 $ret[] = api_format_messages($item, $recipient, $sender);
6049 $success = ['success' => true, 'search_results' => $ret];
6052 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6055 /// @TODO move to top of file or somewhere better
6056 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6059 * Returns a list of saved searches.
6061 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6063 * @param string $type Return format: json or xml
6065 * @return string|array
6068 function api_saved_searches_list($type)
6070 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6073 while ($term = DBA::fetch($terms)) {
6075 'created_at' => api_date(time()),
6076 'id' => intval($term['id']),
6077 'id_str' => $term['id'],
6078 'name' => $term['term'],
6080 'query' => $term['term']
6086 return api_format_data("terms", $type, ['terms' => $result]);
6089 /// @TODO move to top of file or somewhere better
6090 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6093 * Number of comments
6095 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6097 * @param object $data [Status, Status]
6101 function bindComments(&$data)
6103 if (count($data) == 0) {
6109 foreach ($data as $item) {
6110 $ids[] = $item['id'];
6113 $idStr = DBA::escape(implode(', ', $ids));
6114 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6115 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6116 $itemsData = DBA::toArray($items);
6118 foreach ($itemsData as $item) {
6119 $comments[$item['parent']] = $item['comments'];
6122 foreach ($data as $idx => $item) {
6124 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6129 @TODO Maybe open to implement?
6131 [pagename] => api/1.1/statuses/lookup.json
6132 [id] => 605138389168451584
6133 [include_cards] => true
6134 [cards_platform] => Android-12
6135 [include_entities] => true
6136 [include_my_retweet] => 1
6138 [include_reply_count] => true
6139 [include_descendent_reply_count] => true
6143 Not implemented by now:
6144 statuses/retweets_of_me
6149 account/update_location
6150 account/update_profile_background_image
6153 friendica/profile/update
6154 friendica/profile/create
6155 friendica/profile/delete
6157 Not implemented in status.net:
6158 statuses/retweeted_to_me
6159 statuses/retweeted_by_me
6160 direct_messages/destroy
6162 account/update_delivery_device
6163 notifications/follow