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
1313 * @return array|string
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 = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1542 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1544 while ($tag = DBA::fetch($tags)) {
1545 $uriids[] = $tag['uri-id'];
1549 if (empty($uriids)) {
1550 return api_format_data('statuses', $type, $data);
1553 $condition = ['uri-id' => $uriids];
1554 if ($exclude_replies) {
1555 $condition['gravity'] = GRAVITY_PARENT;
1558 $params['group_by'] = ['uri-id'];
1560 $condition = ["`id` > ?
1561 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1562 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1563 AND `body` LIKE CONCAT('%',?,'%')",
1564 $since_id, api_user(), $_REQUEST['q']];
1566 $condition[0] .= ' AND `id` <= ?';
1567 $condition[] = $max_id;
1573 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1574 $id = Item::fetchByLink($searchTerm, api_user());
1577 $id = Item::fetchByLink($searchTerm);
1581 $statuses = Item::select([], ['id' => $id]);
1585 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1587 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1589 bindComments($data['status']);
1591 return api_format_data('statuses', $type, $data);
1594 /// @TODO move to top of file or somewhere better
1595 api_register_func('api/search/tweets', 'api_search', true);
1596 api_register_func('api/search', 'api_search', true);
1599 * Returns the most recent statuses posted by the user and the users they follow.
1601 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1603 * @param string $type Return type (atom, rss, xml, json)
1605 * @return array|string
1606 * @throws BadRequestException
1607 * @throws ForbiddenException
1608 * @throws ImagickException
1609 * @throws InternalServerErrorException
1610 * @throws UnauthorizedException
1611 * @todo Optional parameters
1612 * @todo Add reply info
1614 function api_statuses_home_timeline($type)
1617 $user_info = api_get_user($a);
1619 if (api_user() === false || $user_info === false) {
1620 throw new ForbiddenException();
1623 unset($_REQUEST["user_id"]);
1624 unset($_GET["user_id"]);
1626 unset($_REQUEST["screen_name"]);
1627 unset($_GET["screen_name"]);
1629 // get last network messages
1632 $count = $_REQUEST['count'] ?? 20;
1633 $page = $_REQUEST['page']?? 0;
1634 $since_id = $_REQUEST['since_id'] ?? 0;
1635 $max_id = $_REQUEST['max_id'] ?? 0;
1636 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1637 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1639 $start = max(0, ($page - 1) * $count);
1641 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1642 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1645 $condition[0] .= " AND `item`.`id` <= ?";
1646 $condition[] = $max_id;
1648 if ($exclude_replies) {
1649 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1651 if ($conversation_id > 0) {
1652 $condition[0] .= " AND `item`.`parent` = ?";
1653 $condition[] = $conversation_id;
1656 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1657 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1659 $items = Item::inArray($statuses);
1661 $ret = api_format_items($items, $user_info, false, $type);
1663 // Set all posts from the query above to seen
1665 foreach ($items as $item) {
1666 $idarray[] = intval($item["id"]);
1669 if (!empty($idarray)) {
1670 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1672 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1678 $data = ['status' => $ret];
1683 $data = api_rss_extra($a, $data, $user_info);
1687 return api_format_data("statuses", $type, $data);
1691 /// @TODO move to top of file or somewhere better
1692 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1693 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1696 * Returns the most recent statuses from public users.
1698 * @param string $type Return type (atom, rss, xml, json)
1700 * @return array|string
1701 * @throws BadRequestException
1702 * @throws ForbiddenException
1703 * @throws ImagickException
1704 * @throws InternalServerErrorException
1705 * @throws UnauthorizedException
1707 function api_statuses_public_timeline($type)
1710 $user_info = api_get_user($a);
1712 if (api_user() === false || $user_info === false) {
1713 throw new ForbiddenException();
1716 // get last network messages
1719 $count = $_REQUEST['count'] ?? 20;
1720 $page = $_REQUEST['page'] ?? 1;
1721 $since_id = $_REQUEST['since_id'] ?? 0;
1722 $max_id = $_REQUEST['max_id'] ?? 0;
1723 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1724 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1726 $start = max(0, ($page - 1) * $count);
1728 if ($exclude_replies && !$conversation_id) {
1729 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
1730 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1733 $condition[0] .= " AND `thread`.`iid` <= ?";
1734 $condition[] = $max_id;
1737 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1738 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1740 $r = Item::inArray($statuses);
1742 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
1743 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1746 $condition[0] .= " AND `item`.`id` <= ?";
1747 $condition[] = $max_id;
1749 if ($conversation_id > 0) {
1750 $condition[0] .= " AND `item`.`parent` = ?";
1751 $condition[] = $conversation_id;
1754 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1755 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1757 $r = Item::inArray($statuses);
1760 $ret = api_format_items($r, $user_info, false, $type);
1764 $data = ['status' => $ret];
1769 $data = api_rss_extra($a, $data, $user_info);
1773 return api_format_data("statuses", $type, $data);
1776 /// @TODO move to top of file or somewhere better
1777 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1780 * Returns the most recent statuses posted by users this node knows about.
1782 * @param string $type Return format: json, xml, atom, rss
1783 * @return array|string
1784 * @throws BadRequestException
1785 * @throws ForbiddenException
1786 * @throws ImagickException
1787 * @throws InternalServerErrorException
1788 * @throws UnauthorizedException
1790 function api_statuses_networkpublic_timeline($type)
1793 $user_info = api_get_user($a);
1795 if (api_user() === false || $user_info === false) {
1796 throw new ForbiddenException();
1799 $since_id = $_REQUEST['since_id'] ?? 0;
1800 $max_id = $_REQUEST['max_id'] ?? 0;
1803 $count = $_REQUEST['count'] ?? 20;
1804 $page = $_REQUEST['page'] ?? 1;
1806 $start = max(0, ($page - 1) * $count);
1808 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
1809 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1812 $condition[0] .= " AND `thread`.`iid` <= ?";
1813 $condition[] = $max_id;
1816 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1817 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1819 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1823 $data = ['status' => $ret];
1828 $data = api_rss_extra($a, $data, $user_info);
1832 return api_format_data("statuses", $type, $data);
1835 /// @TODO move to top of file or somewhere better
1836 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1839 * Returns a single status.
1841 * @param string $type Return type (atom, rss, xml, json)
1843 * @return array|string
1844 * @throws BadRequestException
1845 * @throws ForbiddenException
1846 * @throws ImagickException
1847 * @throws InternalServerErrorException
1848 * @throws UnauthorizedException
1849 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1851 function api_statuses_show($type)
1854 $user_info = api_get_user($a);
1856 if (api_user() === false || $user_info === false) {
1857 throw new ForbiddenException();
1861 $id = intval($a->argv[3] ?? 0);
1864 $id = intval($_REQUEST['id'] ?? 0);
1869 $id = intval($a->argv[4] ?? 0);
1872 Logger::log('API: api_statuses_show: ' . $id);
1874 $conversation = !empty($_REQUEST['conversation']);
1876 // try to fetch the item for the local user - or the public item, if there is no local one
1877 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1878 if (!DBA::isResult($uri_item)) {
1879 throw new BadRequestException("There is no status with this id.");
1882 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1883 if (!DBA::isResult($item)) {
1884 throw new BadRequestException("There is no status with this id.");
1889 if ($conversation) {
1890 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1891 $params = ['order' => ['id' => true]];
1893 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1897 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1899 /// @TODO How about copying this to above methods which don't check $r ?
1900 if (!DBA::isResult($statuses)) {
1901 throw new BadRequestException("There is no status with this id.");
1904 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1906 if ($conversation) {
1907 $data = ['status' => $ret];
1908 return api_format_data("statuses", $type, $data);
1910 $data = ['status' => $ret[0]];
1911 return api_format_data("status", $type, $data);
1915 /// @TODO move to top of file or somewhere better
1916 api_register_func('api/statuses/show', 'api_statuses_show', true);
1920 * @param string $type Return type (atom, rss, xml, json)
1922 * @return array|string
1923 * @throws BadRequestException
1924 * @throws ForbiddenException
1925 * @throws ImagickException
1926 * @throws InternalServerErrorException
1927 * @throws UnauthorizedException
1928 * @todo nothing to say?
1930 function api_conversation_show($type)
1933 $user_info = api_get_user($a);
1935 if (api_user() === false || $user_info === false) {
1936 throw new ForbiddenException();
1940 $id = intval($a->argv[3] ?? 0);
1941 $since_id = intval($_REQUEST['since_id'] ?? 0);
1942 $max_id = intval($_REQUEST['max_id'] ?? 0);
1943 $count = intval($_REQUEST['count'] ?? 20);
1944 $page = intval($_REQUEST['page'] ?? 1);
1946 $start = max(0, ($page - 1) * $count);
1949 $id = intval($_REQUEST['id'] ?? 0);
1954 $id = intval($a->argv[4] ?? 0);
1957 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1959 // try to fetch the item for the local user - or the public item, if there is no local one
1960 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1961 if (!DBA::isResult($item)) {
1962 throw new BadRequestException("There is no status with this id.");
1965 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1966 if (!DBA::isResult($parent)) {
1967 throw new BadRequestException("There is no status with this id.");
1970 $id = $parent['id'];
1972 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1973 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1976 $condition[0] .= " AND `item`.`id` <= ?";
1977 $condition[] = $max_id;
1980 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1981 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1983 if (!DBA::isResult($statuses)) {
1984 throw new BadRequestException("There is no status with id $id.");
1987 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1989 $data = ['status' => $ret];
1990 return api_format_data("statuses", $type, $data);
1993 /// @TODO move to top of file or somewhere better
1994 api_register_func('api/conversation/show', 'api_conversation_show', true);
1995 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2000 * @param string $type Return type (atom, rss, xml, json)
2002 * @return array|string
2003 * @throws BadRequestException
2004 * @throws ForbiddenException
2005 * @throws ImagickException
2006 * @throws InternalServerErrorException
2007 * @throws UnauthorizedException
2008 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2010 function api_statuses_repeat($type)
2016 if (api_user() === false) {
2017 throw new ForbiddenException();
2023 $id = intval($a->argv[3] ?? 0);
2026 $id = intval($_REQUEST['id'] ?? 0);
2031 $id = intval($a->argv[4] ?? 0);
2034 Logger::log('API: api_statuses_repeat: '.$id);
2036 $fields = ['uri-id', 'body', 'title', 'attach', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2037 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2039 if (DBA::isResult($item) && $item['body'] != "") {
2040 if (strpos($item['body'], "[/share]") !== false) {
2041 $pos = strpos($item['body'], "[share");
2042 $post = substr($item['body'], $pos);
2044 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2046 if (!empty($item['title'])) {
2047 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2050 $post .= $item['body'];
2051 $post .= "[/share]";
2053 $_REQUEST['body'] = $post;
2054 $_REQUEST['attach'] = $item['attach'];
2055 $_REQUEST['profile_uid'] = api_user();
2056 $_REQUEST['api_source'] = true;
2058 if (empty($_REQUEST['source'])) {
2059 $_REQUEST["source"] = api_source();
2062 $item_id = item_post($a);
2064 /// @todo Copy tags from the original post to the new one
2066 throw new ForbiddenException();
2069 // output the post that we just posted.
2071 return api_status_show($type, $item_id);
2074 /// @TODO move to top of file or somewhere better
2075 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2078 * Destroys a specific status.
2080 * @param string $type Return type (atom, rss, xml, json)
2082 * @return array|string
2083 * @throws BadRequestException
2084 * @throws ForbiddenException
2085 * @throws ImagickException
2086 * @throws InternalServerErrorException
2087 * @throws UnauthorizedException
2088 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2090 function api_statuses_destroy($type)
2094 if (api_user() === false) {
2095 throw new ForbiddenException();
2101 $id = intval($a->argv[3] ?? 0);
2104 $id = intval($_REQUEST['id'] ?? 0);
2109 $id = intval($a->argv[4] ?? 0);
2112 Logger::log('API: api_statuses_destroy: '.$id);
2114 $ret = api_statuses_show($type);
2116 Item::deleteForUser(['id' => $id], api_user());
2121 /// @TODO move to top of file or somewhere better
2122 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2125 * Returns the most recent mentions.
2127 * @param string $type Return type (atom, rss, xml, json)
2129 * @return array|string
2130 * @throws BadRequestException
2131 * @throws ForbiddenException
2132 * @throws ImagickException
2133 * @throws InternalServerErrorException
2134 * @throws UnauthorizedException
2135 * @see http://developer.twitter.com/doc/get/statuses/mentions
2137 function api_statuses_mentions($type)
2140 $user_info = api_get_user($a);
2142 if (api_user() === false || $user_info === false) {
2143 throw new ForbiddenException();
2146 unset($_REQUEST["user_id"]);
2147 unset($_GET["user_id"]);
2149 unset($_REQUEST["screen_name"]);
2150 unset($_GET["screen_name"]);
2152 // get last network messages
2155 $since_id = $_REQUEST['since_id'] ?? 0;
2156 $max_id = $_REQUEST['max_id'] ?? 0;
2157 $count = $_REQUEST['count'] ?? 20;
2158 $page = $_REQUEST['page'] ?? 1;
2160 $start = max(0, ($page - 1) * $count);
2162 $query = "SELECT `item`.`id` FROM `user-item`
2163 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2164 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2165 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2166 AND `user-item`.`iid` > ?";
2167 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2168 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2169 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2170 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2174 $query .= " AND `item`.`id` <= ?";
2175 $condition[] = $max_id;
2178 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2179 $condition[] = $start;
2180 $condition[] = $count;
2182 $useritems = DBA::p($query, $condition);
2184 while ($useritem = DBA::fetch($useritems)) {
2185 $itemids[] = $useritem['id'];
2187 DBA::close($useritems);
2189 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2190 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2192 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2194 $data = ['status' => $ret];
2199 $data = api_rss_extra($a, $data, $user_info);
2203 return api_format_data("statuses", $type, $data);
2206 /// @TODO move to top of file or somewhere better
2207 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2208 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2211 * Returns the most recent statuses posted by the user.
2213 * @param string $type Either "json" or "xml"
2214 * @return string|array
2215 * @throws BadRequestException
2216 * @throws ForbiddenException
2217 * @throws ImagickException
2218 * @throws InternalServerErrorException
2219 * @throws UnauthorizedException
2220 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2222 function api_statuses_user_timeline($type)
2225 $user_info = api_get_user($a);
2227 if (api_user() === false || $user_info === false) {
2228 throw new ForbiddenException();
2232 "api_statuses_user_timeline: api_user: ". api_user() .
2233 "\nuser_info: ".print_r($user_info, true) .
2234 "\n_REQUEST: ".print_r($_REQUEST, true),
2238 $since_id = $_REQUEST['since_id'] ?? 0;
2239 $max_id = $_REQUEST['max_id'] ?? 0;
2240 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2241 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2244 $count = $_REQUEST['count'] ?? 20;
2245 $page = $_REQUEST['page'] ?? 1;
2247 $start = max(0, ($page - 1) * $count);
2249 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2250 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2252 if ($user_info['self'] == 1) {
2253 $condition[0] .= ' AND `item`.`wall` ';
2256 if ($exclude_replies) {
2257 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2260 if ($conversation_id > 0) {
2261 $condition[0] .= " AND `item`.`parent` = ?";
2262 $condition[] = $conversation_id;
2266 $condition[0] .= " AND `item`.`id` <= ?";
2267 $condition[] = $max_id;
2270 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2271 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2273 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2277 $data = ['status' => $ret];
2282 $data = api_rss_extra($a, $data, $user_info);
2286 return api_format_data("statuses", $type, $data);
2289 /// @TODO move to top of file or somewhere better
2290 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2293 * Star/unstar an item.
2294 * param: id : id of the item
2296 * @param string $type Return type (atom, rss, xml, json)
2298 * @return array|string
2299 * @throws BadRequestException
2300 * @throws ForbiddenException
2301 * @throws ImagickException
2302 * @throws InternalServerErrorException
2303 * @throws UnauthorizedException
2304 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2306 function api_favorites_create_destroy($type)
2310 if (api_user() === false) {
2311 throw new ForbiddenException();
2314 // for versioned api.
2315 /// @TODO We need a better global soluton
2316 $action_argv_id = 2;
2317 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2318 $action_argv_id = 3;
2321 if ($a->argc <= $action_argv_id) {
2322 throw new BadRequestException("Invalid request.");
2324 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2325 if ($a->argc == $action_argv_id + 2) {
2326 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2328 $itemid = intval($_REQUEST['id'] ?? 0);
2331 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2333 if (!DBA::isResult($item)) {
2334 throw new BadRequestException("Invalid item.");
2339 $item['starred'] = 1;
2342 $item['starred'] = 0;
2345 throw new BadRequestException("Invalid action ".$action);
2348 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2351 throw new InternalServerErrorException("DB error");
2355 $user_info = api_get_user($a);
2356 $rets = api_format_items([$item], $user_info, false, $type);
2359 $data = ['status' => $ret];
2364 $data = api_rss_extra($a, $data, $user_info);
2368 return api_format_data("status", $type, $data);
2371 /// @TODO move to top of file or somewhere better
2372 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2373 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2376 * Returns the most recent favorite statuses.
2378 * @param string $type Return type (atom, rss, xml, json)
2380 * @return string|array
2381 * @throws BadRequestException
2382 * @throws ForbiddenException
2383 * @throws ImagickException
2384 * @throws InternalServerErrorException
2385 * @throws UnauthorizedException
2387 function api_favorites($type)
2392 $user_info = api_get_user($a);
2394 if (api_user() === false || $user_info === false) {
2395 throw new ForbiddenException();
2400 // in friendica starred item are private
2401 // return favorites only for self
2402 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2404 if ($user_info['self'] == 0) {
2408 $since_id = $_REQUEST['since_id'] ?? 0;
2409 $max_id = $_REQUEST['max_id'] ?? 0;
2410 $count = $_GET['count'] ?? 20;
2411 $page = $_REQUEST['page'] ?? 1;
2413 $start = max(0, ($page - 1) * $count);
2415 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2416 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2418 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2421 $condition[0] .= " AND `item`.`id` <= ?";
2422 $condition[] = $max_id;
2425 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2427 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2432 $data = ['status' => $ret];
2437 $data = api_rss_extra($a, $data, $user_info);
2441 return api_format_data("statuses", $type, $data);
2444 /// @TODO move to top of file or somewhere better
2445 api_register_func('api/favorites', 'api_favorites', true);
2449 * @param array $item
2450 * @param array $recipient
2451 * @param array $sender
2454 * @throws InternalServerErrorException
2456 function api_format_messages($item, $recipient, $sender)
2458 // standard meta information
2460 'id' => $item['id'],
2461 'sender_id' => $sender['id'],
2463 'recipient_id' => $recipient['id'],
2464 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2465 'sender_screen_name' => $sender['screen_name'],
2466 'recipient_screen_name' => $recipient['screen_name'],
2467 'sender' => $sender,
2468 'recipient' => $recipient,
2470 'friendica_seen' => $item['seen'] ?? 0,
2471 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2474 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2475 if (isset($ret['sender']['uid'])) {
2476 unset($ret['sender']['uid']);
2478 if (isset($ret['sender']['self'])) {
2479 unset($ret['sender']['self']);
2481 if (isset($ret['recipient']['uid'])) {
2482 unset($ret['recipient']['uid']);
2484 if (isset($ret['recipient']['self'])) {
2485 unset($ret['recipient']['self']);
2488 //don't send title to regular StatusNET requests to avoid confusing these apps
2489 if (!empty($_GET['getText'])) {
2490 $ret['title'] = $item['title'];
2491 if ($_GET['getText'] == 'html') {
2492 $ret['text'] = BBCode::convert($item['body'], false);
2493 } elseif ($_GET['getText'] == 'plain') {
2494 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2497 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2499 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2500 unset($ret['sender']);
2501 unset($ret['recipient']);
2509 * @param array $item
2512 * @throws InternalServerErrorException
2514 function api_convert_item($item)
2516 $body = $item['body'];
2517 $entities = api_get_entitities($statustext, $body);
2519 // Add pictures to the attachment array and remove them from the body
2520 $attachments = api_get_attachments($body);
2522 // Workaround for ostatus messages where the title is identically to the body
2523 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2524 $statusbody = trim(HTML::toPlaintext($html, 0));
2526 // handle data: images
2527 $statusbody = api_format_items_embeded_images($item, $statusbody);
2529 $statustitle = trim($item['title']);
2531 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2532 $statustext = trim($statusbody);
2534 $statustext = trim($statustitle."\n\n".$statusbody);
2537 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2538 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2541 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2543 // Workaround for clients with limited HTML parser functionality
2544 $search = ["<br>", "<blockquote>", "</blockquote>",
2545 "<h1>", "</h1>", "<h2>", "</h2>",
2546 "<h3>", "</h3>", "<h4>", "</h4>",
2547 "<h5>", "</h5>", "<h6>", "</h6>"];
2548 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2549 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2550 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2551 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2552 $statushtml = str_replace($search, $replace, $statushtml);
2554 if ($item['title'] != "") {
2555 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2559 $oldtext = $statushtml;
2560 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2561 } while ($oldtext != $statushtml);
2563 if (substr($statushtml, 0, 4) == '<br>') {
2564 $statushtml = substr($statushtml, 4);
2567 if (substr($statushtml, 0, -4) == '<br>') {
2568 $statushtml = substr($statushtml, -4);
2571 // feeds without body should contain the link
2572 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2573 $statushtml .= BBCode::convert($item['plink']);
2577 "text" => $statustext,
2578 "html" => $statushtml,
2579 "attachments" => $attachments,
2580 "entities" => $entities
2586 * @param string $body
2589 * @throws InternalServerErrorException
2591 function api_get_attachments(&$body)
2593 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2594 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2596 $URLSearchString = "^\[\]";
2597 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2601 // Remove all embedded pictures, since they are added as attachments
2602 foreach ($images[0] as $orig) {
2603 $body = str_replace($orig, '', $body);
2608 foreach ($images[1] as $image) {
2609 $imagedata = Images::getInfoFromURLCached($image);
2612 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2616 return $attachments;
2621 * @param string $text
2622 * @param string $bbcode
2625 * @throws InternalServerErrorException
2626 * @todo Links at the first character of the post
2628 function api_get_entitities(&$text, $bbcode)
2630 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2632 if ($include_entities != "true") {
2633 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2635 foreach ($images[1] as $image) {
2636 $replace = ProxyUtils::proxifyUrl($image);
2637 $text = str_replace($image, $replace, $text);
2642 $bbcode = BBCode::cleanPictureLinks($bbcode);
2644 // Change pure links in text to bbcode uris
2645 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2648 $entities["hashtags"] = [];
2649 $entities["symbols"] = [];
2650 $entities["urls"] = [];
2651 $entities["user_mentions"] = [];
2653 $URLSearchString = "^\[\]";
2655 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2657 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2658 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2660 $bbcode = preg_replace(
2661 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2662 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2665 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2667 $bbcode = preg_replace(
2668 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2669 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2672 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2674 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2676 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2679 foreach ($urls[1] as $id => $url) {
2680 $start = iconv_strpos($text, $url, 0, "UTF-8");
2681 if (!($start === false)) {
2682 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2686 ksort($ordered_urls);
2690 foreach ($ordered_urls as $url) {
2691 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2692 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2694 $display_url = $url["title"];
2696 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2697 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2699 if (strlen($display_url) > 26) {
2700 $display_url = substr($display_url, 0, 25)."…";
2704 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2705 if (!($start === false)) {
2706 $entities["urls"][] = ["url" => $url["url"],
2707 "expanded_url" => $url["url"],
2708 "display_url" => $display_url,
2709 "indices" => [$start, $start+strlen($url["url"])]];
2710 $offset = $start + 1;
2714 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2715 $ordered_images = [];
2716 foreach ($images as $image) {
2717 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2718 if (!($start === false)) {
2719 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2723 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2724 foreach ($images[1] as $image) {
2725 $start = iconv_strpos($text, $image, 0, "UTF-8");
2726 if (!($start === false)) {
2727 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2733 foreach ($ordered_images as $image) {
2734 $url = $image['url'];
2735 $ext_alt_text = $image['alt'];
2737 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2738 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2740 if (strlen($display_url) > 26) {
2741 $display_url = substr($display_url, 0, 25)."…";
2744 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2745 if (!($start === false)) {
2746 $image = Images::getInfoFromURLCached($url);
2748 // If image cache is activated, then use the following sizes:
2749 // thumb (150), small (340), medium (600) and large (1024)
2750 if (!DI::config()->get("system", "proxy_disabled")) {
2751 $media_url = ProxyUtils::proxifyUrl($url);
2754 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2755 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2757 if (($image[0] > 150) || ($image[1] > 150)) {
2758 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2759 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2762 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2763 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2765 if (($image[0] > 600) || ($image[1] > 600)) {
2766 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2767 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2771 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2774 $entities["media"][] = [
2776 "id_str" => (string) ($start + 1),
2777 "indices" => [$start, $start+strlen($url)],
2778 "media_url" => Strings::normaliseLink($media_url),
2779 "media_url_https" => $media_url,
2781 "display_url" => $display_url,
2782 "expanded_url" => $url,
2783 "ext_alt_text" => $ext_alt_text,
2787 $offset = $start + 1;
2796 * @param array $item
2797 * @param string $text
2801 function api_format_items_embeded_images($item, $text)
2803 $text = preg_replace_callback(
2804 '|data:image/([^;]+)[^=]+=*|m',
2805 function () use ($item) {
2806 return DI::baseUrl() . '/display/' . $item['guid'];
2814 * return <a href='url'>name</a> as array
2816 * @param string $txt text
2821 function api_contactlink_to_array($txt)
2824 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2825 if ($r && count($match)==3) {
2827 'name' => $match[2],
2841 * return likes, dislikes and attend status for item
2843 * @param array $item array
2844 * @param string $type Return type (atom, rss, xml, json)
2847 * likes => int count,
2848 * dislikes => int count
2849 * @throws BadRequestException
2850 * @throws ImagickException
2851 * @throws InternalServerErrorException
2852 * @throws UnauthorizedException
2854 function api_format_items_activities($item, $type = "json")
2863 'attendmaybe' => [],
2867 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2868 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2870 while ($parent_item = Item::fetch($ret)) {
2871 // not used as result should be structured like other user data
2872 //builtin_activity_puller($i, $activities);
2874 // get user data and add it to the array of the activity
2875 $user = api_get_user($a, $parent_item['author-id']);
2876 switch ($parent_item['verb']) {
2877 case Activity::LIKE:
2878 $activities['like'][] = $user;
2880 case Activity::DISLIKE:
2881 $activities['dislike'][] = $user;
2883 case Activity::ATTEND:
2884 $activities['attendyes'][] = $user;
2886 case Activity::ATTENDNO:
2887 $activities['attendno'][] = $user;
2889 case Activity::ATTENDMAYBE:
2890 $activities['attendmaybe'][] = $user;
2892 case Activity::ANNOUNCE:
2893 $activities['announce'][] = $user;
2902 if ($type == "xml") {
2903 $xml_activities = [];
2904 foreach ($activities as $k => $v) {
2905 // change xml element from "like" to "friendica:like"
2906 $xml_activities["friendica:".$k] = $v;
2907 // add user data into xml output
2909 foreach ($v as $user) {
2910 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2913 $activities = $xml_activities;
2920 * format items to be returned by api
2922 * @param array $items array of items
2923 * @param array $user_info
2924 * @param bool $filter_user filter items by $user_info
2925 * @param string $type Return type (atom, rss, xml, json)
2927 * @throws BadRequestException
2928 * @throws ImagickException
2929 * @throws InternalServerErrorException
2930 * @throws UnauthorizedException
2932 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2934 $a = Friendica\DI::app();
2938 foreach ((array)$items as $item) {
2939 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2941 // Look if the posts are matching if they should be filtered by user id
2942 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2946 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2955 * @param array $item Item record
2956 * @param string $type Return format (atom, rss, xml, json)
2957 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2958 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2959 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2960 * @return array API-formatted status
2961 * @throws BadRequestException
2962 * @throws ImagickException
2963 * @throws InternalServerErrorException
2964 * @throws UnauthorizedException
2966 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2968 $a = Friendica\DI::app();
2970 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2971 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2974 localize_item($item);
2976 $in_reply_to = api_in_reply_to($item);
2978 $converted = api_convert_item($item);
2980 if ($type == "xml") {
2981 $geo = "georss:point";
2987 'text' => $converted["text"],
2988 'truncated' => false,
2989 'created_at'=> api_date($item['created']),
2990 'in_reply_to_status_id' => $in_reply_to['status_id'],
2991 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2992 'source' => (($item['app']) ? $item['app'] : 'web'),
2993 'id' => intval($item['id']),
2994 'id_str' => (string) intval($item['id']),
2995 'in_reply_to_user_id' => $in_reply_to['user_id'],
2996 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2997 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2999 'favorited' => $item['starred'] ? true : false,
3000 'user' => $status_user,
3001 'friendica_author' => $author_user,
3002 'friendica_owner' => $owner_user,
3003 'friendica_private' => $item['private'] == Item::PRIVATE,
3004 //'entities' => NULL,
3005 'statusnet_html' => $converted["html"],
3006 'statusnet_conversation_id' => $item['parent'],
3007 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3008 'friendica_activities' => api_format_items_activities($item, $type),
3009 'friendica_title' => $item['title'],
3010 'friendica_html' => BBCode::convert($item['body'], false)
3013 if (count($converted["attachments"]) > 0) {
3014 $status["attachments"] = $converted["attachments"];
3017 if (count($converted["entities"]) > 0) {
3018 $status["entities"] = $converted["entities"];
3021 if ($status["source"] == 'web') {
3022 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3023 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3024 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3027 $retweeted_item = [];
3030 if ($item["id"] == $item["parent"]) {
3031 $body = $item['body'];
3032 $retweeted_item = api_share_as_retweet($item);
3033 if ($body != $item['body']) {
3034 $quoted_item = $retweeted_item;
3035 $retweeted_item = [];
3039 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3040 $announce = api_get_announce($item);
3041 if (!empty($announce)) {
3042 $retweeted_item = $item;
3044 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3048 if (!empty($quoted_item)) {
3049 if ($quoted_item['id'] != $item['id']) {
3050 $quoted_status = api_format_item($quoted_item);
3051 /// @todo Only remove the attachments that are also contained in the quotes status
3052 unset($status['attachments']);
3053 unset($status['entities']);
3055 $conv_quoted = api_convert_item($quoted_item);
3056 $quoted_status = $status;
3057 unset($quoted_status['attachments']);
3058 unset($quoted_status['entities']);
3059 unset($quoted_status['statusnet_conversation_id']);
3060 $quoted_status['text'] = $conv_quoted['text'];
3061 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3063 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3064 } catch (BadRequestException $e) {
3065 // user not found. should be found?
3066 /// @todo check if the user should be always found
3067 $quoted_status["user"] = [];
3070 unset($quoted_status['friendica_author']);
3071 unset($quoted_status['friendica_owner']);
3072 unset($quoted_status['friendica_activities']);
3073 unset($quoted_status['friendica_private']);
3076 if (!empty($retweeted_item)) {
3077 $retweeted_status = $status;
3078 unset($retweeted_status['friendica_author']);
3079 unset($retweeted_status['friendica_owner']);
3080 unset($retweeted_status['friendica_activities']);
3081 unset($retweeted_status['friendica_private']);
3082 unset($retweeted_status['statusnet_conversation_id']);
3083 $status['user'] = $status['friendica_owner'];
3085 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3086 } catch (BadRequestException $e) {
3087 // user not found. should be found?
3088 /// @todo check if the user should be always found
3089 $retweeted_status["user"] = [];
3092 $rt_converted = api_convert_item($retweeted_item);
3094 $retweeted_status['text'] = $rt_converted["text"];
3095 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3096 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3098 if (!empty($quoted_status)) {
3099 $retweeted_status['quoted_status'] = $quoted_status;
3102 $status['friendica_author'] = $retweeted_status['user'];
3103 $status['retweeted_status'] = $retweeted_status;
3104 } elseif (!empty($quoted_status)) {
3105 $root_status = api_convert_item($item);
3107 $status['text'] = $root_status["text"];
3108 $status['statusnet_html'] = $root_status["html"];
3109 $status['quoted_status'] = $quoted_status;
3112 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3113 unset($status["user"]["uid"]);
3114 unset($status["user"]["self"]);
3116 if ($item["coord"] != "") {
3117 $coords = explode(' ', $item["coord"]);
3118 if (count($coords) == 2) {
3119 if ($type == "json") {
3120 $status["geo"] = ['type' => 'Point',
3121 'coordinates' => [(float) $coords[0],
3122 (float) $coords[1]]];
3123 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3124 $status["georss:point"] = $item["coord"];
3133 * Returns the remaining number of API requests available to the user before the API limit is reached.
3135 * @param string $type Return type (atom, rss, xml, json)
3137 * @return array|string
3140 function api_account_rate_limit_status($type)
3142 if ($type == "xml") {
3144 'remaining-hits' => '150',
3145 '@attributes' => ["type" => "integer"],
3146 'hourly-limit' => '150',
3147 '@attributes2' => ["type" => "integer"],
3148 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3149 '@attributes3' => ["type" => "datetime"],
3150 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3151 '@attributes4' => ["type" => "integer"],
3155 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3156 'remaining_hits' => '150',
3157 'hourly_limit' => '150',
3158 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3162 return api_format_data('hash', $type, ['hash' => $hash]);
3165 /// @TODO move to top of file or somewhere better
3166 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3169 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3171 * @param string $type Return type (atom, rss, xml, json)
3173 * @return array|string
3175 function api_help_test($type)
3177 if ($type == 'xml') {
3183 return api_format_data('ok', $type, ["ok" => $ok]);
3186 /// @TODO move to top of file or somewhere better
3187 api_register_func('api/help/test', 'api_help_test', false);
3190 * Returns all lists the user subscribes to.
3192 * @param string $type Return type (atom, rss, xml, json)
3194 * @return array|string
3195 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3197 function api_lists_list($type)
3200 /// @TODO $ret is not filled here?
3201 return api_format_data('lists', $type, ["lists_list" => $ret]);
3204 /// @TODO move to top of file or somewhere better
3205 api_register_func('api/lists/list', 'api_lists_list', true);
3206 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3209 * Returns all groups the user owns.
3211 * @param string $type Return type (atom, rss, xml, json)
3213 * @return array|string
3214 * @throws BadRequestException
3215 * @throws ForbiddenException
3216 * @throws ImagickException
3217 * @throws InternalServerErrorException
3218 * @throws UnauthorizedException
3219 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3221 function api_lists_ownerships($type)
3225 if (api_user() === false) {
3226 throw new ForbiddenException();
3230 $user_info = api_get_user($a);
3231 $uid = $user_info['uid'];
3233 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3235 // loop through all groups
3237 foreach ($groups as $group) {
3238 if ($group['visible']) {
3244 'name' => $group['name'],
3245 'id' => intval($group['id']),
3246 'id_str' => (string) $group['id'],
3247 'user' => $user_info,
3251 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3254 /// @TODO move to top of file or somewhere better
3255 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3258 * Returns recent statuses from users in the specified group.
3260 * @param string $type Return type (atom, rss, xml, json)
3262 * @return array|string
3263 * @throws BadRequestException
3264 * @throws ForbiddenException
3265 * @throws ImagickException
3266 * @throws InternalServerErrorException
3267 * @throws UnauthorizedException
3268 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3270 function api_lists_statuses($type)
3274 $user_info = api_get_user($a);
3275 if (api_user() === false || $user_info === false) {
3276 throw new ForbiddenException();
3279 unset($_REQUEST["user_id"]);
3280 unset($_GET["user_id"]);
3282 unset($_REQUEST["screen_name"]);
3283 unset($_GET["screen_name"]);
3285 if (empty($_REQUEST['list_id'])) {
3286 throw new BadRequestException('list_id not specified');
3290 $count = $_REQUEST['count'] ?? 20;
3291 $page = $_REQUEST['page'] ?? 1;
3292 $since_id = $_REQUEST['since_id'] ?? 0;
3293 $max_id = $_REQUEST['max_id'] ?? 0;
3294 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3295 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3297 $start = max(0, ($page - 1) * $count);
3299 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3300 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3303 $condition[0] .= " AND `item`.`id` <= ?";
3304 $condition[] = $max_id;
3306 if ($exclude_replies > 0) {
3307 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3309 if ($conversation_id > 0) {
3310 $condition[0] .= " AND `item`.`parent` = ?";
3311 $condition[] = $conversation_id;
3314 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3315 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3317 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3319 $data = ['status' => $items];
3324 $data = api_rss_extra($a, $data, $user_info);
3328 return api_format_data("statuses", $type, $data);
3331 /// @TODO move to top of file or somewhere better
3332 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3335 * Returns either the friends of the follower list
3337 * Considers friends and followers lists to be private and won't return
3338 * anything if any user_id parameter is passed.
3340 * @param string $qtype Either "friends" or "followers"
3341 * @return boolean|array
3342 * @throws BadRequestException
3343 * @throws ForbiddenException
3344 * @throws ImagickException
3345 * @throws InternalServerErrorException
3346 * @throws UnauthorizedException
3348 function api_statuses_f($qtype)
3352 if (api_user() === false) {
3353 throw new ForbiddenException();
3357 $count = $_GET['count'] ?? 20;
3358 $page = $_GET['page'] ?? 1;
3360 $start = max(0, ($page - 1) * $count);
3362 $user_info = api_get_user($a);
3364 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3365 /* this is to stop Hotot to load friends multiple times
3366 * I'm not sure if I'm missing return something or
3367 * is a bug in hotot. Workaround, meantime
3371 return array('$users' => $ret);*/
3376 if ($qtype == 'friends') {
3377 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3378 } elseif ($qtype == 'followers') {
3379 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3382 // friends and followers only for self
3383 if ($user_info['self'] == 0) {
3384 $sql_extra = " AND false ";
3387 if ($qtype == 'blocks') {
3388 $sql_filter = 'AND `blocked` AND NOT `pending`';
3389 } elseif ($qtype == 'incoming') {
3390 $sql_filter = 'AND `pending`';
3392 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3410 foreach ($r as $cid) {
3411 $user = api_get_user($a, $cid['nurl']);
3412 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3413 unset($user["uid"]);
3414 unset($user["self"]);
3421 return ['user' => $ret];
3426 * Returns the list of friends of the provided user
3428 * @deprecated By Twitter API in favor of friends/list
3430 * @param string $type Either "json" or "xml"
3431 * @return boolean|string|array
3432 * @throws BadRequestException
3433 * @throws ForbiddenException
3435 function api_statuses_friends($type)
3437 $data = api_statuses_f("friends");
3438 if ($data === false) {
3441 return api_format_data("users", $type, $data);
3445 * Returns the list of followers of the provided user
3447 * @deprecated By Twitter API in favor of friends/list
3449 * @param string $type Either "json" or "xml"
3450 * @return boolean|string|array
3451 * @throws BadRequestException
3452 * @throws ForbiddenException
3454 function api_statuses_followers($type)
3456 $data = api_statuses_f("followers");
3457 if ($data === false) {
3460 return api_format_data("users", $type, $data);
3463 /// @TODO move to top of file or somewhere better
3464 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3465 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3468 * Returns the list of blocked users
3470 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3472 * @param string $type Either "json" or "xml"
3474 * @return boolean|string|array
3475 * @throws BadRequestException
3476 * @throws ForbiddenException
3478 function api_blocks_list($type)
3480 $data = api_statuses_f('blocks');
3481 if ($data === false) {
3484 return api_format_data("users", $type, $data);
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/blocks/list', 'api_blocks_list', true);
3491 * Returns the list of pending users IDs
3493 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3495 * @param string $type Either "json" or "xml"
3497 * @return boolean|string|array
3498 * @throws BadRequestException
3499 * @throws ForbiddenException
3501 function api_friendships_incoming($type)
3503 $data = api_statuses_f('incoming');
3504 if ($data === false) {
3509 foreach ($data['user'] as $user) {
3510 $ids[] = $user['id'];
3513 return api_format_data("ids", $type, ['id' => $ids]);
3516 /// @TODO move to top of file or somewhere better
3517 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3520 * Returns the instance's configuration information.
3522 * @param string $type Return type (atom, rss, xml, json)
3524 * @return array|string
3525 * @throws InternalServerErrorException
3527 function api_statusnet_config($type)
3529 $name = DI::config()->get('config', 'sitename');
3530 $server = DI::baseUrl()->getHostname();
3531 $logo = DI::baseUrl() . '/images/friendica-64.png';
3532 $email = DI::config()->get('config', 'admin_email');
3533 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3534 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3535 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3536 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3537 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3540 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3541 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3542 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3543 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3544 'shorturllength' => '30',
3546 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3547 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3548 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3549 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3554 return api_format_data('config', $type, ['config' => $config]);
3557 /// @TODO move to top of file or somewhere better
3558 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3559 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3563 * @param string $type Return type (atom, rss, xml, json)
3565 * @return array|string
3567 function api_statusnet_version($type)
3570 $fake_statusnet_version = "0.9.7";
3572 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3575 /// @TODO move to top of file or somewhere better
3576 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3577 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3581 * @param string $type Return type (atom, rss, xml, json)
3583 * @param int $rel A contact relationship constant
3584 * @return array|string|void
3585 * @throws BadRequestException
3586 * @throws ForbiddenException
3587 * @throws ImagickException
3588 * @throws InternalServerErrorException
3589 * @throws UnauthorizedException
3590 * @todo use api_format_data() to return data
3592 function api_ff_ids($type, int $rel)
3595 throw new ForbiddenException();
3602 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3604 $contacts = DBA::p("SELECT `pcontact`.`id`
3606 INNER JOIN `contact` AS `pcontact`
3607 ON `contact`.`nurl` = `pcontact`.`nurl`
3608 AND `pcontact`.`uid` = 0
3609 WHERE `contact`.`uid` = ?
3610 AND NOT `contact`.`self`
3611 AND `contact`.`rel` IN (?, ?)",
3618 foreach (DBA::toArray($contacts) as $contact) {
3619 if ($stringify_ids) {
3620 $ids[] = $contact['id'];
3622 $ids[] = intval($contact['id']);
3626 return api_format_data('ids', $type, ['id' => $ids]);
3630 * Returns the ID of every user the user is following.
3632 * @param string $type Return type (atom, rss, xml, json)
3634 * @return array|string
3635 * @throws BadRequestException
3636 * @throws ForbiddenException
3637 * @throws ImagickException
3638 * @throws InternalServerErrorException
3639 * @throws UnauthorizedException
3640 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3642 function api_friends_ids($type)
3644 return api_ff_ids($type, Contact::SHARING);
3648 * Returns the ID of every user following the user.
3650 * @param string $type Return type (atom, rss, xml, json)
3652 * @return array|string
3653 * @throws BadRequestException
3654 * @throws ForbiddenException
3655 * @throws ImagickException
3656 * @throws InternalServerErrorException
3657 * @throws UnauthorizedException
3658 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3660 function api_followers_ids($type)
3662 return api_ff_ids($type, Contact::FOLLOWER);
3665 /// @TODO move to top of file or somewhere better
3666 api_register_func('api/friends/ids', 'api_friends_ids', true);
3667 api_register_func('api/followers/ids', 'api_followers_ids', true);
3670 * Sends a new direct message.
3672 * @param string $type Return type (atom, rss, xml, json)
3674 * @return array|string
3675 * @throws BadRequestException
3676 * @throws ForbiddenException
3677 * @throws ImagickException
3678 * @throws InternalServerErrorException
3679 * @throws NotFoundException
3680 * @throws UnauthorizedException
3681 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3683 function api_direct_messages_new($type)
3687 if (api_user() === false) {
3688 throw new ForbiddenException();
3691 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3695 $sender = api_get_user($a);
3698 if (!empty($_POST['screen_name'])) {
3700 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3702 DBA::escape($_POST['screen_name'])
3705 if (DBA::isResult($r)) {
3706 // Selecting the id by priority, friendica first
3707 api_best_nickname($r);
3709 $recipient = api_get_user($a, $r[0]['nurl']);
3712 $recipient = api_get_user($a, $_POST['user_id']);
3715 if (empty($recipient)) {
3716 throw new NotFoundException('Recipient not found');
3720 if (!empty($_REQUEST['replyto'])) {
3722 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3724 intval($_REQUEST['replyto'])
3726 $replyto = $r[0]['parent-uri'];
3727 $sub = $r[0]['title'];
3729 if (!empty($_REQUEST['title'])) {
3730 $sub = $_REQUEST['title'];
3732 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3736 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3739 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3740 $ret = api_format_messages($r[0], $recipient, $sender);
3742 $ret = ["error"=>$id];
3745 $data = ['direct_message'=>$ret];
3751 $data = api_rss_extra($a, $data, $sender);
3755 return api_format_data("direct-messages", $type, $data);
3758 /// @TODO move to top of file or somewhere better
3759 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3762 * delete a direct_message from mail table through api
3764 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3765 * @return string|array
3766 * @throws BadRequestException
3767 * @throws ForbiddenException
3768 * @throws ImagickException
3769 * @throws InternalServerErrorException
3770 * @throws UnauthorizedException
3771 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3773 function api_direct_messages_destroy($type)
3777 if (api_user() === false) {
3778 throw new ForbiddenException();
3782 $user_info = api_get_user($a);
3784 $id = $_REQUEST['id'] ?? 0;
3786 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3787 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3788 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3790 $uid = $user_info['uid'];
3791 // error if no id or parenturi specified (for clients posting parent-uri as well)
3792 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3793 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3794 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3797 // BadRequestException if no id specified (for clients using Twitter API)
3799 throw new BadRequestException('Message id not specified');
3802 // add parent-uri to sql command if specified by calling app
3803 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3805 // get data of the specified message id
3807 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3812 // error message if specified id is not in database
3813 if (!DBA::isResult($r)) {
3814 if ($verbose == "true") {
3815 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3816 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3818 /// @todo BadRequestException ok for Twitter API clients?
3819 throw new BadRequestException('message id not in database');
3824 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3829 if ($verbose == "true") {
3832 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3833 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3835 $answer = ['result' => 'error', 'message' => 'unknown error'];
3836 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3839 /// @todo return JSON data like Twitter API not yet implemented
3842 /// @TODO move to top of file or somewhere better
3843 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3848 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3849 * @return string|array
3850 * @throws BadRequestException
3851 * @throws ForbiddenException
3852 * @throws ImagickException
3853 * @throws InternalServerErrorException
3854 * @throws NotFoundException
3855 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3857 function api_friendships_destroy($type)
3861 if ($uid === false) {
3862 throw new ForbiddenException();
3865 $contact_id = $_REQUEST['user_id'] ?? 0;
3867 if (empty($contact_id)) {
3868 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3869 throw new BadRequestException("no user_id specified");
3872 // Get Contact by given id
3873 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3875 if(!DBA::isResult($contact)) {
3876 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3877 throw new NotFoundException("no contact found to given ID");
3880 $url = $contact["url"];
3882 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3883 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3884 Strings::normaliseLink($url), $url];
3885 $contact = DBA::selectFirst('contact', [], $condition);
3887 if (!DBA::isResult($contact)) {
3888 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3889 throw new NotFoundException("Not following Contact");
3892 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3893 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3894 throw new ExpectationFailedException("Not supported");
3897 $dissolve = ($contact['rel'] == Contact::SHARING);
3899 $owner = User::getOwnerDataById($uid);
3901 Contact::terminateFriendship($owner, $contact, $dissolve);
3904 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3905 throw new NotFoundException("Error Processing Request");
3908 // Sharing-only contacts get deleted as there no relationship any more
3910 Contact::remove($contact['id']);
3912 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3915 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3916 unset($contact["uid"]);
3917 unset($contact["self"]);
3919 // Set screen_name since Twidere requests it
3920 $contact["screen_name"] = $contact["nick"];
3922 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3924 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3928 * @param string $type Return type (atom, rss, xml, json)
3929 * @param string $box
3930 * @param string $verbose
3932 * @return array|string
3933 * @throws BadRequestException
3934 * @throws ForbiddenException
3935 * @throws ImagickException
3936 * @throws InternalServerErrorException
3937 * @throws UnauthorizedException
3939 function api_direct_messages_box($type, $box, $verbose)
3942 if (api_user() === false) {
3943 throw new ForbiddenException();
3946 $count = $_GET['count'] ?? 20;
3947 $page = $_REQUEST['page'] ?? 1;
3949 $since_id = $_REQUEST['since_id'] ?? 0;
3950 $max_id = $_REQUEST['max_id'] ?? 0;
3952 $user_id = $_REQUEST['user_id'] ?? '';
3953 $screen_name = $_REQUEST['screen_name'] ?? '';
3956 unset($_REQUEST["user_id"]);
3957 unset($_GET["user_id"]);
3959 unset($_REQUEST["screen_name"]);
3960 unset($_GET["screen_name"]);
3962 $user_info = api_get_user($a);
3963 if ($user_info === false) {
3964 throw new ForbiddenException();
3966 $profile_url = $user_info["url"];
3969 $start = max(0, ($page - 1) * $count);
3974 if ($box=="sentbox") {
3975 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3976 } elseif ($box == "conversation") {
3977 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3978 } elseif ($box == "all") {
3979 $sql_extra = "true";
3980 } elseif ($box == "inbox") {
3981 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3985 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3988 if ($user_id != "") {
3989 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3990 } elseif ($screen_name !="") {
3991 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3995 "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",
4001 if ($verbose == "true" && !DBA::isResult($r)) {
4002 $answer = ['result' => 'error', 'message' => 'no mails available'];
4003 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4007 foreach ($r as $item) {
4008 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4009 $recipient = $user_info;
4010 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4011 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4012 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4013 $sender = $user_info;
4016 if (isset($recipient) && isset($sender)) {
4017 $ret[] = api_format_messages($item, $recipient, $sender);
4022 $data = ['direct_message' => $ret];
4027 $data = api_rss_extra($a, $data, $user_info);
4031 return api_format_data("direct-messages", $type, $data);
4035 * Returns the most recent direct messages sent by the user.
4037 * @param string $type Return type (atom, rss, xml, json)
4039 * @return array|string
4040 * @throws BadRequestException
4041 * @throws ForbiddenException
4042 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4044 function api_direct_messages_sentbox($type)
4046 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4047 return api_direct_messages_box($type, "sentbox", $verbose);
4051 * Returns the most recent direct messages sent to the user.
4053 * @param string $type Return type (atom, rss, xml, json)
4055 * @return array|string
4056 * @throws BadRequestException
4057 * @throws ForbiddenException
4058 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4060 function api_direct_messages_inbox($type)
4062 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4063 return api_direct_messages_box($type, "inbox", $verbose);
4068 * @param string $type Return type (atom, rss, xml, json)
4070 * @return array|string
4071 * @throws BadRequestException
4072 * @throws ForbiddenException
4074 function api_direct_messages_all($type)
4076 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4077 return api_direct_messages_box($type, "all", $verbose);
4082 * @param string $type Return type (atom, rss, xml, json)
4084 * @return array|string
4085 * @throws BadRequestException
4086 * @throws ForbiddenException
4088 function api_direct_messages_conversation($type)
4090 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4091 return api_direct_messages_box($type, "conversation", $verbose);
4094 /// @TODO move to top of file or somewhere better
4095 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4096 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4097 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4098 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4101 * Returns an OAuth Request Token.
4103 * @see https://oauth.net/core/1.0/#auth_step1
4105 function api_oauth_request_token()
4107 $oauth1 = new FKOAuth1();
4109 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4110 } catch (Exception $e) {
4111 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4119 * Returns an OAuth Access Token.
4121 * @return array|string
4122 * @see https://oauth.net/core/1.0/#auth_step3
4124 function api_oauth_access_token()
4126 $oauth1 = new FKOAuth1();
4128 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4129 } catch (Exception $e) {
4130 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4137 /// @TODO move to top of file or somewhere better
4138 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4139 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4143 * delete a complete photoalbum with all containing photos from database through api
4145 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4146 * @return string|array
4147 * @throws BadRequestException
4148 * @throws ForbiddenException
4149 * @throws InternalServerErrorException
4151 function api_fr_photoalbum_delete($type)
4153 if (api_user() === false) {
4154 throw new ForbiddenException();
4157 $album = $_REQUEST['album'] ?? '';
4159 // we do not allow calls without album string
4161 throw new BadRequestException("no albumname specified");
4163 // check if album is existing
4165 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4169 if (!DBA::isResult($r)) {
4170 throw new BadRequestException("album not available");
4173 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4174 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4175 foreach ($r as $rr) {
4176 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4177 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4179 if (!DBA::isResult($photo_item)) {
4180 throw new InternalServerErrorException("problem with deleting items occured");
4182 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4185 // now let's delete all photos from the album
4186 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4188 // return success of deletion or error message
4190 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4191 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4193 throw new InternalServerErrorException("unknown error - deleting from database failed");
4198 * update the name of the album for all photos of an album
4200 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4201 * @return string|array
4202 * @throws BadRequestException
4203 * @throws ForbiddenException
4204 * @throws InternalServerErrorException
4206 function api_fr_photoalbum_update($type)
4208 if (api_user() === false) {
4209 throw new ForbiddenException();
4212 $album = $_REQUEST['album'] ?? '';
4213 $album_new = $_REQUEST['album_new'] ?? '';
4215 // we do not allow calls without album string
4217 throw new BadRequestException("no albumname specified");
4219 if ($album_new == "") {
4220 throw new BadRequestException("no new albumname specified");
4222 // check if album is existing
4223 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4224 throw new BadRequestException("album not available");
4226 // now let's update all photos to the albumname
4227 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4229 // return success of updating or error message
4231 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4232 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4234 throw new InternalServerErrorException("unknown error - updating in database failed");
4240 * list all photos of the authenticated user
4242 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4243 * @return string|array
4244 * @throws ForbiddenException
4245 * @throws InternalServerErrorException
4247 function api_fr_photos_list($type)
4249 if (api_user() === false) {
4250 throw new ForbiddenException();
4253 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4254 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4255 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4256 intval(local_user())
4259 'image/jpeg' => 'jpg',
4260 'image/png' => 'png',
4261 'image/gif' => 'gif'
4263 $data = ['photo'=>[]];
4264 if (DBA::isResult($r)) {
4265 foreach ($r as $rr) {
4267 $photo['id'] = $rr['resource-id'];
4268 $photo['album'] = $rr['album'];
4269 $photo['filename'] = $rr['filename'];
4270 $photo['type'] = $rr['type'];
4271 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4272 $photo['created'] = $rr['created'];
4273 $photo['edited'] = $rr['edited'];
4274 $photo['desc'] = $rr['desc'];
4276 if ($type == "xml") {
4277 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4279 $photo['thumb'] = $thumb;
4280 $data['photo'][] = $photo;
4284 return api_format_data("photos", $type, $data);
4288 * upload a new photo or change an existing photo
4290 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4291 * @return string|array
4292 * @throws BadRequestException
4293 * @throws ForbiddenException
4294 * @throws ImagickException
4295 * @throws InternalServerErrorException
4296 * @throws NotFoundException
4298 function api_fr_photo_create_update($type)
4300 if (api_user() === false) {
4301 throw new ForbiddenException();
4304 $photo_id = $_REQUEST['photo_id'] ?? null;
4305 $desc = $_REQUEST['desc'] ?? null;
4306 $album = $_REQUEST['album'] ?? null;
4307 $album_new = $_REQUEST['album_new'] ?? null;
4308 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4309 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4310 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4311 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4312 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4314 // do several checks on input parameters
4315 // we do not allow calls without album string
4316 if ($album == null) {
4317 throw new BadRequestException("no albumname specified");
4319 // if photo_id == null --> we are uploading a new photo
4320 if ($photo_id == null) {
4323 // error if no media posted in create-mode
4324 if (empty($_FILES['media'])) {
4326 throw new BadRequestException("no media data submitted");
4329 // album_new will be ignored in create-mode
4334 // check if photo is existing in databasei
4335 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4336 throw new BadRequestException("photo not available");
4340 // checks on acl strings provided by clients
4341 $acl_input_error = false;
4342 $acl_input_error |= check_acl_input($allow_cid);
4343 $acl_input_error |= check_acl_input($deny_cid);
4344 $acl_input_error |= check_acl_input($allow_gid);
4345 $acl_input_error |= check_acl_input($deny_gid);
4346 if ($acl_input_error) {
4347 throw new BadRequestException("acl data invalid");
4349 // now let's upload the new media in create-mode
4350 if ($mode == "create") {
4351 $media = $_FILES['media'];
4352 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4354 // return success of updating or error message
4355 if (!is_null($data)) {
4356 return api_format_data("photo_create", $type, $data);
4358 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4362 // now let's do the changes in update-mode
4363 if ($mode == "update") {
4364 $updated_fields = [];
4366 if (!is_null($desc)) {
4367 $updated_fields['desc'] = $desc;
4370 if (!is_null($album_new)) {
4371 $updated_fields['album'] = $album_new;
4374 if (!is_null($allow_cid)) {
4375 $allow_cid = trim($allow_cid);
4376 $updated_fields['allow_cid'] = $allow_cid;
4379 if (!is_null($deny_cid)) {
4380 $deny_cid = trim($deny_cid);
4381 $updated_fields['deny_cid'] = $deny_cid;
4384 if (!is_null($allow_gid)) {
4385 $allow_gid = trim($allow_gid);
4386 $updated_fields['allow_gid'] = $allow_gid;
4389 if (!is_null($deny_gid)) {
4390 $deny_gid = trim($deny_gid);
4391 $updated_fields['deny_gid'] = $deny_gid;
4395 if (count($updated_fields) > 0) {
4396 $nothingtodo = false;
4397 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4399 $nothingtodo = true;
4402 if (!empty($_FILES['media'])) {
4403 $nothingtodo = false;
4404 $media = $_FILES['media'];
4405 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4406 if (!is_null($data)) {
4407 return api_format_data("photo_update", $type, $data);
4411 // return success of updating or error message
4413 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4414 return api_format_data("photo_update", $type, ['$result' => $answer]);
4417 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4418 return api_format_data("photo_update", $type, ['$result' => $answer]);
4420 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4423 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4427 * delete a single photo from the database through api
4429 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4430 * @return string|array
4431 * @throws BadRequestException
4432 * @throws ForbiddenException
4433 * @throws InternalServerErrorException
4435 function api_fr_photo_delete($type)
4437 if (api_user() === false) {
4438 throw new ForbiddenException();
4442 $photo_id = $_REQUEST['photo_id'] ?? null;
4444 // do several checks on input parameters
4445 // we do not allow calls without photo id
4446 if ($photo_id == null) {
4447 throw new BadRequestException("no photo_id specified");
4450 // check if photo is existing in database
4451 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4452 throw new BadRequestException("photo not available");
4455 // now we can perform on the deletion of the photo
4456 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4458 // return success of deletion or error message
4460 // retrieve the id of the parent element (the photo element)
4461 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4462 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4464 if (!DBA::isResult($photo_item)) {
4465 throw new InternalServerErrorException("problem with deleting items occured");
4467 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4468 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4469 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4471 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4472 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4474 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4480 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4482 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4483 * @return string|array
4484 * @throws BadRequestException
4485 * @throws ForbiddenException
4486 * @throws InternalServerErrorException
4487 * @throws NotFoundException
4489 function api_fr_photo_detail($type)
4491 if (api_user() === false) {
4492 throw new ForbiddenException();
4494 if (empty($_REQUEST['photo_id'])) {
4495 throw new BadRequestException("No photo id.");
4498 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4499 $photo_id = $_REQUEST['photo_id'];
4501 // prepare json/xml output with data from database for the requested photo
4502 $data = prepare_photo_data($type, $scale, $photo_id);
4504 return api_format_data("photo_detail", $type, $data);
4509 * updates the profile image for the user (either a specified profile or the default profile)
4511 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4513 * @return string|array
4514 * @throws BadRequestException
4515 * @throws ForbiddenException
4516 * @throws ImagickException
4517 * @throws InternalServerErrorException
4518 * @throws NotFoundException
4519 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4521 function api_account_update_profile_image($type)
4523 if (api_user() === false) {
4524 throw new ForbiddenException();
4527 $profile_id = $_REQUEST['profile_id'] ?? 0;
4529 // error if image data is missing
4530 if (empty($_FILES['image'])) {
4531 throw new BadRequestException("no media data submitted");
4534 // check if specified profile id is valid
4535 if ($profile_id != 0) {
4536 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4537 // error message if specified profile id is not in database
4538 if (!DBA::isResult($profile)) {
4539 throw new BadRequestException("profile_id not available");
4541 $is_default_profile = $profile['is-default'];
4543 $is_default_profile = 1;
4546 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4548 if (!empty($_FILES['image'])) {
4549 $media = $_FILES['image'];
4550 } elseif (!empty($_FILES['media'])) {
4551 $media = $_FILES['media'];
4553 // save new profile image
4554 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4557 if (is_array($media['type'])) {
4558 $filetype = $media['type'][0];
4560 $filetype = $media['type'];
4562 if ($filetype == "image/jpeg") {
4564 } elseif ($filetype == "image/png") {
4567 throw new InternalServerErrorException('Unsupported filetype');
4570 // change specified profile or all profiles to the new resource-id
4571 if ($is_default_profile) {
4572 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4573 Photo::update(['profile' => false], $condition);
4575 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4576 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4577 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4580 Contact::updateSelfFromUserID(api_user(), true);
4582 // Update global directory in background
4583 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4584 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4585 Worker::add(PRIORITY_LOW, "Directory", $url);
4588 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4590 // output for client
4592 return api_account_verify_credentials($type);
4594 // SaveMediaToDatabase failed for some reason
4595 throw new InternalServerErrorException("image upload failed");
4599 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4600 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4601 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4602 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4603 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4604 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4605 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4606 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4607 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4610 * Update user profile
4612 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4614 * @return array|string
4615 * @throws BadRequestException
4616 * @throws ForbiddenException
4617 * @throws ImagickException
4618 * @throws InternalServerErrorException
4619 * @throws UnauthorizedException
4621 function api_account_update_profile($type)
4623 $local_user = api_user();
4624 $api_user = api_get_user(DI::app());
4626 if (!empty($_POST['name'])) {
4627 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4628 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4629 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4630 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4633 if (isset($_POST['description'])) {
4634 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4635 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4636 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4639 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4640 // Update global directory in background
4641 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4642 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4645 return api_account_verify_credentials($type);
4648 /// @TODO move to top of file or somewhere better
4649 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4653 * @param string $acl_string
4657 function check_acl_input($acl_string)
4659 if (empty($acl_string)) {
4663 $contact_not_found = false;
4665 // split <x><y><z> into array of cid's
4666 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4668 // check for each cid if it is available on server
4669 $cid_array = $array[0];
4670 foreach ($cid_array as $cid) {
4671 $cid = str_replace("<", "", $cid);
4672 $cid = str_replace(">", "", $cid);
4673 $condition = ['id' => $cid, 'uid' => api_user()];
4674 $contact_not_found |= !DBA::exists('contact', $condition);
4676 return $contact_not_found;
4680 * @param string $mediatype
4681 * @param array $media
4682 * @param string $type
4683 * @param string $album
4684 * @param string $allow_cid
4685 * @param string $deny_cid
4686 * @param string $allow_gid
4687 * @param string $deny_gid
4688 * @param string $desc
4689 * @param integer $profile
4690 * @param boolean $visibility
4691 * @param string $photo_id
4693 * @throws BadRequestException
4694 * @throws ForbiddenException
4695 * @throws ImagickException
4696 * @throws InternalServerErrorException
4697 * @throws NotFoundException
4698 * @throws UnauthorizedException
4700 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)
4708 if (is_array($media)) {
4709 if (is_array($media['tmp_name'])) {
4710 $src = $media['tmp_name'][0];
4712 $src = $media['tmp_name'];
4714 if (is_array($media['name'])) {
4715 $filename = basename($media['name'][0]);
4717 $filename = basename($media['name']);
4719 if (is_array($media['size'])) {
4720 $filesize = intval($media['size'][0]);
4722 $filesize = intval($media['size']);
4724 if (is_array($media['type'])) {
4725 $filetype = $media['type'][0];
4727 $filetype = $media['type'];
4731 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4734 "File upload src: " . $src . " - filename: " . $filename .
4735 " - size: " . $filesize . " - type: " . $filetype,
4739 // check if there was a php upload error
4740 if ($filesize == 0 && $media['error'] == 1) {
4741 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4743 // check against max upload size within Friendica instance
4744 $maximagesize = DI::config()->get('system', 'maximagesize');
4745 if ($maximagesize && ($filesize > $maximagesize)) {
4746 $formattedBytes = Strings::formatBytes($maximagesize);
4747 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4750 // create Photo instance with the data of the image
4751 $imagedata = @file_get_contents($src);
4752 $Image = new Image($imagedata, $filetype);
4753 if (!$Image->isValid()) {
4754 throw new InternalServerErrorException("unable to process image data");
4757 // check orientation of image
4758 $Image->orient($src);
4761 // check max length of images on server
4762 $max_length = DI::config()->get('system', 'max_image_length');
4764 $max_length = MAX_IMAGE_LENGTH;
4766 if ($max_length > 0) {
4767 $Image->scaleDown($max_length);
4768 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4770 $width = $Image->getWidth();
4771 $height = $Image->getHeight();
4773 // create a new resource-id if not already provided
4774 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4776 if ($mediatype == "photo") {
4777 // upload normal image (scales 0, 1, 2)
4778 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4780 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4782 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4784 if ($width > 640 || $height > 640) {
4785 $Image->scaleDown(640);
4786 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4788 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4792 if ($width > 320 || $height > 320) {
4793 $Image->scaleDown(320);
4794 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4796 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4799 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4800 } elseif ($mediatype == "profileimage") {
4801 // upload profile image (scales 4, 5, 6)
4802 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4804 if ($width > 300 || $height > 300) {
4805 $Image->scaleDown(300);
4806 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4808 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4812 if ($width > 80 || $height > 80) {
4813 $Image->scaleDown(80);
4814 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4816 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4820 if ($width > 48 || $height > 48) {
4821 $Image->scaleDown(48);
4822 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4824 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4827 $Image->__destruct();
4828 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4831 if (isset($r) && $r) {
4832 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4833 if ($photo_id == null && $mediatype == "photo") {
4834 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4836 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4837 return prepare_photo_data($type, false, $resource_id);
4839 throw new InternalServerErrorException("image upload failed");
4845 * @param string $hash
4846 * @param string $allow_cid
4847 * @param string $deny_cid
4848 * @param string $allow_gid
4849 * @param string $deny_gid
4850 * @param string $filetype
4851 * @param boolean $visibility
4852 * @throws InternalServerErrorException
4854 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4856 // get data about the api authenticated user
4857 $uri = Item::newURI(intval(api_user()));
4858 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4861 $arr['guid'] = System::createUUID();
4862 $arr['uid'] = intval(api_user());
4864 $arr['parent-uri'] = $uri;
4865 $arr['type'] = 'photo';
4867 $arr['resource-id'] = $hash;
4868 $arr['contact-id'] = $owner_record['id'];
4869 $arr['owner-name'] = $owner_record['name'];
4870 $arr['owner-link'] = $owner_record['url'];
4871 $arr['owner-avatar'] = $owner_record['thumb'];
4872 $arr['author-name'] = $owner_record['name'];
4873 $arr['author-link'] = $owner_record['url'];
4874 $arr['author-avatar'] = $owner_record['thumb'];
4876 $arr['allow_cid'] = $allow_cid;
4877 $arr['allow_gid'] = $allow_gid;
4878 $arr['deny_cid'] = $deny_cid;
4879 $arr['deny_gid'] = $deny_gid;
4880 $arr['visible'] = $visibility;
4884 'image/jpeg' => 'jpg',
4885 'image/png' => 'png',
4886 'image/gif' => 'gif'
4889 // adds link to the thumbnail scale photo
4890 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4891 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4894 // do the magic for storing the item in the database and trigger the federation to other contacts
4900 * @param string $type
4902 * @param string $photo_id
4905 * @throws BadRequestException
4906 * @throws ForbiddenException
4907 * @throws ImagickException
4908 * @throws InternalServerErrorException
4909 * @throws NotFoundException
4910 * @throws UnauthorizedException
4912 function prepare_photo_data($type, $scale, $photo_id)
4915 $user_info = api_get_user($a);
4917 if ($user_info === false) {
4918 throw new ForbiddenException();
4921 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4922 $data_sql = ($scale === false ? "" : "data, ");
4924 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4925 // clients needs to convert this in their way for further processing
4927 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4928 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4929 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4930 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4931 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4932 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4934 intval(local_user()),
4935 DBA::escape($photo_id),
4940 'image/jpeg' => 'jpg',
4941 'image/png' => 'png',
4942 'image/gif' => 'gif'
4945 // prepare output data for photo
4946 if (DBA::isResult($r)) {
4947 $data = ['photo' => $r[0]];
4948 $data['photo']['id'] = $data['photo']['resource-id'];
4949 if ($scale !== false) {
4950 $data['photo']['data'] = base64_encode($data['photo']['data']);
4952 unset($data['photo']['datasize']); //needed only with scale param
4954 if ($type == "xml") {
4955 $data['photo']['links'] = [];
4956 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4957 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4959 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4962 $data['photo']['link'] = [];
4963 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4965 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4966 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4970 unset($data['photo']['resource-id']);
4971 unset($data['photo']['minscale']);
4972 unset($data['photo']['maxscale']);
4974 throw new NotFoundException();
4977 // retrieve item element for getting activities (like, dislike etc.) related to photo
4978 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4979 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4980 if (!DBA::isResult($item)) {
4981 throw new NotFoundException('Photo-related item not found.');
4984 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4986 // retrieve comments on photo
4987 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4988 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4990 $statuses = Item::selectForUser(api_user(), [], $condition);
4992 // prepare output of comments
4993 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
4995 if ($type == "xml") {
4997 foreach ($commentData as $comment) {
4998 $comments[$k++ . ":comment"] = $comment;
5001 foreach ($commentData as $comment) {
5002 $comments[] = $comment;
5005 $data['photo']['friendica_comments'] = $comments;
5007 // include info if rights on photo and rights on item are mismatching
5008 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5009 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5010 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5011 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5012 $data['photo']['rights_mismatch'] = $rights_mismatch;
5019 * Similar as /mod/redir.php
5020 * redirect to 'url' after dfrn auth
5022 * Why this when there is mod/redir.php already?
5023 * This use api_user() and api_login()
5026 * c_url: url of remote contact to auth to
5027 * url: string, url to redirect after auth
5029 function api_friendica_remoteauth()
5031 $url = $_GET['url'] ?? '';
5032 $c_url = $_GET['c_url'] ?? '';
5034 if ($url === '' || $c_url === '') {
5035 throw new BadRequestException("Wrong parameters.");
5038 $c_url = Strings::normaliseLink($c_url);
5042 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5043 if (!DBA::isResult($contact)) {
5044 throw new BadRequestException("Unknown contact");
5047 $cid = $contact['id'];
5049 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5051 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5052 System::externalRedirect($url ?: $c_url);
5055 if ($contact['duplex'] && $contact['issued-id']) {
5056 $orig_id = $contact['issued-id'];
5057 $dfrn_id = '1:' . $orig_id;
5059 if ($contact['duplex'] && $contact['dfrn-id']) {
5060 $orig_id = $contact['dfrn-id'];
5061 $dfrn_id = '0:' . $orig_id;
5064 $sec = Strings::getRandomHex();
5066 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5067 'sec' => $sec, 'expire' => time() + 45];
5068 DBA::insert('profile_check', $fields);
5070 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5071 $dest = ($url ? '&destination_url=' . $url : '');
5073 System::externalRedirect(
5074 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5075 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5076 . '&type=profile&sec=' . $sec . $dest
5079 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5082 * Return an item with announcer data if it had been announced
5084 * @param array $item Item array
5085 * @return array Item array with announce data
5087 function api_get_announce($item)
5089 // Quit if the item already has got a different owner and author
5090 if ($item['owner-id'] != $item['author-id']) {
5094 // Don't change original or Diaspora posts
5095 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5099 // Quit if we do now the original author and it had been a post from a native network
5100 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5104 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5105 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5106 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5107 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5108 if (!DBA::isResult($announce)) {
5112 return array_merge($item, $announce);
5116 * Return the item shared, if the item contains only the [share] tag
5118 * @param array $item Sharer item
5119 * @return array|false Shared item or false if not a reshare
5120 * @throws ImagickException
5121 * @throws InternalServerErrorException
5123 function api_share_as_retweet(&$item)
5125 $body = trim($item["body"]);
5127 if (Diaspora::isReshare($body, false) === false) {
5128 if ($item['author-id'] == $item['owner-id']) {
5131 // Reshares from OStatus, ActivityPub and Twitter
5132 $reshared_item = $item;
5133 $reshared_item['owner-id'] = $reshared_item['author-id'];
5134 $reshared_item['owner-link'] = $reshared_item['author-link'];
5135 $reshared_item['owner-name'] = $reshared_item['author-name'];
5136 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5137 return $reshared_item;
5141 $reshared = Item::getShareArray($item);
5142 if (empty($reshared)) {
5146 $reshared_item = $item;
5148 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5152 if (!empty($reshared['comment'])) {
5153 $item['body'] = $reshared['comment'];
5156 $reshared_item["share-pre-body"] = $reshared['comment'];
5157 $reshared_item["body"] = $reshared['shared'];
5158 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5159 $reshared_item["author-name"] = $reshared['author'];
5160 $reshared_item["author-link"] = $reshared['profile'];
5161 $reshared_item["author-avatar"] = $reshared['avatar'];
5162 $reshared_item["plink"] = $reshared['link'] ?? '';
5163 $reshared_item["created"] = $reshared['posted'];
5164 $reshared_item["edited"] = $reshared['posted'];
5166 // Try to fetch the original item
5167 if (!empty($reshared['guid'])) {
5168 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5169 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5170 $condition = ['id' => $original_id];
5175 if (!empty($condition)) {
5176 $original_item = Item::selectFirst([], $condition);
5177 if (DBA::isResult($original_item)) {
5178 $reshared_item = array_merge($reshared_item, $original_item);
5182 return $reshared_item;
5187 * @param array $item
5192 function api_in_reply_to($item)
5196 $in_reply_to['status_id'] = null;
5197 $in_reply_to['user_id'] = null;
5198 $in_reply_to['status_id_str'] = null;
5199 $in_reply_to['user_id_str'] = null;
5200 $in_reply_to['screen_name'] = null;
5202 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5203 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5204 if (DBA::isResult($parent)) {
5205 $in_reply_to['status_id'] = intval($parent['id']);
5207 $in_reply_to['status_id'] = intval($item['parent']);
5210 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5212 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5213 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5215 if (DBA::isResult($parent)) {
5216 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5217 $in_reply_to['user_id'] = intval($parent['author-id']);
5218 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5221 // There seems to be situation, where both fields are identical:
5222 // https://github.com/friendica/friendica/issues/1010
5223 // This is a bugfix for that.
5224 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5225 Logger::warning(API_LOG_PREFIX . 'ID {id} is similar to reply-to {reply-to}', ['module' => 'api', 'action' => 'in_reply_to', 'id' => $item['id'], 'reply-to' => $in_reply_to['status_id']]);
5226 $in_reply_to['status_id'] = null;
5227 $in_reply_to['user_id'] = null;
5228 $in_reply_to['status_id_str'] = null;
5229 $in_reply_to['user_id_str'] = null;
5230 $in_reply_to['screen_name'] = null;
5234 return $in_reply_to;
5239 * @param string $text
5242 * @throws InternalServerErrorException
5244 function api_clean_plain_items($text)
5246 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5248 $text = BBCode::cleanPictureLinks($text);
5249 $URLSearchString = "^\[\]";
5251 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5253 if ($include_entities == "true") {
5254 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5257 // Simplify "attachment" element
5258 $text = BBCode::removeAttachment($text);
5265 * @param array $contacts
5269 function api_best_nickname(&$contacts)
5273 if (count($contacts) == 0) {
5277 foreach ($contacts as $contact) {
5278 if ($contact["network"] == "") {
5279 $contact["network"] = "dfrn";
5280 $best_contact = [$contact];
5284 if (sizeof($best_contact) == 0) {
5285 foreach ($contacts as $contact) {
5286 if ($contact["network"] == "dfrn") {
5287 $best_contact = [$contact];
5292 if (sizeof($best_contact) == 0) {
5293 foreach ($contacts as $contact) {
5294 if ($contact["network"] == "dspr") {
5295 $best_contact = [$contact];
5300 if (sizeof($best_contact) == 0) {
5301 foreach ($contacts as $contact) {
5302 if ($contact["network"] == "stat") {
5303 $best_contact = [$contact];
5308 if (sizeof($best_contact) == 0) {
5309 foreach ($contacts as $contact) {
5310 if ($contact["network"] == "pump") {
5311 $best_contact = [$contact];
5316 if (sizeof($best_contact) == 0) {
5317 foreach ($contacts as $contact) {
5318 if ($contact["network"] == "twit") {
5319 $best_contact = [$contact];
5324 if (sizeof($best_contact) == 1) {
5325 $contacts = $best_contact;
5327 $contacts = [$contacts[0]];
5332 * Return all or a specified group of the user with the containing contacts.
5334 * @param string $type Return type (atom, rss, xml, json)
5336 * @return array|string
5337 * @throws BadRequestException
5338 * @throws ForbiddenException
5339 * @throws ImagickException
5340 * @throws InternalServerErrorException
5341 * @throws UnauthorizedException
5343 function api_friendica_group_show($type)
5347 if (api_user() === false) {
5348 throw new ForbiddenException();
5352 $user_info = api_get_user($a);
5353 $gid = $_REQUEST['gid'] ?? 0;
5354 $uid = $user_info['uid'];
5356 // get data of the specified group id or all groups if not specified
5359 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5363 // error message if specified gid is not in database
5364 if (!DBA::isResult($r)) {
5365 throw new BadRequestException("gid not available");
5369 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5374 // loop through all groups and retrieve all members for adding data in the user array
5376 foreach ($r as $rr) {
5377 $members = Contact::getByGroupId($rr['id']);
5380 if ($type == "xml") {
5381 $user_element = "users";
5383 foreach ($members as $member) {
5384 $user = api_get_user($a, $member['nurl']);
5385 $users[$k++.":user"] = $user;
5388 $user_element = "user";
5389 foreach ($members as $member) {
5390 $user = api_get_user($a, $member['nurl']);
5394 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5396 return api_format_data("groups", $type, ['group' => $grps]);
5398 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5402 * Delete the specified group of the user.
5404 * @param string $type Return type (atom, rss, xml, json)
5406 * @return array|string
5407 * @throws BadRequestException
5408 * @throws ForbiddenException
5409 * @throws ImagickException
5410 * @throws InternalServerErrorException
5411 * @throws UnauthorizedException
5413 function api_friendica_group_delete($type)
5417 if (api_user() === false) {
5418 throw new ForbiddenException();
5422 $user_info = api_get_user($a);
5423 $gid = $_REQUEST['gid'] ?? 0;
5424 $name = $_REQUEST['name'] ?? '';
5425 $uid = $user_info['uid'];
5427 // error if no gid specified
5428 if ($gid == 0 || $name == "") {
5429 throw new BadRequestException('gid or name not specified');
5432 // get data of the specified group id
5434 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5438 // error message if specified gid is not in database
5439 if (!DBA::isResult($r)) {
5440 throw new BadRequestException('gid not available');
5443 // get data of the specified group id and group name
5445 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5450 // error message if specified gid is not in database
5451 if (!DBA::isResult($rname)) {
5452 throw new BadRequestException('wrong group name');
5456 $ret = Group::removeByName($uid, $name);
5459 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5460 return api_format_data("group_delete", $type, ['result' => $success]);
5462 throw new BadRequestException('other API error');
5465 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5470 * @param string $type Return type (atom, rss, xml, json)
5472 * @return array|string
5473 * @throws BadRequestException
5474 * @throws ForbiddenException
5475 * @throws ImagickException
5476 * @throws InternalServerErrorException
5477 * @throws UnauthorizedException
5478 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5480 function api_lists_destroy($type)
5484 if (api_user() === false) {
5485 throw new ForbiddenException();
5489 $user_info = api_get_user($a);
5490 $gid = $_REQUEST['list_id'] ?? 0;
5491 $uid = $user_info['uid'];
5493 // error if no gid specified
5495 throw new BadRequestException('gid not specified');
5498 // get data of the specified group id
5499 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5500 // error message if specified gid is not in database
5502 throw new BadRequestException('gid not available');
5505 if (Group::remove($gid)) {
5507 'name' => $group['name'],
5508 'id' => intval($gid),
5509 'id_str' => (string) $gid,
5510 'user' => $user_info
5513 return api_format_data("lists", $type, ['lists' => $list]);
5516 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5519 * Add a new group to the database.
5521 * @param string $name Group name
5522 * @param int $uid User ID
5523 * @param array $users List of users to add to the group
5526 * @throws BadRequestException
5528 function group_create($name, $uid, $users = [])
5530 // error if no name specified
5532 throw new BadRequestException('group name not specified');
5535 // get data of the specified group name
5537 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5541 // error message if specified group name already exists
5542 if (DBA::isResult($rname)) {
5543 throw new BadRequestException('group name already exists');
5546 // check if specified group name is a deleted group
5548 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5552 // error message if specified group name already exists
5553 if (DBA::isResult($rname)) {
5554 $reactivate_group = true;
5558 $ret = Group::create($uid, $name);
5560 $gid = Group::getIdByName($uid, $name);
5562 throw new BadRequestException('other API error');
5566 $erroraddinguser = false;
5568 foreach ($users as $user) {
5569 $cid = $user['cid'];
5570 // check if user really exists as contact
5572 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5576 if (count($contact)) {
5577 Group::addMember($gid, $cid);
5579 $erroraddinguser = true;
5580 $errorusers[] = $cid;
5584 // return success message incl. missing users in array
5585 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5587 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5591 * Create the specified group with the posted array of contacts.
5593 * @param string $type Return type (atom, rss, xml, json)
5595 * @return array|string
5596 * @throws BadRequestException
5597 * @throws ForbiddenException
5598 * @throws ImagickException
5599 * @throws InternalServerErrorException
5600 * @throws UnauthorizedException
5602 function api_friendica_group_create($type)
5606 if (api_user() === false) {
5607 throw new ForbiddenException();
5611 $user_info = api_get_user($a);
5612 $name = $_REQUEST['name'] ?? '';
5613 $uid = $user_info['uid'];
5614 $json = json_decode($_POST['json'], true);
5615 $users = $json['user'];
5617 $success = group_create($name, $uid, $users);
5619 return api_format_data("group_create", $type, ['result' => $success]);
5621 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5624 * Create a new group.
5626 * @param string $type Return type (atom, rss, xml, json)
5628 * @return array|string
5629 * @throws BadRequestException
5630 * @throws ForbiddenException
5631 * @throws ImagickException
5632 * @throws InternalServerErrorException
5633 * @throws UnauthorizedException
5634 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5636 function api_lists_create($type)
5640 if (api_user() === false) {
5641 throw new ForbiddenException();
5645 $user_info = api_get_user($a);
5646 $name = $_REQUEST['name'] ?? '';
5647 $uid = $user_info['uid'];
5649 $success = group_create($name, $uid);
5650 if ($success['success']) {
5652 'name' => $success['name'],
5653 'id' => intval($success['gid']),
5654 'id_str' => (string) $success['gid'],
5655 'user' => $user_info
5658 return api_format_data("lists", $type, ['lists'=>$grp]);
5661 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5664 * Update the specified group with the posted array of contacts.
5666 * @param string $type Return type (atom, rss, xml, json)
5668 * @return array|string
5669 * @throws BadRequestException
5670 * @throws ForbiddenException
5671 * @throws ImagickException
5672 * @throws InternalServerErrorException
5673 * @throws UnauthorizedException
5675 function api_friendica_group_update($type)
5679 if (api_user() === false) {
5680 throw new ForbiddenException();
5684 $user_info = api_get_user($a);
5685 $uid = $user_info['uid'];
5686 $gid = $_REQUEST['gid'] ?? 0;
5687 $name = $_REQUEST['name'] ?? '';
5688 $json = json_decode($_POST['json'], true);
5689 $users = $json['user'];
5691 // error if no name specified
5693 throw new BadRequestException('group name not specified');
5696 // error if no gid specified
5698 throw new BadRequestException('gid not specified');
5702 $members = Contact::getByGroupId($gid);
5703 foreach ($members as $member) {
5704 $cid = $member['id'];
5705 foreach ($users as $user) {
5706 $found = ($user['cid'] == $cid ? true : false);
5708 if (!isset($found) || !$found) {
5709 Group::removeMemberByName($uid, $name, $cid);
5714 $erroraddinguser = false;
5716 foreach ($users as $user) {
5717 $cid = $user['cid'];
5718 // check if user really exists as contact
5720 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5725 if (count($contact)) {
5726 Group::addMember($gid, $cid);
5728 $erroraddinguser = true;
5729 $errorusers[] = $cid;
5733 // return success message incl. missing users in array
5734 $status = ($erroraddinguser ? "missing user" : "ok");
5735 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5736 return api_format_data("group_update", $type, ['result' => $success]);
5739 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5742 * Update information about a group.
5744 * @param string $type Return type (atom, rss, xml, json)
5746 * @return array|string
5747 * @throws BadRequestException
5748 * @throws ForbiddenException
5749 * @throws ImagickException
5750 * @throws InternalServerErrorException
5751 * @throws UnauthorizedException
5752 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5754 function api_lists_update($type)
5758 if (api_user() === false) {
5759 throw new ForbiddenException();
5763 $user_info = api_get_user($a);
5764 $gid = $_REQUEST['list_id'] ?? 0;
5765 $name = $_REQUEST['name'] ?? '';
5766 $uid = $user_info['uid'];
5768 // error if no gid specified
5770 throw new BadRequestException('gid not specified');
5773 // get data of the specified group id
5774 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5775 // error message if specified gid is not in database
5777 throw new BadRequestException('gid not available');
5780 if (Group::update($gid, $name)) {
5783 'id' => intval($gid),
5784 'id_str' => (string) $gid,
5785 'user' => $user_info
5788 return api_format_data("lists", $type, ['lists' => $list]);
5792 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5796 * @param string $type Return type (atom, rss, xml, json)
5798 * @return array|string
5799 * @throws BadRequestException
5800 * @throws ForbiddenException
5801 * @throws ImagickException
5802 * @throws InternalServerErrorException
5804 function api_friendica_activity($type)
5808 if (api_user() === false) {
5809 throw new ForbiddenException();
5811 $verb = strtolower($a->argv[3]);
5812 $verb = preg_replace("|\..*$|", "", $verb);
5814 $id = $_REQUEST['id'] ?? 0;
5816 $res = Item::performActivity($id, $verb);
5819 if ($type == "xml") {
5824 return api_format_data('ok', $type, ['ok' => $ok]);
5826 throw new BadRequestException('Error adding activity');
5830 /// @TODO move to top of file or somewhere better
5831 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5832 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5833 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5834 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5835 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5836 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5837 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5838 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5839 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5840 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5843 * Returns notifications
5845 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5847 * @return string|array
5848 * @throws ForbiddenException
5849 * @throws BadRequestException
5852 function api_friendica_notification($type)
5856 if (api_user() === false) {
5857 throw new ForbiddenException();
5860 throw new BadRequestException("Invalid argument count");
5863 $notifications = DI::notification()->getApiList(local_user());
5865 if ($type == "xml") {
5867 if (!empty($notifications)) {
5868 foreach ($notifications as $notification) {
5869 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5873 $result = $xmlnotes;
5874 } elseif (count($notifications) > 0) {
5875 $result = $notifications->getArrayCopy();
5880 return api_format_data("notes", $type, ['note' => $result]);
5884 * Set notification as seen and returns associated item (if possible)
5886 * POST request with 'id' param as notification id
5888 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5889 * @return string|array
5890 * @throws BadRequestException
5891 * @throws ForbiddenException
5892 * @throws ImagickException
5893 * @throws InternalServerErrorException
5894 * @throws UnauthorizedException
5896 function api_friendica_notification_seen($type)
5899 $user_info = api_get_user($a);
5901 if (api_user() === false || $user_info === false) {
5902 throw new ForbiddenException();
5904 if ($a->argc !== 4) {
5905 throw new BadRequestException("Invalid argument count");
5908 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5911 $notify = DI::notify()->getByID($id, api_user());
5912 DI::notify()->setSeen(true, $notify);
5914 if ($notify->otype === Notify\ObjectType::ITEM) {
5915 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5916 if (DBA::isResult($item)) {
5917 // we found the item, return it to the user
5918 $ret = api_format_items([$item], $user_info, false, $type);
5919 $data = ['status' => $ret];
5920 return api_format_data("status", $type, $data);
5922 // the item can't be found, but we set the notification as seen, so we count this as a success
5924 return api_format_data('result', $type, ['result' => "success"]);
5925 } catch (NotFoundException $e) {
5926 throw new BadRequestException('Invalid argument', $e);
5927 } catch (Exception $e) {
5928 throw new InternalServerErrorException('Internal Server exception', $e);
5932 /// @TODO move to top of file or somewhere better
5933 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5934 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5937 * update a direct_message to seen state
5939 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5940 * @return string|array (success result=ok, error result=error with error message)
5941 * @throws BadRequestException
5942 * @throws ForbiddenException
5943 * @throws ImagickException
5944 * @throws InternalServerErrorException
5945 * @throws UnauthorizedException
5947 function api_friendica_direct_messages_setseen($type)
5950 if (api_user() === false) {
5951 throw new ForbiddenException();
5955 $user_info = api_get_user($a);
5956 $uid = $user_info['uid'];
5957 $id = $_REQUEST['id'] ?? 0;
5959 // return error if id is zero
5961 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5962 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5965 // error message if specified id is not in database
5966 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5967 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5968 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5971 // update seen indicator
5972 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5976 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5977 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5979 $answer = ['result' => 'error', 'message' => 'unknown error'];
5980 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5984 /// @TODO move to top of file or somewhere better
5985 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5988 * search for direct_messages containing a searchstring through api
5990 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5991 * @param string $box
5992 * @return string|array (success: success=true if found and search_result contains found messages,
5993 * success=false if nothing was found, search_result='nothing found',
5994 * error: result=error with error message)
5995 * @throws BadRequestException
5996 * @throws ForbiddenException
5997 * @throws ImagickException
5998 * @throws InternalServerErrorException
5999 * @throws UnauthorizedException
6001 function api_friendica_direct_messages_search($type, $box = "")
6005 if (api_user() === false) {
6006 throw new ForbiddenException();
6010 $user_info = api_get_user($a);
6011 $searchstring = $_REQUEST['searchstring'] ?? '';
6012 $uid = $user_info['uid'];
6014 // error if no searchstring specified
6015 if ($searchstring == "") {
6016 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6017 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6020 // get data for the specified searchstring
6022 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
6024 DBA::escape('%'.$searchstring.'%')
6027 $profile_url = $user_info["url"];
6029 // message if nothing was found
6030 if (!DBA::isResult($r)) {
6031 $success = ['success' => false, 'search_results' => 'problem with query'];
6032 } elseif (count($r) == 0) {
6033 $success = ['success' => false, 'search_results' => 'nothing found'];
6036 foreach ($r as $item) {
6037 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6038 $recipient = $user_info;
6039 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6040 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6041 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6042 $sender = $user_info;
6045 if (isset($recipient) && isset($sender)) {
6046 $ret[] = api_format_messages($item, $recipient, $sender);
6049 $success = ['success' => true, 'search_results' => $ret];
6052 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6055 /// @TODO move to top of file or somewhere better
6056 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6059 * Returns a list of saved searches.
6061 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6063 * @param string $type Return format: json or xml
6065 * @return string|array
6068 function api_saved_searches_list($type)
6070 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6073 while ($term = DBA::fetch($terms)) {
6075 'created_at' => api_date(time()),
6076 'id' => intval($term['id']),
6077 'id_str' => $term['id'],
6078 'name' => $term['term'],
6080 'query' => $term['term']
6086 return api_format_data("terms", $type, ['terms' => $result]);
6089 /// @TODO move to top of file or somewhere better
6090 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6093 * Number of comments
6095 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6097 * @param object $data [Status, Status]
6101 function bindComments(&$data)
6103 if (count($data) == 0) {
6109 foreach ($data as $item) {
6110 $ids[] = $item['id'];
6113 $idStr = DBA::escape(implode(', ', $ids));
6114 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6115 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6116 $itemsData = DBA::toArray($items);
6118 foreach ($itemsData as $item) {
6119 $comments[$item['parent']] = $item['comments'];
6122 foreach ($data as $idx => $item) {
6124 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6129 @TODO Maybe open to implement?
6131 [pagename] => api/1.1/statuses/lookup.json
6132 [id] => 605138389168451584
6133 [include_cards] => true
6134 [cards_platform] => Android-12
6135 [include_entities] => true
6136 [include_my_retweet] => 1
6138 [include_reply_count] => true
6139 [include_descendent_reply_count] => true
6143 Not implemented by now:
6144 statuses/retweets_of_me
6149 account/update_location
6150 account/update_profile_background_image
6153 friendica/profile/update
6154 friendica/profile/create
6155 friendica/profile/delete
6157 Not implemented in status.net:
6158 statuses/retweeted_to_me
6159 statuses/retweeted_by_me
6160 direct_messages/destroy
6162 account/update_delivery_device
6163 notifications/follow