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\Network\FKOAuth1;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\NotImplementedException;
55 use Friendica\Network\HTTPException\TooManyRequestsException;
56 use Friendica\Network\HTTPException\UnauthorizedException;
57 use Friendica\Object\Image;
58 use Friendica\Protocol\Activity;
59 use Friendica\Protocol\Diaspora;
60 use Friendica\Util\DateTimeFormat;
61 use Friendica\Util\Images;
62 use Friendica\Util\Network;
63 use Friendica\Util\Proxy as ProxyUtils;
64 use Friendica\Util\Strings;
65 use Friendica\Util\XML;
67 require_once __DIR__ . '/../mod/share.php';
68 require_once __DIR__ . '/../mod/item.php';
69 require_once __DIR__ . '/../mod/wall_upload.php';
71 define('API_METHOD_ANY', '*');
72 define('API_METHOD_GET', 'GET');
73 define('API_METHOD_POST', 'POST,PUT');
74 define('API_METHOD_DELETE', 'POST,DELETE');
76 define('API_LOG_PREFIX', 'API {action} - ');
84 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
85 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
86 * into a page, and visitors will post something without noticing it).
90 if (!empty($_SESSION['allow_api'])) {
98 * Get source name from API client
100 * Clients can send 'source' parameter to be show in post metadata
101 * as "sent via <source>".
102 * Some clients doesn't send a source param, we support ones we know
103 * (only Twidere, atm)
106 * Client source name, default to "api" if unset/unknown
109 function api_source()
111 if (requestdata('source')) {
112 return requestdata('source');
115 // Support for known clients that doesn't send a source name
116 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
117 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
121 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
123 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
130 * Format date for API
132 * @param string $str Source date, as UTC
133 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
136 function api_date($str)
138 // Wed May 23 06:01:13 +0000 2007
139 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
143 * Register a function to be the endpoint for defined API path.
145 * @param string $path API URL path, relative to DI::baseUrl()
146 * @param string $func Function name to call on path request
147 * @param bool $auth API need logged user
148 * @param string $method HTTP method reqiured to call this endpoint.
149 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
150 * Default to API_METHOD_ANY
152 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
162 // Workaround for hotot
163 $path = str_replace("api/", "api/1.1/", $path);
173 * Log in user via OAuth1 or Simple HTTP Auth.
174 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
177 * @throws ForbiddenException
178 * @throws InternalServerErrorException
179 * @throws UnauthorizedException
180 * @hook 'authenticate'
182 * 'username' => username from login form
183 * 'password' => password from login form
184 * 'authenticated' => return status,
185 * 'user_record' => return authenticated user record
187 function api_login(App $a)
189 // workaround for HTTP-auth in CGI mode
190 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
191 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
192 if (strlen($userpass)) {
193 list($name, $password) = explode(':', $userpass);
194 $_SERVER['PHP_AUTH_USER'] = $name;
195 $_SERVER['PHP_AUTH_PW'] = $password;
199 if (empty($_SERVER['PHP_AUTH_USER'])) {
200 // Try OAuth when no user is provided
201 $oauth1 = new FKOAuth1();
204 $request = OAuthRequest::from_request();
205 list($consumer, $token) = $oauth1->verify_request($request);
206 if (!is_null($token)) {
207 $oauth1->loginUser($token->uid);
208 Session::set('allow_api', true);
211 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
212 var_dump($consumer, $token);
214 } catch (Exception $e) {
215 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
218 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
219 header('WWW-Authenticate: Basic realm="Friendica"');
220 throw new UnauthorizedException("This API requires login");
223 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
224 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
226 // allow "user@server" login (but ignore 'server' part)
227 $at = strstr($user, "@", true);
232 // next code from mod/auth.php. needs better solution
236 'username' => trim($user),
237 'password' => trim($password),
238 'authenticated' => 0,
239 'user_record' => null,
243 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
244 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
245 * and later addons should not interfere with an earlier one that succeeded.
247 Hook::callAll('authenticate', $addon_auth);
249 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
250 $record = $addon_auth['user_record'];
252 $user_id = User::authenticate(trim($user), trim($password), true);
253 if ($user_id !== false) {
254 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
258 if (!DBA::isResult($record)) {
259 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
260 header('WWW-Authenticate: Basic realm="Friendica"');
261 //header('HTTP/1.0 401 Unauthorized');
262 //die('This api requires login');
263 throw new UnauthorizedException("This API requires login");
266 DI::auth()->setForUser($a, $record);
268 $_SESSION["allow_api"] = true;
270 Hook::callAll('logged_in', $a->user);
274 * Check HTTP method of called API
276 * API endpoints can define which HTTP method to accept when called.
277 * This function check the current HTTP method agains endpoint
280 * @param string $method Required methods, uppercase, separated by comma
283 function api_check_method($method)
285 if ($method == "*") {
288 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
292 * Main API entry point
294 * Authenticate user, call registered API function, set HTTP headers
297 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
298 * @return string|array API call result
301 function api_call(App $a, App\Arguments $args = null)
303 global $API, $called_api;
310 if (strpos($args->getQueryString(), ".xml") > 0) {
313 if (strpos($args->getQueryString(), ".json") > 0) {
316 if (strpos($args->getQueryString(), ".rss") > 0) {
319 if (strpos($args->getQueryString(), ".atom") > 0) {
324 foreach ($API as $p => $info) {
325 if (strpos($args->getQueryString(), $p) === 0) {
326 if (!api_check_method($info['method'])) {
327 throw new MethodNotAllowedException();
330 $called_api = explode("/", $p);
332 if (!empty($info['auth']) && api_user() === false) {
336 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
337 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
339 $stamp = microtime(true);
340 $return = call_user_func($info['func'], $type);
341 $duration = floatval(microtime(true) - $stamp);
343 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
345 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
347 if (false === $return) {
349 * api function returned false withour throw an
350 * exception. This should not happend, throw a 500
352 throw new InternalServerErrorException();
357 header("Content-Type: text/xml");
360 header("Content-Type: application/json");
361 if (!empty($return)) {
362 $json = json_encode(end($return));
363 if (!empty($_GET['callback'])) {
364 $json = $_GET['callback'] . "(" . $json . ")";
370 header("Content-Type: application/rss+xml");
371 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
374 header("Content-Type: application/atom+xml");
375 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
382 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
383 throw new NotImplementedException();
384 } catch (HTTPException $e) {
385 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
386 return api_error($type, $e, $args);
391 * Format API error string
393 * @param string $type Return type (xml, json, rss, as)
394 * @param object $e HTTPException Error object
395 * @param App\Arguments $args The App arguments
396 * @return string|array error message formatted as $type
398 function api_error($type, $e, App\Arguments $args)
400 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
401 /// @TODO: https://dev.twitter.com/overview/api/response-codes
403 $error = ["error" => $error,
404 "code" => $e->getCode() . " " . $e->httpdesc,
405 "request" => $args->getQueryString()];
407 $return = api_format_data('status', $type, ['status' => $error]);
411 header("Content-Type: text/xml");
414 header("Content-Type: application/json");
415 $return = json_encode($return);
418 header("Content-Type: application/rss+xml");
421 header("Content-Type: application/atom+xml");
429 * Set values for RSS template
432 * @param array $arr Array to be passed to template
433 * @param array $user_info User info
435 * @throws BadRequestException
436 * @throws ImagickException
437 * @throws InternalServerErrorException
438 * @throws UnauthorizedException
439 * @todo find proper type-hints
441 function api_rss_extra(App $a, $arr, $user_info)
443 if (is_null($user_info)) {
444 $user_info = api_get_user($a);
447 $arr['$user'] = $user_info;
449 'alternate' => $user_info['url'],
450 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
451 'base' => DI::baseUrl(),
452 'updated' => api_date(null),
453 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
454 'language' => $user_info['lang'],
455 'logo' => DI::baseUrl() . "/images/friendica-32.png",
463 * Unique contact to contact url.
465 * @param int $id Contact id
466 * @return bool|string
467 * Contact url or False if contact id is unknown
470 function api_unique_id_to_nurl($id)
472 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
474 if (DBA::isResult($r)) {
482 * Get user info array.
485 * @param int|string $contact_id Contact ID or URL
487 * @throws BadRequestException
488 * @throws ImagickException
489 * @throws InternalServerErrorException
490 * @throws UnauthorizedException
492 function api_get_user(App $a, $contact_id = null)
500 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
502 // Searching for contact URL
503 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
504 $user = DBA::escape(Strings::normaliseLink($contact_id));
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 // Searching for contact id with uid = 0
513 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
514 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
517 throw new BadRequestException("User ID ".$contact_id." not found.");
521 $extra_query = "AND `contact`.`nurl` = '%s' ";
522 if (api_user() !== false) {
523 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && !empty($_GET['user_id'])) {
528 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
531 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
540 if (is_null($user) && !empty($_GET['screen_name'])) {
541 $user = DBA::escape($_GET['screen_name']);
542 $extra_query = "AND `contact`.`nick` = '%s' ";
543 if (api_user() !== false) {
544 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
548 if (is_null($user) && !empty($_GET['profileurl'])) {
549 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
550 $extra_query = "AND `contact`.`nurl` = '%s' ";
551 if (api_user() !== false) {
552 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
556 // $called_api is the API path exploded on / and is expected to have at least 2 elements
557 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
558 $argid = count($called_api);
559 if (!empty($a->argv[$argid])) {
560 $data = explode(".", $a->argv[$argid]);
561 if (count($data) > 1) {
562 list($user, $null) = $data;
565 if (is_numeric($user)) {
566 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
570 $extra_query = "AND `contact`.`nurl` = '%s' ";
571 if (api_user() !== false) {
572 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
576 $user = DBA::escape($user);
577 $extra_query = "AND `contact`.`nick` = '%s' ";
578 if (api_user() !== false) {
579 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
584 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
587 if (api_user() === false) {
591 $user = $_SESSION['uid'];
592 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
596 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
600 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
606 // Selecting the id by priority, friendica first
607 if (is_array($uinfo)) {
608 api_best_nickname($uinfo);
611 // if the contact wasn't found, fetch it from the contacts with uid = 0
612 if (!DBA::isResult($uinfo)) {
614 throw new BadRequestException("User not found.");
617 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
619 if (DBA::isResult($contact)) {
621 'id' => $contact["id"],
622 'id_str' => (string) $contact["id"],
623 'name' => $contact["name"],
624 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
625 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
626 'description' => BBCode::toPlaintext($contact["about"]),
627 'profile_image_url' => $contact["micro"],
628 'profile_image_url_https' => $contact["micro"],
629 'profile_image_url_profile_size' => $contact["thumb"],
630 'profile_image_url_large' => $contact["photo"],
631 'url' => $contact["url"],
632 'protected' => false,
633 'followers_count' => 0,
634 'friends_count' => 0,
636 'created_at' => api_date($contact["created"]),
637 'favourites_count' => 0,
639 'time_zone' => 'UTC',
640 'geo_enabled' => false,
642 'statuses_count' => 0,
644 'contributors_enabled' => false,
645 'is_translator' => false,
646 'is_translation_enabled' => false,
647 'following' => false,
648 'follow_request_sent' => false,
649 'statusnet_blocking' => false,
650 'notifications' => false,
651 'statusnet_profile_url' => $contact["url"],
653 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
654 'pid' => Contact::getIdForURL($contact["url"], 0, true),
656 'network' => $contact["network"],
661 throw new BadRequestException("User ".$url." not found.");
665 if ($uinfo[0]['self']) {
666 if ($uinfo[0]['network'] == "") {
667 $uinfo[0]['network'] = Protocol::DFRN;
670 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
671 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
678 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
680 if (!empty($profile['about'])) {
681 $description = $profile['about'];
683 $description = $uinfo[0]["about"];
686 if (!empty($usr['default-location'])) {
687 $location = $usr['default-location'];
688 } elseif (!empty($uinfo[0]["location"])) {
689 $location = $uinfo[0]["location"];
691 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
695 'id' => intval($pcontact_id),
696 'id_str' => (string) intval($pcontact_id),
697 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
698 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
699 'location' => $location,
700 'description' => BBCode::toPlaintext($description),
701 'profile_image_url' => $uinfo[0]['micro'],
702 'profile_image_url_https' => $uinfo[0]['micro'],
703 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
704 'profile_image_url_large' => $uinfo[0]["photo"],
705 'url' => $uinfo[0]['url'],
706 'protected' => false,
707 'followers_count' => intval($countfollowers),
708 'friends_count' => intval($countfriends),
710 'created_at' => api_date($uinfo[0]['created']),
711 'favourites_count' => intval($starred),
713 'time_zone' => 'UTC',
714 'geo_enabled' => false,
716 'statuses_count' => intval($countitems),
718 'contributors_enabled' => false,
719 'is_translator' => false,
720 'is_translation_enabled' => false,
721 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
722 'follow_request_sent' => false,
723 'statusnet_blocking' => false,
724 'notifications' => false,
726 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
727 'statusnet_profile_url' => $uinfo[0]['url'],
728 'uid' => intval($uinfo[0]['uid']),
729 'cid' => intval($uinfo[0]['cid']),
730 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
731 'self' => $uinfo[0]['self'],
732 'network' => $uinfo[0]['network'],
735 // If this is a local user and it uses Frio, we can get its color preferences.
737 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
738 if ($theme_info['theme'] === 'frio') {
739 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
741 if ($schema && ($schema != '---')) {
742 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
743 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
744 require_once $schemefile;
747 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
748 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
749 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
751 if (empty($nav_bg)) {
754 if (empty($link_color)) {
755 $link_color = "#6fdbe8";
757 if (empty($bgcolor)) {
758 $bgcolor = "#ededed";
761 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
762 $ret['profile_link_color'] = str_replace('#', '', $link_color);
763 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
771 * return api-formatted array for item's author and owner
774 * @param array $item item from db
775 * @return array(array:author, array:owner)
776 * @throws BadRequestException
777 * @throws ImagickException
778 * @throws InternalServerErrorException
779 * @throws UnauthorizedException
781 function api_item_get_user(App $a, $item)
783 $status_user = api_get_user($a, $item['author-id'] ?? null);
785 $author_user = $status_user;
787 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
789 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
790 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
792 $owner_user = $author_user;
795 return ([$status_user, $author_user, $owner_user]);
799 * walks recursively through an array with the possibility to change value and key
801 * @param array $array The array to walk through
802 * @param callable $callback The callback function
804 * @return array the transformed array
806 function api_walk_recursive(array &$array, callable $callback)
810 foreach ($array as $k => $v) {
812 if ($callback($v, $k)) {
813 $new_array[$k] = api_walk_recursive($v, $callback);
816 if ($callback($v, $k)) {
827 * Callback function to transform the array in an array that can be transformed in a XML file
829 * @param mixed $item Array item value
830 * @param string $key Array key
832 * @return boolean Should the array item be deleted?
834 function api_reformat_xml(&$item, &$key)
836 if (is_bool($item)) {
837 $item = ($item ? "true" : "false");
840 if (substr($key, 0, 10) == "statusnet_") {
841 $key = "statusnet:".substr($key, 10);
842 } elseif (substr($key, 0, 10) == "friendica_") {
843 $key = "friendica:".substr($key, 10);
845 /// @TODO old-lost code?
847 // $key = "default:".$key;
853 * Creates the XML from a JSON style array
855 * @param array $data JSON style array
856 * @param string $root_element Name of the root element
858 * @return string The XML data
860 function api_create_xml(array $data, $root_element)
862 $childname = key($data);
863 $data2 = array_pop($data);
865 $namespaces = ["" => "http://api.twitter.com",
866 "statusnet" => "http://status.net/schema/api/1/",
867 "friendica" => "http://friendi.ca/schema/api/1/",
868 "georss" => "http://www.georss.org/georss"];
870 /// @todo Auto detection of needed namespaces
871 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
875 if (is_array($data2)) {
877 api_walk_recursive($data2, "api_reformat_xml");
883 foreach ($data2 as $item) {
884 $data4[$i++ . ":" . $childname] = $item;
891 $data3 = [$root_element => $data2];
893 $ret = XML::fromArray($data3, $xml, false, $namespaces);
898 * Formats the data according to the data type
900 * @param string $root_element Name of the root element
901 * @param string $type Return type (atom, rss, xml, json)
902 * @param array $data JSON style array
904 * @return array|string (string|array) XML data or JSON data
906 function api_format_data($root_element, $type, $data)
912 $ret = api_create_xml($data, $root_element);
927 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
928 * returns a 401 status code and an error message if not.
930 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
932 * @param string $type Return type (atom, rss, xml, json)
933 * @return array|string
934 * @throws BadRequestException
935 * @throws ForbiddenException
936 * @throws ImagickException
937 * @throws InternalServerErrorException
938 * @throws UnauthorizedException
940 function api_account_verify_credentials($type)
944 if (api_user() === false) {
945 throw new ForbiddenException();
948 unset($_REQUEST["user_id"]);
949 unset($_GET["user_id"]);
951 unset($_REQUEST["screen_name"]);
952 unset($_GET["screen_name"]);
954 $skip_status = $_REQUEST['skip_status'] ?? false;
956 $user_info = api_get_user($a);
958 // "verified" isn't used here in the standard
959 unset($user_info["verified"]);
961 // - Adding last status
963 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
965 $user_info['status'] = api_format_item($item, $type);
969 // "uid" and "self" are only needed for some internal stuff, so remove it from here
970 unset($user_info["uid"]);
971 unset($user_info["self"]);
973 return api_format_data("user", $type, ['user' => $user_info]);
976 /// @TODO move to top of file or somewhere better
977 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
980 * Get data from $_POST or $_GET
985 function requestdata($k)
987 if (!empty($_POST[$k])) {
990 if (!empty($_GET[$k])) {
997 * Deprecated function to upload media.
999 * @param string $type Return type (atom, rss, xml, json)
1001 * @return array|string
1002 * @throws BadRequestException
1003 * @throws ForbiddenException
1004 * @throws ImagickException
1005 * @throws InternalServerErrorException
1006 * @throws UnauthorizedException
1008 function api_statuses_mediap($type)
1012 if (api_user() === false) {
1013 Logger::log('api_statuses_update: no user');
1014 throw new ForbiddenException();
1016 $user_info = api_get_user($a);
1018 $_REQUEST['profile_uid'] = api_user();
1019 $_REQUEST['api_source'] = true;
1020 $txt = requestdata('status');
1021 /// @TODO old-lost code?
1022 //$txt = urldecode(requestdata('status'));
1024 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1025 $txt = HTML::toBBCodeVideo($txt);
1026 $config = HTMLPurifier_Config::createDefault();
1027 $config->set('Cache.DefinitionImpl', null);
1028 $purifier = new HTMLPurifier($config);
1029 $txt = $purifier->purify($txt);
1031 $txt = HTML::toBBCode($txt);
1033 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1035 $picture = wall_upload_post($a, false);
1037 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1038 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1039 $item_id = item_post($a);
1041 // output the post that we just posted.
1042 return api_status_show($type, $item_id);
1045 /// @TODO move this to top of file or somewhere better!
1046 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1049 * Updates the user’s current status.
1051 * @param string $type Return type (atom, rss, xml, json)
1053 * @return array|string
1054 * @throws BadRequestException
1055 * @throws ForbiddenException
1056 * @throws ImagickException
1057 * @throws InternalServerErrorException
1058 * @throws TooManyRequestsException
1059 * @throws UnauthorizedException
1060 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1062 function api_statuses_update($type)
1066 if (api_user() === false) {
1067 Logger::log('api_statuses_update: no user');
1068 throw new ForbiddenException();
1073 // convert $_POST array items to the form we use for web posts.
1074 if (requestdata('htmlstatus')) {
1075 $txt = requestdata('htmlstatus');
1076 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1077 $txt = HTML::toBBCodeVideo($txt);
1079 $config = HTMLPurifier_Config::createDefault();
1080 $config->set('Cache.DefinitionImpl', null);
1082 $purifier = new HTMLPurifier($config);
1083 $txt = $purifier->purify($txt);
1085 $_REQUEST['body'] = HTML::toBBCode($txt);
1088 $_REQUEST['body'] = requestdata('status');
1091 $_REQUEST['title'] = requestdata('title');
1093 $parent = requestdata('in_reply_to_status_id');
1095 // Twidere sends "-1" if it is no reply ...
1096 if ($parent == -1) {
1100 if (ctype_digit($parent)) {
1101 $_REQUEST['parent'] = $parent;
1103 $_REQUEST['parent_uri'] = $parent;
1106 if (requestdata('lat') && requestdata('long')) {
1107 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1109 $_REQUEST['profile_uid'] = api_user();
1112 // Check for throttling (maximum posts per day, week and month)
1113 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1114 if ($throttle_day > 0) {
1115 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1117 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1118 $posts_day = DBA::count('thread', $condition);
1120 if ($posts_day > $throttle_day) {
1121 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1122 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1123 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));
1127 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1128 if ($throttle_week > 0) {
1129 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1131 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1132 $posts_week = DBA::count('thread', $condition);
1134 if ($posts_week > $throttle_week) {
1135 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1136 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1137 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));
1141 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1142 if ($throttle_month > 0) {
1143 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1145 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1146 $posts_month = DBA::count('thread', $condition);
1148 if ($posts_month > $throttle_month) {
1149 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1150 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1151 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));
1156 if (!empty($_FILES['media'])) {
1157 // upload the image if we have one
1158 $picture = wall_upload_post($a, false);
1159 if (is_array($picture)) {
1160 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1164 if (requestdata('media_ids')) {
1165 $ids = explode(',', requestdata('media_ids'));
1166 foreach ($ids as $id) {
1168 "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",
1172 if (DBA::isResult($r)) {
1173 $phototypes = Images::supportedTypes();
1174 $ext = $phototypes[$r[0]['type']];
1175 $description = $r[0]['desc'] ?? '';
1176 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1177 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1182 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1184 $_REQUEST['api_source'] = true;
1186 if (empty($_REQUEST['source'])) {
1187 $_REQUEST["source"] = api_source();
1190 // call out normal post function
1191 $item_id = item_post($a);
1193 // output the post that we just posted.
1194 return api_status_show($type, $item_id);
1197 /// @TODO move to top of file or somewhere better
1198 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1199 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1202 * Uploads an image to Friendica.
1205 * @throws BadRequestException
1206 * @throws ForbiddenException
1207 * @throws ImagickException
1208 * @throws InternalServerErrorException
1209 * @throws UnauthorizedException
1210 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1212 function api_media_upload()
1216 if (api_user() === false) {
1217 Logger::log('no user');
1218 throw new ForbiddenException();
1223 if (empty($_FILES['media'])) {
1225 throw new BadRequestException("No media.");
1228 $media = wall_upload_post($a, false);
1231 throw new InternalServerErrorException();
1235 $returndata["media_id"] = $media["id"];
1236 $returndata["media_id_string"] = (string)$media["id"];
1237 $returndata["size"] = $media["size"];
1238 $returndata["image"] = ["w" => $media["width"],
1239 "h" => $media["height"],
1240 "image_type" => $media["type"],
1241 "friendica_preview_url" => $media["preview"]];
1243 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1245 return ["media" => $returndata];
1248 /// @TODO move to top of file or somewhere better
1249 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1252 * Updates media meta data (picture descriptions)
1254 * @param string $type Return type (atom, rss, xml, json)
1256 * @return array|string
1257 * @throws BadRequestException
1258 * @throws ForbiddenException
1259 * @throws ImagickException
1260 * @throws InternalServerErrorException
1261 * @throws TooManyRequestsException
1262 * @throws UnauthorizedException
1263 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1265 * @todo Compare the corresponding Twitter function for correct return values
1267 function api_media_metadata_create($type)
1271 if (api_user() === false) {
1272 Logger::info('no user');
1273 throw new ForbiddenException();
1278 $postdata = Network::postdata();
1280 if (empty($postdata)) {
1281 throw new BadRequestException("No post data");
1284 $data = json_decode($postdata, true);
1286 throw new BadRequestException("Invalid post data");
1289 if (empty($data['media_id']) || empty($data['alt_text'])) {
1290 throw new BadRequestException("Missing post data values");
1293 if (empty($data['alt_text']['text'])) {
1294 throw new BadRequestException("No alt text.");
1297 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1299 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1300 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1301 if (!DBA::isResult($photo)) {
1302 throw new BadRequestException("Metadata not found.");
1305 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1308 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1311 * @param string $type Return format (atom, rss, xml, json)
1312 * @param int $item_id
1316 function api_status_show($type, $item_id)
1318 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1322 $item = api_get_item(['id' => $item_id]);
1323 if (!empty($item)) {
1324 $status_info = api_format_item($item, $type);
1327 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1329 return api_format_data('statuses', $type, ['status' => $status_info]);
1333 * Retrieves the last public status of the provided user info
1335 * @param int $ownerId Public contact Id
1336 * @param int $uid User Id
1340 function api_get_last_status($ownerId, $uid)
1343 'author-id'=> $ownerId,
1345 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1346 'private' => [Item::PUBLIC, Item::UNLISTED]
1349 $item = api_get_item($condition);
1355 * Retrieves a single item record based on the provided condition and converts it for API use.
1357 * @param array $condition Item table condition array
1361 function api_get_item(array $condition)
1363 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1369 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1370 * The author's most recent status will be returned inline.
1372 * @param string $type Return type (atom, rss, xml, json)
1373 * @return array|string
1374 * @throws BadRequestException
1375 * @throws ImagickException
1376 * @throws InternalServerErrorException
1377 * @throws UnauthorizedException
1378 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1380 function api_users_show($type)
1382 $a = Friendica\DI::app();
1384 $user_info = api_get_user($a);
1386 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1387 if (!empty($item)) {
1388 $user_info['status'] = api_format_item($item, $type);
1391 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1392 unset($user_info['uid']);
1393 unset($user_info['self']);
1395 return api_format_data('user', $type, ['user' => $user_info]);
1398 /// @TODO move to top of file or somewhere better
1399 api_register_func('api/users/show', 'api_users_show');
1400 api_register_func('api/externalprofile/show', 'api_users_show');
1403 * Search a public user account.
1405 * @param string $type Return type (atom, rss, xml, json)
1407 * @return array|string
1408 * @throws BadRequestException
1409 * @throws ImagickException
1410 * @throws InternalServerErrorException
1411 * @throws UnauthorizedException
1412 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1414 function api_users_search($type)
1420 if (!empty($_GET['q'])) {
1421 $contacts = Contact::selectToArray(
1424 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1432 if (DBA::isResult($contacts)) {
1434 foreach ($contacts as $contact) {
1435 $user_info = api_get_user($a, $contact['id']);
1437 if ($type == 'xml') {
1438 $userlist[$k++ . ':user'] = $user_info;
1440 $userlist[] = $user_info;
1443 $userlist = ['users' => $userlist];
1445 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1448 throw new BadRequestException('No search term specified.');
1451 return api_format_data('users', $type, $userlist);
1454 /// @TODO move to top of file or somewhere better
1455 api_register_func('api/users/search', 'api_users_search');
1458 * Return user objects
1460 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1462 * @param string $type Return format: json or xml
1464 * @return array|string
1465 * @throws BadRequestException
1466 * @throws ImagickException
1467 * @throws InternalServerErrorException
1468 * @throws NotFoundException if the results are empty.
1469 * @throws UnauthorizedException
1471 function api_users_lookup($type)
1475 if (!empty($_REQUEST['user_id'])) {
1476 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1478 $users[] = api_get_user(DI::app(), $id);
1483 if (empty($users)) {
1484 throw new NotFoundException;
1487 return api_format_data("users", $type, ['users' => $users]);
1490 /// @TODO move to top of file or somewhere better
1491 api_register_func('api/users/lookup', 'api_users_lookup', true);
1494 * Returns statuses that match a specified query.
1496 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1498 * @param string $type Return format: json, xml, atom, rss
1500 * @return array|string
1501 * @throws BadRequestException if the "q" parameter is missing.
1502 * @throws ForbiddenException
1503 * @throws ImagickException
1504 * @throws InternalServerErrorException
1505 * @throws UnauthorizedException
1507 function api_search($type)
1510 $user_info = api_get_user($a);
1512 if (api_user() === false || $user_info === false) {
1513 throw new ForbiddenException();
1516 if (empty($_REQUEST['q'])) {
1517 throw new BadRequestException('q parameter is required.');
1520 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1523 $data['status'] = [];
1525 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1526 if (!empty($_REQUEST['rpp'])) {
1527 $count = $_REQUEST['rpp'];
1528 } elseif (!empty($_REQUEST['count'])) {
1529 $count = $_REQUEST['count'];
1532 $since_id = $_REQUEST['since_id'] ?? 0;
1533 $max_id = $_REQUEST['max_id'] ?? 0;
1534 $page = $_REQUEST['page'] ?? 1;
1536 $start = max(0, ($page - 1) * $count);
1538 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1539 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1540 $searchTerm = $matches[1];
1541 $condition = ["`oid` > ?
1542 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1543 AND `otype` = ? AND `type` = ? AND `term` = ?",
1544 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1546 $condition[0] .= ' AND `oid` <= ?';
1547 $condition[] = $max_id;
1549 $terms = DBA::select('term', ['oid'], $condition, []);
1551 while ($term = DBA::fetch($terms)) {
1552 $itemIds[] = $term['oid'];
1556 if (empty($itemIds)) {
1557 return api_format_data('statuses', $type, $data);
1560 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1561 if ($exclude_replies) {
1562 $preCondition[] = '`id` = `parent`';
1565 $condition = [implode(' AND ', $preCondition)];
1567 $condition = ["`id` > ?
1568 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1569 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1570 AND `body` LIKE CONCAT('%',?,'%')",
1571 $since_id, api_user(), $_REQUEST['q']];
1573 $condition[0] .= ' AND `id` <= ?';
1574 $condition[] = $max_id;
1580 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1581 $id = Item::fetchByLink($searchTerm, api_user());
1584 $id = Item::fetchByLink($searchTerm);
1588 $statuses = Item::select([], ['id' => $id]);
1592 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1594 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1596 bindComments($data['status']);
1598 return api_format_data('statuses', $type, $data);
1601 /// @TODO move to top of file or somewhere better
1602 api_register_func('api/search/tweets', 'api_search', true);
1603 api_register_func('api/search', 'api_search', true);
1606 * Returns the most recent statuses posted by the user and the users they follow.
1608 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1610 * @param string $type Return type (atom, rss, xml, json)
1612 * @return array|string
1613 * @throws BadRequestException
1614 * @throws ForbiddenException
1615 * @throws ImagickException
1616 * @throws InternalServerErrorException
1617 * @throws UnauthorizedException
1618 * @todo Optional parameters
1619 * @todo Add reply info
1621 function api_statuses_home_timeline($type)
1624 $user_info = api_get_user($a);
1626 if (api_user() === false || $user_info === false) {
1627 throw new ForbiddenException();
1630 unset($_REQUEST["user_id"]);
1631 unset($_GET["user_id"]);
1633 unset($_REQUEST["screen_name"]);
1634 unset($_GET["screen_name"]);
1636 // get last network messages
1639 $count = $_REQUEST['count'] ?? 20;
1640 $page = $_REQUEST['page']?? 0;
1641 $since_id = $_REQUEST['since_id'] ?? 0;
1642 $max_id = $_REQUEST['max_id'] ?? 0;
1643 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1644 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1646 $start = max(0, ($page - 1) * $count);
1648 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1649 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1652 $condition[0] .= " AND `item`.`id` <= ?";
1653 $condition[] = $max_id;
1655 if ($exclude_replies) {
1656 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1658 if ($conversation_id > 0) {
1659 $condition[0] .= " AND `item`.`parent` = ?";
1660 $condition[] = $conversation_id;
1663 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1664 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1666 $items = Item::inArray($statuses);
1668 $ret = api_format_items($items, $user_info, false, $type);
1670 // Set all posts from the query above to seen
1672 foreach ($items as $item) {
1673 $idarray[] = intval($item["id"]);
1676 if (!empty($idarray)) {
1677 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1679 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1685 $data = ['status' => $ret];
1690 $data = api_rss_extra($a, $data, $user_info);
1694 return api_format_data("statuses", $type, $data);
1698 /// @TODO move to top of file or somewhere better
1699 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1700 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1703 * Returns the most recent statuses from public users.
1705 * @param string $type Return type (atom, rss, xml, json)
1707 * @return array|string
1708 * @throws BadRequestException
1709 * @throws ForbiddenException
1710 * @throws ImagickException
1711 * @throws InternalServerErrorException
1712 * @throws UnauthorizedException
1714 function api_statuses_public_timeline($type)
1717 $user_info = api_get_user($a);
1719 if (api_user() === false || $user_info === false) {
1720 throw new ForbiddenException();
1723 // get last network messages
1726 $count = $_REQUEST['count'] ?? 20;
1727 $page = $_REQUEST['page'] ?? 1;
1728 $since_id = $_REQUEST['since_id'] ?? 0;
1729 $max_id = $_REQUEST['max_id'] ?? 0;
1730 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1731 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1733 $start = max(0, ($page - 1) * $count);
1735 if ($exclude_replies && !$conversation_id) {
1736 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
1737 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1740 $condition[0] .= " AND `thread`.`iid` <= ?";
1741 $condition[] = $max_id;
1744 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1745 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1747 $r = Item::inArray($statuses);
1749 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
1750 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1753 $condition[0] .= " AND `item`.`id` <= ?";
1754 $condition[] = $max_id;
1756 if ($conversation_id > 0) {
1757 $condition[0] .= " AND `item`.`parent` = ?";
1758 $condition[] = $conversation_id;
1761 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1762 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1764 $r = Item::inArray($statuses);
1767 $ret = api_format_items($r, $user_info, false, $type);
1771 $data = ['status' => $ret];
1776 $data = api_rss_extra($a, $data, $user_info);
1780 return api_format_data("statuses", $type, $data);
1783 /// @TODO move to top of file or somewhere better
1784 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1787 * Returns the most recent statuses posted by users this node knows about.
1789 * @param string $type Return format: json, xml, atom, rss
1790 * @return array|string
1791 * @throws BadRequestException
1792 * @throws ForbiddenException
1793 * @throws ImagickException
1794 * @throws InternalServerErrorException
1795 * @throws UnauthorizedException
1797 function api_statuses_networkpublic_timeline($type)
1800 $user_info = api_get_user($a);
1802 if (api_user() === false || $user_info === false) {
1803 throw new ForbiddenException();
1806 $since_id = $_REQUEST['since_id'] ?? 0;
1807 $max_id = $_REQUEST['max_id'] ?? 0;
1810 $count = $_REQUEST['count'] ?? 20;
1811 $page = $_REQUEST['page'] ?? 1;
1813 $start = max(0, ($page - 1) * $count);
1815 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
1816 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1819 $condition[0] .= " AND `thread`.`iid` <= ?";
1820 $condition[] = $max_id;
1823 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1824 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1826 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1830 $data = ['status' => $ret];
1835 $data = api_rss_extra($a, $data, $user_info);
1839 return api_format_data("statuses", $type, $data);
1842 /// @TODO move to top of file or somewhere better
1843 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1846 * Returns a single status.
1848 * @param string $type Return type (atom, rss, xml, json)
1850 * @return array|string
1851 * @throws BadRequestException
1852 * @throws ForbiddenException
1853 * @throws ImagickException
1854 * @throws InternalServerErrorException
1855 * @throws UnauthorizedException
1856 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1858 function api_statuses_show($type)
1861 $user_info = api_get_user($a);
1863 if (api_user() === false || $user_info === false) {
1864 throw new ForbiddenException();
1868 $id = intval($a->argv[3] ?? 0);
1871 $id = intval($_REQUEST['id'] ?? 0);
1876 $id = intval($a->argv[4] ?? 0);
1879 Logger::log('API: api_statuses_show: ' . $id);
1881 $conversation = !empty($_REQUEST['conversation']);
1883 // try to fetch the item for the local user - or the public item, if there is no local one
1884 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1885 if (!DBA::isResult($uri_item)) {
1886 throw new BadRequestException("There is no status with this id.");
1889 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1890 if (!DBA::isResult($item)) {
1891 throw new BadRequestException("There is no status with this id.");
1896 if ($conversation) {
1897 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1898 $params = ['order' => ['id' => true]];
1900 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1904 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1906 /// @TODO How about copying this to above methods which don't check $r ?
1907 if (!DBA::isResult($statuses)) {
1908 throw new BadRequestException("There is no status with this id.");
1911 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1913 if ($conversation) {
1914 $data = ['status' => $ret];
1915 return api_format_data("statuses", $type, $data);
1917 $data = ['status' => $ret[0]];
1918 return api_format_data("status", $type, $data);
1922 /// @TODO move to top of file or somewhere better
1923 api_register_func('api/statuses/show', 'api_statuses_show', true);
1927 * @param string $type Return type (atom, rss, xml, json)
1929 * @return array|string
1930 * @throws BadRequestException
1931 * @throws ForbiddenException
1932 * @throws ImagickException
1933 * @throws InternalServerErrorException
1934 * @throws UnauthorizedException
1935 * @todo nothing to say?
1937 function api_conversation_show($type)
1940 $user_info = api_get_user($a);
1942 if (api_user() === false || $user_info === false) {
1943 throw new ForbiddenException();
1947 $id = intval($a->argv[3] ?? 0);
1948 $since_id = intval($_REQUEST['since_id'] ?? 0);
1949 $max_id = intval($_REQUEST['max_id'] ?? 0);
1950 $count = intval($_REQUEST['count'] ?? 20);
1951 $page = intval($_REQUEST['page'] ?? 1);
1953 $start = max(0, ($page - 1) * $count);
1956 $id = intval($_REQUEST['id'] ?? 0);
1961 $id = intval($a->argv[4] ?? 0);
1964 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1966 // try to fetch the item for the local user - or the public item, if there is no local one
1967 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1968 if (!DBA::isResult($item)) {
1969 throw new BadRequestException("There is no status with this id.");
1972 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1973 if (!DBA::isResult($parent)) {
1974 throw new BadRequestException("There is no status with this id.");
1977 $id = $parent['id'];
1979 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1980 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1983 $condition[0] .= " AND `item`.`id` <= ?";
1984 $condition[] = $max_id;
1987 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1988 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1990 if (!DBA::isResult($statuses)) {
1991 throw new BadRequestException("There is no status with id $id.");
1994 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1996 $data = ['status' => $ret];
1997 return api_format_data("statuses", $type, $data);
2000 /// @TODO move to top of file or somewhere better
2001 api_register_func('api/conversation/show', 'api_conversation_show', true);
2002 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2007 * @param string $type Return type (atom, rss, xml, json)
2009 * @return array|string
2010 * @throws BadRequestException
2011 * @throws ForbiddenException
2012 * @throws ImagickException
2013 * @throws InternalServerErrorException
2014 * @throws UnauthorizedException
2015 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2017 function api_statuses_repeat($type)
2023 if (api_user() === false) {
2024 throw new ForbiddenException();
2030 $id = intval($a->argv[3] ?? 0);
2033 $id = intval($_REQUEST['id'] ?? 0);
2038 $id = intval($a->argv[4] ?? 0);
2041 Logger::log('API: api_statuses_repeat: '.$id);
2043 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2044 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2046 if (DBA::isResult($item) && $item['body'] != "") {
2047 if (strpos($item['body'], "[/share]") !== false) {
2048 $pos = strpos($item['body'], "[share");
2049 $post = substr($item['body'], $pos);
2051 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2053 if (!empty($item['title'])) {
2054 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2057 $post .= $item['body'];
2058 $post .= "[/share]";
2060 $_REQUEST['body'] = $post;
2061 $_REQUEST['tag'] = $item['tag'];
2062 $_REQUEST['attach'] = $item['attach'];
2063 $_REQUEST['profile_uid'] = api_user();
2064 $_REQUEST['api_source'] = true;
2066 if (empty($_REQUEST['source'])) {
2067 $_REQUEST["source"] = api_source();
2070 $item_id = item_post($a);
2072 throw new ForbiddenException();
2075 // output the post that we just posted.
2077 return api_status_show($type, $item_id);
2080 /// @TODO move to top of file or somewhere better
2081 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2084 * Destroys a specific status.
2086 * @param string $type Return type (atom, rss, xml, json)
2088 * @return array|string
2089 * @throws BadRequestException
2090 * @throws ForbiddenException
2091 * @throws ImagickException
2092 * @throws InternalServerErrorException
2093 * @throws UnauthorizedException
2094 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2096 function api_statuses_destroy($type)
2100 if (api_user() === false) {
2101 throw new ForbiddenException();
2107 $id = intval($a->argv[3] ?? 0);
2110 $id = intval($_REQUEST['id'] ?? 0);
2115 $id = intval($a->argv[4] ?? 0);
2118 Logger::log('API: api_statuses_destroy: '.$id);
2120 $ret = api_statuses_show($type);
2122 Item::deleteForUser(['id' => $id], api_user());
2127 /// @TODO move to top of file or somewhere better
2128 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2131 * Returns the most recent mentions.
2133 * @param string $type Return type (atom, rss, xml, json)
2135 * @return array|string
2136 * @throws BadRequestException
2137 * @throws ForbiddenException
2138 * @throws ImagickException
2139 * @throws InternalServerErrorException
2140 * @throws UnauthorizedException
2141 * @see http://developer.twitter.com/doc/get/statuses/mentions
2143 function api_statuses_mentions($type)
2146 $user_info = api_get_user($a);
2148 if (api_user() === false || $user_info === false) {
2149 throw new ForbiddenException();
2152 unset($_REQUEST["user_id"]);
2153 unset($_GET["user_id"]);
2155 unset($_REQUEST["screen_name"]);
2156 unset($_GET["screen_name"]);
2158 // get last network messages
2161 $since_id = $_REQUEST['since_id'] ?? 0;
2162 $max_id = $_REQUEST['max_id'] ?? 0;
2163 $count = $_REQUEST['count'] ?? 20;
2164 $page = $_REQUEST['page'] ?? 1;
2166 $start = max(0, ($page - 1) * $count);
2168 $query = "SELECT `item`.`id` FROM `user-item`
2169 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2170 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2171 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2172 AND `user-item`.`iid` > ?";
2173 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2174 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2175 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2176 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2180 $query .= " AND `item`.`id` <= ?";
2181 $condition[] = $max_id;
2184 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2185 $condition[] = $start;
2186 $condition[] = $count;
2188 $useritems = DBA::p($query, $condition);
2190 while ($useritem = DBA::fetch($useritems)) {
2191 $itemids[] = $useritem['id'];
2193 DBA::close($useritems);
2195 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2196 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2198 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2200 $data = ['status' => $ret];
2205 $data = api_rss_extra($a, $data, $user_info);
2209 return api_format_data("statuses", $type, $data);
2212 /// @TODO move to top of file or somewhere better
2213 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2214 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2217 * Returns the most recent statuses posted by the user.
2219 * @param string $type Either "json" or "xml"
2220 * @return string|array
2221 * @throws BadRequestException
2222 * @throws ForbiddenException
2223 * @throws ImagickException
2224 * @throws InternalServerErrorException
2225 * @throws UnauthorizedException
2226 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2228 function api_statuses_user_timeline($type)
2231 $user_info = api_get_user($a);
2233 if (api_user() === false || $user_info === false) {
2234 throw new ForbiddenException();
2238 "api_statuses_user_timeline: api_user: ". api_user() .
2239 "\nuser_info: ".print_r($user_info, true) .
2240 "\n_REQUEST: ".print_r($_REQUEST, true),
2244 $since_id = $_REQUEST['since_id'] ?? 0;
2245 $max_id = $_REQUEST['max_id'] ?? 0;
2246 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2247 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2250 $count = $_REQUEST['count'] ?? 20;
2251 $page = $_REQUEST['page'] ?? 1;
2253 $start = max(0, ($page - 1) * $count);
2255 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2256 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2258 if ($user_info['self'] == 1) {
2259 $condition[0] .= ' AND `item`.`wall` ';
2262 if ($exclude_replies) {
2263 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2266 if ($conversation_id > 0) {
2267 $condition[0] .= " AND `item`.`parent` = ?";
2268 $condition[] = $conversation_id;
2272 $condition[0] .= " AND `item`.`id` <= ?";
2273 $condition[] = $max_id;
2276 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2277 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2279 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2283 $data = ['status' => $ret];
2288 $data = api_rss_extra($a, $data, $user_info);
2292 return api_format_data("statuses", $type, $data);
2295 /// @TODO move to top of file or somewhere better
2296 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2299 * Star/unstar an item.
2300 * param: id : id of the item
2302 * @param string $type Return type (atom, rss, xml, json)
2304 * @return array|string
2305 * @throws BadRequestException
2306 * @throws ForbiddenException
2307 * @throws ImagickException
2308 * @throws InternalServerErrorException
2309 * @throws UnauthorizedException
2310 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2312 function api_favorites_create_destroy($type)
2316 if (api_user() === false) {
2317 throw new ForbiddenException();
2320 // for versioned api.
2321 /// @TODO We need a better global soluton
2322 $action_argv_id = 2;
2323 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2324 $action_argv_id = 3;
2327 if ($a->argc <= $action_argv_id) {
2328 throw new BadRequestException("Invalid request.");
2330 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2331 if ($a->argc == $action_argv_id + 2) {
2332 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2334 $itemid = intval($_REQUEST['id'] ?? 0);
2337 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2339 if (!DBA::isResult($item)) {
2340 throw new BadRequestException("Invalid item.");
2345 $item['starred'] = 1;
2348 $item['starred'] = 0;
2351 throw new BadRequestException("Invalid action ".$action);
2354 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2357 throw new InternalServerErrorException("DB error");
2361 $user_info = api_get_user($a);
2362 $rets = api_format_items([$item], $user_info, false, $type);
2365 $data = ['status' => $ret];
2370 $data = api_rss_extra($a, $data, $user_info);
2374 return api_format_data("status", $type, $data);
2377 /// @TODO move to top of file or somewhere better
2378 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2379 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2382 * Returns the most recent favorite statuses.
2384 * @param string $type Return type (atom, rss, xml, json)
2386 * @return string|array
2387 * @throws BadRequestException
2388 * @throws ForbiddenException
2389 * @throws ImagickException
2390 * @throws InternalServerErrorException
2391 * @throws UnauthorizedException
2393 function api_favorites($type)
2398 $user_info = api_get_user($a);
2400 if (api_user() === false || $user_info === false) {
2401 throw new ForbiddenException();
2406 // in friendica starred item are private
2407 // return favorites only for self
2408 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2410 if ($user_info['self'] == 0) {
2414 $since_id = $_REQUEST['since_id'] ?? 0;
2415 $max_id = $_REQUEST['max_id'] ?? 0;
2416 $count = $_GET['count'] ?? 20;
2417 $page = $_REQUEST['page'] ?? 1;
2419 $start = max(0, ($page - 1) * $count);
2421 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2422 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2424 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2427 $condition[0] .= " AND `item`.`id` <= ?";
2428 $condition[] = $max_id;
2431 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2433 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2438 $data = ['status' => $ret];
2443 $data = api_rss_extra($a, $data, $user_info);
2447 return api_format_data("statuses", $type, $data);
2450 /// @TODO move to top of file or somewhere better
2451 api_register_func('api/favorites', 'api_favorites', true);
2455 * @param array $item
2456 * @param array $recipient
2457 * @param array $sender
2460 * @throws InternalServerErrorException
2462 function api_format_messages($item, $recipient, $sender)
2464 // standard meta information
2466 'id' => $item['id'],
2467 'sender_id' => $sender['id'],
2469 'recipient_id' => $recipient['id'],
2470 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2471 'sender_screen_name' => $sender['screen_name'],
2472 'recipient_screen_name' => $recipient['screen_name'],
2473 'sender' => $sender,
2474 'recipient' => $recipient,
2476 'friendica_seen' => $item['seen'] ?? 0,
2477 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2480 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2481 if (isset($ret['sender']['uid'])) {
2482 unset($ret['sender']['uid']);
2484 if (isset($ret['sender']['self'])) {
2485 unset($ret['sender']['self']);
2487 if (isset($ret['recipient']['uid'])) {
2488 unset($ret['recipient']['uid']);
2490 if (isset($ret['recipient']['self'])) {
2491 unset($ret['recipient']['self']);
2494 //don't send title to regular StatusNET requests to avoid confusing these apps
2495 if (!empty($_GET['getText'])) {
2496 $ret['title'] = $item['title'];
2497 if ($_GET['getText'] == 'html') {
2498 $ret['text'] = BBCode::convert($item['body'], false);
2499 } elseif ($_GET['getText'] == 'plain') {
2500 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2503 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2505 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2506 unset($ret['sender']);
2507 unset($ret['recipient']);
2515 * @param array $item
2518 * @throws InternalServerErrorException
2520 function api_convert_item($item)
2522 $body = $item['body'];
2523 $entities = api_get_entitities($statustext, $body);
2525 // Add pictures to the attachment array and remove them from the body
2526 $attachments = api_get_attachments($body);
2528 // Workaround for ostatus messages where the title is identically to the body
2529 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2530 $statusbody = trim(HTML::toPlaintext($html, 0));
2532 // handle data: images
2533 $statusbody = api_format_items_embeded_images($item, $statusbody);
2535 $statustitle = trim($item['title']);
2537 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2538 $statustext = trim($statusbody);
2540 $statustext = trim($statustitle."\n\n".$statusbody);
2543 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2544 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2547 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2549 // Workaround for clients with limited HTML parser functionality
2550 $search = ["<br>", "<blockquote>", "</blockquote>",
2551 "<h1>", "</h1>", "<h2>", "</h2>",
2552 "<h3>", "</h3>", "<h4>", "</h4>",
2553 "<h5>", "</h5>", "<h6>", "</h6>"];
2554 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2555 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2556 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2557 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2558 $statushtml = str_replace($search, $replace, $statushtml);
2560 if ($item['title'] != "") {
2561 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2565 $oldtext = $statushtml;
2566 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2567 } while ($oldtext != $statushtml);
2569 if (substr($statushtml, 0, 4) == '<br>') {
2570 $statushtml = substr($statushtml, 4);
2573 if (substr($statushtml, 0, -4) == '<br>') {
2574 $statushtml = substr($statushtml, -4);
2577 // feeds without body should contain the link
2578 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2579 $statushtml .= BBCode::convert($item['plink']);
2583 "text" => $statustext,
2584 "html" => $statushtml,
2585 "attachments" => $attachments,
2586 "entities" => $entities
2592 * @param string $body
2595 * @throws InternalServerErrorException
2597 function api_get_attachments(&$body)
2599 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2600 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2602 $URLSearchString = "^\[\]";
2603 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2607 // Remove all embedded pictures, since they are added as attachments
2608 foreach ($images[0] as $orig) {
2609 $body = str_replace($orig, '', $body);
2614 foreach ($images[1] as $image) {
2615 $imagedata = Images::getInfoFromURLCached($image);
2618 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2622 return $attachments;
2627 * @param string $text
2628 * @param string $bbcode
2631 * @throws InternalServerErrorException
2632 * @todo Links at the first character of the post
2634 function api_get_entitities(&$text, $bbcode)
2636 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2638 if ($include_entities != "true") {
2639 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2641 foreach ($images[1] as $image) {
2642 $replace = ProxyUtils::proxifyUrl($image);
2643 $text = str_replace($image, $replace, $text);
2648 $bbcode = BBCode::cleanPictureLinks($bbcode);
2650 // Change pure links in text to bbcode uris
2651 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2654 $entities["hashtags"] = [];
2655 $entities["symbols"] = [];
2656 $entities["urls"] = [];
2657 $entities["user_mentions"] = [];
2659 $URLSearchString = "^\[\]";
2661 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2663 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2664 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2666 $bbcode = preg_replace(
2667 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2668 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2671 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2673 $bbcode = preg_replace(
2674 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2675 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2678 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2680 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2682 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2685 foreach ($urls[1] as $id => $url) {
2686 $start = iconv_strpos($text, $url, 0, "UTF-8");
2687 if (!($start === false)) {
2688 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2692 ksort($ordered_urls);
2696 foreach ($ordered_urls as $url) {
2697 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2698 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2700 $display_url = $url["title"];
2702 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2703 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2705 if (strlen($display_url) > 26) {
2706 $display_url = substr($display_url, 0, 25)."…";
2710 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2711 if (!($start === false)) {
2712 $entities["urls"][] = ["url" => $url["url"],
2713 "expanded_url" => $url["url"],
2714 "display_url" => $display_url,
2715 "indices" => [$start, $start+strlen($url["url"])]];
2716 $offset = $start + 1;
2720 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2721 $ordered_images = [];
2722 foreach ($images as $image) {
2723 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2724 if (!($start === false)) {
2725 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2729 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2730 foreach ($images[1] as $image) {
2731 $start = iconv_strpos($text, $image, 0, "UTF-8");
2732 if (!($start === false)) {
2733 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2739 foreach ($ordered_images as $image) {
2740 $url = $image['url'];
2741 $ext_alt_text = $image['alt'];
2743 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2744 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2746 if (strlen($display_url) > 26) {
2747 $display_url = substr($display_url, 0, 25)."…";
2750 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2751 if (!($start === false)) {
2752 $image = Images::getInfoFromURLCached($url);
2754 // If image cache is activated, then use the following sizes:
2755 // thumb (150), small (340), medium (600) and large (1024)
2756 if (!DI::config()->get("system", "proxy_disabled")) {
2757 $media_url = ProxyUtils::proxifyUrl($url);
2760 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2761 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2763 if (($image[0] > 150) || ($image[1] > 150)) {
2764 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2765 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2768 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2769 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2771 if (($image[0] > 600) || ($image[1] > 600)) {
2772 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2773 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2777 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2780 $entities["media"][] = [
2782 "id_str" => (string) ($start + 1),
2783 "indices" => [$start, $start+strlen($url)],
2784 "media_url" => Strings::normaliseLink($media_url),
2785 "media_url_https" => $media_url,
2787 "display_url" => $display_url,
2788 "expanded_url" => $url,
2789 "ext_alt_text" => $ext_alt_text,
2793 $offset = $start + 1;
2802 * @param array $item
2803 * @param string $text
2807 function api_format_items_embeded_images($item, $text)
2809 $text = preg_replace_callback(
2810 '|data:image/([^;]+)[^=]+=*|m',
2811 function () use ($item) {
2812 return DI::baseUrl() . '/display/' . $item['guid'];
2820 * return <a href='url'>name</a> as array
2822 * @param string $txt text
2827 function api_contactlink_to_array($txt)
2830 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2831 if ($r && count($match)==3) {
2833 'name' => $match[2],
2847 * return likes, dislikes and attend status for item
2849 * @param array $item array
2850 * @param string $type Return type (atom, rss, xml, json)
2853 * likes => int count,
2854 * dislikes => int count
2855 * @throws BadRequestException
2856 * @throws ImagickException
2857 * @throws InternalServerErrorException
2858 * @throws UnauthorizedException
2860 function api_format_items_activities($item, $type = "json")
2869 'attendmaybe' => [],
2873 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2874 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2876 while ($parent_item = Item::fetch($ret)) {
2877 // not used as result should be structured like other user data
2878 //builtin_activity_puller($i, $activities);
2880 // get user data and add it to the array of the activity
2881 $user = api_get_user($a, $parent_item['author-id']);
2882 switch ($parent_item['verb']) {
2883 case Activity::LIKE:
2884 $activities['like'][] = $user;
2886 case Activity::DISLIKE:
2887 $activities['dislike'][] = $user;
2889 case Activity::ATTEND:
2890 $activities['attendyes'][] = $user;
2892 case Activity::ATTENDNO:
2893 $activities['attendno'][] = $user;
2895 case Activity::ATTENDMAYBE:
2896 $activities['attendmaybe'][] = $user;
2898 case Activity::ANNOUNCE:
2899 $activities['announce'][] = $user;
2908 if ($type == "xml") {
2909 $xml_activities = [];
2910 foreach ($activities as $k => $v) {
2911 // change xml element from "like" to "friendica:like"
2912 $xml_activities["friendica:".$k] = $v;
2913 // add user data into xml output
2915 foreach ($v as $user) {
2916 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2919 $activities = $xml_activities;
2926 * format items to be returned by api
2928 * @param array $items array of items
2929 * @param array $user_info
2930 * @param bool $filter_user filter items by $user_info
2931 * @param string $type Return type (atom, rss, xml, json)
2933 * @throws BadRequestException
2934 * @throws ImagickException
2935 * @throws InternalServerErrorException
2936 * @throws UnauthorizedException
2938 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2940 $a = Friendica\DI::app();
2944 foreach ((array)$items as $item) {
2945 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2947 // Look if the posts are matching if they should be filtered by user id
2948 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2952 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2961 * @param array $item Item record
2962 * @param string $type Return format (atom, rss, xml, json)
2963 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2964 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2965 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2966 * @return array API-formatted status
2967 * @throws BadRequestException
2968 * @throws ImagickException
2969 * @throws InternalServerErrorException
2970 * @throws UnauthorizedException
2972 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2974 $a = Friendica\DI::app();
2976 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2977 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2980 localize_item($item);
2982 $in_reply_to = api_in_reply_to($item);
2984 $converted = api_convert_item($item);
2986 if ($type == "xml") {
2987 $geo = "georss:point";
2993 'text' => $converted["text"],
2994 'truncated' => false,
2995 'created_at'=> api_date($item['created']),
2996 'in_reply_to_status_id' => $in_reply_to['status_id'],
2997 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2998 'source' => (($item['app']) ? $item['app'] : 'web'),
2999 'id' => intval($item['id']),
3000 'id_str' => (string) intval($item['id']),
3001 'in_reply_to_user_id' => $in_reply_to['user_id'],
3002 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3003 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3005 'favorited' => $item['starred'] ? true : false,
3006 'user' => $status_user,
3007 'friendica_author' => $author_user,
3008 'friendica_owner' => $owner_user,
3009 'friendica_private' => $item['private'] == Item::PRIVATE,
3010 //'entities' => NULL,
3011 'statusnet_html' => $converted["html"],
3012 'statusnet_conversation_id' => $item['parent'],
3013 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3014 'friendica_activities' => api_format_items_activities($item, $type),
3015 'friendica_title' => $item['title'],
3016 'friendica_html' => BBCode::convert($item['body'], false)
3019 if (count($converted["attachments"]) > 0) {
3020 $status["attachments"] = $converted["attachments"];
3023 if (count($converted["entities"]) > 0) {
3024 $status["entities"] = $converted["entities"];
3027 if ($status["source"] == 'web') {
3028 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3029 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3030 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3033 $retweeted_item = [];
3036 if ($item["id"] == $item["parent"]) {
3037 $body = $item['body'];
3038 $retweeted_item = api_share_as_retweet($item);
3039 if ($body != $item['body']) {
3040 $quoted_item = $retweeted_item;
3041 $retweeted_item = [];
3045 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3046 $announce = api_get_announce($item);
3047 if (!empty($announce)) {
3048 $retweeted_item = $item;
3050 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3054 if (!empty($quoted_item)) {
3055 if ($quoted_item['id'] != $item['id']) {
3056 $quoted_status = api_format_item($quoted_item);
3057 /// @todo Only remove the attachments that are also contained in the quotes status
3058 unset($status['attachments']);
3059 unset($status['entities']);
3061 $conv_quoted = api_convert_item($quoted_item);
3062 $quoted_status = $status;
3063 unset($quoted_status['attachments']);
3064 unset($quoted_status['entities']);
3065 unset($quoted_status['statusnet_conversation_id']);
3066 $quoted_status['text'] = $conv_quoted['text'];
3067 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3069 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3070 } catch (BadRequestException $e) {
3071 // user not found. should be found?
3072 /// @todo check if the user should be always found
3073 $quoted_status["user"] = [];
3076 unset($quoted_status['friendica_author']);
3077 unset($quoted_status['friendica_owner']);
3078 unset($quoted_status['friendica_activities']);
3079 unset($quoted_status['friendica_private']);
3082 if (!empty($retweeted_item)) {
3083 $retweeted_status = $status;
3084 unset($retweeted_status['friendica_author']);
3085 unset($retweeted_status['friendica_owner']);
3086 unset($retweeted_status['friendica_activities']);
3087 unset($retweeted_status['friendica_private']);
3088 unset($retweeted_status['statusnet_conversation_id']);
3089 $status['user'] = $status['friendica_owner'];
3091 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3092 } catch (BadRequestException $e) {
3093 // user not found. should be found?
3094 /// @todo check if the user should be always found
3095 $retweeted_status["user"] = [];
3098 $rt_converted = api_convert_item($retweeted_item);
3100 $retweeted_status['text'] = $rt_converted["text"];
3101 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3102 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3104 if (!empty($quoted_status)) {
3105 $retweeted_status['quoted_status'] = $quoted_status;
3108 $status['friendica_author'] = $retweeted_status['user'];
3109 $status['retweeted_status'] = $retweeted_status;
3110 } elseif (!empty($quoted_status)) {
3111 $root_status = api_convert_item($item);
3113 $status['text'] = $root_status["text"];
3114 $status['statusnet_html'] = $root_status["html"];
3115 $status['quoted_status'] = $quoted_status;
3118 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3119 unset($status["user"]["uid"]);
3120 unset($status["user"]["self"]);
3122 if ($item["coord"] != "") {
3123 $coords = explode(' ', $item["coord"]);
3124 if (count($coords) == 2) {
3125 if ($type == "json") {
3126 $status["geo"] = ['type' => 'Point',
3127 'coordinates' => [(float) $coords[0],
3128 (float) $coords[1]]];
3129 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3130 $status["georss:point"] = $item["coord"];
3139 * Returns the remaining number of API requests available to the user before the API limit is reached.
3141 * @param string $type Return type (atom, rss, xml, json)
3143 * @return array|string
3146 function api_account_rate_limit_status($type)
3148 if ($type == "xml") {
3150 'remaining-hits' => '150',
3151 '@attributes' => ["type" => "integer"],
3152 'hourly-limit' => '150',
3153 '@attributes2' => ["type" => "integer"],
3154 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3155 '@attributes3' => ["type" => "datetime"],
3156 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3157 '@attributes4' => ["type" => "integer"],
3161 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3162 'remaining_hits' => '150',
3163 'hourly_limit' => '150',
3164 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3168 return api_format_data('hash', $type, ['hash' => $hash]);
3171 /// @TODO move to top of file or somewhere better
3172 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3175 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3177 * @param string $type Return type (atom, rss, xml, json)
3179 * @return array|string
3181 function api_help_test($type)
3183 if ($type == 'xml') {
3189 return api_format_data('ok', $type, ["ok" => $ok]);
3192 /// @TODO move to top of file or somewhere better
3193 api_register_func('api/help/test', 'api_help_test', false);
3196 * Returns all lists the user subscribes to.
3198 * @param string $type Return type (atom, rss, xml, json)
3200 * @return array|string
3201 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3203 function api_lists_list($type)
3206 /// @TODO $ret is not filled here?
3207 return api_format_data('lists', $type, ["lists_list" => $ret]);
3210 /// @TODO move to top of file or somewhere better
3211 api_register_func('api/lists/list', 'api_lists_list', true);
3212 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3215 * Returns all groups the user owns.
3217 * @param string $type Return type (atom, rss, xml, json)
3219 * @return array|string
3220 * @throws BadRequestException
3221 * @throws ForbiddenException
3222 * @throws ImagickException
3223 * @throws InternalServerErrorException
3224 * @throws UnauthorizedException
3225 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3227 function api_lists_ownerships($type)
3231 if (api_user() === false) {
3232 throw new ForbiddenException();
3236 $user_info = api_get_user($a);
3237 $uid = $user_info['uid'];
3239 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3241 // loop through all groups
3243 foreach ($groups as $group) {
3244 if ($group['visible']) {
3250 'name' => $group['name'],
3251 'id' => intval($group['id']),
3252 'id_str' => (string) $group['id'],
3253 'user' => $user_info,
3257 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3260 /// @TODO move to top of file or somewhere better
3261 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3264 * Returns recent statuses from users in the specified group.
3266 * @param string $type Return type (atom, rss, xml, json)
3268 * @return array|string
3269 * @throws BadRequestException
3270 * @throws ForbiddenException
3271 * @throws ImagickException
3272 * @throws InternalServerErrorException
3273 * @throws UnauthorizedException
3274 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3276 function api_lists_statuses($type)
3280 $user_info = api_get_user($a);
3281 if (api_user() === false || $user_info === false) {
3282 throw new ForbiddenException();
3285 unset($_REQUEST["user_id"]);
3286 unset($_GET["user_id"]);
3288 unset($_REQUEST["screen_name"]);
3289 unset($_GET["screen_name"]);
3291 if (empty($_REQUEST['list_id'])) {
3292 throw new BadRequestException('list_id not specified');
3296 $count = $_REQUEST['count'] ?? 20;
3297 $page = $_REQUEST['page'] ?? 1;
3298 $since_id = $_REQUEST['since_id'] ?? 0;
3299 $max_id = $_REQUEST['max_id'] ?? 0;
3300 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3301 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3303 $start = max(0, ($page - 1) * $count);
3305 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3306 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3309 $condition[0] .= " AND `item`.`id` <= ?";
3310 $condition[] = $max_id;
3312 if ($exclude_replies > 0) {
3313 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3315 if ($conversation_id > 0) {
3316 $condition[0] .= " AND `item`.`parent` = ?";
3317 $condition[] = $conversation_id;
3320 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3321 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3323 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3325 $data = ['status' => $items];
3330 $data = api_rss_extra($a, $data, $user_info);
3334 return api_format_data("statuses", $type, $data);
3337 /// @TODO move to top of file or somewhere better
3338 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3341 * Returns either the friends of the follower list
3343 * Considers friends and followers lists to be private and won't return
3344 * anything if any user_id parameter is passed.
3346 * @param string $qtype Either "friends" or "followers"
3347 * @return boolean|array
3348 * @throws BadRequestException
3349 * @throws ForbiddenException
3350 * @throws ImagickException
3351 * @throws InternalServerErrorException
3352 * @throws UnauthorizedException
3354 function api_statuses_f($qtype)
3358 if (api_user() === false) {
3359 throw new ForbiddenException();
3363 $count = $_GET['count'] ?? 20;
3364 $page = $_GET['page'] ?? 1;
3366 $start = max(0, ($page - 1) * $count);
3368 $user_info = api_get_user($a);
3370 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3371 /* this is to stop Hotot to load friends multiple times
3372 * I'm not sure if I'm missing return something or
3373 * is a bug in hotot. Workaround, meantime
3377 return array('$users' => $ret);*/
3382 if ($qtype == 'friends') {
3383 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3384 } elseif ($qtype == 'followers') {
3385 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3388 // friends and followers only for self
3389 if ($user_info['self'] == 0) {
3390 $sql_extra = " AND false ";
3393 if ($qtype == 'blocks') {
3394 $sql_filter = 'AND `blocked` AND NOT `pending`';
3395 } elseif ($qtype == 'incoming') {
3396 $sql_filter = 'AND `pending`';
3398 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3416 foreach ($r as $cid) {
3417 $user = api_get_user($a, $cid['nurl']);
3418 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3419 unset($user["uid"]);
3420 unset($user["self"]);
3427 return ['user' => $ret];
3432 * Returns the list of friends of the provided user
3434 * @deprecated By Twitter API in favor of friends/list
3436 * @param string $type Either "json" or "xml"
3437 * @return boolean|string|array
3438 * @throws BadRequestException
3439 * @throws ForbiddenException
3441 function api_statuses_friends($type)
3443 $data = api_statuses_f("friends");
3444 if ($data === false) {
3447 return api_format_data("users", $type, $data);
3451 * Returns the list of followers of the provided user
3453 * @deprecated By Twitter API in favor of friends/list
3455 * @param string $type Either "json" or "xml"
3456 * @return boolean|string|array
3457 * @throws BadRequestException
3458 * @throws ForbiddenException
3460 function api_statuses_followers($type)
3462 $data = api_statuses_f("followers");
3463 if ($data === false) {
3466 return api_format_data("users", $type, $data);
3469 /// @TODO move to top of file or somewhere better
3470 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3471 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3474 * Returns the list of blocked users
3476 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3478 * @param string $type Either "json" or "xml"
3480 * @return boolean|string|array
3481 * @throws BadRequestException
3482 * @throws ForbiddenException
3484 function api_blocks_list($type)
3486 $data = api_statuses_f('blocks');
3487 if ($data === false) {
3490 return api_format_data("users", $type, $data);
3493 /// @TODO move to top of file or somewhere better
3494 api_register_func('api/blocks/list', 'api_blocks_list', true);
3497 * Returns the list of pending users IDs
3499 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3501 * @param string $type Either "json" or "xml"
3503 * @return boolean|string|array
3504 * @throws BadRequestException
3505 * @throws ForbiddenException
3507 function api_friendships_incoming($type)
3509 $data = api_statuses_f('incoming');
3510 if ($data === false) {
3515 foreach ($data['user'] as $user) {
3516 $ids[] = $user['id'];
3519 return api_format_data("ids", $type, ['id' => $ids]);
3522 /// @TODO move to top of file or somewhere better
3523 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3526 * Returns the instance's configuration information.
3528 * @param string $type Return type (atom, rss, xml, json)
3530 * @return array|string
3531 * @throws InternalServerErrorException
3533 function api_statusnet_config($type)
3535 $name = DI::config()->get('config', 'sitename');
3536 $server = DI::baseUrl()->getHostname();
3537 $logo = DI::baseUrl() . '/images/friendica-64.png';
3538 $email = DI::config()->get('config', 'admin_email');
3539 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3540 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3541 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3542 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3543 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3546 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3547 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3548 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3549 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3550 'shorturllength' => '30',
3552 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3553 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3554 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3555 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3560 return api_format_data('config', $type, ['config' => $config]);
3563 /// @TODO move to top of file or somewhere better
3564 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3565 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3569 * @param string $type Return type (atom, rss, xml, json)
3571 * @return array|string
3573 function api_statusnet_version($type)
3576 $fake_statusnet_version = "0.9.7";
3578 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3581 /// @TODO move to top of file or somewhere better
3582 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3583 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3587 * @param string $type Return type (atom, rss, xml, json)
3589 * @param int $rel A contact relationship constant
3590 * @return array|string|void
3591 * @throws BadRequestException
3592 * @throws ForbiddenException
3593 * @throws ImagickException
3594 * @throws InternalServerErrorException
3595 * @throws UnauthorizedException
3596 * @todo use api_format_data() to return data
3598 function api_ff_ids($type, int $rel)
3601 throw new ForbiddenException();
3608 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3610 $contacts = DBA::p("SELECT `pcontact`.`id`
3612 INNER JOIN `contact` AS `pcontact`
3613 ON `contact`.`nurl` = `pcontact`.`nurl`
3614 AND `pcontact`.`uid` = 0
3615 WHERE `contact`.`uid` = ?
3616 AND NOT `contact`.`self`
3617 AND `contact`.`rel` IN (?, ?)",
3624 foreach (DBA::toArray($contacts) as $contact) {
3625 if ($stringify_ids) {
3626 $ids[] = $contact['id'];
3628 $ids[] = intval($contact['id']);
3632 return api_format_data('ids', $type, ['id' => $ids]);
3636 * Returns the ID of every user the user is following.
3638 * @param string $type Return type (atom, rss, xml, json)
3640 * @return array|string
3641 * @throws BadRequestException
3642 * @throws ForbiddenException
3643 * @throws ImagickException
3644 * @throws InternalServerErrorException
3645 * @throws UnauthorizedException
3646 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3648 function api_friends_ids($type)
3650 return api_ff_ids($type, Contact::SHARING);
3654 * Returns the ID of every user following the user.
3656 * @param string $type Return type (atom, rss, xml, json)
3658 * @return array|string
3659 * @throws BadRequestException
3660 * @throws ForbiddenException
3661 * @throws ImagickException
3662 * @throws InternalServerErrorException
3663 * @throws UnauthorizedException
3664 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3666 function api_followers_ids($type)
3668 return api_ff_ids($type, Contact::FOLLOWER);
3671 /// @TODO move to top of file or somewhere better
3672 api_register_func('api/friends/ids', 'api_friends_ids', true);
3673 api_register_func('api/followers/ids', 'api_followers_ids', true);
3676 * Sends a new direct message.
3678 * @param string $type Return type (atom, rss, xml, json)
3680 * @return array|string
3681 * @throws BadRequestException
3682 * @throws ForbiddenException
3683 * @throws ImagickException
3684 * @throws InternalServerErrorException
3685 * @throws NotFoundException
3686 * @throws UnauthorizedException
3687 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3689 function api_direct_messages_new($type)
3693 if (api_user() === false) {
3694 throw new ForbiddenException();
3697 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3701 $sender = api_get_user($a);
3704 if (!empty($_POST['screen_name'])) {
3706 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3708 DBA::escape($_POST['screen_name'])
3711 if (DBA::isResult($r)) {
3712 // Selecting the id by priority, friendica first
3713 api_best_nickname($r);
3715 $recipient = api_get_user($a, $r[0]['nurl']);
3718 $recipient = api_get_user($a, $_POST['user_id']);
3721 if (empty($recipient)) {
3722 throw new NotFoundException('Recipient not found');
3726 if (!empty($_REQUEST['replyto'])) {
3728 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3730 intval($_REQUEST['replyto'])
3732 $replyto = $r[0]['parent-uri'];
3733 $sub = $r[0]['title'];
3735 if (!empty($_REQUEST['title'])) {
3736 $sub = $_REQUEST['title'];
3738 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3742 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3745 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3746 $ret = api_format_messages($r[0], $recipient, $sender);
3748 $ret = ["error"=>$id];
3751 $data = ['direct_message'=>$ret];
3757 $data = api_rss_extra($a, $data, $sender);
3761 return api_format_data("direct-messages", $type, $data);
3764 /// @TODO move to top of file or somewhere better
3765 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3768 * delete a direct_message from mail table through api
3770 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3771 * @return string|array
3772 * @throws BadRequestException
3773 * @throws ForbiddenException
3774 * @throws ImagickException
3775 * @throws InternalServerErrorException
3776 * @throws UnauthorizedException
3777 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3779 function api_direct_messages_destroy($type)
3783 if (api_user() === false) {
3784 throw new ForbiddenException();
3788 $user_info = api_get_user($a);
3790 $id = $_REQUEST['id'] ?? 0;
3792 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3793 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3794 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3796 $uid = $user_info['uid'];
3797 // error if no id or parenturi specified (for clients posting parent-uri as well)
3798 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3799 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3800 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3803 // BadRequestException if no id specified (for clients using Twitter API)
3805 throw new BadRequestException('Message id not specified');
3808 // add parent-uri to sql command if specified by calling app
3809 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3811 // get data of the specified message id
3813 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3818 // error message if specified id is not in database
3819 if (!DBA::isResult($r)) {
3820 if ($verbose == "true") {
3821 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3822 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3824 /// @todo BadRequestException ok for Twitter API clients?
3825 throw new BadRequestException('message id not in database');
3830 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3835 if ($verbose == "true") {
3838 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3839 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3841 $answer = ['result' => 'error', 'message' => 'unknown error'];
3842 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3845 /// @todo return JSON data like Twitter API not yet implemented
3848 /// @TODO move to top of file or somewhere better
3849 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3854 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3855 * @return string|array
3856 * @throws BadRequestException
3857 * @throws ForbiddenException
3858 * @throws ImagickException
3859 * @throws InternalServerErrorException
3860 * @throws NotFoundException
3861 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3863 function api_friendships_destroy($type)
3867 if ($uid === false) {
3868 throw new ForbiddenException();
3871 $contact_id = $_REQUEST['user_id'] ?? 0;
3873 if (empty($contact_id)) {
3874 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3875 throw new BadRequestException("no user_id specified");
3878 // Get Contact by given id
3879 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3881 if(!DBA::isResult($contact)) {
3882 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3883 throw new NotFoundException("no contact found to given ID");
3886 $url = $contact["url"];
3888 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3889 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3890 Strings::normaliseLink($url), $url];
3891 $contact = DBA::selectFirst('contact', [], $condition);
3893 if (!DBA::isResult($contact)) {
3894 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3895 throw new NotFoundException("Not following Contact");
3898 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3899 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3900 throw new ExpectationFailedException("Not supported");
3903 $dissolve = ($contact['rel'] == Contact::SHARING);
3905 $owner = User::getOwnerDataById($uid);
3907 Contact::terminateFriendship($owner, $contact, $dissolve);
3910 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3911 throw new NotFoundException("Error Processing Request");
3914 // Sharing-only contacts get deleted as there no relationship any more
3916 Contact::remove($contact['id']);
3918 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3921 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3922 unset($contact["uid"]);
3923 unset($contact["self"]);
3925 // Set screen_name since Twidere requests it
3926 $contact["screen_name"] = $contact["nick"];
3928 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3930 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3934 * @param string $type Return type (atom, rss, xml, json)
3935 * @param string $box
3936 * @param string $verbose
3938 * @return array|string
3939 * @throws BadRequestException
3940 * @throws ForbiddenException
3941 * @throws ImagickException
3942 * @throws InternalServerErrorException
3943 * @throws UnauthorizedException
3945 function api_direct_messages_box($type, $box, $verbose)
3948 if (api_user() === false) {
3949 throw new ForbiddenException();
3952 $count = $_GET['count'] ?? 20;
3953 $page = $_REQUEST['page'] ?? 1;
3955 $since_id = $_REQUEST['since_id'] ?? 0;
3956 $max_id = $_REQUEST['max_id'] ?? 0;
3958 $user_id = $_REQUEST['user_id'] ?? '';
3959 $screen_name = $_REQUEST['screen_name'] ?? '';
3962 unset($_REQUEST["user_id"]);
3963 unset($_GET["user_id"]);
3965 unset($_REQUEST["screen_name"]);
3966 unset($_GET["screen_name"]);
3968 $user_info = api_get_user($a);
3969 if ($user_info === false) {
3970 throw new ForbiddenException();
3972 $profile_url = $user_info["url"];
3975 $start = max(0, ($page - 1) * $count);
3980 if ($box=="sentbox") {
3981 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3982 } elseif ($box == "conversation") {
3983 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3984 } elseif ($box == "all") {
3985 $sql_extra = "true";
3986 } elseif ($box == "inbox") {
3987 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3991 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3994 if ($user_id != "") {
3995 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3996 } elseif ($screen_name !="") {
3997 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4001 "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",
4007 if ($verbose == "true" && !DBA::isResult($r)) {
4008 $answer = ['result' => 'error', 'message' => 'no mails available'];
4009 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4013 foreach ($r as $item) {
4014 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4015 $recipient = $user_info;
4016 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4017 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4018 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4019 $sender = $user_info;
4022 if (isset($recipient) && isset($sender)) {
4023 $ret[] = api_format_messages($item, $recipient, $sender);
4028 $data = ['direct_message' => $ret];
4033 $data = api_rss_extra($a, $data, $user_info);
4037 return api_format_data("direct-messages", $type, $data);
4041 * Returns the most recent direct messages sent by the user.
4043 * @param string $type Return type (atom, rss, xml, json)
4045 * @return array|string
4046 * @throws BadRequestException
4047 * @throws ForbiddenException
4048 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4050 function api_direct_messages_sentbox($type)
4052 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4053 return api_direct_messages_box($type, "sentbox", $verbose);
4057 * Returns the most recent direct messages sent to the user.
4059 * @param string $type Return type (atom, rss, xml, json)
4061 * @return array|string
4062 * @throws BadRequestException
4063 * @throws ForbiddenException
4064 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4066 function api_direct_messages_inbox($type)
4068 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4069 return api_direct_messages_box($type, "inbox", $verbose);
4074 * @param string $type Return type (atom, rss, xml, json)
4076 * @return array|string
4077 * @throws BadRequestException
4078 * @throws ForbiddenException
4080 function api_direct_messages_all($type)
4082 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4083 return api_direct_messages_box($type, "all", $verbose);
4088 * @param string $type Return type (atom, rss, xml, json)
4090 * @return array|string
4091 * @throws BadRequestException
4092 * @throws ForbiddenException
4094 function api_direct_messages_conversation($type)
4096 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4097 return api_direct_messages_box($type, "conversation", $verbose);
4100 /// @TODO move to top of file or somewhere better
4101 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4102 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4103 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4104 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4107 * Returns an OAuth Request Token.
4109 * @see https://oauth.net/core/1.0/#auth_step1
4111 function api_oauth_request_token()
4113 $oauth1 = new FKOAuth1();
4115 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4116 } catch (Exception $e) {
4117 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4125 * Returns an OAuth Access Token.
4127 * @return array|string
4128 * @see https://oauth.net/core/1.0/#auth_step3
4130 function api_oauth_access_token()
4132 $oauth1 = new FKOAuth1();
4134 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4135 } catch (Exception $e) {
4136 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4143 /// @TODO move to top of file or somewhere better
4144 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4145 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4149 * delete a complete photoalbum with all containing photos from database through api
4151 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4152 * @return string|array
4153 * @throws BadRequestException
4154 * @throws ForbiddenException
4155 * @throws InternalServerErrorException
4157 function api_fr_photoalbum_delete($type)
4159 if (api_user() === false) {
4160 throw new ForbiddenException();
4163 $album = $_REQUEST['album'] ?? '';
4165 // we do not allow calls without album string
4167 throw new BadRequestException("no albumname specified");
4169 // check if album is existing
4171 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4175 if (!DBA::isResult($r)) {
4176 throw new BadRequestException("album not available");
4179 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4180 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4181 foreach ($r as $rr) {
4182 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4183 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4185 if (!DBA::isResult($photo_item)) {
4186 throw new InternalServerErrorException("problem with deleting items occured");
4188 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4191 // now let's delete all photos from the album
4192 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4194 // return success of deletion or error message
4196 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4197 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4199 throw new InternalServerErrorException("unknown error - deleting from database failed");
4204 * update the name of the album for all photos of an album
4206 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4207 * @return string|array
4208 * @throws BadRequestException
4209 * @throws ForbiddenException
4210 * @throws InternalServerErrorException
4212 function api_fr_photoalbum_update($type)
4214 if (api_user() === false) {
4215 throw new ForbiddenException();
4218 $album = $_REQUEST['album'] ?? '';
4219 $album_new = $_REQUEST['album_new'] ?? '';
4221 // we do not allow calls without album string
4223 throw new BadRequestException("no albumname specified");
4225 if ($album_new == "") {
4226 throw new BadRequestException("no new albumname specified");
4228 // check if album is existing
4229 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4230 throw new BadRequestException("album not available");
4232 // now let's update all photos to the albumname
4233 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4235 // return success of updating or error message
4237 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4238 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4240 throw new InternalServerErrorException("unknown error - updating in database failed");
4246 * list all photos of the authenticated user
4248 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4249 * @return string|array
4250 * @throws ForbiddenException
4251 * @throws InternalServerErrorException
4253 function api_fr_photos_list($type)
4255 if (api_user() === false) {
4256 throw new ForbiddenException();
4259 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4260 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4261 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4262 intval(local_user())
4265 'image/jpeg' => 'jpg',
4266 'image/png' => 'png',
4267 'image/gif' => 'gif'
4269 $data = ['photo'=>[]];
4270 if (DBA::isResult($r)) {
4271 foreach ($r as $rr) {
4273 $photo['id'] = $rr['resource-id'];
4274 $photo['album'] = $rr['album'];
4275 $photo['filename'] = $rr['filename'];
4276 $photo['type'] = $rr['type'];
4277 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4278 $photo['created'] = $rr['created'];
4279 $photo['edited'] = $rr['edited'];
4280 $photo['desc'] = $rr['desc'];
4282 if ($type == "xml") {
4283 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4285 $photo['thumb'] = $thumb;
4286 $data['photo'][] = $photo;
4290 return api_format_data("photos", $type, $data);
4294 * upload a new photo or change an existing photo
4296 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4297 * @return string|array
4298 * @throws BadRequestException
4299 * @throws ForbiddenException
4300 * @throws ImagickException
4301 * @throws InternalServerErrorException
4302 * @throws NotFoundException
4304 function api_fr_photo_create_update($type)
4306 if (api_user() === false) {
4307 throw new ForbiddenException();
4310 $photo_id = $_REQUEST['photo_id'] ?? null;
4311 $desc = $_REQUEST['desc'] ?? null;
4312 $album = $_REQUEST['album'] ?? null;
4313 $album_new = $_REQUEST['album_new'] ?? null;
4314 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4315 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4316 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4317 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4318 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4320 // do several checks on input parameters
4321 // we do not allow calls without album string
4322 if ($album == null) {
4323 throw new BadRequestException("no albumname specified");
4325 // if photo_id == null --> we are uploading a new photo
4326 if ($photo_id == null) {
4329 // error if no media posted in create-mode
4330 if (empty($_FILES['media'])) {
4332 throw new BadRequestException("no media data submitted");
4335 // album_new will be ignored in create-mode
4340 // check if photo is existing in databasei
4341 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4342 throw new BadRequestException("photo not available");
4346 // checks on acl strings provided by clients
4347 $acl_input_error = false;
4348 $acl_input_error |= check_acl_input($allow_cid);
4349 $acl_input_error |= check_acl_input($deny_cid);
4350 $acl_input_error |= check_acl_input($allow_gid);
4351 $acl_input_error |= check_acl_input($deny_gid);
4352 if ($acl_input_error) {
4353 throw new BadRequestException("acl data invalid");
4355 // now let's upload the new media in create-mode
4356 if ($mode == "create") {
4357 $media = $_FILES['media'];
4358 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4360 // return success of updating or error message
4361 if (!is_null($data)) {
4362 return api_format_data("photo_create", $type, $data);
4364 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4368 // now let's do the changes in update-mode
4369 if ($mode == "update") {
4370 $updated_fields = [];
4372 if (!is_null($desc)) {
4373 $updated_fields['desc'] = $desc;
4376 if (!is_null($album_new)) {
4377 $updated_fields['album'] = $album_new;
4380 if (!is_null($allow_cid)) {
4381 $allow_cid = trim($allow_cid);
4382 $updated_fields['allow_cid'] = $allow_cid;
4385 if (!is_null($deny_cid)) {
4386 $deny_cid = trim($deny_cid);
4387 $updated_fields['deny_cid'] = $deny_cid;
4390 if (!is_null($allow_gid)) {
4391 $allow_gid = trim($allow_gid);
4392 $updated_fields['allow_gid'] = $allow_gid;
4395 if (!is_null($deny_gid)) {
4396 $deny_gid = trim($deny_gid);
4397 $updated_fields['deny_gid'] = $deny_gid;
4401 if (count($updated_fields) > 0) {
4402 $nothingtodo = false;
4403 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4405 $nothingtodo = true;
4408 if (!empty($_FILES['media'])) {
4409 $nothingtodo = false;
4410 $media = $_FILES['media'];
4411 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4412 if (!is_null($data)) {
4413 return api_format_data("photo_update", $type, $data);
4417 // return success of updating or error message
4419 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4420 return api_format_data("photo_update", $type, ['$result' => $answer]);
4423 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4424 return api_format_data("photo_update", $type, ['$result' => $answer]);
4426 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4429 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4433 * delete a single photo from the database through api
4435 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4436 * @return string|array
4437 * @throws BadRequestException
4438 * @throws ForbiddenException
4439 * @throws InternalServerErrorException
4441 function api_fr_photo_delete($type)
4443 if (api_user() === false) {
4444 throw new ForbiddenException();
4448 $photo_id = $_REQUEST['photo_id'] ?? null;
4450 // do several checks on input parameters
4451 // we do not allow calls without photo id
4452 if ($photo_id == null) {
4453 throw new BadRequestException("no photo_id specified");
4456 // check if photo is existing in database
4457 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4458 throw new BadRequestException("photo not available");
4461 // now we can perform on the deletion of the photo
4462 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4464 // return success of deletion or error message
4466 // retrieve the id of the parent element (the photo element)
4467 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4468 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4470 if (!DBA::isResult($photo_item)) {
4471 throw new InternalServerErrorException("problem with deleting items occured");
4473 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4474 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4475 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4477 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4478 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4480 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4486 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4488 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4489 * @return string|array
4490 * @throws BadRequestException
4491 * @throws ForbiddenException
4492 * @throws InternalServerErrorException
4493 * @throws NotFoundException
4495 function api_fr_photo_detail($type)
4497 if (api_user() === false) {
4498 throw new ForbiddenException();
4500 if (empty($_REQUEST['photo_id'])) {
4501 throw new BadRequestException("No photo id.");
4504 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4505 $photo_id = $_REQUEST['photo_id'];
4507 // prepare json/xml output with data from database for the requested photo
4508 $data = prepare_photo_data($type, $scale, $photo_id);
4510 return api_format_data("photo_detail", $type, $data);
4515 * updates the profile image for the user (either a specified profile or the default profile)
4517 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4519 * @return string|array
4520 * @throws BadRequestException
4521 * @throws ForbiddenException
4522 * @throws ImagickException
4523 * @throws InternalServerErrorException
4524 * @throws NotFoundException
4525 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4527 function api_account_update_profile_image($type)
4529 if (api_user() === false) {
4530 throw new ForbiddenException();
4533 $profile_id = $_REQUEST['profile_id'] ?? 0;
4535 // error if image data is missing
4536 if (empty($_FILES['image'])) {
4537 throw new BadRequestException("no media data submitted");
4540 // check if specified profile id is valid
4541 if ($profile_id != 0) {
4542 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4543 // error message if specified profile id is not in database
4544 if (!DBA::isResult($profile)) {
4545 throw new BadRequestException("profile_id not available");
4547 $is_default_profile = $profile['is-default'];
4549 $is_default_profile = 1;
4552 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4554 if (!empty($_FILES['image'])) {
4555 $media = $_FILES['image'];
4556 } elseif (!empty($_FILES['media'])) {
4557 $media = $_FILES['media'];
4559 // save new profile image
4560 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4563 if (is_array($media['type'])) {
4564 $filetype = $media['type'][0];
4566 $filetype = $media['type'];
4568 if ($filetype == "image/jpeg") {
4570 } elseif ($filetype == "image/png") {
4573 throw new InternalServerErrorException('Unsupported filetype');
4576 // change specified profile or all profiles to the new resource-id
4577 if ($is_default_profile) {
4578 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4579 Photo::update(['profile' => false], $condition);
4581 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4582 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4583 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4586 Contact::updateSelfFromUserID(api_user(), true);
4588 // Update global directory in background
4589 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4590 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4591 Worker::add(PRIORITY_LOW, "Directory", $url);
4594 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4596 // output for client
4598 return api_account_verify_credentials($type);
4600 // SaveMediaToDatabase failed for some reason
4601 throw new InternalServerErrorException("image upload failed");
4605 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4606 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4607 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4608 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4609 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4610 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4611 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4612 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4613 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4616 * Update user profile
4618 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4620 * @return array|string
4621 * @throws BadRequestException
4622 * @throws ForbiddenException
4623 * @throws ImagickException
4624 * @throws InternalServerErrorException
4625 * @throws UnauthorizedException
4627 function api_account_update_profile($type)
4629 $local_user = api_user();
4630 $api_user = api_get_user(DI::app());
4632 if (!empty($_POST['name'])) {
4633 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4634 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4635 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4636 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4639 if (isset($_POST['description'])) {
4640 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4641 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4642 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4645 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4646 // Update global directory in background
4647 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4648 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4651 return api_account_verify_credentials($type);
4654 /// @TODO move to top of file or somewhere better
4655 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4659 * @param string $acl_string
4663 function check_acl_input($acl_string)
4665 if (empty($acl_string)) {
4669 $contact_not_found = false;
4671 // split <x><y><z> into array of cid's
4672 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4674 // check for each cid if it is available on server
4675 $cid_array = $array[0];
4676 foreach ($cid_array as $cid) {
4677 $cid = str_replace("<", "", $cid);
4678 $cid = str_replace(">", "", $cid);
4679 $condition = ['id' => $cid, 'uid' => api_user()];
4680 $contact_not_found |= !DBA::exists('contact', $condition);
4682 return $contact_not_found;
4686 * @param string $mediatype
4687 * @param array $media
4688 * @param string $type
4689 * @param string $album
4690 * @param string $allow_cid
4691 * @param string $deny_cid
4692 * @param string $allow_gid
4693 * @param string $deny_gid
4694 * @param string $desc
4695 * @param integer $profile
4696 * @param boolean $visibility
4697 * @param string $photo_id
4699 * @throws BadRequestException
4700 * @throws ForbiddenException
4701 * @throws ImagickException
4702 * @throws InternalServerErrorException
4703 * @throws NotFoundException
4704 * @throws UnauthorizedException
4706 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)
4714 if (is_array($media)) {
4715 if (is_array($media['tmp_name'])) {
4716 $src = $media['tmp_name'][0];
4718 $src = $media['tmp_name'];
4720 if (is_array($media['name'])) {
4721 $filename = basename($media['name'][0]);
4723 $filename = basename($media['name']);
4725 if (is_array($media['size'])) {
4726 $filesize = intval($media['size'][0]);
4728 $filesize = intval($media['size']);
4730 if (is_array($media['type'])) {
4731 $filetype = $media['type'][0];
4733 $filetype = $media['type'];
4737 if ($filetype == "") {
4738 $filetype = Images::guessType($filename);
4740 $imagedata = @getimagesize($src);
4742 $filetype = $imagedata['mime'];
4745 "File upload src: " . $src . " - filename: " . $filename .
4746 " - size: " . $filesize . " - type: " . $filetype,
4750 // check if there was a php upload error
4751 if ($filesize == 0 && $media['error'] == 1) {
4752 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4754 // check against max upload size within Friendica instance
4755 $maximagesize = DI::config()->get('system', 'maximagesize');
4756 if ($maximagesize && ($filesize > $maximagesize)) {
4757 $formattedBytes = Strings::formatBytes($maximagesize);
4758 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4761 // create Photo instance with the data of the image
4762 $imagedata = @file_get_contents($src);
4763 $Image = new Image($imagedata, $filetype);
4764 if (!$Image->isValid()) {
4765 throw new InternalServerErrorException("unable to process image data");
4768 // check orientation of image
4769 $Image->orient($src);
4772 // check max length of images on server
4773 $max_length = DI::config()->get('system', 'max_image_length');
4775 $max_length = MAX_IMAGE_LENGTH;
4777 if ($max_length > 0) {
4778 $Image->scaleDown($max_length);
4779 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4781 $width = $Image->getWidth();
4782 $height = $Image->getHeight();
4784 // create a new resource-id if not already provided
4785 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4787 if ($mediatype == "photo") {
4788 // upload normal image (scales 0, 1, 2)
4789 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4791 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4793 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4795 if ($width > 640 || $height > 640) {
4796 $Image->scaleDown(640);
4797 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4799 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4803 if ($width > 320 || $height > 320) {
4804 $Image->scaleDown(320);
4805 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4807 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4810 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4811 } elseif ($mediatype == "profileimage") {
4812 // upload profile image (scales 4, 5, 6)
4813 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4815 if ($width > 300 || $height > 300) {
4816 $Image->scaleDown(300);
4817 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4819 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4823 if ($width > 80 || $height > 80) {
4824 $Image->scaleDown(80);
4825 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4827 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4831 if ($width > 48 || $height > 48) {
4832 $Image->scaleDown(48);
4833 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4835 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4838 $Image->__destruct();
4839 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4842 if (isset($r) && $r) {
4843 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4844 if ($photo_id == null && $mediatype == "photo") {
4845 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4847 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4848 return prepare_photo_data($type, false, $resource_id);
4850 throw new InternalServerErrorException("image upload failed");
4856 * @param string $hash
4857 * @param string $allow_cid
4858 * @param string $deny_cid
4859 * @param string $allow_gid
4860 * @param string $deny_gid
4861 * @param string $filetype
4862 * @param boolean $visibility
4863 * @throws InternalServerErrorException
4865 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4867 // get data about the api authenticated user
4868 $uri = Item::newURI(intval(api_user()));
4869 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4872 $arr['guid'] = System::createUUID();
4873 $arr['uid'] = intval(api_user());
4875 $arr['parent-uri'] = $uri;
4876 $arr['type'] = 'photo';
4878 $arr['resource-id'] = $hash;
4879 $arr['contact-id'] = $owner_record['id'];
4880 $arr['owner-name'] = $owner_record['name'];
4881 $arr['owner-link'] = $owner_record['url'];
4882 $arr['owner-avatar'] = $owner_record['thumb'];
4883 $arr['author-name'] = $owner_record['name'];
4884 $arr['author-link'] = $owner_record['url'];
4885 $arr['author-avatar'] = $owner_record['thumb'];
4887 $arr['allow_cid'] = $allow_cid;
4888 $arr['allow_gid'] = $allow_gid;
4889 $arr['deny_cid'] = $deny_cid;
4890 $arr['deny_gid'] = $deny_gid;
4891 $arr['visible'] = $visibility;
4895 'image/jpeg' => 'jpg',
4896 'image/png' => 'png',
4897 'image/gif' => 'gif'
4900 // adds link to the thumbnail scale photo
4901 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4902 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4905 // do the magic for storing the item in the database and trigger the federation to other contacts
4911 * @param string $type
4913 * @param string $photo_id
4916 * @throws BadRequestException
4917 * @throws ForbiddenException
4918 * @throws ImagickException
4919 * @throws InternalServerErrorException
4920 * @throws NotFoundException
4921 * @throws UnauthorizedException
4923 function prepare_photo_data($type, $scale, $photo_id)
4926 $user_info = api_get_user($a);
4928 if ($user_info === false) {
4929 throw new ForbiddenException();
4932 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4933 $data_sql = ($scale === false ? "" : "data, ");
4935 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4936 // clients needs to convert this in their way for further processing
4938 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4939 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4940 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4941 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4942 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4943 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4945 intval(local_user()),
4946 DBA::escape($photo_id),
4951 'image/jpeg' => 'jpg',
4952 'image/png' => 'png',
4953 'image/gif' => 'gif'
4956 // prepare output data for photo
4957 if (DBA::isResult($r)) {
4958 $data = ['photo' => $r[0]];
4959 $data['photo']['id'] = $data['photo']['resource-id'];
4960 if ($scale !== false) {
4961 $data['photo']['data'] = base64_encode($data['photo']['data']);
4963 unset($data['photo']['datasize']); //needed only with scale param
4965 if ($type == "xml") {
4966 $data['photo']['links'] = [];
4967 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4968 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4970 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4973 $data['photo']['link'] = [];
4974 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4976 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4977 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4981 unset($data['photo']['resource-id']);
4982 unset($data['photo']['minscale']);
4983 unset($data['photo']['maxscale']);
4985 throw new NotFoundException();
4988 // retrieve item element for getting activities (like, dislike etc.) related to photo
4989 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4990 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4991 if (!DBA::isResult($item)) {
4992 throw new NotFoundException('Photo-related item not found.');
4995 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4997 // retrieve comments on photo
4998 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4999 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5001 $statuses = Item::selectForUser(api_user(), [], $condition);
5003 // prepare output of comments
5004 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5006 if ($type == "xml") {
5008 foreach ($commentData as $comment) {
5009 $comments[$k++ . ":comment"] = $comment;
5012 foreach ($commentData as $comment) {
5013 $comments[] = $comment;
5016 $data['photo']['friendica_comments'] = $comments;
5018 // include info if rights on photo and rights on item are mismatching
5019 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5020 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5021 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5022 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5023 $data['photo']['rights_mismatch'] = $rights_mismatch;
5030 * Similar as /mod/redir.php
5031 * redirect to 'url' after dfrn auth
5033 * Why this when there is mod/redir.php already?
5034 * This use api_user() and api_login()
5037 * c_url: url of remote contact to auth to
5038 * url: string, url to redirect after auth
5040 function api_friendica_remoteauth()
5042 $url = $_GET['url'] ?? '';
5043 $c_url = $_GET['c_url'] ?? '';
5045 if ($url === '' || $c_url === '') {
5046 throw new BadRequestException("Wrong parameters.");
5049 $c_url = Strings::normaliseLink($c_url);
5053 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5054 if (!DBA::isResult($contact)) {
5055 throw new BadRequestException("Unknown contact");
5058 $cid = $contact['id'];
5060 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5062 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5063 System::externalRedirect($url ?: $c_url);
5066 if ($contact['duplex'] && $contact['issued-id']) {
5067 $orig_id = $contact['issued-id'];
5068 $dfrn_id = '1:' . $orig_id;
5070 if ($contact['duplex'] && $contact['dfrn-id']) {
5071 $orig_id = $contact['dfrn-id'];
5072 $dfrn_id = '0:' . $orig_id;
5075 $sec = Strings::getRandomHex();
5077 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5078 'sec' => $sec, 'expire' => time() + 45];
5079 DBA::insert('profile_check', $fields);
5081 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5082 $dest = ($url ? '&destination_url=' . $url : '');
5084 System::externalRedirect(
5085 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5086 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5087 . '&type=profile&sec=' . $sec . $dest
5090 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5093 * Return an item with announcer data if it had been announced
5095 * @param array $item Item array
5096 * @return array Item array with announce data
5098 function api_get_announce($item)
5100 // Quit if the item already has got a different owner and author
5101 if ($item['owner-id'] != $item['author-id']) {
5105 // Don't change original or Diaspora posts
5106 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5110 // Quit if we do now the original author and it had been a post from a native network
5111 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5115 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5116 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5117 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5118 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5119 if (!DBA::isResult($announce)) {
5123 return array_merge($item, $announce);
5127 * Return the item shared, if the item contains only the [share] tag
5129 * @param array $item Sharer item
5130 * @return array|false Shared item or false if not a reshare
5131 * @throws ImagickException
5132 * @throws InternalServerErrorException
5134 function api_share_as_retweet(&$item)
5136 $body = trim($item["body"]);
5138 if (Diaspora::isReshare($body, false) === false) {
5139 if ($item['author-id'] == $item['owner-id']) {
5142 // Reshares from OStatus, ActivityPub and Twitter
5143 $reshared_item = $item;
5144 $reshared_item['owner-id'] = $reshared_item['author-id'];
5145 $reshared_item['owner-link'] = $reshared_item['author-link'];
5146 $reshared_item['owner-name'] = $reshared_item['author-name'];
5147 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5148 return $reshared_item;
5152 $reshared = Item::getShareArray($item);
5153 if (empty($reshared)) {
5157 $reshared_item = $item;
5159 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5163 if (!empty($reshared['comment'])) {
5164 $item['body'] = $reshared['comment'];
5167 $reshared_item["share-pre-body"] = $reshared['comment'];
5168 $reshared_item["body"] = $reshared['shared'];
5169 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5170 $reshared_item["author-name"] = $reshared['author'];
5171 $reshared_item["author-link"] = $reshared['profile'];
5172 $reshared_item["author-avatar"] = $reshared['avatar'];
5173 $reshared_item["plink"] = $reshared['link'] ?? '';
5174 $reshared_item["created"] = $reshared['posted'];
5175 $reshared_item["edited"] = $reshared['posted'];
5177 // Try to fetch the original item
5178 if (!empty($reshared['guid'])) {
5179 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5180 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5181 $condition = ['id' => $original_id];
5186 if (!empty($condition)) {
5187 $original_item = Item::selectFirst([], $condition);
5188 if (DBA::isResult($original_item)) {
5189 $reshared_item = array_merge($reshared_item, $original_item);
5193 return $reshared_item;
5198 * @param array $item
5203 function api_in_reply_to($item)
5207 $in_reply_to['status_id'] = null;
5208 $in_reply_to['user_id'] = null;
5209 $in_reply_to['status_id_str'] = null;
5210 $in_reply_to['user_id_str'] = null;
5211 $in_reply_to['screen_name'] = null;
5213 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5214 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5215 if (DBA::isResult($parent)) {
5216 $in_reply_to['status_id'] = intval($parent['id']);
5218 $in_reply_to['status_id'] = intval($item['parent']);
5221 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5223 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5224 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5226 if (DBA::isResult($parent)) {
5227 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5228 $in_reply_to['user_id'] = intval($parent['author-id']);
5229 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5232 // There seems to be situation, where both fields are identical:
5233 // https://github.com/friendica/friendica/issues/1010
5234 // This is a bugfix for that.
5235 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5236 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']]);
5237 $in_reply_to['status_id'] = null;
5238 $in_reply_to['user_id'] = null;
5239 $in_reply_to['status_id_str'] = null;
5240 $in_reply_to['user_id_str'] = null;
5241 $in_reply_to['screen_name'] = null;
5245 return $in_reply_to;
5250 * @param string $text
5253 * @throws InternalServerErrorException
5255 function api_clean_plain_items($text)
5257 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5259 $text = BBCode::cleanPictureLinks($text);
5260 $URLSearchString = "^\[\]";
5262 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5264 if ($include_entities == "true") {
5265 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5268 // Simplify "attachment" element
5269 $text = BBCode::removeAttachment($text);
5276 * @param array $contacts
5280 function api_best_nickname(&$contacts)
5284 if (count($contacts) == 0) {
5288 foreach ($contacts as $contact) {
5289 if ($contact["network"] == "") {
5290 $contact["network"] = "dfrn";
5291 $best_contact = [$contact];
5295 if (sizeof($best_contact) == 0) {
5296 foreach ($contacts as $contact) {
5297 if ($contact["network"] == "dfrn") {
5298 $best_contact = [$contact];
5303 if (sizeof($best_contact) == 0) {
5304 foreach ($contacts as $contact) {
5305 if ($contact["network"] == "dspr") {
5306 $best_contact = [$contact];
5311 if (sizeof($best_contact) == 0) {
5312 foreach ($contacts as $contact) {
5313 if ($contact["network"] == "stat") {
5314 $best_contact = [$contact];
5319 if (sizeof($best_contact) == 0) {
5320 foreach ($contacts as $contact) {
5321 if ($contact["network"] == "pump") {
5322 $best_contact = [$contact];
5327 if (sizeof($best_contact) == 0) {
5328 foreach ($contacts as $contact) {
5329 if ($contact["network"] == "twit") {
5330 $best_contact = [$contact];
5335 if (sizeof($best_contact) == 1) {
5336 $contacts = $best_contact;
5338 $contacts = [$contacts[0]];
5343 * Return all or a specified group of the user with the containing contacts.
5345 * @param string $type Return type (atom, rss, xml, json)
5347 * @return array|string
5348 * @throws BadRequestException
5349 * @throws ForbiddenException
5350 * @throws ImagickException
5351 * @throws InternalServerErrorException
5352 * @throws UnauthorizedException
5354 function api_friendica_group_show($type)
5358 if (api_user() === false) {
5359 throw new ForbiddenException();
5363 $user_info = api_get_user($a);
5364 $gid = $_REQUEST['gid'] ?? 0;
5365 $uid = $user_info['uid'];
5367 // get data of the specified group id or all groups if not specified
5370 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5374 // error message if specified gid is not in database
5375 if (!DBA::isResult($r)) {
5376 throw new BadRequestException("gid not available");
5380 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5385 // loop through all groups and retrieve all members for adding data in the user array
5387 foreach ($r as $rr) {
5388 $members = Contact::getByGroupId($rr['id']);
5391 if ($type == "xml") {
5392 $user_element = "users";
5394 foreach ($members as $member) {
5395 $user = api_get_user($a, $member['nurl']);
5396 $users[$k++.":user"] = $user;
5399 $user_element = "user";
5400 foreach ($members as $member) {
5401 $user = api_get_user($a, $member['nurl']);
5405 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5407 return api_format_data("groups", $type, ['group' => $grps]);
5409 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5413 * Delete the specified group of the user.
5415 * @param string $type Return type (atom, rss, xml, json)
5417 * @return array|string
5418 * @throws BadRequestException
5419 * @throws ForbiddenException
5420 * @throws ImagickException
5421 * @throws InternalServerErrorException
5422 * @throws UnauthorizedException
5424 function api_friendica_group_delete($type)
5428 if (api_user() === false) {
5429 throw new ForbiddenException();
5433 $user_info = api_get_user($a);
5434 $gid = $_REQUEST['gid'] ?? 0;
5435 $name = $_REQUEST['name'] ?? '';
5436 $uid = $user_info['uid'];
5438 // error if no gid specified
5439 if ($gid == 0 || $name == "") {
5440 throw new BadRequestException('gid or name not specified');
5443 // get data of the specified group id
5445 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5449 // error message if specified gid is not in database
5450 if (!DBA::isResult($r)) {
5451 throw new BadRequestException('gid not available');
5454 // get data of the specified group id and group name
5456 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5461 // error message if specified gid is not in database
5462 if (!DBA::isResult($rname)) {
5463 throw new BadRequestException('wrong group name');
5467 $ret = Group::removeByName($uid, $name);
5470 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5471 return api_format_data("group_delete", $type, ['result' => $success]);
5473 throw new BadRequestException('other API error');
5476 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5481 * @param string $type Return type (atom, rss, xml, json)
5483 * @return array|string
5484 * @throws BadRequestException
5485 * @throws ForbiddenException
5486 * @throws ImagickException
5487 * @throws InternalServerErrorException
5488 * @throws UnauthorizedException
5489 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5491 function api_lists_destroy($type)
5495 if (api_user() === false) {
5496 throw new ForbiddenException();
5500 $user_info = api_get_user($a);
5501 $gid = $_REQUEST['list_id'] ?? 0;
5502 $uid = $user_info['uid'];
5504 // error if no gid specified
5506 throw new BadRequestException('gid not specified');
5509 // get data of the specified group id
5510 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5511 // error message if specified gid is not in database
5513 throw new BadRequestException('gid not available');
5516 if (Group::remove($gid)) {
5518 'name' => $group['name'],
5519 'id' => intval($gid),
5520 'id_str' => (string) $gid,
5521 'user' => $user_info
5524 return api_format_data("lists", $type, ['lists' => $list]);
5527 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5530 * Add a new group to the database.
5532 * @param string $name Group name
5533 * @param int $uid User ID
5534 * @param array $users List of users to add to the group
5537 * @throws BadRequestException
5539 function group_create($name, $uid, $users = [])
5541 // error if no name specified
5543 throw new BadRequestException('group name not specified');
5546 // get data of the specified group name
5548 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5552 // error message if specified group name already exists
5553 if (DBA::isResult($rname)) {
5554 throw new BadRequestException('group name already exists');
5557 // check if specified group name is a deleted group
5559 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5563 // error message if specified group name already exists
5564 if (DBA::isResult($rname)) {
5565 $reactivate_group = true;
5569 $ret = Group::create($uid, $name);
5571 $gid = Group::getIdByName($uid, $name);
5573 throw new BadRequestException('other API error');
5577 $erroraddinguser = false;
5579 foreach ($users as $user) {
5580 $cid = $user['cid'];
5581 // check if user really exists as contact
5583 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5587 if (count($contact)) {
5588 Group::addMember($gid, $cid);
5590 $erroraddinguser = true;
5591 $errorusers[] = $cid;
5595 // return success message incl. missing users in array
5596 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5598 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5602 * Create the specified group with the posted array of contacts.
5604 * @param string $type Return type (atom, rss, xml, json)
5606 * @return array|string
5607 * @throws BadRequestException
5608 * @throws ForbiddenException
5609 * @throws ImagickException
5610 * @throws InternalServerErrorException
5611 * @throws UnauthorizedException
5613 function api_friendica_group_create($type)
5617 if (api_user() === false) {
5618 throw new ForbiddenException();
5622 $user_info = api_get_user($a);
5623 $name = $_REQUEST['name'] ?? '';
5624 $uid = $user_info['uid'];
5625 $json = json_decode($_POST['json'], true);
5626 $users = $json['user'];
5628 $success = group_create($name, $uid, $users);
5630 return api_format_data("group_create", $type, ['result' => $success]);
5632 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5635 * Create a new group.
5637 * @param string $type Return type (atom, rss, xml, json)
5639 * @return array|string
5640 * @throws BadRequestException
5641 * @throws ForbiddenException
5642 * @throws ImagickException
5643 * @throws InternalServerErrorException
5644 * @throws UnauthorizedException
5645 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5647 function api_lists_create($type)
5651 if (api_user() === false) {
5652 throw new ForbiddenException();
5656 $user_info = api_get_user($a);
5657 $name = $_REQUEST['name'] ?? '';
5658 $uid = $user_info['uid'];
5660 $success = group_create($name, $uid);
5661 if ($success['success']) {
5663 'name' => $success['name'],
5664 'id' => intval($success['gid']),
5665 'id_str' => (string) $success['gid'],
5666 'user' => $user_info
5669 return api_format_data("lists", $type, ['lists'=>$grp]);
5672 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5675 * Update the specified group with the posted array of contacts.
5677 * @param string $type Return type (atom, rss, xml, json)
5679 * @return array|string
5680 * @throws BadRequestException
5681 * @throws ForbiddenException
5682 * @throws ImagickException
5683 * @throws InternalServerErrorException
5684 * @throws UnauthorizedException
5686 function api_friendica_group_update($type)
5690 if (api_user() === false) {
5691 throw new ForbiddenException();
5695 $user_info = api_get_user($a);
5696 $uid = $user_info['uid'];
5697 $gid = $_REQUEST['gid'] ?? 0;
5698 $name = $_REQUEST['name'] ?? '';
5699 $json = json_decode($_POST['json'], true);
5700 $users = $json['user'];
5702 // error if no name specified
5704 throw new BadRequestException('group name not specified');
5707 // error if no gid specified
5709 throw new BadRequestException('gid not specified');
5713 $members = Contact::getByGroupId($gid);
5714 foreach ($members as $member) {
5715 $cid = $member['id'];
5716 foreach ($users as $user) {
5717 $found = ($user['cid'] == $cid ? true : false);
5719 if (!isset($found) || !$found) {
5720 Group::removeMemberByName($uid, $name, $cid);
5725 $erroraddinguser = false;
5727 foreach ($users as $user) {
5728 $cid = $user['cid'];
5729 // check if user really exists as contact
5731 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5736 if (count($contact)) {
5737 Group::addMember($gid, $cid);
5739 $erroraddinguser = true;
5740 $errorusers[] = $cid;
5744 // return success message incl. missing users in array
5745 $status = ($erroraddinguser ? "missing user" : "ok");
5746 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5747 return api_format_data("group_update", $type, ['result' => $success]);
5750 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5753 * Update information about a group.
5755 * @param string $type Return type (atom, rss, xml, json)
5757 * @return array|string
5758 * @throws BadRequestException
5759 * @throws ForbiddenException
5760 * @throws ImagickException
5761 * @throws InternalServerErrorException
5762 * @throws UnauthorizedException
5763 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5765 function api_lists_update($type)
5769 if (api_user() === false) {
5770 throw new ForbiddenException();
5774 $user_info = api_get_user($a);
5775 $gid = $_REQUEST['list_id'] ?? 0;
5776 $name = $_REQUEST['name'] ?? '';
5777 $uid = $user_info['uid'];
5779 // error if no gid specified
5781 throw new BadRequestException('gid not specified');
5784 // get data of the specified group id
5785 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5786 // error message if specified gid is not in database
5788 throw new BadRequestException('gid not available');
5791 if (Group::update($gid, $name)) {
5794 'id' => intval($gid),
5795 'id_str' => (string) $gid,
5796 'user' => $user_info
5799 return api_format_data("lists", $type, ['lists' => $list]);
5803 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5807 * @param string $type Return type (atom, rss, xml, json)
5809 * @return array|string
5810 * @throws BadRequestException
5811 * @throws ForbiddenException
5812 * @throws ImagickException
5813 * @throws InternalServerErrorException
5815 function api_friendica_activity($type)
5819 if (api_user() === false) {
5820 throw new ForbiddenException();
5822 $verb = strtolower($a->argv[3]);
5823 $verb = preg_replace("|\..*$|", "", $verb);
5825 $id = $_REQUEST['id'] ?? 0;
5827 $res = Item::performActivity($id, $verb);
5830 if ($type == "xml") {
5835 return api_format_data('ok', $type, ['ok' => $ok]);
5837 throw new BadRequestException('Error adding activity');
5841 /// @TODO move to top of file or somewhere better
5842 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5843 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5844 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5845 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5846 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5847 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5848 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5849 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5850 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5851 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5854 * Returns notifications
5856 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5858 * @return string|array
5859 * @throws ForbiddenException
5860 * @throws BadRequestException
5863 function api_friendica_notification($type)
5867 if (api_user() === false) {
5868 throw new ForbiddenException();
5871 throw new BadRequestException("Invalid argument count");
5874 $notifications = DI::notification()->getApiList(local_user());
5876 if ($type == "xml") {
5878 if (!empty($notifications)) {
5879 foreach ($notifications as $notification) {
5880 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5884 $result = $xmlnotes;
5885 } elseif (count($notifications) > 0) {
5886 $result = $notifications->getArrayCopy();
5891 return api_format_data("notes", $type, ['note' => $result]);
5895 * Set notification as seen and returns associated item (if possible)
5897 * POST request with 'id' param as notification id
5899 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5900 * @return string|array
5901 * @throws BadRequestException
5902 * @throws ForbiddenException
5903 * @throws ImagickException
5904 * @throws InternalServerErrorException
5905 * @throws UnauthorizedException
5907 function api_friendica_notification_seen($type)
5910 $user_info = api_get_user($a);
5912 if (api_user() === false || $user_info === false) {
5913 throw new ForbiddenException();
5915 if ($a->argc !== 4) {
5916 throw new BadRequestException("Invalid argument count");
5919 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5922 $notify = DI::notify()->getByID($id, api_user());
5923 DI::notify()->setSeen(true, $notify);
5925 if ($notify->otype === Notify\ObjectType::ITEM) {
5926 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5927 if (DBA::isResult($item)) {
5928 // we found the item, return it to the user
5929 $ret = api_format_items([$item], $user_info, false, $type);
5930 $data = ['status' => $ret];
5931 return api_format_data("status", $type, $data);
5933 // the item can't be found, but we set the notification as seen, so we count this as a success
5935 return api_format_data('result', $type, ['result' => "success"]);
5936 } catch (NotFoundException $e) {
5937 throw new BadRequestException('Invalid argument', $e);
5938 } catch (Exception $e) {
5939 throw new InternalServerErrorException('Internal Server exception', $e);
5943 /// @TODO move to top of file or somewhere better
5944 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5945 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5948 * update a direct_message to seen state
5950 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5951 * @return string|array (success result=ok, error result=error with error message)
5952 * @throws BadRequestException
5953 * @throws ForbiddenException
5954 * @throws ImagickException
5955 * @throws InternalServerErrorException
5956 * @throws UnauthorizedException
5958 function api_friendica_direct_messages_setseen($type)
5961 if (api_user() === false) {
5962 throw new ForbiddenException();
5966 $user_info = api_get_user($a);
5967 $uid = $user_info['uid'];
5968 $id = $_REQUEST['id'] ?? 0;
5970 // return error if id is zero
5972 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5973 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5976 // error message if specified id is not in database
5977 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5978 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5979 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5982 // update seen indicator
5983 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5987 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5988 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5990 $answer = ['result' => 'error', 'message' => 'unknown error'];
5991 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5995 /// @TODO move to top of file or somewhere better
5996 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5999 * search for direct_messages containing a searchstring through api
6001 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6002 * @param string $box
6003 * @return string|array (success: success=true if found and search_result contains found messages,
6004 * success=false if nothing was found, search_result='nothing found',
6005 * error: result=error with error message)
6006 * @throws BadRequestException
6007 * @throws ForbiddenException
6008 * @throws ImagickException
6009 * @throws InternalServerErrorException
6010 * @throws UnauthorizedException
6012 function api_friendica_direct_messages_search($type, $box = "")
6016 if (api_user() === false) {
6017 throw new ForbiddenException();
6021 $user_info = api_get_user($a);
6022 $searchstring = $_REQUEST['searchstring'] ?? '';
6023 $uid = $user_info['uid'];
6025 // error if no searchstring specified
6026 if ($searchstring == "") {
6027 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6028 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6031 // get data for the specified searchstring
6033 "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",
6035 DBA::escape('%'.$searchstring.'%')
6038 $profile_url = $user_info["url"];
6040 // message if nothing was found
6041 if (!DBA::isResult($r)) {
6042 $success = ['success' => false, 'search_results' => 'problem with query'];
6043 } elseif (count($r) == 0) {
6044 $success = ['success' => false, 'search_results' => 'nothing found'];
6047 foreach ($r as $item) {
6048 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6049 $recipient = $user_info;
6050 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6051 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6052 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6053 $sender = $user_info;
6056 if (isset($recipient) && isset($sender)) {
6057 $ret[] = api_format_messages($item, $recipient, $sender);
6060 $success = ['success' => true, 'search_results' => $ret];
6063 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6066 /// @TODO move to top of file or somewhere better
6067 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6070 * Returns a list of saved searches.
6072 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6074 * @param string $type Return format: json or xml
6076 * @return string|array
6079 function api_saved_searches_list($type)
6081 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6084 while ($term = DBA::fetch($terms)) {
6086 'created_at' => api_date(time()),
6087 'id' => intval($term['id']),
6088 'id_str' => $term['id'],
6089 'name' => $term['term'],
6091 'query' => $term['term']
6097 return api_format_data("terms", $type, ['terms' => $result]);
6100 /// @TODO move to top of file or somewhere better
6101 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6104 * Number of comments
6106 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6108 * @param object $data [Status, Status]
6112 function bindComments(&$data)
6114 if (count($data) == 0) {
6120 foreach ($data as $item) {
6121 $ids[] = $item['id'];
6124 $idStr = DBA::escape(implode(', ', $ids));
6125 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6126 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6127 $itemsData = DBA::toArray($items);
6129 foreach ($itemsData as $item) {
6130 $comments[$item['parent']] = $item['comments'];
6133 foreach ($data as $idx => $item) {
6135 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6140 @TODO Maybe open to implement?
6142 [pagename] => api/1.1/statuses/lookup.json
6143 [id] => 605138389168451584
6144 [include_cards] => true
6145 [cards_platform] => Android-12
6146 [include_entities] => true
6147 [include_my_retweet] => 1
6149 [include_reply_count] => true
6150 [include_descendent_reply_count] => true
6154 Not implemented by now:
6155 statuses/retweets_of_me
6160 account/update_location
6161 account/update_profile_background_image
6164 friendica/profile/update
6165 friendica/profile/create
6166 friendica/profile/delete
6168 Not implemented in status.net:
6169 statuses/retweeted_to_me
6170 statuses/retweeted_by_me
6171 direct_messages/destroy
6173 account/update_delivery_device
6174 notifications/follow