3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Session;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Network\FKOAuth1;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPException\BadRequestException;
35 use Friendica\Network\HTTPException\ExpectationFailedException;
36 use Friendica\Network\HTTPException\ForbiddenException;
37 use Friendica\Network\HTTPException\InternalServerErrorException;
38 use Friendica\Network\HTTPException\MethodNotAllowedException;
39 use Friendica\Network\HTTPException\NotFoundException;
40 use Friendica\Network\HTTPException\NotImplementedException;
41 use Friendica\Network\HTTPException\TooManyRequestsException;
42 use Friendica\Network\HTTPException\UnauthorizedException;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Activity;
45 use Friendica\Protocol\Diaspora;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy as ProxyUtils;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
53 require_once __DIR__ . '/../mod/share.php';
54 require_once __DIR__ . '/../mod/item.php';
55 require_once __DIR__ . '/../mod/wall_upload.php';
57 define('API_METHOD_ANY', '*');
58 define('API_METHOD_GET', 'GET');
59 define('API_METHOD_POST', 'POST,PUT');
60 define('API_METHOD_DELETE', 'POST,DELETE');
62 define('API_LOG_PREFIX', 'API {action} - ');
68 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
69 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
70 * into a page, and visitors will post something without noticing it).
72 * @brief Auth API user
76 if (!empty($_SESSION['allow_api'])) {
84 * Clients can send 'source' parameter to be show in post metadata
85 * as "sent via <source>".
86 * Some clients doesn't send a source param, we support ones we know
89 * @brief Get source name from API client
92 * Client source name, default to "api" if unset/unknown
97 if (requestdata('source')) {
98 return requestdata('source');
101 // Support for known clients that doesn't send a source name
102 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
103 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
107 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
109 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
116 * @brief Format date for API
118 * @param string $str Source date, as UTC
119 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
122 function api_date($str)
124 // Wed May 23 06:01:13 +0000 2007
125 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
129 * Register a function to be the endpoint for defined API path.
131 * @brief Register API endpoint
133 * @param string $path API URL path, relative to DI::baseUrl()
134 * @param string $func Function name to call on path request
135 * @param bool $auth API need logged user
136 * @param string $method HTTP method reqiured to call this endpoint.
137 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
138 * Default to API_METHOD_ANY
140 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
150 // Workaround for hotot
151 $path = str_replace("api/", "api/1.1/", $path);
161 * Log in user via OAuth1 or Simple HTTP Auth.
162 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
164 * @brief Login API user
167 * @throws ForbiddenException
168 * @throws InternalServerErrorException
169 * @throws UnauthorizedException
170 * @hook 'authenticate'
172 * 'username' => username from login form
173 * 'password' => password from login form
174 * 'authenticated' => return status,
175 * 'user_record' => return authenticated user record
177 function api_login(App $a)
179 $oauth1 = new FKOAuth1();
182 $request = OAuthRequest::from_request();
183 list($consumer, $token) = $oauth1->verify_request($request);
184 if (!is_null($token)) {
185 $oauth1->loginUser($token->uid);
186 Session::set('allow_api', true);
189 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
190 var_dump($consumer, $token);
192 } catch (Exception $e) {
193 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
196 // workaround for HTTP-auth in CGI mode
197 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
198 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
199 if (strlen($userpass)) {
200 list($name, $password) = explode(':', $userpass);
201 $_SERVER['PHP_AUTH_USER'] = $name;
202 $_SERVER['PHP_AUTH_PW'] = $password;
206 if (empty($_SERVER['PHP_AUTH_USER'])) {
207 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
208 header('WWW-Authenticate: Basic realm="Friendica"');
209 throw new UnauthorizedException("This API requires login");
212 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
213 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
215 // allow "user@server" login (but ignore 'server' part)
216 $at = strstr($user, "@", true);
221 // next code from mod/auth.php. needs better solution
225 'username' => trim($user),
226 'password' => trim($password),
227 'authenticated' => 0,
228 'user_record' => null,
232 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
233 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
234 * and later addons should not interfere with an earlier one that succeeded.
236 Hook::callAll('authenticate', $addon_auth);
238 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
239 $record = $addon_auth['user_record'];
241 $user_id = User::authenticate(trim($user), trim($password), true);
242 if ($user_id !== false) {
243 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
247 if (!DBA::isResult($record)) {
248 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
249 header('WWW-Authenticate: Basic realm="Friendica"');
250 //header('HTTP/1.0 401 Unauthorized');
251 //die('This api requires login');
252 throw new UnauthorizedException("This API requires login");
255 DI::auth()->setForUser($a, $record);
257 $_SESSION["allow_api"] = true;
259 Hook::callAll('logged_in', $a->user);
263 * API endpoints can define which HTTP method to accept when called.
264 * This function check the current HTTP method agains endpoint
267 * @brief Check HTTP method of called API
269 * @param string $method Required methods, uppercase, separated by comma
272 function api_check_method($method)
274 if ($method == "*") {
277 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
281 * Authenticate user, call registered API function, set HTTP headers
283 * @brief Main API entry point
286 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
287 * @return string|array API call result
290 function api_call(App $a, App\Arguments $args = null)
292 global $API, $called_api;
299 if (strpos($args->getQueryString(), ".xml") > 0) {
302 if (strpos($args->getQueryString(), ".json") > 0) {
305 if (strpos($args->getQueryString(), ".rss") > 0) {
308 if (strpos($args->getQueryString(), ".atom") > 0) {
313 foreach ($API as $p => $info) {
314 if (strpos($args->getQueryString(), $p) === 0) {
315 if (!api_check_method($info['method'])) {
316 throw new MethodNotAllowedException();
319 $called_api = explode("/", $p);
320 //unset($_SERVER['PHP_AUTH_USER']);
322 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
323 if (!empty($info['auth']) && api_user() === false) {
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
328 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
330 $stamp = microtime(true);
331 $return = call_user_func($info['func'], $type);
332 $duration = floatval(microtime(true) - $stamp);
334 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
336 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
338 if (false === $return) {
340 * api function returned false withour throw an
341 * exception. This should not happend, throw a 500
343 throw new InternalServerErrorException();
348 header("Content-Type: text/xml");
351 header("Content-Type: application/json");
352 if (!empty($return)) {
353 $json = json_encode(end($return));
354 if (!empty($_GET['callback'])) {
355 $json = $_GET['callback'] . "(" . $json . ")";
361 header("Content-Type: application/rss+xml");
362 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
365 header("Content-Type: application/atom+xml");
366 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
373 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
374 throw new NotImplementedException();
375 } catch (HTTPException $e) {
376 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
377 return api_error($type, $e, $args);
382 * @brief Format API error string
384 * @param string $type Return type (xml, json, rss, as)
385 * @param object $e HTTPException Error object
386 * @param App\Arguments $args The App arguments
387 * @return string|array error message formatted as $type
389 function api_error($type, $e, App\Arguments $args)
391 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
392 /// @TODO: https://dev.twitter.com/overview/api/response-codes
394 $error = ["error" => $error,
395 "code" => $e->getCode() . " " . $e->httpdesc,
396 "request" => $args->getQueryString()];
398 $return = api_format_data('status', $type, ['status' => $error]);
402 header("Content-Type: text/xml");
405 header("Content-Type: application/json");
406 $return = json_encode($return);
409 header("Content-Type: application/rss+xml");
412 header("Content-Type: application/atom+xml");
420 * @brief Set values for RSS template
423 * @param array $arr Array to be passed to template
424 * @param array $user_info User info
426 * @throws BadRequestException
427 * @throws ImagickException
428 * @throws InternalServerErrorException
429 * @throws UnauthorizedException
430 * @todo find proper type-hints
432 function api_rss_extra(App $a, $arr, $user_info)
434 if (is_null($user_info)) {
435 $user_info = api_get_user($a);
438 $arr['$user'] = $user_info;
440 'alternate' => $user_info['url'],
441 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
442 'base' => DI::baseUrl(),
443 'updated' => api_date(null),
444 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
445 'language' => $user_info['lang'],
446 'logo' => DI::baseUrl() . "/images/friendica-32.png",
454 * @brief Unique contact to contact url.
456 * @param int $id Contact id
457 * @return bool|string
458 * Contact url or False if contact id is unknown
461 function api_unique_id_to_nurl($id)
463 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
465 if (DBA::isResult($r)) {
473 * @brief Get user info array.
476 * @param int|string $contact_id Contact ID or URL
478 * @throws BadRequestException
479 * @throws ImagickException
480 * @throws InternalServerErrorException
481 * @throws UnauthorizedException
483 function api_get_user(App $a, $contact_id = null)
491 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
493 // Searching for contact URL
494 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
495 $user = DBA::escape(Strings::normaliseLink($contact_id));
497 $extra_query = "AND `contact`.`nurl` = '%s' ";
498 if (api_user() !== false) {
499 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
503 // Searching for contact id with uid = 0
504 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
505 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
508 throw new BadRequestException("User ID ".$contact_id." not found.");
512 $extra_query = "AND `contact`.`nurl` = '%s' ";
513 if (api_user() !== false) {
514 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
518 if (is_null($user) && !empty($_GET['user_id'])) {
519 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
522 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
526 $extra_query = "AND `contact`.`nurl` = '%s' ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
531 if (is_null($user) && !empty($_GET['screen_name'])) {
532 $user = DBA::escape($_GET['screen_name']);
533 $extra_query = "AND `contact`.`nick` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 if (is_null($user) && !empty($_GET['profileurl'])) {
540 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
547 // $called_api is the API path exploded on / and is expected to have at least 2 elements
548 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
549 $argid = count($called_api);
550 if (!empty($a->argv[$argid])) {
551 $data = explode(".", $a->argv[$argid]);
552 if (count($data) > 1) {
553 list($user, $null) = $data;
556 if (is_numeric($user)) {
557 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
561 $extra_query = "AND `contact`.`nurl` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 $user = DBA::escape($user);
568 $extra_query = "AND `contact`.`nick` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
575 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
578 if (api_user() === false) {
582 $user = $_SESSION['uid'];
583 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
587 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
591 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
597 // Selecting the id by priority, friendica first
598 if (is_array($uinfo)) {
599 api_best_nickname($uinfo);
602 // if the contact wasn't found, fetch it from the contacts with uid = 0
603 if (!DBA::isResult($uinfo)) {
605 throw new BadRequestException("User not found.");
608 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
610 if (DBA::isResult($contact)) {
612 'id' => $contact["id"],
613 'id_str' => (string) $contact["id"],
614 'name' => $contact["name"],
615 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
616 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
617 'description' => BBCode::toPlaintext($contact["about"]),
618 'profile_image_url' => $contact["micro"],
619 'profile_image_url_https' => $contact["micro"],
620 'profile_image_url_profile_size' => $contact["thumb"],
621 'profile_image_url_large' => $contact["photo"],
622 'url' => $contact["url"],
623 'protected' => false,
624 'followers_count' => 0,
625 'friends_count' => 0,
627 'created_at' => api_date($contact["created"]),
628 'favourites_count' => 0,
630 'time_zone' => 'UTC',
631 'geo_enabled' => false,
633 'statuses_count' => 0,
635 'contributors_enabled' => false,
636 'is_translator' => false,
637 'is_translation_enabled' => false,
638 'following' => false,
639 'follow_request_sent' => false,
640 'statusnet_blocking' => false,
641 'notifications' => false,
642 'statusnet_profile_url' => $contact["url"],
644 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
645 'pid' => Contact::getIdForURL($contact["url"], 0, true),
647 'network' => $contact["network"],
652 throw new BadRequestException("User ".$url." not found.");
656 if ($uinfo[0]['self']) {
657 if ($uinfo[0]['network'] == "") {
658 $uinfo[0]['network'] = Protocol::DFRN;
661 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
662 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
669 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
671 if (!empty($profile['about'])) {
672 $description = $profile['about'];
674 $description = $uinfo[0]["about"];
677 if (!empty($usr['default-location'])) {
678 $location = $usr['default-location'];
679 } elseif (!empty($uinfo[0]["location"])) {
680 $location = $uinfo[0]["location"];
682 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
686 'id' => intval($pcontact_id),
687 'id_str' => (string) intval($pcontact_id),
688 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
689 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
690 'location' => $location,
691 'description' => BBCode::toPlaintext($description),
692 'profile_image_url' => $uinfo[0]['micro'],
693 'profile_image_url_https' => $uinfo[0]['micro'],
694 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
695 'profile_image_url_large' => $uinfo[0]["photo"],
696 'url' => $uinfo[0]['url'],
697 'protected' => false,
698 'followers_count' => intval($countfollowers),
699 'friends_count' => intval($countfriends),
701 'created_at' => api_date($uinfo[0]['created']),
702 'favourites_count' => intval($starred),
704 'time_zone' => 'UTC',
705 'geo_enabled' => false,
707 'statuses_count' => intval($countitems),
709 'contributors_enabled' => false,
710 'is_translator' => false,
711 'is_translation_enabled' => false,
712 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
713 'follow_request_sent' => false,
714 'statusnet_blocking' => false,
715 'notifications' => false,
717 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
718 'statusnet_profile_url' => $uinfo[0]['url'],
719 'uid' => intval($uinfo[0]['uid']),
720 'cid' => intval($uinfo[0]['cid']),
721 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
722 'self' => $uinfo[0]['self'],
723 'network' => $uinfo[0]['network'],
726 // If this is a local user and it uses Frio, we can get its color preferences.
728 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
729 if ($theme_info['theme'] === 'frio') {
730 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
732 if ($schema && ($schema != '---')) {
733 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
734 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
735 require_once $schemefile;
738 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
739 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
740 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
742 if (empty($nav_bg)) {
745 if (empty($link_color)) {
746 $link_color = "#6fdbe8";
748 if (empty($bgcolor)) {
749 $bgcolor = "#ededed";
752 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
753 $ret['profile_link_color'] = str_replace('#', '', $link_color);
754 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
762 * @brief return api-formatted array for item's author and owner
765 * @param array $item item from db
766 * @return array(array:author, array:owner)
767 * @throws BadRequestException
768 * @throws ImagickException
769 * @throws InternalServerErrorException
770 * @throws UnauthorizedException
772 function api_item_get_user(App $a, $item)
774 $status_user = api_get_user($a, $item['author-id'] ?? null);
776 $author_user = $status_user;
778 $status_user["protected"] = $item['private'] ?? 0;
780 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
781 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
783 $owner_user = $author_user;
786 return ([$status_user, $author_user, $owner_user]);
790 * @brief walks recursively through an array with the possibility to change value and key
792 * @param array $array The array to walk through
793 * @param callable $callback The callback function
795 * @return array the transformed array
797 function api_walk_recursive(array &$array, callable $callback)
801 foreach ($array as $k => $v) {
803 if ($callback($v, $k)) {
804 $new_array[$k] = api_walk_recursive($v, $callback);
807 if ($callback($v, $k)) {
818 * @brief Callback function to transform the array in an array that can be transformed in a XML file
820 * @param mixed $item Array item value
821 * @param string $key Array key
823 * @return boolean Should the array item be deleted?
825 function api_reformat_xml(&$item, &$key)
827 if (is_bool($item)) {
828 $item = ($item ? "true" : "false");
831 if (substr($key, 0, 10) == "statusnet_") {
832 $key = "statusnet:".substr($key, 10);
833 } elseif (substr($key, 0, 10) == "friendica_") {
834 $key = "friendica:".substr($key, 10);
836 /// @TODO old-lost code?
838 // $key = "default:".$key;
844 * @brief Creates the XML from a JSON style array
846 * @param array $data JSON style array
847 * @param string $root_element Name of the root element
849 * @return string The XML data
851 function api_create_xml(array $data, $root_element)
853 $childname = key($data);
854 $data2 = array_pop($data);
856 $namespaces = ["" => "http://api.twitter.com",
857 "statusnet" => "http://status.net/schema/api/1/",
858 "friendica" => "http://friendi.ca/schema/api/1/",
859 "georss" => "http://www.georss.org/georss"];
861 /// @todo Auto detection of needed namespaces
862 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
866 if (is_array($data2)) {
868 api_walk_recursive($data2, "api_reformat_xml");
874 foreach ($data2 as $item) {
875 $data4[$i++ . ":" . $childname] = $item;
882 $data3 = [$root_element => $data2];
884 $ret = XML::fromArray($data3, $xml, false, $namespaces);
889 * @brief Formats the data according to the data type
891 * @param string $root_element Name of the root element
892 * @param string $type Return type (atom, rss, xml, json)
893 * @param array $data JSON style array
895 * @return array|string (string|array) XML data or JSON data
897 function api_format_data($root_element, $type, $data)
903 $ret = api_create_xml($data, $root_element);
918 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
919 * returns a 401 status code and an error message if not.
921 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
923 * @param string $type Return type (atom, rss, xml, json)
924 * @return array|string
925 * @throws BadRequestException
926 * @throws ForbiddenException
927 * @throws ImagickException
928 * @throws InternalServerErrorException
929 * @throws UnauthorizedException
931 function api_account_verify_credentials($type)
935 if (api_user() === false) {
936 throw new ForbiddenException();
939 unset($_REQUEST["user_id"]);
940 unset($_GET["user_id"]);
942 unset($_REQUEST["screen_name"]);
943 unset($_GET["screen_name"]);
945 $skip_status = $_REQUEST['skip_status'] ?? false;
947 $user_info = api_get_user($a);
949 // "verified" isn't used here in the standard
950 unset($user_info["verified"]);
952 // - Adding last status
954 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
956 $user_info['status'] = api_format_item($item, $type);
960 // "uid" and "self" are only needed for some internal stuff, so remove it from here
961 unset($user_info["uid"]);
962 unset($user_info["self"]);
964 return api_format_data("user", $type, ['user' => $user_info]);
967 /// @TODO move to top of file or somewhere better
968 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
971 * Get data from $_POST or $_GET
976 function requestdata($k)
978 if (!empty($_POST[$k])) {
981 if (!empty($_GET[$k])) {
988 * Deprecated function to upload media.
990 * @param string $type Return type (atom, rss, xml, json)
992 * @return array|string
993 * @throws BadRequestException
994 * @throws ForbiddenException
995 * @throws ImagickException
996 * @throws InternalServerErrorException
997 * @throws UnauthorizedException
999 function api_statuses_mediap($type)
1003 if (api_user() === false) {
1004 Logger::log('api_statuses_update: no user');
1005 throw new ForbiddenException();
1007 $user_info = api_get_user($a);
1009 $_REQUEST['profile_uid'] = api_user();
1010 $_REQUEST['api_source'] = true;
1011 $txt = requestdata('status');
1012 /// @TODO old-lost code?
1013 //$txt = urldecode(requestdata('status'));
1015 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1016 $txt = HTML::toBBCodeVideo($txt);
1017 $config = HTMLPurifier_Config::createDefault();
1018 $config->set('Cache.DefinitionImpl', null);
1019 $purifier = new HTMLPurifier($config);
1020 $txt = $purifier->purify($txt);
1022 $txt = HTML::toBBCode($txt);
1024 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1026 $picture = wall_upload_post($a, false);
1028 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1029 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1030 $item_id = item_post($a);
1032 // output the post that we just posted.
1033 return api_status_show($type, $item_id);
1036 /// @TODO move this to top of file or somewhere better!
1037 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1040 * Updates the user’s current status.
1042 * @param string $type Return type (atom, rss, xml, json)
1044 * @return array|string
1045 * @throws BadRequestException
1046 * @throws ForbiddenException
1047 * @throws ImagickException
1048 * @throws InternalServerErrorException
1049 * @throws TooManyRequestsException
1050 * @throws UnauthorizedException
1051 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1053 function api_statuses_update($type)
1057 if (api_user() === false) {
1058 Logger::log('api_statuses_update: no user');
1059 throw new ForbiddenException();
1064 // convert $_POST array items to the form we use for web posts.
1065 if (requestdata('htmlstatus')) {
1066 $txt = requestdata('htmlstatus');
1067 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1068 $txt = HTML::toBBCodeVideo($txt);
1070 $config = HTMLPurifier_Config::createDefault();
1071 $config->set('Cache.DefinitionImpl', null);
1073 $purifier = new HTMLPurifier($config);
1074 $txt = $purifier->purify($txt);
1076 $_REQUEST['body'] = HTML::toBBCode($txt);
1079 $_REQUEST['body'] = requestdata('status');
1082 $_REQUEST['title'] = requestdata('title');
1084 $parent = requestdata('in_reply_to_status_id');
1086 // Twidere sends "-1" if it is no reply ...
1087 if ($parent == -1) {
1091 if (ctype_digit($parent)) {
1092 $_REQUEST['parent'] = $parent;
1094 $_REQUEST['parent_uri'] = $parent;
1097 if (requestdata('lat') && requestdata('long')) {
1098 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1100 $_REQUEST['profile_uid'] = api_user();
1103 // Check for throttling (maximum posts per day, week and month)
1104 $throttle_day = Config::get('system', 'throttle_limit_day');
1105 if ($throttle_day > 0) {
1106 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1108 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1109 $posts_day = DBA::count('thread', $condition);
1111 if ($posts_day > $throttle_day) {
1112 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1113 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1114 throw new TooManyRequestsException(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));
1118 $throttle_week = Config::get('system', 'throttle_limit_week');
1119 if ($throttle_week > 0) {
1120 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1122 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1123 $posts_week = DBA::count('thread', $condition);
1125 if ($posts_week > $throttle_week) {
1126 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1127 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1128 throw new TooManyRequestsException(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));
1132 $throttle_month = Config::get('system', 'throttle_limit_month');
1133 if ($throttle_month > 0) {
1134 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1136 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1137 $posts_month = DBA::count('thread', $condition);
1139 if ($posts_month > $throttle_month) {
1140 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1141 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1142 throw new TooManyRequestsException(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));
1147 if (!empty($_FILES['media'])) {
1148 // upload the image if we have one
1149 $picture = wall_upload_post($a, false);
1150 if (is_array($picture)) {
1151 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1155 if (requestdata('media_ids')) {
1156 $ids = explode(',', requestdata('media_ids'));
1157 foreach ($ids as $id) {
1159 "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",
1163 if (DBA::isResult($r)) {
1164 $phototypes = Images::supportedTypes();
1165 $ext = $phototypes[$r[0]['type']];
1166 $description = $r[0]['desc'] ?? '';
1167 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1168 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1173 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1175 $_REQUEST['api_source'] = true;
1177 if (empty($_REQUEST['source'])) {
1178 $_REQUEST["source"] = api_source();
1181 // call out normal post function
1182 $item_id = item_post($a);
1184 // output the post that we just posted.
1185 return api_status_show($type, $item_id);
1188 /// @TODO move to top of file or somewhere better
1189 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1190 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1193 * Uploads an image to Friendica.
1196 * @throws BadRequestException
1197 * @throws ForbiddenException
1198 * @throws ImagickException
1199 * @throws InternalServerErrorException
1200 * @throws UnauthorizedException
1201 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1203 function api_media_upload()
1207 if (api_user() === false) {
1208 Logger::log('no user');
1209 throw new ForbiddenException();
1214 if (empty($_FILES['media'])) {
1216 throw new BadRequestException("No media.");
1219 $media = wall_upload_post($a, false);
1222 throw new InternalServerErrorException();
1226 $returndata["media_id"] = $media["id"];
1227 $returndata["media_id_string"] = (string)$media["id"];
1228 $returndata["size"] = $media["size"];
1229 $returndata["image"] = ["w" => $media["width"],
1230 "h" => $media["height"],
1231 "image_type" => $media["type"],
1232 "friendica_preview_url" => $media["preview"]];
1234 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1236 return ["media" => $returndata];
1239 /// @TODO move to top of file or somewhere better
1240 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1243 * Updates media meta data (picture descriptions)
1245 * @param string $type Return type (atom, rss, xml, json)
1247 * @return array|string
1248 * @throws BadRequestException
1249 * @throws ForbiddenException
1250 * @throws ImagickException
1251 * @throws InternalServerErrorException
1252 * @throws TooManyRequestsException
1253 * @throws UnauthorizedException
1254 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1256 * @todo Compare the corresponding Twitter function for correct return values
1258 function api_media_metadata_create($type)
1262 if (api_user() === false) {
1263 Logger::info('no user');
1264 throw new ForbiddenException();
1269 $postdata = Network::postdata();
1271 if (empty($postdata)) {
1272 throw new BadRequestException("No post data");
1275 $data = json_decode($postdata, true);
1277 throw new BadRequestException("Invalid post data");
1280 if (empty($data['media_id']) || empty($data['alt_text'])) {
1281 throw new BadRequestException("Missing post data values");
1284 if (empty($data['alt_text']['text'])) {
1285 throw new BadRequestException("No alt text.");
1288 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1290 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1291 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1292 if (!DBA::isResult($photo)) {
1293 throw new BadRequestException("Metadata not found.");
1296 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1299 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1302 * @param string $type Return format (atom, rss, xml, json)
1303 * @param int $item_id
1307 function api_status_show($type, $item_id)
1309 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1313 $item = api_get_item(['id' => $item_id]);
1314 if (!empty($item)) {
1315 $status_info = api_format_item($item, $type);
1318 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1320 return api_format_data('statuses', $type, ['status' => $status_info]);
1324 * Retrieves the last public status of the provided user info
1326 * @param int $ownerId Public contact Id
1327 * @param int $uid User Id
1331 function api_get_last_status($ownerId, $uid)
1334 'author-id'=> $ownerId,
1336 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1340 $item = api_get_item($condition);
1346 * Retrieves a single item record based on the provided condition and converts it for API use.
1348 * @param array $condition Item table condition array
1352 function api_get_item(array $condition)
1354 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1360 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1361 * The author's most recent status will be returned inline.
1363 * @param string $type Return type (atom, rss, xml, json)
1364 * @return array|string
1365 * @throws BadRequestException
1366 * @throws ImagickException
1367 * @throws InternalServerErrorException
1368 * @throws UnauthorizedException
1369 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1371 function api_users_show($type)
1373 $a = Friendica\DI::app();
1375 $user_info = api_get_user($a);
1377 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1378 if (!empty($item)) {
1379 $user_info['status'] = api_format_item($item, $type);
1382 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1383 unset($user_info['uid']);
1384 unset($user_info['self']);
1386 return api_format_data('user', $type, ['user' => $user_info]);
1389 /// @TODO move to top of file or somewhere better
1390 api_register_func('api/users/show', 'api_users_show');
1391 api_register_func('api/externalprofile/show', 'api_users_show');
1394 * Search a public user account.
1396 * @param string $type Return type (atom, rss, xml, json)
1398 * @return array|string
1399 * @throws BadRequestException
1400 * @throws ImagickException
1401 * @throws InternalServerErrorException
1402 * @throws UnauthorizedException
1403 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1405 function api_users_search($type)
1411 if (!empty($_GET['q'])) {
1412 $contacts = Contact::selectToArray(
1415 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1423 if (DBA::isResult($contacts)) {
1425 foreach ($contacts as $contact) {
1426 $user_info = api_get_user($a, $contact['id']);
1428 if ($type == 'xml') {
1429 $userlist[$k++ . ':user'] = $user_info;
1431 $userlist[] = $user_info;
1434 $userlist = ['users' => $userlist];
1436 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1439 throw new BadRequestException('No search term specified.');
1442 return api_format_data('users', $type, $userlist);
1445 /// @TODO move to top of file or somewhere better
1446 api_register_func('api/users/search', 'api_users_search');
1449 * Return user objects
1451 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1453 * @param string $type Return format: json or xml
1455 * @return array|string
1456 * @throws BadRequestException
1457 * @throws ImagickException
1458 * @throws InternalServerErrorException
1459 * @throws NotFoundException if the results are empty.
1460 * @throws UnauthorizedException
1462 function api_users_lookup($type)
1466 if (!empty($_REQUEST['user_id'])) {
1467 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1469 $users[] = api_get_user(get_app(), $id);
1474 if (empty($users)) {
1475 throw new NotFoundException;
1478 return api_format_data("users", $type, ['users' => $users]);
1481 /// @TODO move to top of file or somewhere better
1482 api_register_func('api/users/lookup', 'api_users_lookup', true);
1485 * Returns statuses that match a specified query.
1487 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1489 * @param string $type Return format: json, xml, atom, rss
1491 * @return array|string
1492 * @throws BadRequestException if the "q" parameter is missing.
1493 * @throws ForbiddenException
1494 * @throws ImagickException
1495 * @throws InternalServerErrorException
1496 * @throws UnauthorizedException
1498 function api_search($type)
1501 $user_info = api_get_user($a);
1503 if (api_user() === false || $user_info === false) {
1504 throw new ForbiddenException();
1507 if (empty($_REQUEST['q'])) {
1508 throw new BadRequestException('q parameter is required.');
1511 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1514 $data['status'] = [];
1516 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1517 if (!empty($_REQUEST['rpp'])) {
1518 $count = $_REQUEST['rpp'];
1519 } elseif (!empty($_REQUEST['count'])) {
1520 $count = $_REQUEST['count'];
1523 $since_id = $_REQUEST['since_id'] ?? 0;
1524 $max_id = $_REQUEST['max_id'] ?? 0;
1525 $page = $_REQUEST['page'] ?? 1;
1527 $start = max(0, ($page - 1) * $count);
1529 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1530 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1531 $searchTerm = $matches[1];
1532 $condition = ["`oid` > ?
1533 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1534 AND `otype` = ? AND `type` = ? AND `term` = ?",
1535 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1537 $condition[0] .= ' AND `oid` <= ?';
1538 $condition[] = $max_id;
1540 $terms = DBA::select('term', ['oid'], $condition, []);
1542 while ($term = DBA::fetch($terms)) {
1543 $itemIds[] = $term['oid'];
1547 if (empty($itemIds)) {
1548 return api_format_data('statuses', $type, $data);
1551 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1552 if ($exclude_replies) {
1553 $preCondition[] = '`id` = `parent`';
1556 $condition = [implode(' AND ', $preCondition)];
1558 $condition = ["`id` > ?
1559 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1560 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1561 AND `body` LIKE CONCAT('%',?,'%')",
1562 $since_id, api_user(), $_REQUEST['q']];
1564 $condition[0] .= ' AND `id` <= ?';
1565 $condition[] = $max_id;
1571 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1572 $id = Item::fetchByLink($searchTerm, api_user());
1575 $id = Item::fetchByLink($searchTerm);
1579 $statuses = Item::select([], ['id' => $id]);
1583 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1585 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1587 bindComments($data['status']);
1589 return api_format_data('statuses', $type, $data);
1592 /// @TODO move to top of file or somewhere better
1593 api_register_func('api/search/tweets', 'api_search', true);
1594 api_register_func('api/search', 'api_search', true);
1597 * Returns the most recent statuses posted by the user and the users they follow.
1599 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1601 * @param string $type Return type (atom, rss, xml, json)
1603 * @return array|string
1604 * @throws BadRequestException
1605 * @throws ForbiddenException
1606 * @throws ImagickException
1607 * @throws InternalServerErrorException
1608 * @throws UnauthorizedException
1609 * @todo Optional parameters
1610 * @todo Add reply info
1612 function api_statuses_home_timeline($type)
1615 $user_info = api_get_user($a);
1617 if (api_user() === false || $user_info === false) {
1618 throw new ForbiddenException();
1621 unset($_REQUEST["user_id"]);
1622 unset($_GET["user_id"]);
1624 unset($_REQUEST["screen_name"]);
1625 unset($_GET["screen_name"]);
1627 // get last network messages
1630 $count = $_REQUEST['count'] ?? 20;
1631 $page = $_REQUEST['page']?? 0;
1632 $since_id = $_REQUEST['since_id'] ?? 0;
1633 $max_id = $_REQUEST['max_id'] ?? 0;
1634 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1635 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1637 $start = max(0, ($page - 1) * $count);
1639 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1640 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1643 $condition[0] .= " AND `item`.`id` <= ?";
1644 $condition[] = $max_id;
1646 if ($exclude_replies) {
1647 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1649 if ($conversation_id > 0) {
1650 $condition[0] .= " AND `item`.`parent` = ?";
1651 $condition[] = $conversation_id;
1654 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1655 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1657 $items = Item::inArray($statuses);
1659 $ret = api_format_items($items, $user_info, false, $type);
1661 // Set all posts from the query above to seen
1663 foreach ($items as $item) {
1664 $idarray[] = intval($item["id"]);
1667 if (!empty($idarray)) {
1668 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1670 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1676 $data = ['status' => $ret];
1681 $data = api_rss_extra($a, $data, $user_info);
1685 return api_format_data("statuses", $type, $data);
1689 /// @TODO move to top of file or somewhere better
1690 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1691 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1694 * Returns the most recent statuses from public users.
1696 * @param string $type Return type (atom, rss, xml, json)
1698 * @return array|string
1699 * @throws BadRequestException
1700 * @throws ForbiddenException
1701 * @throws ImagickException
1702 * @throws InternalServerErrorException
1703 * @throws UnauthorizedException
1705 function api_statuses_public_timeline($type)
1708 $user_info = api_get_user($a);
1710 if (api_user() === false || $user_info === false) {
1711 throw new ForbiddenException();
1714 // get last network messages
1717 $count = $_REQUEST['count'] ?? 20;
1718 $page = $_REQUEST['page'] ?? 1;
1719 $since_id = $_REQUEST['since_id'] ?? 0;
1720 $max_id = $_REQUEST['max_id'] ?? 0;
1721 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1722 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1724 $start = max(0, ($page - 1) * $count);
1726 if ($exclude_replies && !$conversation_id) {
1727 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1728 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1731 $condition[0] .= " AND `thread`.`iid` <= ?";
1732 $condition[] = $max_id;
1735 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1736 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1738 $r = Item::inArray($statuses);
1740 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1741 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1744 $condition[0] .= " AND `item`.`id` <= ?";
1745 $condition[] = $max_id;
1747 if ($conversation_id > 0) {
1748 $condition[0] .= " AND `item`.`parent` = ?";
1749 $condition[] = $conversation_id;
1752 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1753 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1755 $r = Item::inArray($statuses);
1758 $ret = api_format_items($r, $user_info, false, $type);
1762 $data = ['status' => $ret];
1767 $data = api_rss_extra($a, $data, $user_info);
1771 return api_format_data("statuses", $type, $data);
1774 /// @TODO move to top of file or somewhere better
1775 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1778 * Returns the most recent statuses posted by users this node knows about.
1780 * @brief Returns the list of public federated posts 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 NOT `private`",
1809 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
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 = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2037 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
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['tag'] = $item['tag'];
2055 $_REQUEST['attach'] = $item['attach'];
2056 $_REQUEST['profile_uid'] = api_user();
2057 $_REQUEST['api_source'] = true;
2059 if (empty($_REQUEST['source'])) {
2060 $_REQUEST["source"] = api_source();
2063 $item_id = item_post($a);
2065 throw new ForbiddenException();
2068 // output the post that we just posted.
2070 return api_status_show($type, $item_id);
2073 /// @TODO move to top of file or somewhere better
2074 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2077 * Destroys a specific status.
2079 * @param string $type Return type (atom, rss, xml, json)
2081 * @return array|string
2082 * @throws BadRequestException
2083 * @throws ForbiddenException
2084 * @throws ImagickException
2085 * @throws InternalServerErrorException
2086 * @throws UnauthorizedException
2087 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2089 function api_statuses_destroy($type)
2093 if (api_user() === false) {
2094 throw new ForbiddenException();
2100 $id = intval($a->argv[3] ?? 0);
2103 $id = intval($_REQUEST['id'] ?? 0);
2108 $id = intval($a->argv[4] ?? 0);
2111 Logger::log('API: api_statuses_destroy: '.$id);
2113 $ret = api_statuses_show($type);
2115 Item::deleteForUser(['id' => $id], api_user());
2120 /// @TODO move to top of file or somewhere better
2121 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2124 * Returns the most recent mentions.
2126 * @param string $type Return type (atom, rss, xml, json)
2128 * @return array|string
2129 * @throws BadRequestException
2130 * @throws ForbiddenException
2131 * @throws ImagickException
2132 * @throws InternalServerErrorException
2133 * @throws UnauthorizedException
2134 * @see http://developer.twitter.com/doc/get/statuses/mentions
2136 function api_statuses_mentions($type)
2139 $user_info = api_get_user($a);
2141 if (api_user() === false || $user_info === false) {
2142 throw new ForbiddenException();
2145 unset($_REQUEST["user_id"]);
2146 unset($_GET["user_id"]);
2148 unset($_REQUEST["screen_name"]);
2149 unset($_GET["screen_name"]);
2151 // get last network messages
2154 $since_id = $_REQUEST['since_id'] ?? 0;
2155 $max_id = $_REQUEST['max_id'] ?? 0;
2156 $count = $_REQUEST['count'] ?? 20;
2157 $page = $_REQUEST['page'] ?? 1;
2159 $start = max(0, ($page - 1) * $count);
2161 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ? AND `mention`
2162 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND NOT `thread`.`ignored`)",
2163 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2166 $condition[0] .= " AND `item`.`id` <= ?";
2167 $condition[] = $max_id;
2170 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2171 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2173 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2175 $data = ['status' => $ret];
2180 $data = api_rss_extra($a, $data, $user_info);
2184 return api_format_data("statuses", $type, $data);
2187 /// @TODO move to top of file or somewhere better
2188 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2189 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2192 * Returns the most recent statuses posted by the user.
2194 * @brief Returns a user's public timeline
2196 * @param string $type Either "json" or "xml"
2197 * @return string|array
2198 * @throws BadRequestException
2199 * @throws ForbiddenException
2200 * @throws ImagickException
2201 * @throws InternalServerErrorException
2202 * @throws UnauthorizedException
2203 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2205 function api_statuses_user_timeline($type)
2208 $user_info = api_get_user($a);
2210 if (api_user() === false || $user_info === false) {
2211 throw new ForbiddenException();
2215 "api_statuses_user_timeline: api_user: ". api_user() .
2216 "\nuser_info: ".print_r($user_info, true) .
2217 "\n_REQUEST: ".print_r($_REQUEST, true),
2221 $since_id = $_REQUEST['since_id'] ?? 0;
2222 $max_id = $_REQUEST['max_id'] ?? 0;
2223 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2224 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2227 $count = $_REQUEST['count'] ?? 20;
2228 $page = $_REQUEST['page'] ?? 1;
2230 $start = max(0, ($page - 1) * $count);
2232 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2233 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2235 if ($user_info['self'] == 1) {
2236 $condition[0] .= ' AND `item`.`wall` ';
2239 if ($exclude_replies) {
2240 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2243 if ($conversation_id > 0) {
2244 $condition[0] .= " AND `item`.`parent` = ?";
2245 $condition[] = $conversation_id;
2249 $condition[0] .= " AND `item`.`id` <= ?";
2250 $condition[] = $max_id;
2253 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2254 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2256 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2260 $data = ['status' => $ret];
2265 $data = api_rss_extra($a, $data, $user_info);
2269 return api_format_data("statuses", $type, $data);
2272 /// @TODO move to top of file or somewhere better
2273 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2276 * Star/unstar an item.
2277 * param: id : id of the item
2279 * @param string $type Return type (atom, rss, xml, json)
2281 * @return array|string
2282 * @throws BadRequestException
2283 * @throws ForbiddenException
2284 * @throws ImagickException
2285 * @throws InternalServerErrorException
2286 * @throws UnauthorizedException
2287 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2289 function api_favorites_create_destroy($type)
2293 if (api_user() === false) {
2294 throw new ForbiddenException();
2297 // for versioned api.
2298 /// @TODO We need a better global soluton
2299 $action_argv_id = 2;
2300 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2301 $action_argv_id = 3;
2304 if ($a->argc <= $action_argv_id) {
2305 throw new BadRequestException("Invalid request.");
2307 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2308 if ($a->argc == $action_argv_id + 2) {
2309 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2311 $itemid = intval($_REQUEST['id'] ?? 0);
2314 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2316 if (!DBA::isResult($item)) {
2317 throw new BadRequestException("Invalid item.");
2322 $item['starred'] = 1;
2325 $item['starred'] = 0;
2328 throw new BadRequestException("Invalid action ".$action);
2331 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2334 throw new InternalServerErrorException("DB error");
2338 $user_info = api_get_user($a);
2339 $rets = api_format_items([$item], $user_info, false, $type);
2342 $data = ['status' => $ret];
2347 $data = api_rss_extra($a, $data, $user_info);
2351 return api_format_data("status", $type, $data);
2354 /// @TODO move to top of file or somewhere better
2355 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2356 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2359 * Returns the most recent favorite statuses.
2361 * @param string $type Return type (atom, rss, xml, json)
2363 * @return string|array
2364 * @throws BadRequestException
2365 * @throws ForbiddenException
2366 * @throws ImagickException
2367 * @throws InternalServerErrorException
2368 * @throws UnauthorizedException
2370 function api_favorites($type)
2375 $user_info = api_get_user($a);
2377 if (api_user() === false || $user_info === false) {
2378 throw new ForbiddenException();
2383 // in friendica starred item are private
2384 // return favorites only for self
2385 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2387 if ($user_info['self'] == 0) {
2391 $since_id = $_REQUEST['since_id'] ?? 0;
2392 $max_id = $_REQUEST['max_id'] ?? 0;
2393 $count = $_GET['count'] ?? 20;
2394 $page = $_REQUEST['page'] ?? 1;
2396 $start = max(0, ($page - 1) * $count);
2398 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2399 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2401 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2404 $condition[0] .= " AND `item`.`id` <= ?";
2405 $condition[] = $max_id;
2408 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2410 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2415 $data = ['status' => $ret];
2420 $data = api_rss_extra($a, $data, $user_info);
2424 return api_format_data("statuses", $type, $data);
2427 /// @TODO move to top of file or somewhere better
2428 api_register_func('api/favorites', 'api_favorites', true);
2432 * @param array $item
2433 * @param array $recipient
2434 * @param array $sender
2437 * @throws InternalServerErrorException
2439 function api_format_messages($item, $recipient, $sender)
2441 // standard meta information
2443 'id' => $item['id'],
2444 'sender_id' => $sender['id'],
2446 'recipient_id' => $recipient['id'],
2447 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2448 'sender_screen_name' => $sender['screen_name'],
2449 'recipient_screen_name' => $recipient['screen_name'],
2450 'sender' => $sender,
2451 'recipient' => $recipient,
2453 'friendica_seen' => $item['seen'] ?? 0,
2454 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2457 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2458 if (isset($ret['sender']['uid'])) {
2459 unset($ret['sender']['uid']);
2461 if (isset($ret['sender']['self'])) {
2462 unset($ret['sender']['self']);
2464 if (isset($ret['recipient']['uid'])) {
2465 unset($ret['recipient']['uid']);
2467 if (isset($ret['recipient']['self'])) {
2468 unset($ret['recipient']['self']);
2471 //don't send title to regular StatusNET requests to avoid confusing these apps
2472 if (!empty($_GET['getText'])) {
2473 $ret['title'] = $item['title'];
2474 if ($_GET['getText'] == 'html') {
2475 $ret['text'] = BBCode::convert($item['body'], false);
2476 } elseif ($_GET['getText'] == 'plain') {
2477 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2480 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2482 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2483 unset($ret['sender']);
2484 unset($ret['recipient']);
2492 * @param array $item
2495 * @throws InternalServerErrorException
2497 function api_convert_item($item)
2499 $body = $item['body'];
2500 $entities = api_get_entitities($statustext, $body);
2502 // Add pictures to the attachment array and remove them from the body
2503 $attachments = api_get_attachments($body);
2505 // Workaround for ostatus messages where the title is identically to the body
2506 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2507 $statusbody = trim(HTML::toPlaintext($html, 0));
2509 // handle data: images
2510 $statusbody = api_format_items_embeded_images($item, $statusbody);
2512 $statustitle = trim($item['title']);
2514 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2515 $statustext = trim($statusbody);
2517 $statustext = trim($statustitle."\n\n".$statusbody);
2520 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2521 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2524 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2526 // Workaround for clients with limited HTML parser functionality
2527 $search = ["<br>", "<blockquote>", "</blockquote>",
2528 "<h1>", "</h1>", "<h2>", "</h2>",
2529 "<h3>", "</h3>", "<h4>", "</h4>",
2530 "<h5>", "</h5>", "<h6>", "</h6>"];
2531 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2532 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2533 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2534 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2535 $statushtml = str_replace($search, $replace, $statushtml);
2537 if ($item['title'] != "") {
2538 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2542 $oldtext = $statushtml;
2543 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2544 } while ($oldtext != $statushtml);
2546 if (substr($statushtml, 0, 4) == '<br>') {
2547 $statushtml = substr($statushtml, 4);
2550 if (substr($statushtml, 0, -4) == '<br>') {
2551 $statushtml = substr($statushtml, -4);
2554 // feeds without body should contain the link
2555 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2556 $statushtml .= BBCode::convert($item['plink']);
2560 "text" => $statustext,
2561 "html" => $statushtml,
2562 "attachments" => $attachments,
2563 "entities" => $entities
2569 * @param string $body
2572 * @throws InternalServerErrorException
2574 function api_get_attachments(&$body)
2576 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2577 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2579 $URLSearchString = "^\[\]";
2580 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2584 // Remove all embedded pictures, since they are added as attachments
2585 foreach ($images[0] as $orig) {
2586 $body = str_replace($orig, '', $body);
2591 foreach ($images[1] as $image) {
2592 $imagedata = Images::getInfoFromURLCached($image);
2595 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2599 return $attachments;
2604 * @param string $text
2605 * @param string $bbcode
2608 * @throws InternalServerErrorException
2609 * @todo Links at the first character of the post
2611 function api_get_entitities(&$text, $bbcode)
2613 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2615 if ($include_entities != "true") {
2616 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2618 foreach ($images[1] as $image) {
2619 $replace = ProxyUtils::proxifyUrl($image);
2620 $text = str_replace($image, $replace, $text);
2625 $bbcode = BBCode::cleanPictureLinks($bbcode);
2627 // Change pure links in text to bbcode uris
2628 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2631 $entities["hashtags"] = [];
2632 $entities["symbols"] = [];
2633 $entities["urls"] = [];
2634 $entities["user_mentions"] = [];
2636 $URLSearchString = "^\[\]";
2638 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2640 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2641 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2643 $bbcode = preg_replace(
2644 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2645 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2648 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2650 $bbcode = preg_replace(
2651 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2652 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2655 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2657 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2659 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2662 foreach ($urls[1] as $id => $url) {
2663 $start = iconv_strpos($text, $url, 0, "UTF-8");
2664 if (!($start === false)) {
2665 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2669 ksort($ordered_urls);
2673 foreach ($ordered_urls as $url) {
2674 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2675 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2677 $display_url = $url["title"];
2679 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2680 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2682 if (strlen($display_url) > 26) {
2683 $display_url = substr($display_url, 0, 25)."…";
2687 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2688 if (!($start === false)) {
2689 $entities["urls"][] = ["url" => $url["url"],
2690 "expanded_url" => $url["url"],
2691 "display_url" => $display_url,
2692 "indices" => [$start, $start+strlen($url["url"])]];
2693 $offset = $start + 1;
2697 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2698 $ordered_images = [];
2699 foreach ($images as $image) {
2700 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2701 if (!($start === false)) {
2702 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2706 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2707 foreach ($images[1] as $image) {
2708 $start = iconv_strpos($text, $image, 0, "UTF-8");
2709 if (!($start === false)) {
2710 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2716 foreach ($ordered_images as $image) {
2717 $url = $image['url'];
2718 $ext_alt_text = $image['alt'];
2720 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2721 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2723 if (strlen($display_url) > 26) {
2724 $display_url = substr($display_url, 0, 25)."…";
2727 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2728 if (!($start === false)) {
2729 $image = Images::getInfoFromURLCached($url);
2731 // If image cache is activated, then use the following sizes:
2732 // thumb (150), small (340), medium (600) and large (1024)
2733 if (!Config::get("system", "proxy_disabled")) {
2734 $media_url = ProxyUtils::proxifyUrl($url);
2737 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2738 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2740 if (($image[0] > 150) || ($image[1] > 150)) {
2741 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2742 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2745 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2746 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2748 if (($image[0] > 600) || ($image[1] > 600)) {
2749 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2750 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2754 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2757 $entities["media"][] = [
2759 "id_str" => (string) ($start + 1),
2760 "indices" => [$start, $start+strlen($url)],
2761 "media_url" => Strings::normaliseLink($media_url),
2762 "media_url_https" => $media_url,
2764 "display_url" => $display_url,
2765 "expanded_url" => $url,
2766 "ext_alt_text" => $ext_alt_text,
2770 $offset = $start + 1;
2779 * @param array $item
2780 * @param string $text
2784 function api_format_items_embeded_images($item, $text)
2786 $text = preg_replace_callback(
2787 '|data:image/([^;]+)[^=]+=*|m',
2788 function () use ($item) {
2789 return DI::baseUrl() . '/display/' . $item['guid'];
2797 * @brief return <a href='url'>name</a> as array
2799 * @param string $txt text
2804 function api_contactlink_to_array($txt)
2807 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2808 if ($r && count($match)==3) {
2810 'name' => $match[2],
2824 * @brief return likes, dislikes and attend status for item
2826 * @param array $item array
2827 * @param string $type Return type (atom, rss, xml, json)
2830 * likes => int count,
2831 * dislikes => int count
2832 * @throws BadRequestException
2833 * @throws ImagickException
2834 * @throws InternalServerErrorException
2835 * @throws UnauthorizedException
2837 function api_format_items_activities($item, $type = "json")
2846 'attendmaybe' => [],
2850 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2851 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2853 while ($parent_item = Item::fetch($ret)) {
2854 // not used as result should be structured like other user data
2855 //builtin_activity_puller($i, $activities);
2857 // get user data and add it to the array of the activity
2858 $user = api_get_user($a, $parent_item['author-id']);
2859 switch ($parent_item['verb']) {
2860 case Activity::LIKE:
2861 $activities['like'][] = $user;
2863 case Activity::DISLIKE:
2864 $activities['dislike'][] = $user;
2866 case Activity::ATTEND:
2867 $activities['attendyes'][] = $user;
2869 case Activity::ATTENDNO:
2870 $activities['attendno'][] = $user;
2872 case Activity::ATTENDMAYBE:
2873 $activities['attendmaybe'][] = $user;
2875 case Activity::ANNOUNCE:
2876 $activities['announce'][] = $user;
2885 if ($type == "xml") {
2886 $xml_activities = [];
2887 foreach ($activities as $k => $v) {
2888 // change xml element from "like" to "friendica:like"
2889 $xml_activities["friendica:".$k] = $v;
2890 // add user data into xml output
2892 foreach ($v as $user) {
2893 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2896 $activities = $xml_activities;
2904 * @brief return data from profiles
2906 * @param array $profile_row array containing data from db table 'profile'
2908 * @throws InternalServerErrorException
2910 function api_format_items_profiles($profile_row)
2913 'profile_id' => $profile_row['id'],
2914 'profile_name' => $profile_row['profile-name'],
2915 'is_default' => $profile_row['is-default'] ? true : false,
2916 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2917 'profile_photo' => $profile_row['photo'],
2918 'profile_thumb' => $profile_row['thumb'],
2919 'publish' => $profile_row['publish'] ? true : false,
2920 'net_publish' => $profile_row['net-publish'] ? true : false,
2921 'description' => $profile_row['pdesc'],
2922 'date_of_birth' => $profile_row['dob'],
2923 'address' => $profile_row['address'],
2924 'city' => $profile_row['locality'],
2925 'region' => $profile_row['region'],
2926 'postal_code' => $profile_row['postal-code'],
2927 'country' => $profile_row['country-name'],
2928 'hometown' => $profile_row['hometown'],
2929 'gender' => $profile_row['gender'],
2930 'marital' => $profile_row['marital'],
2931 'marital_with' => $profile_row['with'],
2932 'marital_since' => $profile_row['howlong'],
2933 'sexual' => $profile_row['sexual'],
2934 'politic' => $profile_row['politic'],
2935 'religion' => $profile_row['religion'],
2936 'public_keywords' => $profile_row['pub_keywords'],
2937 'private_keywords' => $profile_row['prv_keywords'],
2938 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2939 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2940 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2941 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2942 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2943 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2944 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2945 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2946 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2947 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2948 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2949 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2950 'homepage' => $profile_row['homepage'],
2957 * @brief format items to be returned by api
2959 * @param array $items array of items
2960 * @param array $user_info
2961 * @param bool $filter_user filter items by $user_info
2962 * @param string $type Return type (atom, rss, xml, json)
2964 * @throws BadRequestException
2965 * @throws ImagickException
2966 * @throws InternalServerErrorException
2967 * @throws UnauthorizedException
2969 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2971 $a = Friendica\DI::app();
2975 foreach ((array)$items as $item) {
2976 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2978 // Look if the posts are matching if they should be filtered by user id
2979 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2983 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2992 * @param array $item Item record
2993 * @param string $type Return format (atom, rss, xml, json)
2994 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2995 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2996 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2997 * @return array API-formatted status
2998 * @throws BadRequestException
2999 * @throws ImagickException
3000 * @throws InternalServerErrorException
3001 * @throws UnauthorizedException
3003 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3005 $a = Friendica\DI::app();
3007 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3008 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3011 localize_item($item);
3013 $in_reply_to = api_in_reply_to($item);
3015 $converted = api_convert_item($item);
3017 if ($type == "xml") {
3018 $geo = "georss:point";
3024 'text' => $converted["text"],
3025 'truncated' => false,
3026 'created_at'=> api_date($item['created']),
3027 'in_reply_to_status_id' => $in_reply_to['status_id'],
3028 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3029 'source' => (($item['app']) ? $item['app'] : 'web'),
3030 'id' => intval($item['id']),
3031 'id_str' => (string) intval($item['id']),
3032 'in_reply_to_user_id' => $in_reply_to['user_id'],
3033 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3034 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3036 'favorited' => $item['starred'] ? true : false,
3037 'user' => $status_user,
3038 'friendica_author' => $author_user,
3039 'friendica_owner' => $owner_user,
3040 'friendica_private' => $item['private'] == 1,
3041 //'entities' => NULL,
3042 'statusnet_html' => $converted["html"],
3043 'statusnet_conversation_id' => $item['parent'],
3044 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3045 'friendica_activities' => api_format_items_activities($item, $type),
3046 'friendica_title' => $item['title'],
3047 'friendica_html' => BBCode::convert($item['body'], false)
3050 if (count($converted["attachments"]) > 0) {
3051 $status["attachments"] = $converted["attachments"];
3054 if (count($converted["entities"]) > 0) {
3055 $status["entities"] = $converted["entities"];
3058 if ($status["source"] == 'web') {
3059 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3060 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3061 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3064 $retweeted_item = [];
3067 if ($item["id"] == $item["parent"]) {
3068 $body = $item['body'];
3069 $retweeted_item = api_share_as_retweet($item);
3070 if ($body != $item['body']) {
3071 $quoted_item = $retweeted_item;
3072 $retweeted_item = [];
3076 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3077 $announce = api_get_announce($item);
3078 if (!empty($announce)) {
3079 $retweeted_item = $item;
3081 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3085 if (!empty($quoted_item)) {
3086 if ($quoted_item['id'] != $item['id']) {
3087 $quoted_status = api_format_item($quoted_item);
3088 /// @todo Only remove the attachments that are also contained in the quotes status
3089 unset($status['attachments']);
3090 unset($status['entities']);
3092 $conv_quoted = api_convert_item($quoted_item);
3093 $quoted_status = $status;
3094 unset($quoted_status['attachments']);
3095 unset($quoted_status['entities']);
3096 unset($quoted_status['statusnet_conversation_id']);
3097 $quoted_status['text'] = $conv_quoted['text'];
3098 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3100 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3101 } catch (BadRequestException $e) {
3102 // user not found. should be found?
3103 /// @todo check if the user should be always found
3104 $quoted_status["user"] = [];
3107 unset($quoted_status['friendica_author']);
3108 unset($quoted_status['friendica_owner']);
3109 unset($quoted_status['friendica_activities']);
3110 unset($quoted_status['friendica_private']);
3113 if (!empty($retweeted_item)) {
3114 $retweeted_status = $status;
3115 unset($retweeted_status['friendica_author']);
3116 unset($retweeted_status['friendica_owner']);
3117 unset($retweeted_status['friendica_activities']);
3118 unset($retweeted_status['friendica_private']);
3119 unset($retweeted_status['statusnet_conversation_id']);
3120 $status['user'] = $status['friendica_owner'];
3122 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3123 } catch (BadRequestException $e) {
3124 // user not found. should be found?
3125 /// @todo check if the user should be always found
3126 $retweeted_status["user"] = [];
3129 $rt_converted = api_convert_item($retweeted_item);
3131 $retweeted_status['text'] = $rt_converted["text"];
3132 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3133 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3135 if (!empty($quoted_status)) {
3136 $retweeted_status['quoted_status'] = $quoted_status;
3139 $status['friendica_author'] = $retweeted_status['user'];
3140 $status['retweeted_status'] = $retweeted_status;
3141 } elseif (!empty($quoted_status)) {
3142 $root_status = api_convert_item($item);
3144 $status['text'] = $root_status["text"];
3145 $status['statusnet_html'] = $root_status["html"];
3146 $status['quoted_status'] = $quoted_status;
3149 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3150 unset($status["user"]["uid"]);
3151 unset($status["user"]["self"]);
3153 if ($item["coord"] != "") {
3154 $coords = explode(' ', $item["coord"]);
3155 if (count($coords) == 2) {
3156 if ($type == "json") {
3157 $status["geo"] = ['type' => 'Point',
3158 'coordinates' => [(float) $coords[0],
3159 (float) $coords[1]]];
3160 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3161 $status["georss:point"] = $item["coord"];
3170 * Returns the remaining number of API requests available to the user before the API limit is reached.
3172 * @param string $type Return type (atom, rss, xml, json)
3174 * @return array|string
3177 function api_account_rate_limit_status($type)
3179 if ($type == "xml") {
3181 'remaining-hits' => '150',
3182 '@attributes' => ["type" => "integer"],
3183 'hourly-limit' => '150',
3184 '@attributes2' => ["type" => "integer"],
3185 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3186 '@attributes3' => ["type" => "datetime"],
3187 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3188 '@attributes4' => ["type" => "integer"],
3192 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3193 'remaining_hits' => '150',
3194 'hourly_limit' => '150',
3195 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3199 return api_format_data('hash', $type, ['hash' => $hash]);
3202 /// @TODO move to top of file or somewhere better
3203 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3206 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3208 * @param string $type Return type (atom, rss, xml, json)
3210 * @return array|string
3212 function api_help_test($type)
3214 if ($type == 'xml') {
3220 return api_format_data('ok', $type, ["ok" => $ok]);
3223 /// @TODO move to top of file or somewhere better
3224 api_register_func('api/help/test', 'api_help_test', false);
3227 * Returns all lists the user subscribes to.
3229 * @param string $type Return type (atom, rss, xml, json)
3231 * @return array|string
3232 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3234 function api_lists_list($type)
3237 /// @TODO $ret is not filled here?
3238 return api_format_data('lists', $type, ["lists_list" => $ret]);
3241 /// @TODO move to top of file or somewhere better
3242 api_register_func('api/lists/list', 'api_lists_list', true);
3243 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3246 * Returns all groups the user owns.
3248 * @param string $type Return type (atom, rss, xml, json)
3250 * @return array|string
3251 * @throws BadRequestException
3252 * @throws ForbiddenException
3253 * @throws ImagickException
3254 * @throws InternalServerErrorException
3255 * @throws UnauthorizedException
3256 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3258 function api_lists_ownerships($type)
3262 if (api_user() === false) {
3263 throw new ForbiddenException();
3267 $user_info = api_get_user($a);
3268 $uid = $user_info['uid'];
3270 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3272 // loop through all groups
3274 foreach ($groups as $group) {
3275 if ($group['visible']) {
3281 'name' => $group['name'],
3282 'id' => intval($group['id']),
3283 'id_str' => (string) $group['id'],
3284 'user' => $user_info,
3288 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3291 /// @TODO move to top of file or somewhere better
3292 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3295 * Returns recent statuses from users in the specified group.
3297 * @param string $type Return type (atom, rss, xml, json)
3299 * @return array|string
3300 * @throws BadRequestException
3301 * @throws ForbiddenException
3302 * @throws ImagickException
3303 * @throws InternalServerErrorException
3304 * @throws UnauthorizedException
3305 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3307 function api_lists_statuses($type)
3311 $user_info = api_get_user($a);
3312 if (api_user() === false || $user_info === false) {
3313 throw new ForbiddenException();
3316 unset($_REQUEST["user_id"]);
3317 unset($_GET["user_id"]);
3319 unset($_REQUEST["screen_name"]);
3320 unset($_GET["screen_name"]);
3322 if (empty($_REQUEST['list_id'])) {
3323 throw new BadRequestException('list_id not specified');
3327 $count = $_REQUEST['count'] ?? 20;
3328 $page = $_REQUEST['page'] ?? 1;
3329 $since_id = $_REQUEST['since_id'] ?? 0;
3330 $max_id = $_REQUEST['max_id'] ?? 0;
3331 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3332 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3334 $start = max(0, ($page - 1) * $count);
3336 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3337 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3340 $condition[0] .= " AND `item`.`id` <= ?";
3341 $condition[] = $max_id;
3343 if ($exclude_replies > 0) {
3344 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3346 if ($conversation_id > 0) {
3347 $condition[0] .= " AND `item`.`parent` = ?";
3348 $condition[] = $conversation_id;
3351 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3352 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3354 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3356 $data = ['status' => $items];
3361 $data = api_rss_extra($a, $data, $user_info);
3365 return api_format_data("statuses", $type, $data);
3368 /// @TODO move to top of file or somewhere better
3369 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3372 * Considers friends and followers lists to be private and won't return
3373 * anything if any user_id parameter is passed.
3375 * @brief Returns either the friends of the follower list
3377 * @param string $qtype Either "friends" or "followers"
3378 * @return boolean|array
3379 * @throws BadRequestException
3380 * @throws ForbiddenException
3381 * @throws ImagickException
3382 * @throws InternalServerErrorException
3383 * @throws UnauthorizedException
3385 function api_statuses_f($qtype)
3389 if (api_user() === false) {
3390 throw new ForbiddenException();
3394 $count = $_GET['count'] ?? 20;
3395 $page = $_GET['page'] ?? 1;
3397 $start = max(0, ($page - 1) * $count);
3399 $user_info = api_get_user($a);
3401 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3402 /* this is to stop Hotot to load friends multiple times
3403 * I'm not sure if I'm missing return something or
3404 * is a bug in hotot. Workaround, meantime
3408 return array('$users' => $ret);*/
3413 if ($qtype == 'friends') {
3414 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3415 } elseif ($qtype == 'followers') {
3416 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3419 // friends and followers only for self
3420 if ($user_info['self'] == 0) {
3421 $sql_extra = " AND false ";
3424 if ($qtype == 'blocks') {
3425 $sql_filter = 'AND `blocked` AND NOT `pending`';
3426 } elseif ($qtype == 'incoming') {
3427 $sql_filter = 'AND `pending`';
3429 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3447 foreach ($r as $cid) {
3448 $user = api_get_user($a, $cid['nurl']);
3449 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3450 unset($user["uid"]);
3451 unset($user["self"]);
3458 return ['user' => $ret];
3463 * Returns the user's friends.
3465 * @brief Returns the list of friends of the provided user
3467 * @deprecated By Twitter API in favor of friends/list
3469 * @param string $type Either "json" or "xml"
3470 * @return boolean|string|array
3471 * @throws BadRequestException
3472 * @throws ForbiddenException
3474 function api_statuses_friends($type)
3476 $data = api_statuses_f("friends");
3477 if ($data === false) {
3480 return api_format_data("users", $type, $data);
3484 * Returns the user's followers.
3486 * @brief Returns the list of followers of the provided user
3488 * @deprecated By Twitter API in favor of friends/list
3490 * @param string $type Either "json" or "xml"
3491 * @return boolean|string|array
3492 * @throws BadRequestException
3493 * @throws ForbiddenException
3495 function api_statuses_followers($type)
3497 $data = api_statuses_f("followers");
3498 if ($data === false) {
3501 return api_format_data("users", $type, $data);
3504 /// @TODO move to top of file or somewhere better
3505 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3506 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3509 * Returns the list of blocked users
3511 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3513 * @param string $type Either "json" or "xml"
3515 * @return boolean|string|array
3516 * @throws BadRequestException
3517 * @throws ForbiddenException
3519 function api_blocks_list($type)
3521 $data = api_statuses_f('blocks');
3522 if ($data === false) {
3525 return api_format_data("users", $type, $data);
3528 /// @TODO move to top of file or somewhere better
3529 api_register_func('api/blocks/list', 'api_blocks_list', true);
3532 * Returns the list of pending users IDs
3534 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3536 * @param string $type Either "json" or "xml"
3538 * @return boolean|string|array
3539 * @throws BadRequestException
3540 * @throws ForbiddenException
3542 function api_friendships_incoming($type)
3544 $data = api_statuses_f('incoming');
3545 if ($data === false) {
3550 foreach ($data['user'] as $user) {
3551 $ids[] = $user['id'];
3554 return api_format_data("ids", $type, ['id' => $ids]);
3557 /// @TODO move to top of file or somewhere better
3558 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3561 * Returns the instance's configuration information.
3563 * @param string $type Return type (atom, rss, xml, json)
3565 * @return array|string
3566 * @throws InternalServerErrorException
3568 function api_statusnet_config($type)
3570 $name = Config::get('config', 'sitename');
3571 $server = DI::baseUrl()->getHostname();
3572 $logo = DI::baseUrl() . '/images/friendica-64.png';
3573 $email = Config::get('config', 'admin_email');
3574 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3575 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3576 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3577 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3578 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3581 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3582 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3583 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3584 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3585 'shorturllength' => '30',
3587 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3588 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3589 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3590 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3595 return api_format_data('config', $type, ['config' => $config]);
3598 /// @TODO move to top of file or somewhere better
3599 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3600 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3604 * @param string $type Return type (atom, rss, xml, json)
3606 * @return array|string
3608 function api_statusnet_version($type)
3611 $fake_statusnet_version = "0.9.7";
3613 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3616 /// @TODO move to top of file or somewhere better
3617 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3618 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3622 * @param string $type Return type (atom, rss, xml, json)
3624 * @param int $rel A contact relationship constant
3625 * @return array|string|void
3626 * @throws BadRequestException
3627 * @throws ForbiddenException
3628 * @throws ImagickException
3629 * @throws InternalServerErrorException
3630 * @throws UnauthorizedException
3631 * @todo use api_format_data() to return data
3633 function api_ff_ids($type, int $rel)
3636 throw new ForbiddenException();
3643 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3645 $contacts = DBA::p("SELECT `pcontact`.`id`
3647 INNER JOIN `contact` AS `pcontact`
3648 ON `contact`.`nurl` = `pcontact`.`nurl`
3649 AND `pcontact`.`uid` = 0
3650 WHERE `contact`.`uid` = ?
3651 AND NOT `contact`.`self`
3652 AND `contact`.`rel` IN (?, ?)",
3659 foreach (DBA::toArray($contacts) as $contact) {
3660 if ($stringify_ids) {
3661 $ids[] = $contact['id'];
3663 $ids[] = intval($contact['id']);
3667 return api_format_data('ids', $type, ['id' => $ids]);
3671 * Returns the ID of every user the user is following.
3673 * @param string $type Return type (atom, rss, xml, json)
3675 * @return array|string
3676 * @throws BadRequestException
3677 * @throws ForbiddenException
3678 * @throws ImagickException
3679 * @throws InternalServerErrorException
3680 * @throws UnauthorizedException
3681 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3683 function api_friends_ids($type)
3685 return api_ff_ids($type, Contact::SHARING);
3689 * Returns the ID of every user following the user.
3691 * @param string $type Return type (atom, rss, xml, json)
3693 * @return array|string
3694 * @throws BadRequestException
3695 * @throws ForbiddenException
3696 * @throws ImagickException
3697 * @throws InternalServerErrorException
3698 * @throws UnauthorizedException
3699 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3701 function api_followers_ids($type)
3703 return api_ff_ids($type, Contact::FOLLOWER);
3706 /// @TODO move to top of file or somewhere better
3707 api_register_func('api/friends/ids', 'api_friends_ids', true);
3708 api_register_func('api/followers/ids', 'api_followers_ids', true);
3711 * Sends a new direct message.
3713 * @param string $type Return type (atom, rss, xml, json)
3715 * @return array|string
3716 * @throws BadRequestException
3717 * @throws ForbiddenException
3718 * @throws ImagickException
3719 * @throws InternalServerErrorException
3720 * @throws NotFoundException
3721 * @throws UnauthorizedException
3722 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3724 function api_direct_messages_new($type)
3728 if (api_user() === false) {
3729 throw new ForbiddenException();
3732 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3736 $sender = api_get_user($a);
3739 if (!empty($_POST['screen_name'])) {
3741 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3743 DBA::escape($_POST['screen_name'])
3746 if (DBA::isResult($r)) {
3747 // Selecting the id by priority, friendica first
3748 api_best_nickname($r);
3750 $recipient = api_get_user($a, $r[0]['nurl']);
3753 $recipient = api_get_user($a, $_POST['user_id']);
3756 if (empty($recipient)) {
3757 throw new NotFoundException('Recipient not found');
3761 if (!empty($_REQUEST['replyto'])) {
3763 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3765 intval($_REQUEST['replyto'])
3767 $replyto = $r[0]['parent-uri'];
3768 $sub = $r[0]['title'];
3770 if (!empty($_REQUEST['title'])) {
3771 $sub = $_REQUEST['title'];
3773 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3777 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3780 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3781 $ret = api_format_messages($r[0], $recipient, $sender);
3783 $ret = ["error"=>$id];
3786 $data = ['direct_message'=>$ret];
3792 $data = api_rss_extra($a, $data, $sender);
3796 return api_format_data("direct-messages", $type, $data);
3799 /// @TODO move to top of file or somewhere better
3800 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3803 * Destroys a direct message.
3805 * @brief delete a direct_message from mail table through api
3807 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3808 * @return string|array
3809 * @throws BadRequestException
3810 * @throws ForbiddenException
3811 * @throws ImagickException
3812 * @throws InternalServerErrorException
3813 * @throws UnauthorizedException
3814 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3816 function api_direct_messages_destroy($type)
3820 if (api_user() === false) {
3821 throw new ForbiddenException();
3825 $user_info = api_get_user($a);
3827 $id = $_REQUEST['id'] ?? 0;
3829 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3830 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3831 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3833 $uid = $user_info['uid'];
3834 // error if no id or parenturi specified (for clients posting parent-uri as well)
3835 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3836 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3837 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3840 // BadRequestException if no id specified (for clients using Twitter API)
3842 throw new BadRequestException('Message id not specified');
3845 // add parent-uri to sql command if specified by calling app
3846 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3848 // get data of the specified message id
3850 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3855 // error message if specified id is not in database
3856 if (!DBA::isResult($r)) {
3857 if ($verbose == "true") {
3858 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3859 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3861 /// @todo BadRequestException ok for Twitter API clients?
3862 throw new BadRequestException('message id not in database');
3867 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3872 if ($verbose == "true") {
3875 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3876 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3878 $answer = ['result' => 'error', 'message' => 'unknown error'];
3879 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3882 /// @todo return JSON data like Twitter API not yet implemented
3885 /// @TODO move to top of file or somewhere better
3886 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3891 * @brief unfollow contact
3893 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3894 * @return string|array
3895 * @throws BadRequestException
3896 * @throws ForbiddenException
3897 * @throws ImagickException
3898 * @throws InternalServerErrorException
3899 * @throws NotFoundException
3900 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3902 function api_friendships_destroy($type)
3906 if ($uid === false) {
3907 throw new ForbiddenException();
3910 $contact_id = $_REQUEST['user_id'] ?? 0;
3912 if (empty($contact_id)) {
3913 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3914 throw new BadRequestException("no user_id specified");
3917 // Get Contact by given id
3918 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3920 if(!DBA::isResult($contact)) {
3921 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3922 throw new NotFoundException("no contact found to given ID");
3925 $url = $contact["url"];
3927 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3928 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3929 Strings::normaliseLink($url), $url];
3930 $contact = DBA::selectFirst('contact', [], $condition);
3932 if (!DBA::isResult($contact)) {
3933 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3934 throw new NotFoundException("Not following Contact");
3937 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3938 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3939 throw new ExpectationFailedException("Not supported");
3942 $dissolve = ($contact['rel'] == Contact::SHARING);
3944 $owner = User::getOwnerDataById($uid);
3946 Contact::terminateFriendship($owner, $contact, $dissolve);
3949 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3950 throw new NotFoundException("Error Processing Request");
3953 // Sharing-only contacts get deleted as there no relationship any more
3955 Contact::remove($contact['id']);
3957 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3960 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3961 unset($contact["uid"]);
3962 unset($contact["self"]);
3964 // Set screen_name since Twidere requests it
3965 $contact["screen_name"] = $contact["nick"];
3967 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3969 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3973 * @param string $type Return type (atom, rss, xml, json)
3974 * @param string $box
3975 * @param string $verbose
3977 * @return array|string
3978 * @throws BadRequestException
3979 * @throws ForbiddenException
3980 * @throws ImagickException
3981 * @throws InternalServerErrorException
3982 * @throws UnauthorizedException
3984 function api_direct_messages_box($type, $box, $verbose)
3987 if (api_user() === false) {
3988 throw new ForbiddenException();
3991 $count = $_GET['count'] ?? 20;
3992 $page = $_REQUEST['page'] ?? 1;
3994 $since_id = $_REQUEST['since_id'] ?? 0;
3995 $max_id = $_REQUEST['max_id'] ?? 0;
3997 $user_id = $_REQUEST['user_id'] ?? '';
3998 $screen_name = $_REQUEST['screen_name'] ?? '';
4001 unset($_REQUEST["user_id"]);
4002 unset($_GET["user_id"]);
4004 unset($_REQUEST["screen_name"]);
4005 unset($_GET["screen_name"]);
4007 $user_info = api_get_user($a);
4008 if ($user_info === false) {
4009 throw new ForbiddenException();
4011 $profile_url = $user_info["url"];
4014 $start = max(0, ($page - 1) * $count);
4019 if ($box=="sentbox") {
4020 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4021 } elseif ($box == "conversation") {
4022 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4023 } elseif ($box == "all") {
4024 $sql_extra = "true";
4025 } elseif ($box == "inbox") {
4026 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4030 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4033 if ($user_id != "") {
4034 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4035 } elseif ($screen_name !="") {
4036 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4040 "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",
4046 if ($verbose == "true" && !DBA::isResult($r)) {
4047 $answer = ['result' => 'error', 'message' => 'no mails available'];
4048 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4052 foreach ($r as $item) {
4053 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4054 $recipient = $user_info;
4055 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4056 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4057 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4058 $sender = $user_info;
4061 if (isset($recipient) && isset($sender)) {
4062 $ret[] = api_format_messages($item, $recipient, $sender);
4067 $data = ['direct_message' => $ret];
4072 $data = api_rss_extra($a, $data, $user_info);
4076 return api_format_data("direct-messages", $type, $data);
4080 * Returns the most recent direct messages sent by the user.
4082 * @param string $type Return type (atom, rss, xml, json)
4084 * @return array|string
4085 * @throws BadRequestException
4086 * @throws ForbiddenException
4087 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4089 function api_direct_messages_sentbox($type)
4091 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4092 return api_direct_messages_box($type, "sentbox", $verbose);
4096 * Returns the most recent direct messages sent to the user.
4098 * @param string $type Return type (atom, rss, xml, json)
4100 * @return array|string
4101 * @throws BadRequestException
4102 * @throws ForbiddenException
4103 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4105 function api_direct_messages_inbox($type)
4107 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4108 return api_direct_messages_box($type, "inbox", $verbose);
4113 * @param string $type Return type (atom, rss, xml, json)
4115 * @return array|string
4116 * @throws BadRequestException
4117 * @throws ForbiddenException
4119 function api_direct_messages_all($type)
4121 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4122 return api_direct_messages_box($type, "all", $verbose);
4127 * @param string $type Return type (atom, rss, xml, json)
4129 * @return array|string
4130 * @throws BadRequestException
4131 * @throws ForbiddenException
4133 function api_direct_messages_conversation($type)
4135 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4136 return api_direct_messages_box($type, "conversation", $verbose);
4139 /// @TODO move to top of file or somewhere better
4140 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4141 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4142 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4143 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4146 * Returns an OAuth Request Token.
4148 * @see https://oauth.net/core/1.0/#auth_step1
4150 function api_oauth_request_token()
4152 $oauth1 = new FKOAuth1();
4154 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4155 } catch (Exception $e) {
4156 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4164 * Returns an OAuth Access Token.
4166 * @return array|string
4167 * @see https://oauth.net/core/1.0/#auth_step3
4169 function api_oauth_access_token()
4171 $oauth1 = new FKOAuth1();
4173 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4174 } catch (Exception $e) {
4175 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4182 /// @TODO move to top of file or somewhere better
4183 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4184 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4188 * @brief delete a complete photoalbum with all containing photos from database through api
4190 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4191 * @return string|array
4192 * @throws BadRequestException
4193 * @throws ForbiddenException
4194 * @throws InternalServerErrorException
4196 function api_fr_photoalbum_delete($type)
4198 if (api_user() === false) {
4199 throw new ForbiddenException();
4202 $album = $_REQUEST['album'] ?? '';
4204 // we do not allow calls without album string
4206 throw new BadRequestException("no albumname specified");
4208 // check if album is existing
4210 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4214 if (!DBA::isResult($r)) {
4215 throw new BadRequestException("album not available");
4218 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4219 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4220 foreach ($r as $rr) {
4221 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4222 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4224 if (!DBA::isResult($photo_item)) {
4225 throw new InternalServerErrorException("problem with deleting items occured");
4227 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4230 // now let's delete all photos from the album
4231 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4233 // return success of deletion or error message
4235 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4236 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4238 throw new InternalServerErrorException("unknown error - deleting from database failed");
4243 * @brief update the name of the album for all photos of an album
4245 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4246 * @return string|array
4247 * @throws BadRequestException
4248 * @throws ForbiddenException
4249 * @throws InternalServerErrorException
4251 function api_fr_photoalbum_update($type)
4253 if (api_user() === false) {
4254 throw new ForbiddenException();
4257 $album = $_REQUEST['album'] ?? '';
4258 $album_new = $_REQUEST['album_new'] ?? '';
4260 // we do not allow calls without album string
4262 throw new BadRequestException("no albumname specified");
4264 if ($album_new == "") {
4265 throw new BadRequestException("no new albumname specified");
4267 // check if album is existing
4268 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4269 throw new BadRequestException("album not available");
4271 // now let's update all photos to the albumname
4272 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4274 // return success of updating or error message
4276 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4277 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4279 throw new InternalServerErrorException("unknown error - updating in database failed");
4285 * @brief list all photos of the authenticated user
4287 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4288 * @return string|array
4289 * @throws ForbiddenException
4290 * @throws InternalServerErrorException
4292 function api_fr_photos_list($type)
4294 if (api_user() === false) {
4295 throw new ForbiddenException();
4298 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4299 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4300 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4301 intval(local_user())
4304 'image/jpeg' => 'jpg',
4305 'image/png' => 'png',
4306 'image/gif' => 'gif'
4308 $data = ['photo'=>[]];
4309 if (DBA::isResult($r)) {
4310 foreach ($r as $rr) {
4312 $photo['id'] = $rr['resource-id'];
4313 $photo['album'] = $rr['album'];
4314 $photo['filename'] = $rr['filename'];
4315 $photo['type'] = $rr['type'];
4316 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4317 $photo['created'] = $rr['created'];
4318 $photo['edited'] = $rr['edited'];
4319 $photo['desc'] = $rr['desc'];
4321 if ($type == "xml") {
4322 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4324 $photo['thumb'] = $thumb;
4325 $data['photo'][] = $photo;
4329 return api_format_data("photos", $type, $data);
4333 * @brief upload a new photo or change an existing photo
4335 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4336 * @return string|array
4337 * @throws BadRequestException
4338 * @throws ForbiddenException
4339 * @throws ImagickException
4340 * @throws InternalServerErrorException
4341 * @throws NotFoundException
4343 function api_fr_photo_create_update($type)
4345 if (api_user() === false) {
4346 throw new ForbiddenException();
4349 $photo_id = $_REQUEST['photo_id'] ?? null;
4350 $desc = $_REQUEST['desc'] ?? null;
4351 $album = $_REQUEST['album'] ?? null;
4352 $album_new = $_REQUEST['album_new'] ?? null;
4353 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4354 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4355 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4356 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4357 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4359 // do several checks on input parameters
4360 // we do not allow calls without album string
4361 if ($album == null) {
4362 throw new BadRequestException("no albumname specified");
4364 // if photo_id == null --> we are uploading a new photo
4365 if ($photo_id == null) {
4368 // error if no media posted in create-mode
4369 if (empty($_FILES['media'])) {
4371 throw new BadRequestException("no media data submitted");
4374 // album_new will be ignored in create-mode
4379 // check if photo is existing in databasei
4380 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4381 throw new BadRequestException("photo not available");
4385 // checks on acl strings provided by clients
4386 $acl_input_error = false;
4387 $acl_input_error |= check_acl_input($allow_cid);
4388 $acl_input_error |= check_acl_input($deny_cid);
4389 $acl_input_error |= check_acl_input($allow_gid);
4390 $acl_input_error |= check_acl_input($deny_gid);
4391 if ($acl_input_error) {
4392 throw new BadRequestException("acl data invalid");
4394 // now let's upload the new media in create-mode
4395 if ($mode == "create") {
4396 $media = $_FILES['media'];
4397 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4399 // return success of updating or error message
4400 if (!is_null($data)) {
4401 return api_format_data("photo_create", $type, $data);
4403 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4407 // now let's do the changes in update-mode
4408 if ($mode == "update") {
4409 $updated_fields = [];
4411 if (!is_null($desc)) {
4412 $updated_fields['desc'] = $desc;
4415 if (!is_null($album_new)) {
4416 $updated_fields['album'] = $album_new;
4419 if (!is_null($allow_cid)) {
4420 $allow_cid = trim($allow_cid);
4421 $updated_fields['allow_cid'] = $allow_cid;
4424 if (!is_null($deny_cid)) {
4425 $deny_cid = trim($deny_cid);
4426 $updated_fields['deny_cid'] = $deny_cid;
4429 if (!is_null($allow_gid)) {
4430 $allow_gid = trim($allow_gid);
4431 $updated_fields['allow_gid'] = $allow_gid;
4434 if (!is_null($deny_gid)) {
4435 $deny_gid = trim($deny_gid);
4436 $updated_fields['deny_gid'] = $deny_gid;
4440 if (count($updated_fields) > 0) {
4441 $nothingtodo = false;
4442 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4444 $nothingtodo = true;
4447 if (!empty($_FILES['media'])) {
4448 $nothingtodo = false;
4449 $media = $_FILES['media'];
4450 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4451 if (!is_null($data)) {
4452 return api_format_data("photo_update", $type, $data);
4456 // return success of updating or error message
4458 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4459 return api_format_data("photo_update", $type, ['$result' => $answer]);
4462 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4463 return api_format_data("photo_update", $type, ['$result' => $answer]);
4465 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4468 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4472 * @brief delete a single photo from the database through api
4474 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4475 * @return string|array
4476 * @throws BadRequestException
4477 * @throws ForbiddenException
4478 * @throws InternalServerErrorException
4480 function api_fr_photo_delete($type)
4482 if (api_user() === false) {
4483 throw new ForbiddenException();
4487 $photo_id = $_REQUEST['photo_id'] ?? null;
4489 // do several checks on input parameters
4490 // we do not allow calls without photo id
4491 if ($photo_id == null) {
4492 throw new BadRequestException("no photo_id specified");
4495 // check if photo is existing in database
4496 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4497 throw new BadRequestException("photo not available");
4500 // now we can perform on the deletion of the photo
4501 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4503 // return success of deletion or error message
4505 // retrieve the id of the parent element (the photo element)
4506 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4507 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4509 if (!DBA::isResult($photo_item)) {
4510 throw new InternalServerErrorException("problem with deleting items occured");
4512 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4513 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4514 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4516 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4517 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4519 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4525 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4527 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4528 * @return string|array
4529 * @throws BadRequestException
4530 * @throws ForbiddenException
4531 * @throws InternalServerErrorException
4532 * @throws NotFoundException
4534 function api_fr_photo_detail($type)
4536 if (api_user() === false) {
4537 throw new ForbiddenException();
4539 if (empty($_REQUEST['photo_id'])) {
4540 throw new BadRequestException("No photo id.");
4543 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4544 $photo_id = $_REQUEST['photo_id'];
4546 // prepare json/xml output with data from database for the requested photo
4547 $data = prepare_photo_data($type, $scale, $photo_id);
4549 return api_format_data("photo_detail", $type, $data);
4554 * Updates the user’s profile image.
4556 * @brief updates the profile image for the user (either a specified profile or the default profile)
4558 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4560 * @return string|array
4561 * @throws BadRequestException
4562 * @throws ForbiddenException
4563 * @throws ImagickException
4564 * @throws InternalServerErrorException
4565 * @throws NotFoundException
4566 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4568 function api_account_update_profile_image($type)
4570 if (api_user() === false) {
4571 throw new ForbiddenException();
4574 $profile_id = $_REQUEST['profile_id'] ?? 0;
4576 // error if image data is missing
4577 if (empty($_FILES['image'])) {
4578 throw new BadRequestException("no media data submitted");
4581 // check if specified profile id is valid
4582 if ($profile_id != 0) {
4583 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4584 // error message if specified profile id is not in database
4585 if (!DBA::isResult($profile)) {
4586 throw new BadRequestException("profile_id not available");
4588 $is_default_profile = $profile['is-default'];
4590 $is_default_profile = 1;
4593 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4595 if (!empty($_FILES['image'])) {
4596 $media = $_FILES['image'];
4597 } elseif (!empty($_FILES['media'])) {
4598 $media = $_FILES['media'];
4600 // save new profile image
4601 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4604 if (is_array($media['type'])) {
4605 $filetype = $media['type'][0];
4607 $filetype = $media['type'];
4609 if ($filetype == "image/jpeg") {
4611 } elseif ($filetype == "image/png") {
4614 throw new InternalServerErrorException('Unsupported filetype');
4617 // change specified profile or all profiles to the new resource-id
4618 if ($is_default_profile) {
4619 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4620 Photo::update(['profile' => false], $condition);
4622 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4623 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4624 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4627 Contact::updateSelfFromUserID(api_user(), true);
4629 // Update global directory in background
4630 $url = DI::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4631 if ($url && strlen(Config::get('system', 'directory'))) {
4632 Worker::add(PRIORITY_LOW, "Directory", $url);
4635 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4637 // output for client
4639 return api_account_verify_credentials($type);
4641 // SaveMediaToDatabase failed for some reason
4642 throw new InternalServerErrorException("image upload failed");
4646 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4647 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4648 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4649 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4650 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4651 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4652 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4653 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4654 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4657 * Update user profile
4659 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4661 * @return array|string
4662 * @throws BadRequestException
4663 * @throws ForbiddenException
4664 * @throws ImagickException
4665 * @throws InternalServerErrorException
4666 * @throws UnauthorizedException
4668 function api_account_update_profile($type)
4670 $local_user = api_user();
4671 $api_user = api_get_user(get_app());
4673 if (!empty($_POST['name'])) {
4674 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4675 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4676 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4677 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4680 if (isset($_POST['description'])) {
4681 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4682 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4683 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4686 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4687 // Update global directory in background
4688 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4689 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4692 return api_account_verify_credentials($type);
4695 /// @TODO move to top of file or somewhere better
4696 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4700 * @param string $acl_string
4704 function check_acl_input($acl_string)
4706 if (empty($acl_string)) {
4710 $contact_not_found = false;
4712 // split <x><y><z> into array of cid's
4713 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4715 // check for each cid if it is available on server
4716 $cid_array = $array[0];
4717 foreach ($cid_array as $cid) {
4718 $cid = str_replace("<", "", $cid);
4719 $cid = str_replace(">", "", $cid);
4720 $condition = ['id' => $cid, 'uid' => api_user()];
4721 $contact_not_found |= !DBA::exists('contact', $condition);
4723 return $contact_not_found;
4727 * @param string $mediatype
4728 * @param array $media
4729 * @param string $type
4730 * @param string $album
4731 * @param string $allow_cid
4732 * @param string $deny_cid
4733 * @param string $allow_gid
4734 * @param string $deny_gid
4735 * @param string $desc
4736 * @param integer $profile
4737 * @param boolean $visibility
4738 * @param string $photo_id
4740 * @throws BadRequestException
4741 * @throws ForbiddenException
4742 * @throws ImagickException
4743 * @throws InternalServerErrorException
4744 * @throws NotFoundException
4745 * @throws UnauthorizedException
4747 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)
4755 if (is_array($media)) {
4756 if (is_array($media['tmp_name'])) {
4757 $src = $media['tmp_name'][0];
4759 $src = $media['tmp_name'];
4761 if (is_array($media['name'])) {
4762 $filename = basename($media['name'][0]);
4764 $filename = basename($media['name']);
4766 if (is_array($media['size'])) {
4767 $filesize = intval($media['size'][0]);
4769 $filesize = intval($media['size']);
4771 if (is_array($media['type'])) {
4772 $filetype = $media['type'][0];
4774 $filetype = $media['type'];
4778 if ($filetype == "") {
4779 $filetype = Images::guessType($filename);
4781 $imagedata = @getimagesize($src);
4783 $filetype = $imagedata['mime'];
4786 "File upload src: " . $src . " - filename: " . $filename .
4787 " - size: " . $filesize . " - type: " . $filetype,
4791 // check if there was a php upload error
4792 if ($filesize == 0 && $media['error'] == 1) {
4793 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4795 // check against max upload size within Friendica instance
4796 $maximagesize = Config::get('system', 'maximagesize');
4797 if ($maximagesize && ($filesize > $maximagesize)) {
4798 $formattedBytes = Strings::formatBytes($maximagesize);
4799 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4802 // create Photo instance with the data of the image
4803 $imagedata = @file_get_contents($src);
4804 $Image = new Image($imagedata, $filetype);
4805 if (!$Image->isValid()) {
4806 throw new InternalServerErrorException("unable to process image data");
4809 // check orientation of image
4810 $Image->orient($src);
4813 // check max length of images on server
4814 $max_length = Config::get('system', 'max_image_length');
4816 $max_length = MAX_IMAGE_LENGTH;
4818 if ($max_length > 0) {
4819 $Image->scaleDown($max_length);
4820 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4822 $width = $Image->getWidth();
4823 $height = $Image->getHeight();
4825 // create a new resource-id if not already provided
4826 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4828 if ($mediatype == "photo") {
4829 // upload normal image (scales 0, 1, 2)
4830 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4832 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4834 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4836 if ($width > 640 || $height > 640) {
4837 $Image->scaleDown(640);
4838 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4840 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4844 if ($width > 320 || $height > 320) {
4845 $Image->scaleDown(320);
4846 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4848 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4851 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4852 } elseif ($mediatype == "profileimage") {
4853 // upload profile image (scales 4, 5, 6)
4854 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4856 if ($width > 300 || $height > 300) {
4857 $Image->scaleDown(300);
4858 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4860 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4864 if ($width > 80 || $height > 80) {
4865 $Image->scaleDown(80);
4866 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4868 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4872 if ($width > 48 || $height > 48) {
4873 $Image->scaleDown(48);
4874 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4876 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4879 $Image->__destruct();
4880 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4883 if (isset($r) && $r) {
4884 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4885 if ($photo_id == null && $mediatype == "photo") {
4886 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4888 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4889 return prepare_photo_data($type, false, $resource_id);
4891 throw new InternalServerErrorException("image upload failed");
4897 * @param string $hash
4898 * @param string $allow_cid
4899 * @param string $deny_cid
4900 * @param string $allow_gid
4901 * @param string $deny_gid
4902 * @param string $filetype
4903 * @param boolean $visibility
4904 * @throws InternalServerErrorException
4906 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4908 // get data about the api authenticated user
4909 $uri = Item::newURI(intval(api_user()));
4910 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4913 $arr['guid'] = System::createUUID();
4914 $arr['uid'] = intval(api_user());
4916 $arr['parent-uri'] = $uri;
4917 $arr['type'] = 'photo';
4919 $arr['resource-id'] = $hash;
4920 $arr['contact-id'] = $owner_record['id'];
4921 $arr['owner-name'] = $owner_record['name'];
4922 $arr['owner-link'] = $owner_record['url'];
4923 $arr['owner-avatar'] = $owner_record['thumb'];
4924 $arr['author-name'] = $owner_record['name'];
4925 $arr['author-link'] = $owner_record['url'];
4926 $arr['author-avatar'] = $owner_record['thumb'];
4928 $arr['allow_cid'] = $allow_cid;
4929 $arr['allow_gid'] = $allow_gid;
4930 $arr['deny_cid'] = $deny_cid;
4931 $arr['deny_gid'] = $deny_gid;
4932 $arr['visible'] = $visibility;
4936 'image/jpeg' => 'jpg',
4937 'image/png' => 'png',
4938 'image/gif' => 'gif'
4941 // adds link to the thumbnail scale photo
4942 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4943 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4946 // do the magic for storing the item in the database and trigger the federation to other contacts
4952 * @param string $type
4954 * @param string $photo_id
4957 * @throws BadRequestException
4958 * @throws ForbiddenException
4959 * @throws ImagickException
4960 * @throws InternalServerErrorException
4961 * @throws NotFoundException
4962 * @throws UnauthorizedException
4964 function prepare_photo_data($type, $scale, $photo_id)
4967 $user_info = api_get_user($a);
4969 if ($user_info === false) {
4970 throw new ForbiddenException();
4973 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4974 $data_sql = ($scale === false ? "" : "data, ");
4976 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4977 // clients needs to convert this in their way for further processing
4979 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4980 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4981 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4982 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4983 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4984 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4986 intval(local_user()),
4987 DBA::escape($photo_id),
4992 'image/jpeg' => 'jpg',
4993 'image/png' => 'png',
4994 'image/gif' => 'gif'
4997 // prepare output data for photo
4998 if (DBA::isResult($r)) {
4999 $data = ['photo' => $r[0]];
5000 $data['photo']['id'] = $data['photo']['resource-id'];
5001 if ($scale !== false) {
5002 $data['photo']['data'] = base64_encode($data['photo']['data']);
5004 unset($data['photo']['datasize']); //needed only with scale param
5006 if ($type == "xml") {
5007 $data['photo']['links'] = [];
5008 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5009 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5011 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5014 $data['photo']['link'] = [];
5015 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5017 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5018 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5022 unset($data['photo']['resource-id']);
5023 unset($data['photo']['minscale']);
5024 unset($data['photo']['maxscale']);
5026 throw new NotFoundException();
5029 // retrieve item element for getting activities (like, dislike etc.) related to photo
5030 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5031 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5033 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5035 // retrieve comments on photo
5036 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5037 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5039 $statuses = Item::selectForUser(api_user(), [], $condition);
5041 // prepare output of comments
5042 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5044 if ($type == "xml") {
5046 foreach ($commentData as $comment) {
5047 $comments[$k++ . ":comment"] = $comment;
5050 foreach ($commentData as $comment) {
5051 $comments[] = $comment;
5054 $data['photo']['friendica_comments'] = $comments;
5056 // include info if rights on photo and rights on item are mismatching
5057 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5058 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5059 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5060 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5061 $data['photo']['rights_mismatch'] = $rights_mismatch;
5068 * Similar as /mod/redir.php
5069 * redirect to 'url' after dfrn auth
5071 * Why this when there is mod/redir.php already?
5072 * This use api_user() and api_login()
5075 * c_url: url of remote contact to auth to
5076 * url: string, url to redirect after auth
5078 function api_friendica_remoteauth()
5080 $url = $_GET['url'] ?? '';
5081 $c_url = $_GET['c_url'] ?? '';
5083 if ($url === '' || $c_url === '') {
5084 throw new BadRequestException("Wrong parameters.");
5087 $c_url = Strings::normaliseLink($c_url);
5091 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5092 if (!DBA::isResult($contact)) {
5093 throw new BadRequestException("Unknown contact");
5096 $cid = $contact['id'];
5098 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5100 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5101 System::externalRedirect($url ?: $c_url);
5104 if ($contact['duplex'] && $contact['issued-id']) {
5105 $orig_id = $contact['issued-id'];
5106 $dfrn_id = '1:' . $orig_id;
5108 if ($contact['duplex'] && $contact['dfrn-id']) {
5109 $orig_id = $contact['dfrn-id'];
5110 $dfrn_id = '0:' . $orig_id;
5113 $sec = Strings::getRandomHex();
5115 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5116 'sec' => $sec, 'expire' => time() + 45];
5117 DBA::insert('profile_check', $fields);
5119 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5120 $dest = ($url ? '&destination_url=' . $url : '');
5122 System::externalRedirect(
5123 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5124 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5125 . '&type=profile&sec=' . $sec . $dest
5128 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5131 * Return an item with announcer data if it had been announced
5133 * @param array $item Item array
5134 * @return array Item array with announce data
5136 function api_get_announce($item)
5138 // Quit if the item already has got a different owner and author
5139 if ($item['owner-id'] != $item['author-id']) {
5143 // Don't change original or Diaspora posts
5144 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5148 // Quit if we do now the original author and it had been a post from a native network
5149 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5153 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5154 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5155 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5156 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5157 if (!DBA::isResult($announce)) {
5161 return array_merge($item, $announce);
5165 * @brief Return the item shared, if the item contains only the [share] tag
5167 * @param array $item Sharer item
5168 * @return array|false Shared item or false if not a reshare
5169 * @throws ImagickException
5170 * @throws InternalServerErrorException
5172 function api_share_as_retweet(&$item)
5174 $body = trim($item["body"]);
5176 if (Diaspora::isReshare($body, false) === false) {
5177 if ($item['author-id'] == $item['owner-id']) {
5180 // Reshares from OStatus, ActivityPub and Twitter
5181 $reshared_item = $item;
5182 $reshared_item['owner-id'] = $reshared_item['author-id'];
5183 $reshared_item['owner-link'] = $reshared_item['author-link'];
5184 $reshared_item['owner-name'] = $reshared_item['author-name'];
5185 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5186 return $reshared_item;
5190 $reshared = Item::getShareArray($item);
5191 if (empty($reshared)) {
5195 $reshared_item = $item;
5197 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5201 if (!empty($reshared['comment'])) {
5202 $item['body'] = $reshared['comment'];
5205 $reshared_item["share-pre-body"] = $reshared['comment'];
5206 $reshared_item["body"] = $reshared['shared'];
5207 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5208 $reshared_item["author-name"] = $reshared['author'];
5209 $reshared_item["author-link"] = $reshared['profile'];
5210 $reshared_item["author-avatar"] = $reshared['avatar'];
5211 $reshared_item["plink"] = $reshared['link'] ?? '';
5212 $reshared_item["created"] = $reshared['posted'];
5213 $reshared_item["edited"] = $reshared['posted'];
5215 // Try to fetch the original item
5216 if (!empty($reshared['guid'])) {
5217 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5218 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5219 $condition = ['id' => $original_id];
5224 if (!empty($condition)) {
5225 $original_item = Item::selectFirst([], $condition);
5226 if (DBA::isResult($original_item)) {
5227 $reshared_item = array_merge($reshared_item, $original_item);
5231 return $reshared_item;
5236 * @param array $item
5241 function api_in_reply_to($item)
5245 $in_reply_to['status_id'] = null;
5246 $in_reply_to['user_id'] = null;
5247 $in_reply_to['status_id_str'] = null;
5248 $in_reply_to['user_id_str'] = null;
5249 $in_reply_to['screen_name'] = null;
5251 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5252 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5253 if (DBA::isResult($parent)) {
5254 $in_reply_to['status_id'] = intval($parent['id']);
5256 $in_reply_to['status_id'] = intval($item['parent']);
5259 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5261 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5262 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5264 if (DBA::isResult($parent)) {
5265 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5266 $in_reply_to['user_id'] = intval($parent['author-id']);
5267 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5270 // There seems to be situation, where both fields are identical:
5271 // https://github.com/friendica/friendica/issues/1010
5272 // This is a bugfix for that.
5273 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5274 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']]);
5275 $in_reply_to['status_id'] = null;
5276 $in_reply_to['user_id'] = null;
5277 $in_reply_to['status_id_str'] = null;
5278 $in_reply_to['user_id_str'] = null;
5279 $in_reply_to['screen_name'] = null;
5283 return $in_reply_to;
5288 * @param string $text
5291 * @throws InternalServerErrorException
5293 function api_clean_plain_items($text)
5295 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5297 $text = BBCode::cleanPictureLinks($text);
5298 $URLSearchString = "^\[\]";
5300 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5302 if ($include_entities == "true") {
5303 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5306 // Simplify "attachment" element
5307 $text = BBCode::removeAttachment($text);
5314 * @param array $contacts
5318 function api_best_nickname(&$contacts)
5322 if (count($contacts) == 0) {
5326 foreach ($contacts as $contact) {
5327 if ($contact["network"] == "") {
5328 $contact["network"] = "dfrn";
5329 $best_contact = [$contact];
5333 if (sizeof($best_contact) == 0) {
5334 foreach ($contacts as $contact) {
5335 if ($contact["network"] == "dfrn") {
5336 $best_contact = [$contact];
5341 if (sizeof($best_contact) == 0) {
5342 foreach ($contacts as $contact) {
5343 if ($contact["network"] == "dspr") {
5344 $best_contact = [$contact];
5349 if (sizeof($best_contact) == 0) {
5350 foreach ($contacts as $contact) {
5351 if ($contact["network"] == "stat") {
5352 $best_contact = [$contact];
5357 if (sizeof($best_contact) == 0) {
5358 foreach ($contacts as $contact) {
5359 if ($contact["network"] == "pump") {
5360 $best_contact = [$contact];
5365 if (sizeof($best_contact) == 0) {
5366 foreach ($contacts as $contact) {
5367 if ($contact["network"] == "twit") {
5368 $best_contact = [$contact];
5373 if (sizeof($best_contact) == 1) {
5374 $contacts = $best_contact;
5376 $contacts = [$contacts[0]];
5381 * Return all or a specified group of the user with the containing contacts.
5383 * @param string $type Return type (atom, rss, xml, json)
5385 * @return array|string
5386 * @throws BadRequestException
5387 * @throws ForbiddenException
5388 * @throws ImagickException
5389 * @throws InternalServerErrorException
5390 * @throws UnauthorizedException
5392 function api_friendica_group_show($type)
5396 if (api_user() === false) {
5397 throw new ForbiddenException();
5401 $user_info = api_get_user($a);
5402 $gid = $_REQUEST['gid'] ?? 0;
5403 $uid = $user_info['uid'];
5405 // get data of the specified group id or all groups if not specified
5408 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5412 // error message if specified gid is not in database
5413 if (!DBA::isResult($r)) {
5414 throw new BadRequestException("gid not available");
5418 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5423 // loop through all groups and retrieve all members for adding data in the user array
5425 foreach ($r as $rr) {
5426 $members = Contact::getByGroupId($rr['id']);
5429 if ($type == "xml") {
5430 $user_element = "users";
5432 foreach ($members as $member) {
5433 $user = api_get_user($a, $member['nurl']);
5434 $users[$k++.":user"] = $user;
5437 $user_element = "user";
5438 foreach ($members as $member) {
5439 $user = api_get_user($a, $member['nurl']);
5443 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5445 return api_format_data("groups", $type, ['group' => $grps]);
5447 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5451 * Delete the specified group of the user.
5453 * @param string $type Return type (atom, rss, xml, json)
5455 * @return array|string
5456 * @throws BadRequestException
5457 * @throws ForbiddenException
5458 * @throws ImagickException
5459 * @throws InternalServerErrorException
5460 * @throws UnauthorizedException
5462 function api_friendica_group_delete($type)
5466 if (api_user() === false) {
5467 throw new ForbiddenException();
5471 $user_info = api_get_user($a);
5472 $gid = $_REQUEST['gid'] ?? 0;
5473 $name = $_REQUEST['name'] ?? '';
5474 $uid = $user_info['uid'];
5476 // error if no gid specified
5477 if ($gid == 0 || $name == "") {
5478 throw new BadRequestException('gid or name not specified');
5481 // get data of the specified group id
5483 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5487 // error message if specified gid is not in database
5488 if (!DBA::isResult($r)) {
5489 throw new BadRequestException('gid not available');
5492 // get data of the specified group id and group name
5494 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5499 // error message if specified gid is not in database
5500 if (!DBA::isResult($rname)) {
5501 throw new BadRequestException('wrong group name');
5505 $ret = Group::removeByName($uid, $name);
5508 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5509 return api_format_data("group_delete", $type, ['result' => $success]);
5511 throw new BadRequestException('other API error');
5514 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5519 * @param string $type Return type (atom, rss, xml, json)
5521 * @return array|string
5522 * @throws BadRequestException
5523 * @throws ForbiddenException
5524 * @throws ImagickException
5525 * @throws InternalServerErrorException
5526 * @throws UnauthorizedException
5527 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5529 function api_lists_destroy($type)
5533 if (api_user() === false) {
5534 throw new ForbiddenException();
5538 $user_info = api_get_user($a);
5539 $gid = $_REQUEST['list_id'] ?? 0;
5540 $uid = $user_info['uid'];
5542 // error if no gid specified
5544 throw new BadRequestException('gid not specified');
5547 // get data of the specified group id
5548 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5549 // error message if specified gid is not in database
5551 throw new BadRequestException('gid not available');
5554 if (Group::remove($gid)) {
5556 'name' => $group['name'],
5557 'id' => intval($gid),
5558 'id_str' => (string) $gid,
5559 'user' => $user_info
5562 return api_format_data("lists", $type, ['lists' => $list]);
5565 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5568 * Add a new group to the database.
5570 * @param string $name Group name
5571 * @param int $uid User ID
5572 * @param array $users List of users to add to the group
5575 * @throws BadRequestException
5577 function group_create($name, $uid, $users = [])
5579 // error if no name specified
5581 throw new BadRequestException('group name not specified');
5584 // get data of the specified group name
5586 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5590 // error message if specified group name already exists
5591 if (DBA::isResult($rname)) {
5592 throw new BadRequestException('group name already exists');
5595 // check if specified group name is a deleted group
5597 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5601 // error message if specified group name already exists
5602 if (DBA::isResult($rname)) {
5603 $reactivate_group = true;
5607 $ret = Group::create($uid, $name);
5609 $gid = Group::getIdByName($uid, $name);
5611 throw new BadRequestException('other API error');
5615 $erroraddinguser = false;
5617 foreach ($users as $user) {
5618 $cid = $user['cid'];
5619 // check if user really exists as contact
5621 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5625 if (count($contact)) {
5626 Group::addMember($gid, $cid);
5628 $erroraddinguser = true;
5629 $errorusers[] = $cid;
5633 // return success message incl. missing users in array
5634 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5636 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5640 * Create the specified group with the posted array of contacts.
5642 * @param string $type Return type (atom, rss, xml, json)
5644 * @return array|string
5645 * @throws BadRequestException
5646 * @throws ForbiddenException
5647 * @throws ImagickException
5648 * @throws InternalServerErrorException
5649 * @throws UnauthorizedException
5651 function api_friendica_group_create($type)
5655 if (api_user() === false) {
5656 throw new ForbiddenException();
5660 $user_info = api_get_user($a);
5661 $name = $_REQUEST['name'] ?? '';
5662 $uid = $user_info['uid'];
5663 $json = json_decode($_POST['json'], true);
5664 $users = $json['user'];
5666 $success = group_create($name, $uid, $users);
5668 return api_format_data("group_create", $type, ['result' => $success]);
5670 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5673 * Create a new group.
5675 * @param string $type Return type (atom, rss, xml, json)
5677 * @return array|string
5678 * @throws BadRequestException
5679 * @throws ForbiddenException
5680 * @throws ImagickException
5681 * @throws InternalServerErrorException
5682 * @throws UnauthorizedException
5683 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5685 function api_lists_create($type)
5689 if (api_user() === false) {
5690 throw new ForbiddenException();
5694 $user_info = api_get_user($a);
5695 $name = $_REQUEST['name'] ?? '';
5696 $uid = $user_info['uid'];
5698 $success = group_create($name, $uid);
5699 if ($success['success']) {
5701 'name' => $success['name'],
5702 'id' => intval($success['gid']),
5703 'id_str' => (string) $success['gid'],
5704 'user' => $user_info
5707 return api_format_data("lists", $type, ['lists'=>$grp]);
5710 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5713 * Update the specified group with the posted array of contacts.
5715 * @param string $type Return type (atom, rss, xml, json)
5717 * @return array|string
5718 * @throws BadRequestException
5719 * @throws ForbiddenException
5720 * @throws ImagickException
5721 * @throws InternalServerErrorException
5722 * @throws UnauthorizedException
5724 function api_friendica_group_update($type)
5728 if (api_user() === false) {
5729 throw new ForbiddenException();
5733 $user_info = api_get_user($a);
5734 $uid = $user_info['uid'];
5735 $gid = $_REQUEST['gid'] ?? 0;
5736 $name = $_REQUEST['name'] ?? '';
5737 $json = json_decode($_POST['json'], true);
5738 $users = $json['user'];
5740 // error if no name specified
5742 throw new BadRequestException('group name not specified');
5745 // error if no gid specified
5747 throw new BadRequestException('gid not specified');
5751 $members = Contact::getByGroupId($gid);
5752 foreach ($members as $member) {
5753 $cid = $member['id'];
5754 foreach ($users as $user) {
5755 $found = ($user['cid'] == $cid ? true : false);
5757 if (!isset($found) || !$found) {
5758 Group::removeMemberByName($uid, $name, $cid);
5763 $erroraddinguser = false;
5765 foreach ($users as $user) {
5766 $cid = $user['cid'];
5767 // check if user really exists as contact
5769 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5774 if (count($contact)) {
5775 Group::addMember($gid, $cid);
5777 $erroraddinguser = true;
5778 $errorusers[] = $cid;
5782 // return success message incl. missing users in array
5783 $status = ($erroraddinguser ? "missing user" : "ok");
5784 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5785 return api_format_data("group_update", $type, ['result' => $success]);
5788 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5791 * Update information about a group.
5793 * @param string $type Return type (atom, rss, xml, json)
5795 * @return array|string
5796 * @throws BadRequestException
5797 * @throws ForbiddenException
5798 * @throws ImagickException
5799 * @throws InternalServerErrorException
5800 * @throws UnauthorizedException
5801 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5803 function api_lists_update($type)
5807 if (api_user() === false) {
5808 throw new ForbiddenException();
5812 $user_info = api_get_user($a);
5813 $gid = $_REQUEST['list_id'] ?? 0;
5814 $name = $_REQUEST['name'] ?? '';
5815 $uid = $user_info['uid'];
5817 // error if no gid specified
5819 throw new BadRequestException('gid not specified');
5822 // get data of the specified group id
5823 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5824 // error message if specified gid is not in database
5826 throw new BadRequestException('gid not available');
5829 if (Group::update($gid, $name)) {
5832 'id' => intval($gid),
5833 'id_str' => (string) $gid,
5834 'user' => $user_info
5837 return api_format_data("lists", $type, ['lists' => $list]);
5841 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5845 * @param string $type Return type (atom, rss, xml, json)
5847 * @return array|string
5848 * @throws BadRequestException
5849 * @throws ForbiddenException
5850 * @throws ImagickException
5851 * @throws InternalServerErrorException
5853 function api_friendica_activity($type)
5857 if (api_user() === false) {
5858 throw new ForbiddenException();
5860 $verb = strtolower($a->argv[3]);
5861 $verb = preg_replace("|\..*$|", "", $verb);
5863 $id = $_REQUEST['id'] ?? 0;
5865 $res = Item::performLike($id, $verb);
5868 if ($type == "xml") {
5873 return api_format_data('ok', $type, ['ok' => $ok]);
5875 throw new BadRequestException('Error adding activity');
5879 /// @TODO move to top of file or somewhere better
5880 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5881 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5882 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5883 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5884 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5885 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5886 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5887 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5888 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5889 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5892 * @brief Returns notifications
5894 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5895 * @return string|array
5896 * @throws BadRequestException
5897 * @throws ForbiddenException
5898 * @throws InternalServerErrorException
5900 function api_friendica_notification($type)
5904 if (api_user() === false) {
5905 throw new ForbiddenException();
5908 throw new BadRequestException("Invalid argument count");
5910 $notes = DI::notify()->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5912 if ($type == "xml") {
5914 if (!empty($notes)) {
5915 foreach ($notes as $note) {
5916 $xmlnotes[] = ["@attributes" => $note];
5922 return api_format_data("notes", $type, ['note' => $notes]);
5926 * POST request with 'id' param as notification id
5928 * @brief Set notification as seen and returns associated item (if possible)
5930 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5931 * @return string|array
5932 * @throws BadRequestException
5933 * @throws ForbiddenException
5934 * @throws ImagickException
5935 * @throws InternalServerErrorException
5936 * @throws UnauthorizedException
5938 function api_friendica_notification_seen($type)
5941 $user_info = api_get_user($a);
5943 if (api_user() === false || $user_info === false) {
5944 throw new ForbiddenException();
5947 throw new BadRequestException("Invalid argument count");
5950 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5953 $note = $nm->getByID($id);
5954 if (is_null($note)) {
5955 throw new BadRequestException("Invalid argument");
5958 $nm->setSeen($note);
5959 if ($note['otype']=='item') {
5960 // would be really better with an ItemsManager and $im->getByID() :-P
5961 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5962 if (DBA::isResult($item)) {
5963 // we found the item, return it to the user
5964 $ret = api_format_items([$item], $user_info, false, $type);
5965 $data = ['status' => $ret];
5966 return api_format_data("status", $type, $data);
5968 // the item can't be found, but we set the note as seen, so we count this as a success
5970 return api_format_data('result', $type, ['result' => "success"]);
5973 /// @TODO move to top of file or somewhere better
5974 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5975 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5978 * @brief update a direct_message to seen state
5980 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5981 * @return string|array (success result=ok, error result=error with error message)
5982 * @throws BadRequestException
5983 * @throws ForbiddenException
5984 * @throws ImagickException
5985 * @throws InternalServerErrorException
5986 * @throws UnauthorizedException
5988 function api_friendica_direct_messages_setseen($type)
5991 if (api_user() === false) {
5992 throw new ForbiddenException();
5996 $user_info = api_get_user($a);
5997 $uid = $user_info['uid'];
5998 $id = $_REQUEST['id'] ?? 0;
6000 // return error if id is zero
6002 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6003 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6006 // error message if specified id is not in database
6007 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6008 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6009 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6012 // update seen indicator
6013 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6017 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6018 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6020 $answer = ['result' => 'error', 'message' => 'unknown error'];
6021 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6025 /// @TODO move to top of file or somewhere better
6026 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6029 * @brief search for direct_messages containing a searchstring through api
6031 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6032 * @param string $box
6033 * @return string|array (success: success=true if found and search_result contains found messages,
6034 * success=false if nothing was found, search_result='nothing found',
6035 * error: result=error with error message)
6036 * @throws BadRequestException
6037 * @throws ForbiddenException
6038 * @throws ImagickException
6039 * @throws InternalServerErrorException
6040 * @throws UnauthorizedException
6042 function api_friendica_direct_messages_search($type, $box = "")
6046 if (api_user() === false) {
6047 throw new ForbiddenException();
6051 $user_info = api_get_user($a);
6052 $searchstring = $_REQUEST['searchstring'] ?? '';
6053 $uid = $user_info['uid'];
6055 // error if no searchstring specified
6056 if ($searchstring == "") {
6057 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6058 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6061 // get data for the specified searchstring
6063 "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",
6065 DBA::escape('%'.$searchstring.'%')
6068 $profile_url = $user_info["url"];
6070 // message if nothing was found
6071 if (!DBA::isResult($r)) {
6072 $success = ['success' => false, 'search_results' => 'problem with query'];
6073 } elseif (count($r) == 0) {
6074 $success = ['success' => false, 'search_results' => 'nothing found'];
6077 foreach ($r as $item) {
6078 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6079 $recipient = $user_info;
6080 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6081 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6082 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6083 $sender = $user_info;
6086 if (isset($recipient) && isset($sender)) {
6087 $ret[] = api_format_messages($item, $recipient, $sender);
6090 $success = ['success' => true, 'search_results' => $ret];
6093 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6096 /// @TODO move to top of file or somewhere better
6097 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6100 * @brief return data of all the profiles a user has to the client
6102 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6103 * @return string|array
6104 * @throws BadRequestException
6105 * @throws ForbiddenException
6106 * @throws ImagickException
6107 * @throws InternalServerErrorException
6108 * @throws UnauthorizedException
6110 function api_friendica_profile_show($type)
6114 if (api_user() === false) {
6115 throw new ForbiddenException();
6119 $profile_id = $_REQUEST['profile_id'] ?? 0;
6121 // retrieve general information about profiles for user
6122 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6123 $directory = Config::get('system', 'directory');
6125 // get data of the specified profile id or all profiles of the user if not specified
6126 if ($profile_id != 0) {
6127 $r = Profile::getById(api_user(), $profile_id);
6128 // error message if specified gid is not in database
6129 if (!DBA::isResult($r)) {
6130 throw new BadRequestException("profile_id not available");
6133 $r = Profile::getListByUser(api_user());
6135 // loop through all returned profiles and retrieve data and users
6138 if (DBA::isResult($r)) {
6139 foreach ($r as $rr) {
6140 $profile = api_format_items_profiles($rr);
6142 // select all users from contact table, loop and prepare standard return for user data
6144 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6145 foreach ($nurls as $nurl) {
6146 $user = api_get_user($a, $nurl['nurl']);
6147 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6149 $profile['users'] = $users;
6151 // add prepared profile data to array for final return
6152 if ($type == "xml") {
6153 $profiles[$k++ . ":profile"] = $profile;
6155 $profiles[] = $profile;
6160 // return settings, authenticated user and profiles data
6161 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6163 $result = ['multi_profiles' => $multi_profiles ? true : false,
6164 'global_dir' => $directory,
6165 'friendica_owner' => api_get_user($a, $self['nurl']),
6166 'profiles' => $profiles];
6167 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6169 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6172 * Returns a list of saved searches.
6174 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6176 * @param string $type Return format: json or xml
6178 * @return string|array
6181 function api_saved_searches_list($type)
6183 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6186 while ($term = DBA::fetch($terms)) {
6188 'created_at' => api_date(time()),
6189 'id' => intval($term['id']),
6190 'id_str' => $term['id'],
6191 'name' => $term['term'],
6193 'query' => $term['term']
6199 return api_format_data("terms", $type, ['terms' => $result]);
6202 /// @TODO move to top of file or somewhere better
6203 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6206 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6208 * @brief Number of comments
6210 * @param object $data [Status, Status]
6214 function bindComments(&$data)
6216 if (count($data) == 0) {
6222 foreach ($data as $item) {
6223 $ids[] = $item['id'];
6226 $idStr = DBA::escape(implode(', ', $ids));
6227 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6228 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6229 $itemsData = DBA::toArray($items);
6231 foreach ($itemsData as $item) {
6232 $comments[$item['parent']] = $item['comments'];
6235 foreach ($data as $idx => $item) {
6237 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6242 @TODO Maybe open to implement?
6244 [pagename] => api/1.1/statuses/lookup.json
6245 [id] => 605138389168451584
6246 [include_cards] => true
6247 [cards_platform] => Android-12
6248 [include_entities] => true
6249 [include_my_retweet] => 1
6251 [include_reply_count] => true
6252 [include_descendent_reply_count] => true
6256 Not implemented by now:
6257 statuses/retweets_of_me
6262 account/update_location
6263 account/update_profile_background_image
6266 friendica/profile/update
6267 friendica/profile/create
6268 friendica/profile/delete
6270 Not implemented in status.net:
6271 statuses/retweeted_to_me
6272 statuses/retweeted_by_me
6273 direct_messages/destroy
6275 account/update_delivery_device
6276 notifications/follow