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\Model\UserItem;
33 use Friendica\Network\FKOAuth1;
34 use Friendica\Network\HTTPException;
35 use Friendica\Network\HTTPException\BadRequestException;
36 use Friendica\Network\HTTPException\ExpectationFailedException;
37 use Friendica\Network\HTTPException\ForbiddenException;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Network\HTTPException\MethodNotAllowedException;
40 use Friendica\Network\HTTPException\NotFoundException;
41 use Friendica\Network\HTTPException\NotImplementedException;
42 use Friendica\Network\HTTPException\TooManyRequestsException;
43 use Friendica\Network\HTTPException\UnauthorizedException;
44 use Friendica\Object\Image;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Diaspora;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Images;
49 use Friendica\Util\Network;
50 use Friendica\Util\Proxy as ProxyUtils;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
54 require_once __DIR__ . '/../mod/share.php';
55 require_once __DIR__ . '/../mod/item.php';
56 require_once __DIR__ . '/../mod/wall_upload.php';
58 define('API_METHOD_ANY', '*');
59 define('API_METHOD_GET', 'GET');
60 define('API_METHOD_POST', 'POST,PUT');
61 define('API_METHOD_DELETE', 'POST,DELETE');
63 define('API_LOG_PREFIX', 'API {action} - ');
69 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
70 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
71 * into a page, and visitors will post something without noticing it).
73 * @brief Auth API user
77 if (!empty($_SESSION['allow_api'])) {
85 * Clients can send 'source' parameter to be show in post metadata
86 * as "sent via <source>".
87 * Some clients doesn't send a source param, we support ones we know
90 * @brief Get source name from API client
93 * Client source name, default to "api" if unset/unknown
98 if (requestdata('source')) {
99 return requestdata('source');
102 // Support for known clients that doesn't send a source name
103 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
104 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
108 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
110 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
117 * @brief Format date for API
119 * @param string $str Source date, as UTC
120 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
123 function api_date($str)
125 // Wed May 23 06:01:13 +0000 2007
126 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
130 * Register a function to be the endpoint for defined API path.
132 * @brief Register API endpoint
134 * @param string $path API URL path, relative to DI::baseUrl()
135 * @param string $func Function name to call on path request
136 * @param bool $auth API need logged user
137 * @param string $method HTTP method reqiured to call this endpoint.
138 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
139 * Default to API_METHOD_ANY
141 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
151 // Workaround for hotot
152 $path = str_replace("api/", "api/1.1/", $path);
162 * Log in user via OAuth1 or Simple HTTP Auth.
163 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
165 * @brief Login API user
168 * @throws ForbiddenException
169 * @throws InternalServerErrorException
170 * @throws UnauthorizedException
171 * @hook 'authenticate'
173 * 'username' => username from login form
174 * 'password' => password from login form
175 * 'authenticated' => return status,
176 * 'user_record' => return authenticated user record
178 function api_login(App $a)
180 $oauth1 = new FKOAuth1();
183 $request = OAuthRequest::from_request();
184 list($consumer, $token) = $oauth1->verify_request($request);
185 if (!is_null($token)) {
186 $oauth1->loginUser($token->uid);
187 Session::set('allow_api', true);
190 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
191 var_dump($consumer, $token);
193 } catch (Exception $e) {
194 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
197 // workaround for HTTP-auth in CGI mode
198 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
199 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
200 if (strlen($userpass)) {
201 list($name, $password) = explode(':', $userpass);
202 $_SERVER['PHP_AUTH_USER'] = $name;
203 $_SERVER['PHP_AUTH_PW'] = $password;
207 if (empty($_SERVER['PHP_AUTH_USER'])) {
208 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
209 header('WWW-Authenticate: Basic realm="Friendica"');
210 throw new UnauthorizedException("This API requires login");
213 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
214 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
216 // allow "user@server" login (but ignore 'server' part)
217 $at = strstr($user, "@", true);
222 // next code from mod/auth.php. needs better solution
226 'username' => trim($user),
227 'password' => trim($password),
228 'authenticated' => 0,
229 'user_record' => null,
233 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
234 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
235 * and later addons should not interfere with an earlier one that succeeded.
237 Hook::callAll('authenticate', $addon_auth);
239 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
240 $record = $addon_auth['user_record'];
242 $user_id = User::authenticate(trim($user), trim($password), true);
243 if ($user_id !== false) {
244 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
248 if (!DBA::isResult($record)) {
249 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
250 header('WWW-Authenticate: Basic realm="Friendica"');
251 //header('HTTP/1.0 401 Unauthorized');
252 //die('This api requires login');
253 throw new UnauthorizedException("This API requires login");
256 DI::auth()->setForUser($a, $record);
258 $_SESSION["allow_api"] = true;
260 Hook::callAll('logged_in', $a->user);
264 * API endpoints can define which HTTP method to accept when called.
265 * This function check the current HTTP method agains endpoint
268 * @brief Check HTTP method of called API
270 * @param string $method Required methods, uppercase, separated by comma
273 function api_check_method($method)
275 if ($method == "*") {
278 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
282 * Authenticate user, call registered API function, set HTTP headers
284 * @brief Main API entry point
287 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
288 * @return string|array API call result
291 function api_call(App $a, App\Arguments $args = null)
293 global $API, $called_api;
300 if (strpos($args->getQueryString(), ".xml") > 0) {
303 if (strpos($args->getQueryString(), ".json") > 0) {
306 if (strpos($args->getQueryString(), ".rss") > 0) {
309 if (strpos($args->getQueryString(), ".atom") > 0) {
314 foreach ($API as $p => $info) {
315 if (strpos($args->getQueryString(), $p) === 0) {
316 if (!api_check_method($info['method'])) {
317 throw new MethodNotAllowedException();
320 $called_api = explode("/", $p);
321 //unset($_SERVER['PHP_AUTH_USER']);
323 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
324 if (!empty($info['auth']) && api_user() === false) {
328 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
329 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
331 $stamp = microtime(true);
332 $return = call_user_func($info['func'], $type);
333 $duration = floatval(microtime(true) - $stamp);
335 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
337 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
339 if (false === $return) {
341 * api function returned false withour throw an
342 * exception. This should not happend, throw a 500
344 throw new InternalServerErrorException();
349 header("Content-Type: text/xml");
352 header("Content-Type: application/json");
353 if (!empty($return)) {
354 $json = json_encode(end($return));
355 if (!empty($_GET['callback'])) {
356 $json = $_GET['callback'] . "(" . $json . ")";
362 header("Content-Type: application/rss+xml");
363 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
366 header("Content-Type: application/atom+xml");
367 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
374 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
375 throw new NotImplementedException();
376 } catch (HTTPException $e) {
377 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
378 return api_error($type, $e, $args);
383 * @brief Format API error string
385 * @param string $type Return type (xml, json, rss, as)
386 * @param object $e HTTPException Error object
387 * @param App\Arguments $args The App arguments
388 * @return string|array error message formatted as $type
390 function api_error($type, $e, App\Arguments $args)
392 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
393 /// @TODO: https://dev.twitter.com/overview/api/response-codes
395 $error = ["error" => $error,
396 "code" => $e->getCode() . " " . $e->httpdesc,
397 "request" => $args->getQueryString()];
399 $return = api_format_data('status', $type, ['status' => $error]);
403 header("Content-Type: text/xml");
406 header("Content-Type: application/json");
407 $return = json_encode($return);
410 header("Content-Type: application/rss+xml");
413 header("Content-Type: application/atom+xml");
421 * @brief Set values for RSS template
424 * @param array $arr Array to be passed to template
425 * @param array $user_info User info
427 * @throws BadRequestException
428 * @throws ImagickException
429 * @throws InternalServerErrorException
430 * @throws UnauthorizedException
431 * @todo find proper type-hints
433 function api_rss_extra(App $a, $arr, $user_info)
435 if (is_null($user_info)) {
436 $user_info = api_get_user($a);
439 $arr['$user'] = $user_info;
441 'alternate' => $user_info['url'],
442 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
443 'base' => DI::baseUrl(),
444 'updated' => api_date(null),
445 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
446 'language' => $user_info['lang'],
447 'logo' => DI::baseUrl() . "/images/friendica-32.png",
455 * @brief Unique contact to contact url.
457 * @param int $id Contact id
458 * @return bool|string
459 * Contact url or False if contact id is unknown
462 function api_unique_id_to_nurl($id)
464 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
466 if (DBA::isResult($r)) {
474 * @brief Get user info array.
477 * @param int|string $contact_id Contact ID or URL
479 * @throws BadRequestException
480 * @throws ImagickException
481 * @throws InternalServerErrorException
482 * @throws UnauthorizedException
484 function api_get_user(App $a, $contact_id = null)
492 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
494 // Searching for contact URL
495 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
496 $user = DBA::escape(Strings::normaliseLink($contact_id));
498 $extra_query = "AND `contact`.`nurl` = '%s' ";
499 if (api_user() !== false) {
500 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
504 // Searching for contact id with uid = 0
505 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
506 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
509 throw new BadRequestException("User ID ".$contact_id." not found.");
513 $extra_query = "AND `contact`.`nurl` = '%s' ";
514 if (api_user() !== false) {
515 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
519 if (is_null($user) && !empty($_GET['user_id'])) {
520 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
523 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
527 $extra_query = "AND `contact`.`nurl` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
532 if (is_null($user) && !empty($_GET['screen_name'])) {
533 $user = DBA::escape($_GET['screen_name']);
534 $extra_query = "AND `contact`.`nick` = '%s' ";
535 if (api_user() !== false) {
536 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
540 if (is_null($user) && !empty($_GET['profileurl'])) {
541 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
542 $extra_query = "AND `contact`.`nurl` = '%s' ";
543 if (api_user() !== false) {
544 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
548 // $called_api is the API path exploded on / and is expected to have at least 2 elements
549 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
550 $argid = count($called_api);
551 if (!empty($a->argv[$argid])) {
552 $data = explode(".", $a->argv[$argid]);
553 if (count($data) > 1) {
554 list($user, $null) = $data;
557 if (is_numeric($user)) {
558 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
562 $extra_query = "AND `contact`.`nurl` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
568 $user = DBA::escape($user);
569 $extra_query = "AND `contact`.`nick` = '%s' ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
576 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
579 if (api_user() === false) {
583 $user = $_SESSION['uid'];
584 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
588 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
592 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
598 // Selecting the id by priority, friendica first
599 if (is_array($uinfo)) {
600 api_best_nickname($uinfo);
603 // if the contact wasn't found, fetch it from the contacts with uid = 0
604 if (!DBA::isResult($uinfo)) {
606 throw new BadRequestException("User not found.");
609 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
611 if (DBA::isResult($contact)) {
613 'id' => $contact["id"],
614 'id_str' => (string) $contact["id"],
615 'name' => $contact["name"],
616 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
617 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
618 'description' => BBCode::toPlaintext($contact["about"]),
619 'profile_image_url' => $contact["micro"],
620 'profile_image_url_https' => $contact["micro"],
621 'profile_image_url_profile_size' => $contact["thumb"],
622 'profile_image_url_large' => $contact["photo"],
623 'url' => $contact["url"],
624 'protected' => false,
625 'followers_count' => 0,
626 'friends_count' => 0,
628 'created_at' => api_date($contact["created"]),
629 'favourites_count' => 0,
631 'time_zone' => 'UTC',
632 'geo_enabled' => false,
634 'statuses_count' => 0,
636 'contributors_enabled' => false,
637 'is_translator' => false,
638 'is_translation_enabled' => false,
639 'following' => false,
640 'follow_request_sent' => false,
641 'statusnet_blocking' => false,
642 'notifications' => false,
643 'statusnet_profile_url' => $contact["url"],
645 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
646 'pid' => Contact::getIdForURL($contact["url"], 0, true),
648 'network' => $contact["network"],
653 throw new BadRequestException("User ".$url." not found.");
657 if ($uinfo[0]['self']) {
658 if ($uinfo[0]['network'] == "") {
659 $uinfo[0]['network'] = Protocol::DFRN;
662 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
663 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
670 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
672 if (!empty($profile['about'])) {
673 $description = $profile['about'];
675 $description = $uinfo[0]["about"];
678 if (!empty($usr['default-location'])) {
679 $location = $usr['default-location'];
680 } elseif (!empty($uinfo[0]["location"])) {
681 $location = $uinfo[0]["location"];
683 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
687 'id' => intval($pcontact_id),
688 'id_str' => (string) intval($pcontact_id),
689 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
690 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
691 'location' => $location,
692 'description' => BBCode::toPlaintext($description),
693 'profile_image_url' => $uinfo[0]['micro'],
694 'profile_image_url_https' => $uinfo[0]['micro'],
695 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
696 'profile_image_url_large' => $uinfo[0]["photo"],
697 'url' => $uinfo[0]['url'],
698 'protected' => false,
699 'followers_count' => intval($countfollowers),
700 'friends_count' => intval($countfriends),
702 'created_at' => api_date($uinfo[0]['created']),
703 'favourites_count' => intval($starred),
705 'time_zone' => 'UTC',
706 'geo_enabled' => false,
708 'statuses_count' => intval($countitems),
710 'contributors_enabled' => false,
711 'is_translator' => false,
712 'is_translation_enabled' => false,
713 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
714 'follow_request_sent' => false,
715 'statusnet_blocking' => false,
716 'notifications' => false,
718 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
719 'statusnet_profile_url' => $uinfo[0]['url'],
720 'uid' => intval($uinfo[0]['uid']),
721 'cid' => intval($uinfo[0]['cid']),
722 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
723 'self' => $uinfo[0]['self'],
724 'network' => $uinfo[0]['network'],
727 // If this is a local user and it uses Frio, we can get its color preferences.
729 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
730 if ($theme_info['theme'] === 'frio') {
731 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
733 if ($schema && ($schema != '---')) {
734 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
735 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
736 require_once $schemefile;
739 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
740 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
741 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
743 if (empty($nav_bg)) {
746 if (empty($link_color)) {
747 $link_color = "#6fdbe8";
749 if (empty($bgcolor)) {
750 $bgcolor = "#ededed";
753 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
754 $ret['profile_link_color'] = str_replace('#', '', $link_color);
755 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
763 * @brief return api-formatted array for item's author and owner
766 * @param array $item item from db
767 * @return array(array:author, array:owner)
768 * @throws BadRequestException
769 * @throws ImagickException
770 * @throws InternalServerErrorException
771 * @throws UnauthorizedException
773 function api_item_get_user(App $a, $item)
775 $status_user = api_get_user($a, $item['author-id'] ?? null);
777 $author_user = $status_user;
779 $status_user["protected"] = $item['private'] ?? 0;
781 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
782 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
784 $owner_user = $author_user;
787 return ([$status_user, $author_user, $owner_user]);
791 * @brief walks recursively through an array with the possibility to change value and key
793 * @param array $array The array to walk through
794 * @param callable $callback The callback function
796 * @return array the transformed array
798 function api_walk_recursive(array &$array, callable $callback)
802 foreach ($array as $k => $v) {
804 if ($callback($v, $k)) {
805 $new_array[$k] = api_walk_recursive($v, $callback);
808 if ($callback($v, $k)) {
819 * @brief Callback function to transform the array in an array that can be transformed in a XML file
821 * @param mixed $item Array item value
822 * @param string $key Array key
824 * @return boolean Should the array item be deleted?
826 function api_reformat_xml(&$item, &$key)
828 if (is_bool($item)) {
829 $item = ($item ? "true" : "false");
832 if (substr($key, 0, 10) == "statusnet_") {
833 $key = "statusnet:".substr($key, 10);
834 } elseif (substr($key, 0, 10) == "friendica_") {
835 $key = "friendica:".substr($key, 10);
837 /// @TODO old-lost code?
839 // $key = "default:".$key;
845 * @brief Creates the XML from a JSON style array
847 * @param array $data JSON style array
848 * @param string $root_element Name of the root element
850 * @return string The XML data
852 function api_create_xml(array $data, $root_element)
854 $childname = key($data);
855 $data2 = array_pop($data);
857 $namespaces = ["" => "http://api.twitter.com",
858 "statusnet" => "http://status.net/schema/api/1/",
859 "friendica" => "http://friendi.ca/schema/api/1/",
860 "georss" => "http://www.georss.org/georss"];
862 /// @todo Auto detection of needed namespaces
863 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
867 if (is_array($data2)) {
869 api_walk_recursive($data2, "api_reformat_xml");
875 foreach ($data2 as $item) {
876 $data4[$i++ . ":" . $childname] = $item;
883 $data3 = [$root_element => $data2];
885 $ret = XML::fromArray($data3, $xml, false, $namespaces);
890 * @brief Formats the data according to the data type
892 * @param string $root_element Name of the root element
893 * @param string $type Return type (atom, rss, xml, json)
894 * @param array $data JSON style array
896 * @return array|string (string|array) XML data or JSON data
898 function api_format_data($root_element, $type, $data)
904 $ret = api_create_xml($data, $root_element);
919 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
920 * returns a 401 status code and an error message if not.
922 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
924 * @param string $type Return type (atom, rss, xml, json)
925 * @return array|string
926 * @throws BadRequestException
927 * @throws ForbiddenException
928 * @throws ImagickException
929 * @throws InternalServerErrorException
930 * @throws UnauthorizedException
932 function api_account_verify_credentials($type)
936 if (api_user() === false) {
937 throw new ForbiddenException();
940 unset($_REQUEST["user_id"]);
941 unset($_GET["user_id"]);
943 unset($_REQUEST["screen_name"]);
944 unset($_GET["screen_name"]);
946 $skip_status = $_REQUEST['skip_status'] ?? false;
948 $user_info = api_get_user($a);
950 // "verified" isn't used here in the standard
951 unset($user_info["verified"]);
953 // - Adding last status
955 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
957 $user_info['status'] = api_format_item($item, $type);
961 // "uid" and "self" are only needed for some internal stuff, so remove it from here
962 unset($user_info["uid"]);
963 unset($user_info["self"]);
965 return api_format_data("user", $type, ['user' => $user_info]);
968 /// @TODO move to top of file or somewhere better
969 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
972 * Get data from $_POST or $_GET
977 function requestdata($k)
979 if (!empty($_POST[$k])) {
982 if (!empty($_GET[$k])) {
989 * Deprecated function to upload media.
991 * @param string $type Return type (atom, rss, xml, json)
993 * @return array|string
994 * @throws BadRequestException
995 * @throws ForbiddenException
996 * @throws ImagickException
997 * @throws InternalServerErrorException
998 * @throws UnauthorizedException
1000 function api_statuses_mediap($type)
1004 if (api_user() === false) {
1005 Logger::log('api_statuses_update: no user');
1006 throw new ForbiddenException();
1008 $user_info = api_get_user($a);
1010 $_REQUEST['profile_uid'] = api_user();
1011 $_REQUEST['api_source'] = true;
1012 $txt = requestdata('status');
1013 /// @TODO old-lost code?
1014 //$txt = urldecode(requestdata('status'));
1016 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1017 $txt = HTML::toBBCodeVideo($txt);
1018 $config = HTMLPurifier_Config::createDefault();
1019 $config->set('Cache.DefinitionImpl', null);
1020 $purifier = new HTMLPurifier($config);
1021 $txt = $purifier->purify($txt);
1023 $txt = HTML::toBBCode($txt);
1025 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1027 $picture = wall_upload_post($a, false);
1029 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1030 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1031 $item_id = item_post($a);
1033 // output the post that we just posted.
1034 return api_status_show($type, $item_id);
1037 /// @TODO move this to top of file or somewhere better!
1038 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1041 * Updates the user’s current status.
1043 * @param string $type Return type (atom, rss, xml, json)
1045 * @return array|string
1046 * @throws BadRequestException
1047 * @throws ForbiddenException
1048 * @throws ImagickException
1049 * @throws InternalServerErrorException
1050 * @throws TooManyRequestsException
1051 * @throws UnauthorizedException
1052 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1054 function api_statuses_update($type)
1058 if (api_user() === false) {
1059 Logger::log('api_statuses_update: no user');
1060 throw new ForbiddenException();
1065 // convert $_POST array items to the form we use for web posts.
1066 if (requestdata('htmlstatus')) {
1067 $txt = requestdata('htmlstatus');
1068 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1069 $txt = HTML::toBBCodeVideo($txt);
1071 $config = HTMLPurifier_Config::createDefault();
1072 $config->set('Cache.DefinitionImpl', null);
1074 $purifier = new HTMLPurifier($config);
1075 $txt = $purifier->purify($txt);
1077 $_REQUEST['body'] = HTML::toBBCode($txt);
1080 $_REQUEST['body'] = requestdata('status');
1083 $_REQUEST['title'] = requestdata('title');
1085 $parent = requestdata('in_reply_to_status_id');
1087 // Twidere sends "-1" if it is no reply ...
1088 if ($parent == -1) {
1092 if (ctype_digit($parent)) {
1093 $_REQUEST['parent'] = $parent;
1095 $_REQUEST['parent_uri'] = $parent;
1098 if (requestdata('lat') && requestdata('long')) {
1099 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1101 $_REQUEST['profile_uid'] = api_user();
1104 // Check for throttling (maximum posts per day, week and month)
1105 $throttle_day = Config::get('system', 'throttle_limit_day');
1106 if ($throttle_day > 0) {
1107 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1109 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1110 $posts_day = DBA::count('thread', $condition);
1112 if ($posts_day > $throttle_day) {
1113 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1114 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1115 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));
1119 $throttle_week = Config::get('system', 'throttle_limit_week');
1120 if ($throttle_week > 0) {
1121 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1123 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1124 $posts_week = DBA::count('thread', $condition);
1126 if ($posts_week > $throttle_week) {
1127 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1128 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1129 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));
1133 $throttle_month = Config::get('system', 'throttle_limit_month');
1134 if ($throttle_month > 0) {
1135 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1137 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1138 $posts_month = DBA::count('thread', $condition);
1140 if ($posts_month > $throttle_month) {
1141 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1142 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1143 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));
1148 if (!empty($_FILES['media'])) {
1149 // upload the image if we have one
1150 $picture = wall_upload_post($a, false);
1151 if (is_array($picture)) {
1152 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1156 if (requestdata('media_ids')) {
1157 $ids = explode(',', requestdata('media_ids'));
1158 foreach ($ids as $id) {
1160 "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",
1164 if (DBA::isResult($r)) {
1165 $phototypes = Images::supportedTypes();
1166 $ext = $phototypes[$r[0]['type']];
1167 $description = $r[0]['desc'] ?? '';
1168 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1169 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1174 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1176 $_REQUEST['api_source'] = true;
1178 if (empty($_REQUEST['source'])) {
1179 $_REQUEST["source"] = api_source();
1182 // call out normal post function
1183 $item_id = item_post($a);
1185 // output the post that we just posted.
1186 return api_status_show($type, $item_id);
1189 /// @TODO move to top of file or somewhere better
1190 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1191 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1194 * Uploads an image to Friendica.
1197 * @throws BadRequestException
1198 * @throws ForbiddenException
1199 * @throws ImagickException
1200 * @throws InternalServerErrorException
1201 * @throws UnauthorizedException
1202 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1204 function api_media_upload()
1208 if (api_user() === false) {
1209 Logger::log('no user');
1210 throw new ForbiddenException();
1215 if (empty($_FILES['media'])) {
1217 throw new BadRequestException("No media.");
1220 $media = wall_upload_post($a, false);
1223 throw new InternalServerErrorException();
1227 $returndata["media_id"] = $media["id"];
1228 $returndata["media_id_string"] = (string)$media["id"];
1229 $returndata["size"] = $media["size"];
1230 $returndata["image"] = ["w" => $media["width"],
1231 "h" => $media["height"],
1232 "image_type" => $media["type"],
1233 "friendica_preview_url" => $media["preview"]];
1235 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1237 return ["media" => $returndata];
1240 /// @TODO move to top of file or somewhere better
1241 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1244 * Updates media meta data (picture descriptions)
1246 * @param string $type Return type (atom, rss, xml, json)
1248 * @return array|string
1249 * @throws BadRequestException
1250 * @throws ForbiddenException
1251 * @throws ImagickException
1252 * @throws InternalServerErrorException
1253 * @throws TooManyRequestsException
1254 * @throws UnauthorizedException
1255 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1257 * @todo Compare the corresponding Twitter function for correct return values
1259 function api_media_metadata_create($type)
1263 if (api_user() === false) {
1264 Logger::info('no user');
1265 throw new ForbiddenException();
1270 $postdata = Network::postdata();
1272 if (empty($postdata)) {
1273 throw new BadRequestException("No post data");
1276 $data = json_decode($postdata, true);
1278 throw new BadRequestException("Invalid post data");
1281 if (empty($data['media_id']) || empty($data['alt_text'])) {
1282 throw new BadRequestException("Missing post data values");
1285 if (empty($data['alt_text']['text'])) {
1286 throw new BadRequestException("No alt text.");
1289 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1291 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1292 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1293 if (!DBA::isResult($photo)) {
1294 throw new BadRequestException("Metadata not found.");
1297 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1300 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1303 * @param string $type Return format (atom, rss, xml, json)
1304 * @param int $item_id
1308 function api_status_show($type, $item_id)
1310 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1314 $item = api_get_item(['id' => $item_id]);
1315 if (!empty($item)) {
1316 $status_info = api_format_item($item, $type);
1319 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1321 return api_format_data('statuses', $type, ['status' => $status_info]);
1325 * Retrieves the last public status of the provided user info
1327 * @param int $ownerId Public contact Id
1328 * @param int $uid User Id
1332 function api_get_last_status($ownerId, $uid)
1335 'author-id'=> $ownerId,
1337 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1341 $item = api_get_item($condition);
1347 * Retrieves a single item record based on the provided condition and converts it for API use.
1349 * @param array $condition Item table condition array
1353 function api_get_item(array $condition)
1355 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1361 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1362 * The author's most recent status will be returned inline.
1364 * @param string $type Return type (atom, rss, xml, json)
1365 * @return array|string
1366 * @throws BadRequestException
1367 * @throws ImagickException
1368 * @throws InternalServerErrorException
1369 * @throws UnauthorizedException
1370 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1372 function api_users_show($type)
1374 $a = Friendica\DI::app();
1376 $user_info = api_get_user($a);
1378 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1379 if (!empty($item)) {
1380 $user_info['status'] = api_format_item($item, $type);
1383 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1384 unset($user_info['uid']);
1385 unset($user_info['self']);
1387 return api_format_data('user', $type, ['user' => $user_info]);
1390 /// @TODO move to top of file or somewhere better
1391 api_register_func('api/users/show', 'api_users_show');
1392 api_register_func('api/externalprofile/show', 'api_users_show');
1395 * Search a public user account.
1397 * @param string $type Return type (atom, rss, xml, json)
1399 * @return array|string
1400 * @throws BadRequestException
1401 * @throws ImagickException
1402 * @throws InternalServerErrorException
1403 * @throws UnauthorizedException
1404 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1406 function api_users_search($type)
1412 if (!empty($_GET['q'])) {
1413 $contacts = Contact::selectToArray(
1416 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1424 if (DBA::isResult($contacts)) {
1426 foreach ($contacts as $contact) {
1427 $user_info = api_get_user($a, $contact['id']);
1429 if ($type == 'xml') {
1430 $userlist[$k++ . ':user'] = $user_info;
1432 $userlist[] = $user_info;
1435 $userlist = ['users' => $userlist];
1437 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1440 throw new BadRequestException('No search term specified.');
1443 return api_format_data('users', $type, $userlist);
1446 /// @TODO move to top of file or somewhere better
1447 api_register_func('api/users/search', 'api_users_search');
1450 * Return user objects
1452 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1454 * @param string $type Return format: json or xml
1456 * @return array|string
1457 * @throws BadRequestException
1458 * @throws ImagickException
1459 * @throws InternalServerErrorException
1460 * @throws NotFoundException if the results are empty.
1461 * @throws UnauthorizedException
1463 function api_users_lookup($type)
1467 if (!empty($_REQUEST['user_id'])) {
1468 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1470 $users[] = api_get_user(DI::app(), $id);
1475 if (empty($users)) {
1476 throw new NotFoundException;
1479 return api_format_data("users", $type, ['users' => $users]);
1482 /// @TODO move to top of file or somewhere better
1483 api_register_func('api/users/lookup', 'api_users_lookup', true);
1486 * Returns statuses that match a specified query.
1488 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1490 * @param string $type Return format: json, xml, atom, rss
1492 * @return array|string
1493 * @throws BadRequestException if the "q" parameter is missing.
1494 * @throws ForbiddenException
1495 * @throws ImagickException
1496 * @throws InternalServerErrorException
1497 * @throws UnauthorizedException
1499 function api_search($type)
1502 $user_info = api_get_user($a);
1504 if (api_user() === false || $user_info === false) {
1505 throw new ForbiddenException();
1508 if (empty($_REQUEST['q'])) {
1509 throw new BadRequestException('q parameter is required.');
1512 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1515 $data['status'] = [];
1517 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1518 if (!empty($_REQUEST['rpp'])) {
1519 $count = $_REQUEST['rpp'];
1520 } elseif (!empty($_REQUEST['count'])) {
1521 $count = $_REQUEST['count'];
1524 $since_id = $_REQUEST['since_id'] ?? 0;
1525 $max_id = $_REQUEST['max_id'] ?? 0;
1526 $page = $_REQUEST['page'] ?? 1;
1528 $start = max(0, ($page - 1) * $count);
1530 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1531 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1532 $searchTerm = $matches[1];
1533 $condition = ["`oid` > ?
1534 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1535 AND `otype` = ? AND `type` = ? AND `term` = ?",
1536 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1538 $condition[0] .= ' AND `oid` <= ?';
1539 $condition[] = $max_id;
1541 $terms = DBA::select('term', ['oid'], $condition, []);
1543 while ($term = DBA::fetch($terms)) {
1544 $itemIds[] = $term['oid'];
1548 if (empty($itemIds)) {
1549 return api_format_data('statuses', $type, $data);
1552 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1553 if ($exclude_replies) {
1554 $preCondition[] = '`id` = `parent`';
1557 $condition = [implode(' AND ', $preCondition)];
1559 $condition = ["`id` > ?
1560 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1561 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1562 AND `body` LIKE CONCAT('%',?,'%')",
1563 $since_id, api_user(), $_REQUEST['q']];
1565 $condition[0] .= ' AND `id` <= ?';
1566 $condition[] = $max_id;
1572 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1573 $id = Item::fetchByLink($searchTerm, api_user());
1576 $id = Item::fetchByLink($searchTerm);
1580 $statuses = Item::select([], ['id' => $id]);
1584 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1586 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1588 bindComments($data['status']);
1590 return api_format_data('statuses', $type, $data);
1593 /// @TODO move to top of file or somewhere better
1594 api_register_func('api/search/tweets', 'api_search', true);
1595 api_register_func('api/search', 'api_search', true);
1598 * Returns the most recent statuses posted by the user and the users they follow.
1600 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1602 * @param string $type Return type (atom, rss, xml, json)
1604 * @return array|string
1605 * @throws BadRequestException
1606 * @throws ForbiddenException
1607 * @throws ImagickException
1608 * @throws InternalServerErrorException
1609 * @throws UnauthorizedException
1610 * @todo Optional parameters
1611 * @todo Add reply info
1613 function api_statuses_home_timeline($type)
1616 $user_info = api_get_user($a);
1618 if (api_user() === false || $user_info === false) {
1619 throw new ForbiddenException();
1622 unset($_REQUEST["user_id"]);
1623 unset($_GET["user_id"]);
1625 unset($_REQUEST["screen_name"]);
1626 unset($_GET["screen_name"]);
1628 // get last network messages
1631 $count = $_REQUEST['count'] ?? 20;
1632 $page = $_REQUEST['page']?? 0;
1633 $since_id = $_REQUEST['since_id'] ?? 0;
1634 $max_id = $_REQUEST['max_id'] ?? 0;
1635 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1636 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1638 $start = max(0, ($page - 1) * $count);
1640 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1641 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1644 $condition[0] .= " AND `item`.`id` <= ?";
1645 $condition[] = $max_id;
1647 if ($exclude_replies) {
1648 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1650 if ($conversation_id > 0) {
1651 $condition[0] .= " AND `item`.`parent` = ?";
1652 $condition[] = $conversation_id;
1655 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1656 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1658 $items = Item::inArray($statuses);
1660 $ret = api_format_items($items, $user_info, false, $type);
1662 // Set all posts from the query above to seen
1664 foreach ($items as $item) {
1665 $idarray[] = intval($item["id"]);
1668 if (!empty($idarray)) {
1669 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1671 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1677 $data = ['status' => $ret];
1682 $data = api_rss_extra($a, $data, $user_info);
1686 return api_format_data("statuses", $type, $data);
1690 /// @TODO move to top of file or somewhere better
1691 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1692 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1695 * Returns the most recent statuses from public users.
1697 * @param string $type Return type (atom, rss, xml, json)
1699 * @return array|string
1700 * @throws BadRequestException
1701 * @throws ForbiddenException
1702 * @throws ImagickException
1703 * @throws InternalServerErrorException
1704 * @throws UnauthorizedException
1706 function api_statuses_public_timeline($type)
1709 $user_info = api_get_user($a);
1711 if (api_user() === false || $user_info === false) {
1712 throw new ForbiddenException();
1715 // get last network messages
1718 $count = $_REQUEST['count'] ?? 20;
1719 $page = $_REQUEST['page'] ?? 1;
1720 $since_id = $_REQUEST['since_id'] ?? 0;
1721 $max_id = $_REQUEST['max_id'] ?? 0;
1722 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1723 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1725 $start = max(0, ($page - 1) * $count);
1727 if ($exclude_replies && !$conversation_id) {
1728 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1729 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1732 $condition[0] .= " AND `thread`.`iid` <= ?";
1733 $condition[] = $max_id;
1736 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1737 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1739 $r = Item::inArray($statuses);
1741 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1742 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1745 $condition[0] .= " AND `item`.`id` <= ?";
1746 $condition[] = $max_id;
1748 if ($conversation_id > 0) {
1749 $condition[0] .= " AND `item`.`parent` = ?";
1750 $condition[] = $conversation_id;
1753 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1754 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1756 $r = Item::inArray($statuses);
1759 $ret = api_format_items($r, $user_info, false, $type);
1763 $data = ['status' => $ret];
1768 $data = api_rss_extra($a, $data, $user_info);
1772 return api_format_data("statuses", $type, $data);
1775 /// @TODO move to top of file or somewhere better
1776 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1779 * Returns the most recent statuses posted by users this node knows about.
1781 * @brief Returns the list of public federated posts this node knows about
1783 * @param string $type Return format: json, xml, atom, rss
1784 * @return array|string
1785 * @throws BadRequestException
1786 * @throws ForbiddenException
1787 * @throws ImagickException
1788 * @throws InternalServerErrorException
1789 * @throws UnauthorizedException
1791 function api_statuses_networkpublic_timeline($type)
1794 $user_info = api_get_user($a);
1796 if (api_user() === false || $user_info === false) {
1797 throw new ForbiddenException();
1800 $since_id = $_REQUEST['since_id'] ?? 0;
1801 $max_id = $_REQUEST['max_id'] ?? 0;
1804 $count = $_REQUEST['count'] ?? 20;
1805 $page = $_REQUEST['page'] ?? 1;
1807 $start = max(0, ($page - 1) * $count);
1809 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1810 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1813 $condition[0] .= " AND `thread`.`iid` <= ?";
1814 $condition[] = $max_id;
1817 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1818 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1820 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1824 $data = ['status' => $ret];
1829 $data = api_rss_extra($a, $data, $user_info);
1833 return api_format_data("statuses", $type, $data);
1836 /// @TODO move to top of file or somewhere better
1837 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1840 * Returns a single status.
1842 * @param string $type Return type (atom, rss, xml, json)
1844 * @return array|string
1845 * @throws BadRequestException
1846 * @throws ForbiddenException
1847 * @throws ImagickException
1848 * @throws InternalServerErrorException
1849 * @throws UnauthorizedException
1850 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1852 function api_statuses_show($type)
1855 $user_info = api_get_user($a);
1857 if (api_user() === false || $user_info === false) {
1858 throw new ForbiddenException();
1862 $id = intval($a->argv[3] ?? 0);
1865 $id = intval($_REQUEST['id'] ?? 0);
1870 $id = intval($a->argv[4] ?? 0);
1873 Logger::log('API: api_statuses_show: ' . $id);
1875 $conversation = !empty($_REQUEST['conversation']);
1877 // try to fetch the item for the local user - or the public item, if there is no local one
1878 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1879 if (!DBA::isResult($uri_item)) {
1880 throw new BadRequestException("There is no status with this id.");
1883 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1884 if (!DBA::isResult($item)) {
1885 throw new BadRequestException("There is no status with this id.");
1890 if ($conversation) {
1891 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1892 $params = ['order' => ['id' => true]];
1894 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1898 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1900 /// @TODO How about copying this to above methods which don't check $r ?
1901 if (!DBA::isResult($statuses)) {
1902 throw new BadRequestException("There is no status with this id.");
1905 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1907 if ($conversation) {
1908 $data = ['status' => $ret];
1909 return api_format_data("statuses", $type, $data);
1911 $data = ['status' => $ret[0]];
1912 return api_format_data("status", $type, $data);
1916 /// @TODO move to top of file or somewhere better
1917 api_register_func('api/statuses/show', 'api_statuses_show', true);
1921 * @param string $type Return type (atom, rss, xml, json)
1923 * @return array|string
1924 * @throws BadRequestException
1925 * @throws ForbiddenException
1926 * @throws ImagickException
1927 * @throws InternalServerErrorException
1928 * @throws UnauthorizedException
1929 * @todo nothing to say?
1931 function api_conversation_show($type)
1934 $user_info = api_get_user($a);
1936 if (api_user() === false || $user_info === false) {
1937 throw new ForbiddenException();
1941 $id = intval($a->argv[3] ?? 0);
1942 $since_id = intval($_REQUEST['since_id'] ?? 0);
1943 $max_id = intval($_REQUEST['max_id'] ?? 0);
1944 $count = intval($_REQUEST['count'] ?? 20);
1945 $page = intval($_REQUEST['page'] ?? 1);
1947 $start = max(0, ($page - 1) * $count);
1950 $id = intval($_REQUEST['id'] ?? 0);
1955 $id = intval($a->argv[4] ?? 0);
1958 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1960 // try to fetch the item for the local user - or the public item, if there is no local one
1961 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1962 if (!DBA::isResult($item)) {
1963 throw new BadRequestException("There is no status with this id.");
1966 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1967 if (!DBA::isResult($parent)) {
1968 throw new BadRequestException("There is no status with this id.");
1971 $id = $parent['id'];
1973 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1974 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1977 $condition[0] .= " AND `item`.`id` <= ?";
1978 $condition[] = $max_id;
1981 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1982 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1984 if (!DBA::isResult($statuses)) {
1985 throw new BadRequestException("There is no status with id $id.");
1988 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1990 $data = ['status' => $ret];
1991 return api_format_data("statuses", $type, $data);
1994 /// @TODO move to top of file or somewhere better
1995 api_register_func('api/conversation/show', 'api_conversation_show', true);
1996 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2001 * @param string $type Return type (atom, rss, xml, json)
2003 * @return array|string
2004 * @throws BadRequestException
2005 * @throws ForbiddenException
2006 * @throws ImagickException
2007 * @throws InternalServerErrorException
2008 * @throws UnauthorizedException
2009 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2011 function api_statuses_repeat($type)
2017 if (api_user() === false) {
2018 throw new ForbiddenException();
2024 $id = intval($a->argv[3] ?? 0);
2027 $id = intval($_REQUEST['id'] ?? 0);
2032 $id = intval($a->argv[4] ?? 0);
2035 Logger::log('API: api_statuses_repeat: '.$id);
2037 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2038 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2040 if (DBA::isResult($item) && $item['body'] != "") {
2041 if (strpos($item['body'], "[/share]") !== false) {
2042 $pos = strpos($item['body'], "[share");
2043 $post = substr($item['body'], $pos);
2045 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2047 if (!empty($item['title'])) {
2048 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2051 $post .= $item['body'];
2052 $post .= "[/share]";
2054 $_REQUEST['body'] = $post;
2055 $_REQUEST['tag'] = $item['tag'];
2056 $_REQUEST['attach'] = $item['attach'];
2057 $_REQUEST['profile_uid'] = api_user();
2058 $_REQUEST['api_source'] = true;
2060 if (empty($_REQUEST['source'])) {
2061 $_REQUEST["source"] = api_source();
2064 $item_id = item_post($a);
2066 throw new ForbiddenException();
2069 // output the post that we just posted.
2071 return api_status_show($type, $item_id);
2074 /// @TODO move to top of file or somewhere better
2075 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2078 * Destroys a specific status.
2080 * @param string $type Return type (atom, rss, xml, json)
2082 * @return array|string
2083 * @throws BadRequestException
2084 * @throws ForbiddenException
2085 * @throws ImagickException
2086 * @throws InternalServerErrorException
2087 * @throws UnauthorizedException
2088 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2090 function api_statuses_destroy($type)
2094 if (api_user() === false) {
2095 throw new ForbiddenException();
2101 $id = intval($a->argv[3] ?? 0);
2104 $id = intval($_REQUEST['id'] ?? 0);
2109 $id = intval($a->argv[4] ?? 0);
2112 Logger::log('API: api_statuses_destroy: '.$id);
2114 $ret = api_statuses_show($type);
2116 Item::deleteForUser(['id' => $id], api_user());
2121 /// @TODO move to top of file or somewhere better
2122 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2125 * Returns the most recent mentions.
2127 * @param string $type Return type (atom, rss, xml, json)
2129 * @return array|string
2130 * @throws BadRequestException
2131 * @throws ForbiddenException
2132 * @throws ImagickException
2133 * @throws InternalServerErrorException
2134 * @throws UnauthorizedException
2135 * @see http://developer.twitter.com/doc/get/statuses/mentions
2137 function api_statuses_mentions($type)
2140 $user_info = api_get_user($a);
2142 if (api_user() === false || $user_info === false) {
2143 throw new ForbiddenException();
2146 unset($_REQUEST["user_id"]);
2147 unset($_GET["user_id"]);
2149 unset($_REQUEST["screen_name"]);
2150 unset($_GET["screen_name"]);
2152 // get last network messages
2155 $since_id = $_REQUEST['since_id'] ?? 0;
2156 $max_id = $_REQUEST['max_id'] ?? 0;
2157 $count = $_REQUEST['count'] ?? 20;
2158 $page = $_REQUEST['page'] ?? 1;
2160 $start = max(0, ($page - 1) * $count);
2162 $query = "SELECT `item`.`id` FROM `user-item`
2163 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2164 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2165 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2166 AND `user-item`.`iid` > ?";
2167 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2168 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2169 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT,
2173 $query .= " AND `item`.`id` <= ?";
2174 $condition[] = $max_id;
2177 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2178 $condition[] = $start;
2179 $condition[] = $count;
2181 $useritems = DBA::p($query, $condition);
2183 while ($useritem = DBA::fetch($useritems)) {
2184 $itemids[] = $useritem['id'];
2186 DBA::close($useritems);
2188 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2189 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2191 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2193 $data = ['status' => $ret];
2198 $data = api_rss_extra($a, $data, $user_info);
2202 return api_format_data("statuses", $type, $data);
2205 /// @TODO move to top of file or somewhere better
2206 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2207 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2210 * Returns the most recent statuses posted by the user.
2212 * @brief Returns a user's public timeline
2214 * @param string $type Either "json" or "xml"
2215 * @return string|array
2216 * @throws BadRequestException
2217 * @throws ForbiddenException
2218 * @throws ImagickException
2219 * @throws InternalServerErrorException
2220 * @throws UnauthorizedException
2221 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2223 function api_statuses_user_timeline($type)
2226 $user_info = api_get_user($a);
2228 if (api_user() === false || $user_info === false) {
2229 throw new ForbiddenException();
2233 "api_statuses_user_timeline: api_user: ". api_user() .
2234 "\nuser_info: ".print_r($user_info, true) .
2235 "\n_REQUEST: ".print_r($_REQUEST, true),
2239 $since_id = $_REQUEST['since_id'] ?? 0;
2240 $max_id = $_REQUEST['max_id'] ?? 0;
2241 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2242 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2245 $count = $_REQUEST['count'] ?? 20;
2246 $page = $_REQUEST['page'] ?? 1;
2248 $start = max(0, ($page - 1) * $count);
2250 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2251 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2253 if ($user_info['self'] == 1) {
2254 $condition[0] .= ' AND `item`.`wall` ';
2257 if ($exclude_replies) {
2258 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2261 if ($conversation_id > 0) {
2262 $condition[0] .= " AND `item`.`parent` = ?";
2263 $condition[] = $conversation_id;
2267 $condition[0] .= " AND `item`.`id` <= ?";
2268 $condition[] = $max_id;
2271 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2272 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2274 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2278 $data = ['status' => $ret];
2283 $data = api_rss_extra($a, $data, $user_info);
2287 return api_format_data("statuses", $type, $data);
2290 /// @TODO move to top of file or somewhere better
2291 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2294 * Star/unstar an item.
2295 * param: id : id of the item
2297 * @param string $type Return type (atom, rss, xml, json)
2299 * @return array|string
2300 * @throws BadRequestException
2301 * @throws ForbiddenException
2302 * @throws ImagickException
2303 * @throws InternalServerErrorException
2304 * @throws UnauthorizedException
2305 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2307 function api_favorites_create_destroy($type)
2311 if (api_user() === false) {
2312 throw new ForbiddenException();
2315 // for versioned api.
2316 /// @TODO We need a better global soluton
2317 $action_argv_id = 2;
2318 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2319 $action_argv_id = 3;
2322 if ($a->argc <= $action_argv_id) {
2323 throw new BadRequestException("Invalid request.");
2325 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2326 if ($a->argc == $action_argv_id + 2) {
2327 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2329 $itemid = intval($_REQUEST['id'] ?? 0);
2332 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2334 if (!DBA::isResult($item)) {
2335 throw new BadRequestException("Invalid item.");
2340 $item['starred'] = 1;
2343 $item['starred'] = 0;
2346 throw new BadRequestException("Invalid action ".$action);
2349 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2352 throw new InternalServerErrorException("DB error");
2356 $user_info = api_get_user($a);
2357 $rets = api_format_items([$item], $user_info, false, $type);
2360 $data = ['status' => $ret];
2365 $data = api_rss_extra($a, $data, $user_info);
2369 return api_format_data("status", $type, $data);
2372 /// @TODO move to top of file or somewhere better
2373 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2374 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2377 * Returns the most recent favorite statuses.
2379 * @param string $type Return type (atom, rss, xml, json)
2381 * @return string|array
2382 * @throws BadRequestException
2383 * @throws ForbiddenException
2384 * @throws ImagickException
2385 * @throws InternalServerErrorException
2386 * @throws UnauthorizedException
2388 function api_favorites($type)
2393 $user_info = api_get_user($a);
2395 if (api_user() === false || $user_info === false) {
2396 throw new ForbiddenException();
2401 // in friendica starred item are private
2402 // return favorites only for self
2403 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2405 if ($user_info['self'] == 0) {
2409 $since_id = $_REQUEST['since_id'] ?? 0;
2410 $max_id = $_REQUEST['max_id'] ?? 0;
2411 $count = $_GET['count'] ?? 20;
2412 $page = $_REQUEST['page'] ?? 1;
2414 $start = max(0, ($page - 1) * $count);
2416 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2417 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2419 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2422 $condition[0] .= " AND `item`.`id` <= ?";
2423 $condition[] = $max_id;
2426 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2428 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2433 $data = ['status' => $ret];
2438 $data = api_rss_extra($a, $data, $user_info);
2442 return api_format_data("statuses", $type, $data);
2445 /// @TODO move to top of file or somewhere better
2446 api_register_func('api/favorites', 'api_favorites', true);
2450 * @param array $item
2451 * @param array $recipient
2452 * @param array $sender
2455 * @throws InternalServerErrorException
2457 function api_format_messages($item, $recipient, $sender)
2459 // standard meta information
2461 'id' => $item['id'],
2462 'sender_id' => $sender['id'],
2464 'recipient_id' => $recipient['id'],
2465 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2466 'sender_screen_name' => $sender['screen_name'],
2467 'recipient_screen_name' => $recipient['screen_name'],
2468 'sender' => $sender,
2469 'recipient' => $recipient,
2471 'friendica_seen' => $item['seen'] ?? 0,
2472 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2475 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2476 if (isset($ret['sender']['uid'])) {
2477 unset($ret['sender']['uid']);
2479 if (isset($ret['sender']['self'])) {
2480 unset($ret['sender']['self']);
2482 if (isset($ret['recipient']['uid'])) {
2483 unset($ret['recipient']['uid']);
2485 if (isset($ret['recipient']['self'])) {
2486 unset($ret['recipient']['self']);
2489 //don't send title to regular StatusNET requests to avoid confusing these apps
2490 if (!empty($_GET['getText'])) {
2491 $ret['title'] = $item['title'];
2492 if ($_GET['getText'] == 'html') {
2493 $ret['text'] = BBCode::convert($item['body'], false);
2494 } elseif ($_GET['getText'] == 'plain') {
2495 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2498 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2500 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2501 unset($ret['sender']);
2502 unset($ret['recipient']);
2510 * @param array $item
2513 * @throws InternalServerErrorException
2515 function api_convert_item($item)
2517 $body = $item['body'];
2518 $entities = api_get_entitities($statustext, $body);
2520 // Add pictures to the attachment array and remove them from the body
2521 $attachments = api_get_attachments($body);
2523 // Workaround for ostatus messages where the title is identically to the body
2524 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2525 $statusbody = trim(HTML::toPlaintext($html, 0));
2527 // handle data: images
2528 $statusbody = api_format_items_embeded_images($item, $statusbody);
2530 $statustitle = trim($item['title']);
2532 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2533 $statustext = trim($statusbody);
2535 $statustext = trim($statustitle."\n\n".$statusbody);
2538 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2539 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2542 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2544 // Workaround for clients with limited HTML parser functionality
2545 $search = ["<br>", "<blockquote>", "</blockquote>",
2546 "<h1>", "</h1>", "<h2>", "</h2>",
2547 "<h3>", "</h3>", "<h4>", "</h4>",
2548 "<h5>", "</h5>", "<h6>", "</h6>"];
2549 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2550 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2551 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2552 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2553 $statushtml = str_replace($search, $replace, $statushtml);
2555 if ($item['title'] != "") {
2556 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2560 $oldtext = $statushtml;
2561 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2562 } while ($oldtext != $statushtml);
2564 if (substr($statushtml, 0, 4) == '<br>') {
2565 $statushtml = substr($statushtml, 4);
2568 if (substr($statushtml, 0, -4) == '<br>') {
2569 $statushtml = substr($statushtml, -4);
2572 // feeds without body should contain the link
2573 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2574 $statushtml .= BBCode::convert($item['plink']);
2578 "text" => $statustext,
2579 "html" => $statushtml,
2580 "attachments" => $attachments,
2581 "entities" => $entities
2587 * @param string $body
2590 * @throws InternalServerErrorException
2592 function api_get_attachments(&$body)
2594 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2595 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2597 $URLSearchString = "^\[\]";
2598 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2602 // Remove all embedded pictures, since they are added as attachments
2603 foreach ($images[0] as $orig) {
2604 $body = str_replace($orig, '', $body);
2609 foreach ($images[1] as $image) {
2610 $imagedata = Images::getInfoFromURLCached($image);
2613 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2617 return $attachments;
2622 * @param string $text
2623 * @param string $bbcode
2626 * @throws InternalServerErrorException
2627 * @todo Links at the first character of the post
2629 function api_get_entitities(&$text, $bbcode)
2631 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2633 if ($include_entities != "true") {
2634 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2636 foreach ($images[1] as $image) {
2637 $replace = ProxyUtils::proxifyUrl($image);
2638 $text = str_replace($image, $replace, $text);
2643 $bbcode = BBCode::cleanPictureLinks($bbcode);
2645 // Change pure links in text to bbcode uris
2646 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2649 $entities["hashtags"] = [];
2650 $entities["symbols"] = [];
2651 $entities["urls"] = [];
2652 $entities["user_mentions"] = [];
2654 $URLSearchString = "^\[\]";
2656 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2658 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2659 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2661 $bbcode = preg_replace(
2662 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2663 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2666 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2668 $bbcode = preg_replace(
2669 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2670 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2673 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2675 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2677 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2680 foreach ($urls[1] as $id => $url) {
2681 $start = iconv_strpos($text, $url, 0, "UTF-8");
2682 if (!($start === false)) {
2683 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2687 ksort($ordered_urls);
2691 foreach ($ordered_urls as $url) {
2692 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2693 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2695 $display_url = $url["title"];
2697 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2698 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2700 if (strlen($display_url) > 26) {
2701 $display_url = substr($display_url, 0, 25)."…";
2705 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2706 if (!($start === false)) {
2707 $entities["urls"][] = ["url" => $url["url"],
2708 "expanded_url" => $url["url"],
2709 "display_url" => $display_url,
2710 "indices" => [$start, $start+strlen($url["url"])]];
2711 $offset = $start + 1;
2715 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2716 $ordered_images = [];
2717 foreach ($images as $image) {
2718 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2719 if (!($start === false)) {
2720 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2724 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2725 foreach ($images[1] as $image) {
2726 $start = iconv_strpos($text, $image, 0, "UTF-8");
2727 if (!($start === false)) {
2728 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2734 foreach ($ordered_images as $image) {
2735 $url = $image['url'];
2736 $ext_alt_text = $image['alt'];
2738 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2739 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2741 if (strlen($display_url) > 26) {
2742 $display_url = substr($display_url, 0, 25)."…";
2745 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2746 if (!($start === false)) {
2747 $image = Images::getInfoFromURLCached($url);
2749 // If image cache is activated, then use the following sizes:
2750 // thumb (150), small (340), medium (600) and large (1024)
2751 if (!Config::get("system", "proxy_disabled")) {
2752 $media_url = ProxyUtils::proxifyUrl($url);
2755 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2756 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2758 if (($image[0] > 150) || ($image[1] > 150)) {
2759 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2760 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2763 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2764 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2766 if (($image[0] > 600) || ($image[1] > 600)) {
2767 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2768 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2772 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2775 $entities["media"][] = [
2777 "id_str" => (string) ($start + 1),
2778 "indices" => [$start, $start+strlen($url)],
2779 "media_url" => Strings::normaliseLink($media_url),
2780 "media_url_https" => $media_url,
2782 "display_url" => $display_url,
2783 "expanded_url" => $url,
2784 "ext_alt_text" => $ext_alt_text,
2788 $offset = $start + 1;
2797 * @param array $item
2798 * @param string $text
2802 function api_format_items_embeded_images($item, $text)
2804 $text = preg_replace_callback(
2805 '|data:image/([^;]+)[^=]+=*|m',
2806 function () use ($item) {
2807 return DI::baseUrl() . '/display/' . $item['guid'];
2815 * @brief return <a href='url'>name</a> as array
2817 * @param string $txt text
2822 function api_contactlink_to_array($txt)
2825 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2826 if ($r && count($match)==3) {
2828 'name' => $match[2],
2842 * @brief return likes, dislikes and attend status for item
2844 * @param array $item array
2845 * @param string $type Return type (atom, rss, xml, json)
2848 * likes => int count,
2849 * dislikes => int count
2850 * @throws BadRequestException
2851 * @throws ImagickException
2852 * @throws InternalServerErrorException
2853 * @throws UnauthorizedException
2855 function api_format_items_activities($item, $type = "json")
2864 'attendmaybe' => [],
2868 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2869 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2871 while ($parent_item = Item::fetch($ret)) {
2872 // not used as result should be structured like other user data
2873 //builtin_activity_puller($i, $activities);
2875 // get user data and add it to the array of the activity
2876 $user = api_get_user($a, $parent_item['author-id']);
2877 switch ($parent_item['verb']) {
2878 case Activity::LIKE:
2879 $activities['like'][] = $user;
2881 case Activity::DISLIKE:
2882 $activities['dislike'][] = $user;
2884 case Activity::ATTEND:
2885 $activities['attendyes'][] = $user;
2887 case Activity::ATTENDNO:
2888 $activities['attendno'][] = $user;
2890 case Activity::ATTENDMAYBE:
2891 $activities['attendmaybe'][] = $user;
2893 case Activity::ANNOUNCE:
2894 $activities['announce'][] = $user;
2903 if ($type == "xml") {
2904 $xml_activities = [];
2905 foreach ($activities as $k => $v) {
2906 // change xml element from "like" to "friendica:like"
2907 $xml_activities["friendica:".$k] = $v;
2908 // add user data into xml output
2910 foreach ($v as $user) {
2911 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2914 $activities = $xml_activities;
2922 * @brief return data from profiles
2924 * @param array $profile_row array containing data from db table 'profile'
2926 * @throws InternalServerErrorException
2928 function api_format_items_profiles($profile_row)
2931 'profile_id' => $profile_row['id'],
2932 'profile_name' => $profile_row['profile-name'],
2933 'is_default' => $profile_row['is-default'] ? true : false,
2934 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2935 'profile_photo' => $profile_row['photo'],
2936 'profile_thumb' => $profile_row['thumb'],
2937 'publish' => $profile_row['publish'] ? true : false,
2938 'net_publish' => $profile_row['net-publish'] ? true : false,
2939 'description' => $profile_row['pdesc'],
2940 'date_of_birth' => $profile_row['dob'],
2941 'address' => $profile_row['address'],
2942 'city' => $profile_row['locality'],
2943 'region' => $profile_row['region'],
2944 'postal_code' => $profile_row['postal-code'],
2945 'country' => $profile_row['country-name'],
2946 'hometown' => $profile_row['hometown'],
2947 'gender' => $profile_row['gender'],
2948 'marital' => $profile_row['marital'],
2949 'marital_with' => $profile_row['with'],
2950 'marital_since' => $profile_row['howlong'],
2951 'sexual' => $profile_row['sexual'],
2952 'politic' => $profile_row['politic'],
2953 'religion' => $profile_row['religion'],
2954 'public_keywords' => $profile_row['pub_keywords'],
2955 'private_keywords' => $profile_row['prv_keywords'],
2956 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2957 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2958 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2959 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2960 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2961 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2962 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2963 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2964 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2965 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2966 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2967 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2968 'homepage' => $profile_row['homepage'],
2975 * @brief format items to be returned by api
2977 * @param array $items array of items
2978 * @param array $user_info
2979 * @param bool $filter_user filter items by $user_info
2980 * @param string $type Return type (atom, rss, xml, json)
2982 * @throws BadRequestException
2983 * @throws ImagickException
2984 * @throws InternalServerErrorException
2985 * @throws UnauthorizedException
2987 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2989 $a = Friendica\DI::app();
2993 foreach ((array)$items as $item) {
2994 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2996 // Look if the posts are matching if they should be filtered by user id
2997 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3001 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3010 * @param array $item Item record
3011 * @param string $type Return format (atom, rss, xml, json)
3012 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3013 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3014 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3015 * @return array API-formatted status
3016 * @throws BadRequestException
3017 * @throws ImagickException
3018 * @throws InternalServerErrorException
3019 * @throws UnauthorizedException
3021 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3023 $a = Friendica\DI::app();
3025 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3026 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3029 localize_item($item);
3031 $in_reply_to = api_in_reply_to($item);
3033 $converted = api_convert_item($item);
3035 if ($type == "xml") {
3036 $geo = "georss:point";
3042 'text' => $converted["text"],
3043 'truncated' => false,
3044 'created_at'=> api_date($item['created']),
3045 'in_reply_to_status_id' => $in_reply_to['status_id'],
3046 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3047 'source' => (($item['app']) ? $item['app'] : 'web'),
3048 'id' => intval($item['id']),
3049 'id_str' => (string) intval($item['id']),
3050 'in_reply_to_user_id' => $in_reply_to['user_id'],
3051 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3052 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3054 'favorited' => $item['starred'] ? true : false,
3055 'user' => $status_user,
3056 'friendica_author' => $author_user,
3057 'friendica_owner' => $owner_user,
3058 'friendica_private' => $item['private'] == 1,
3059 //'entities' => NULL,
3060 'statusnet_html' => $converted["html"],
3061 'statusnet_conversation_id' => $item['parent'],
3062 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3063 'friendica_activities' => api_format_items_activities($item, $type),
3064 'friendica_title' => $item['title'],
3065 'friendica_html' => BBCode::convert($item['body'], false)
3068 if (count($converted["attachments"]) > 0) {
3069 $status["attachments"] = $converted["attachments"];
3072 if (count($converted["entities"]) > 0) {
3073 $status["entities"] = $converted["entities"];
3076 if ($status["source"] == 'web') {
3077 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3078 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3079 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3082 $retweeted_item = [];
3085 if ($item["id"] == $item["parent"]) {
3086 $body = $item['body'];
3087 $retweeted_item = api_share_as_retweet($item);
3088 if ($body != $item['body']) {
3089 $quoted_item = $retweeted_item;
3090 $retweeted_item = [];
3094 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3095 $announce = api_get_announce($item);
3096 if (!empty($announce)) {
3097 $retweeted_item = $item;
3099 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3103 if (!empty($quoted_item)) {
3104 if ($quoted_item['id'] != $item['id']) {
3105 $quoted_status = api_format_item($quoted_item);
3106 /// @todo Only remove the attachments that are also contained in the quotes status
3107 unset($status['attachments']);
3108 unset($status['entities']);
3110 $conv_quoted = api_convert_item($quoted_item);
3111 $quoted_status = $status;
3112 unset($quoted_status['attachments']);
3113 unset($quoted_status['entities']);
3114 unset($quoted_status['statusnet_conversation_id']);
3115 $quoted_status['text'] = $conv_quoted['text'];
3116 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3118 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3119 } catch (BadRequestException $e) {
3120 // user not found. should be found?
3121 /// @todo check if the user should be always found
3122 $quoted_status["user"] = [];
3125 unset($quoted_status['friendica_author']);
3126 unset($quoted_status['friendica_owner']);
3127 unset($quoted_status['friendica_activities']);
3128 unset($quoted_status['friendica_private']);
3131 if (!empty($retweeted_item)) {
3132 $retweeted_status = $status;
3133 unset($retweeted_status['friendica_author']);
3134 unset($retweeted_status['friendica_owner']);
3135 unset($retweeted_status['friendica_activities']);
3136 unset($retweeted_status['friendica_private']);
3137 unset($retweeted_status['statusnet_conversation_id']);
3138 $status['user'] = $status['friendica_owner'];
3140 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3141 } catch (BadRequestException $e) {
3142 // user not found. should be found?
3143 /// @todo check if the user should be always found
3144 $retweeted_status["user"] = [];
3147 $rt_converted = api_convert_item($retweeted_item);
3149 $retweeted_status['text'] = $rt_converted["text"];
3150 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3151 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3153 if (!empty($quoted_status)) {
3154 $retweeted_status['quoted_status'] = $quoted_status;
3157 $status['friendica_author'] = $retweeted_status['user'];
3158 $status['retweeted_status'] = $retweeted_status;
3159 } elseif (!empty($quoted_status)) {
3160 $root_status = api_convert_item($item);
3162 $status['text'] = $root_status["text"];
3163 $status['statusnet_html'] = $root_status["html"];
3164 $status['quoted_status'] = $quoted_status;
3167 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3168 unset($status["user"]["uid"]);
3169 unset($status["user"]["self"]);
3171 if ($item["coord"] != "") {
3172 $coords = explode(' ', $item["coord"]);
3173 if (count($coords) == 2) {
3174 if ($type == "json") {
3175 $status["geo"] = ['type' => 'Point',
3176 'coordinates' => [(float) $coords[0],
3177 (float) $coords[1]]];
3178 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3179 $status["georss:point"] = $item["coord"];
3188 * Returns the remaining number of API requests available to the user before the API limit is reached.
3190 * @param string $type Return type (atom, rss, xml, json)
3192 * @return array|string
3195 function api_account_rate_limit_status($type)
3197 if ($type == "xml") {
3199 'remaining-hits' => '150',
3200 '@attributes' => ["type" => "integer"],
3201 'hourly-limit' => '150',
3202 '@attributes2' => ["type" => "integer"],
3203 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3204 '@attributes3' => ["type" => "datetime"],
3205 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3206 '@attributes4' => ["type" => "integer"],
3210 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3211 'remaining_hits' => '150',
3212 'hourly_limit' => '150',
3213 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3217 return api_format_data('hash', $type, ['hash' => $hash]);
3220 /// @TODO move to top of file or somewhere better
3221 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3224 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3226 * @param string $type Return type (atom, rss, xml, json)
3228 * @return array|string
3230 function api_help_test($type)
3232 if ($type == 'xml') {
3238 return api_format_data('ok', $type, ["ok" => $ok]);
3241 /// @TODO move to top of file or somewhere better
3242 api_register_func('api/help/test', 'api_help_test', false);
3245 * Returns all lists the user subscribes to.
3247 * @param string $type Return type (atom, rss, xml, json)
3249 * @return array|string
3250 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3252 function api_lists_list($type)
3255 /// @TODO $ret is not filled here?
3256 return api_format_data('lists', $type, ["lists_list" => $ret]);
3259 /// @TODO move to top of file or somewhere better
3260 api_register_func('api/lists/list', 'api_lists_list', true);
3261 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3264 * Returns all groups the user owns.
3266 * @param string $type Return type (atom, rss, xml, json)
3268 * @return array|string
3269 * @throws BadRequestException
3270 * @throws ForbiddenException
3271 * @throws ImagickException
3272 * @throws InternalServerErrorException
3273 * @throws UnauthorizedException
3274 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3276 function api_lists_ownerships($type)
3280 if (api_user() === false) {
3281 throw new ForbiddenException();
3285 $user_info = api_get_user($a);
3286 $uid = $user_info['uid'];
3288 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3290 // loop through all groups
3292 foreach ($groups as $group) {
3293 if ($group['visible']) {
3299 'name' => $group['name'],
3300 'id' => intval($group['id']),
3301 'id_str' => (string) $group['id'],
3302 'user' => $user_info,
3306 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3309 /// @TODO move to top of file or somewhere better
3310 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3313 * Returns recent statuses from users in the specified group.
3315 * @param string $type Return type (atom, rss, xml, json)
3317 * @return array|string
3318 * @throws BadRequestException
3319 * @throws ForbiddenException
3320 * @throws ImagickException
3321 * @throws InternalServerErrorException
3322 * @throws UnauthorizedException
3323 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3325 function api_lists_statuses($type)
3329 $user_info = api_get_user($a);
3330 if (api_user() === false || $user_info === false) {
3331 throw new ForbiddenException();
3334 unset($_REQUEST["user_id"]);
3335 unset($_GET["user_id"]);
3337 unset($_REQUEST["screen_name"]);
3338 unset($_GET["screen_name"]);
3340 if (empty($_REQUEST['list_id'])) {
3341 throw new BadRequestException('list_id not specified');
3345 $count = $_REQUEST['count'] ?? 20;
3346 $page = $_REQUEST['page'] ?? 1;
3347 $since_id = $_REQUEST['since_id'] ?? 0;
3348 $max_id = $_REQUEST['max_id'] ?? 0;
3349 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3350 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3352 $start = max(0, ($page - 1) * $count);
3354 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3355 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3358 $condition[0] .= " AND `item`.`id` <= ?";
3359 $condition[] = $max_id;
3361 if ($exclude_replies > 0) {
3362 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3364 if ($conversation_id > 0) {
3365 $condition[0] .= " AND `item`.`parent` = ?";
3366 $condition[] = $conversation_id;
3369 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3370 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3372 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3374 $data = ['status' => $items];
3379 $data = api_rss_extra($a, $data, $user_info);
3383 return api_format_data("statuses", $type, $data);
3386 /// @TODO move to top of file or somewhere better
3387 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3390 * Considers friends and followers lists to be private and won't return
3391 * anything if any user_id parameter is passed.
3393 * @brief Returns either the friends of the follower list
3395 * @param string $qtype Either "friends" or "followers"
3396 * @return boolean|array
3397 * @throws BadRequestException
3398 * @throws ForbiddenException
3399 * @throws ImagickException
3400 * @throws InternalServerErrorException
3401 * @throws UnauthorizedException
3403 function api_statuses_f($qtype)
3407 if (api_user() === false) {
3408 throw new ForbiddenException();
3412 $count = $_GET['count'] ?? 20;
3413 $page = $_GET['page'] ?? 1;
3415 $start = max(0, ($page - 1) * $count);
3417 $user_info = api_get_user($a);
3419 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3420 /* this is to stop Hotot to load friends multiple times
3421 * I'm not sure if I'm missing return something or
3422 * is a bug in hotot. Workaround, meantime
3426 return array('$users' => $ret);*/
3431 if ($qtype == 'friends') {
3432 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3433 } elseif ($qtype == 'followers') {
3434 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3437 // friends and followers only for self
3438 if ($user_info['self'] == 0) {
3439 $sql_extra = " AND false ";
3442 if ($qtype == 'blocks') {
3443 $sql_filter = 'AND `blocked` AND NOT `pending`';
3444 } elseif ($qtype == 'incoming') {
3445 $sql_filter = 'AND `pending`';
3447 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3465 foreach ($r as $cid) {
3466 $user = api_get_user($a, $cid['nurl']);
3467 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3468 unset($user["uid"]);
3469 unset($user["self"]);
3476 return ['user' => $ret];
3481 * Returns the user's friends.
3483 * @brief Returns the list of friends of the provided user
3485 * @deprecated By Twitter API in favor of friends/list
3487 * @param string $type Either "json" or "xml"
3488 * @return boolean|string|array
3489 * @throws BadRequestException
3490 * @throws ForbiddenException
3492 function api_statuses_friends($type)
3494 $data = api_statuses_f("friends");
3495 if ($data === false) {
3498 return api_format_data("users", $type, $data);
3502 * Returns the user's followers.
3504 * @brief Returns the list of followers of the provided user
3506 * @deprecated By Twitter API in favor of friends/list
3508 * @param string $type Either "json" or "xml"
3509 * @return boolean|string|array
3510 * @throws BadRequestException
3511 * @throws ForbiddenException
3513 function api_statuses_followers($type)
3515 $data = api_statuses_f("followers");
3516 if ($data === false) {
3519 return api_format_data("users", $type, $data);
3522 /// @TODO move to top of file or somewhere better
3523 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3524 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3527 * Returns the list of blocked users
3529 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3531 * @param string $type Either "json" or "xml"
3533 * @return boolean|string|array
3534 * @throws BadRequestException
3535 * @throws ForbiddenException
3537 function api_blocks_list($type)
3539 $data = api_statuses_f('blocks');
3540 if ($data === false) {
3543 return api_format_data("users", $type, $data);
3546 /// @TODO move to top of file or somewhere better
3547 api_register_func('api/blocks/list', 'api_blocks_list', true);
3550 * Returns the list of pending users IDs
3552 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3554 * @param string $type Either "json" or "xml"
3556 * @return boolean|string|array
3557 * @throws BadRequestException
3558 * @throws ForbiddenException
3560 function api_friendships_incoming($type)
3562 $data = api_statuses_f('incoming');
3563 if ($data === false) {
3568 foreach ($data['user'] as $user) {
3569 $ids[] = $user['id'];
3572 return api_format_data("ids", $type, ['id' => $ids]);
3575 /// @TODO move to top of file or somewhere better
3576 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3579 * Returns the instance's configuration information.
3581 * @param string $type Return type (atom, rss, xml, json)
3583 * @return array|string
3584 * @throws InternalServerErrorException
3586 function api_statusnet_config($type)
3588 $name = Config::get('config', 'sitename');
3589 $server = DI::baseUrl()->getHostname();
3590 $logo = DI::baseUrl() . '/images/friendica-64.png';
3591 $email = Config::get('config', 'admin_email');
3592 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3593 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3594 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3595 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3596 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3599 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3600 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3601 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3602 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3603 'shorturllength' => '30',
3605 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3606 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3607 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3608 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3613 return api_format_data('config', $type, ['config' => $config]);
3616 /// @TODO move to top of file or somewhere better
3617 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3618 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3622 * @param string $type Return type (atom, rss, xml, json)
3624 * @return array|string
3626 function api_statusnet_version($type)
3629 $fake_statusnet_version = "0.9.7";
3631 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3634 /// @TODO move to top of file or somewhere better
3635 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3636 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3640 * @param string $type Return type (atom, rss, xml, json)
3642 * @param int $rel A contact relationship constant
3643 * @return array|string|void
3644 * @throws BadRequestException
3645 * @throws ForbiddenException
3646 * @throws ImagickException
3647 * @throws InternalServerErrorException
3648 * @throws UnauthorizedException
3649 * @todo use api_format_data() to return data
3651 function api_ff_ids($type, int $rel)
3654 throw new ForbiddenException();
3661 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3663 $contacts = DBA::p("SELECT `pcontact`.`id`
3665 INNER JOIN `contact` AS `pcontact`
3666 ON `contact`.`nurl` = `pcontact`.`nurl`
3667 AND `pcontact`.`uid` = 0
3668 WHERE `contact`.`uid` = ?
3669 AND NOT `contact`.`self`
3670 AND `contact`.`rel` IN (?, ?)",
3677 foreach (DBA::toArray($contacts) as $contact) {
3678 if ($stringify_ids) {
3679 $ids[] = $contact['id'];
3681 $ids[] = intval($contact['id']);
3685 return api_format_data('ids', $type, ['id' => $ids]);
3689 * Returns the ID of every user the user is following.
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-friends-ids
3701 function api_friends_ids($type)
3703 return api_ff_ids($type, Contact::SHARING);
3707 * Returns the ID of every user following the user.
3709 * @param string $type Return type (atom, rss, xml, json)
3711 * @return array|string
3712 * @throws BadRequestException
3713 * @throws ForbiddenException
3714 * @throws ImagickException
3715 * @throws InternalServerErrorException
3716 * @throws UnauthorizedException
3717 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3719 function api_followers_ids($type)
3721 return api_ff_ids($type, Contact::FOLLOWER);
3724 /// @TODO move to top of file or somewhere better
3725 api_register_func('api/friends/ids', 'api_friends_ids', true);
3726 api_register_func('api/followers/ids', 'api_followers_ids', true);
3729 * Sends a new direct message.
3731 * @param string $type Return type (atom, rss, xml, json)
3733 * @return array|string
3734 * @throws BadRequestException
3735 * @throws ForbiddenException
3736 * @throws ImagickException
3737 * @throws InternalServerErrorException
3738 * @throws NotFoundException
3739 * @throws UnauthorizedException
3740 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3742 function api_direct_messages_new($type)
3746 if (api_user() === false) {
3747 throw new ForbiddenException();
3750 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3754 $sender = api_get_user($a);
3757 if (!empty($_POST['screen_name'])) {
3759 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3761 DBA::escape($_POST['screen_name'])
3764 if (DBA::isResult($r)) {
3765 // Selecting the id by priority, friendica first
3766 api_best_nickname($r);
3768 $recipient = api_get_user($a, $r[0]['nurl']);
3771 $recipient = api_get_user($a, $_POST['user_id']);
3774 if (empty($recipient)) {
3775 throw new NotFoundException('Recipient not found');
3779 if (!empty($_REQUEST['replyto'])) {
3781 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3783 intval($_REQUEST['replyto'])
3785 $replyto = $r[0]['parent-uri'];
3786 $sub = $r[0]['title'];
3788 if (!empty($_REQUEST['title'])) {
3789 $sub = $_REQUEST['title'];
3791 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3795 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3798 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3799 $ret = api_format_messages($r[0], $recipient, $sender);
3801 $ret = ["error"=>$id];
3804 $data = ['direct_message'=>$ret];
3810 $data = api_rss_extra($a, $data, $sender);
3814 return api_format_data("direct-messages", $type, $data);
3817 /// @TODO move to top of file or somewhere better
3818 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3821 * Destroys a direct message.
3823 * @brief delete a direct_message from mail table through api
3825 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3826 * @return string|array
3827 * @throws BadRequestException
3828 * @throws ForbiddenException
3829 * @throws ImagickException
3830 * @throws InternalServerErrorException
3831 * @throws UnauthorizedException
3832 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3834 function api_direct_messages_destroy($type)
3838 if (api_user() === false) {
3839 throw new ForbiddenException();
3843 $user_info = api_get_user($a);
3845 $id = $_REQUEST['id'] ?? 0;
3847 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3848 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3849 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3851 $uid = $user_info['uid'];
3852 // error if no id or parenturi specified (for clients posting parent-uri as well)
3853 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3854 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3855 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3858 // BadRequestException if no id specified (for clients using Twitter API)
3860 throw new BadRequestException('Message id not specified');
3863 // add parent-uri to sql command if specified by calling app
3864 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3866 // get data of the specified message id
3868 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3873 // error message if specified id is not in database
3874 if (!DBA::isResult($r)) {
3875 if ($verbose == "true") {
3876 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3877 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3879 /// @todo BadRequestException ok for Twitter API clients?
3880 throw new BadRequestException('message id not in database');
3885 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3890 if ($verbose == "true") {
3893 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3894 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3896 $answer = ['result' => 'error', 'message' => 'unknown error'];
3897 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3900 /// @todo return JSON data like Twitter API not yet implemented
3903 /// @TODO move to top of file or somewhere better
3904 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3909 * @brief unfollow contact
3911 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3912 * @return string|array
3913 * @throws BadRequestException
3914 * @throws ForbiddenException
3915 * @throws ImagickException
3916 * @throws InternalServerErrorException
3917 * @throws NotFoundException
3918 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3920 function api_friendships_destroy($type)
3924 if ($uid === false) {
3925 throw new ForbiddenException();
3928 $contact_id = $_REQUEST['user_id'] ?? 0;
3930 if (empty($contact_id)) {
3931 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3932 throw new BadRequestException("no user_id specified");
3935 // Get Contact by given id
3936 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3938 if(!DBA::isResult($contact)) {
3939 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3940 throw new NotFoundException("no contact found to given ID");
3943 $url = $contact["url"];
3945 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3946 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3947 Strings::normaliseLink($url), $url];
3948 $contact = DBA::selectFirst('contact', [], $condition);
3950 if (!DBA::isResult($contact)) {
3951 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3952 throw new NotFoundException("Not following Contact");
3955 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3956 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3957 throw new ExpectationFailedException("Not supported");
3960 $dissolve = ($contact['rel'] == Contact::SHARING);
3962 $owner = User::getOwnerDataById($uid);
3964 Contact::terminateFriendship($owner, $contact, $dissolve);
3967 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3968 throw new NotFoundException("Error Processing Request");
3971 // Sharing-only contacts get deleted as there no relationship any more
3973 Contact::remove($contact['id']);
3975 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3978 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3979 unset($contact["uid"]);
3980 unset($contact["self"]);
3982 // Set screen_name since Twidere requests it
3983 $contact["screen_name"] = $contact["nick"];
3985 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3987 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3991 * @param string $type Return type (atom, rss, xml, json)
3992 * @param string $box
3993 * @param string $verbose
3995 * @return array|string
3996 * @throws BadRequestException
3997 * @throws ForbiddenException
3998 * @throws ImagickException
3999 * @throws InternalServerErrorException
4000 * @throws UnauthorizedException
4002 function api_direct_messages_box($type, $box, $verbose)
4005 if (api_user() === false) {
4006 throw new ForbiddenException();
4009 $count = $_GET['count'] ?? 20;
4010 $page = $_REQUEST['page'] ?? 1;
4012 $since_id = $_REQUEST['since_id'] ?? 0;
4013 $max_id = $_REQUEST['max_id'] ?? 0;
4015 $user_id = $_REQUEST['user_id'] ?? '';
4016 $screen_name = $_REQUEST['screen_name'] ?? '';
4019 unset($_REQUEST["user_id"]);
4020 unset($_GET["user_id"]);
4022 unset($_REQUEST["screen_name"]);
4023 unset($_GET["screen_name"]);
4025 $user_info = api_get_user($a);
4026 if ($user_info === false) {
4027 throw new ForbiddenException();
4029 $profile_url = $user_info["url"];
4032 $start = max(0, ($page - 1) * $count);
4037 if ($box=="sentbox") {
4038 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4039 } elseif ($box == "conversation") {
4040 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4041 } elseif ($box == "all") {
4042 $sql_extra = "true";
4043 } elseif ($box == "inbox") {
4044 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4048 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4051 if ($user_id != "") {
4052 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4053 } elseif ($screen_name !="") {
4054 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4058 "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",
4064 if ($verbose == "true" && !DBA::isResult($r)) {
4065 $answer = ['result' => 'error', 'message' => 'no mails available'];
4066 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4070 foreach ($r as $item) {
4071 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4072 $recipient = $user_info;
4073 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4074 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4075 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4076 $sender = $user_info;
4079 if (isset($recipient) && isset($sender)) {
4080 $ret[] = api_format_messages($item, $recipient, $sender);
4085 $data = ['direct_message' => $ret];
4090 $data = api_rss_extra($a, $data, $user_info);
4094 return api_format_data("direct-messages", $type, $data);
4098 * Returns the most recent direct messages sent by the user.
4100 * @param string $type Return type (atom, rss, xml, json)
4102 * @return array|string
4103 * @throws BadRequestException
4104 * @throws ForbiddenException
4105 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4107 function api_direct_messages_sentbox($type)
4109 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4110 return api_direct_messages_box($type, "sentbox", $verbose);
4114 * Returns the most recent direct messages sent to the user.
4116 * @param string $type Return type (atom, rss, xml, json)
4118 * @return array|string
4119 * @throws BadRequestException
4120 * @throws ForbiddenException
4121 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4123 function api_direct_messages_inbox($type)
4125 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4126 return api_direct_messages_box($type, "inbox", $verbose);
4131 * @param string $type Return type (atom, rss, xml, json)
4133 * @return array|string
4134 * @throws BadRequestException
4135 * @throws ForbiddenException
4137 function api_direct_messages_all($type)
4139 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4140 return api_direct_messages_box($type, "all", $verbose);
4145 * @param string $type Return type (atom, rss, xml, json)
4147 * @return array|string
4148 * @throws BadRequestException
4149 * @throws ForbiddenException
4151 function api_direct_messages_conversation($type)
4153 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4154 return api_direct_messages_box($type, "conversation", $verbose);
4157 /// @TODO move to top of file or somewhere better
4158 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4159 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4160 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4161 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4164 * Returns an OAuth Request Token.
4166 * @see https://oauth.net/core/1.0/#auth_step1
4168 function api_oauth_request_token()
4170 $oauth1 = new FKOAuth1();
4172 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4173 } catch (Exception $e) {
4174 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4182 * Returns an OAuth Access Token.
4184 * @return array|string
4185 * @see https://oauth.net/core/1.0/#auth_step3
4187 function api_oauth_access_token()
4189 $oauth1 = new FKOAuth1();
4191 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4192 } catch (Exception $e) {
4193 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4200 /// @TODO move to top of file or somewhere better
4201 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4202 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4206 * @brief delete a complete photoalbum with all containing photos from database through api
4208 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4209 * @return string|array
4210 * @throws BadRequestException
4211 * @throws ForbiddenException
4212 * @throws InternalServerErrorException
4214 function api_fr_photoalbum_delete($type)
4216 if (api_user() === false) {
4217 throw new ForbiddenException();
4220 $album = $_REQUEST['album'] ?? '';
4222 // we do not allow calls without album string
4224 throw new BadRequestException("no albumname specified");
4226 // check if album is existing
4228 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4232 if (!DBA::isResult($r)) {
4233 throw new BadRequestException("album not available");
4236 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4237 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4238 foreach ($r as $rr) {
4239 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4240 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4242 if (!DBA::isResult($photo_item)) {
4243 throw new InternalServerErrorException("problem with deleting items occured");
4245 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4248 // now let's delete all photos from the album
4249 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4251 // return success of deletion or error message
4253 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4254 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4256 throw new InternalServerErrorException("unknown error - deleting from database failed");
4261 * @brief update the name of the album for all photos of an album
4263 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4264 * @return string|array
4265 * @throws BadRequestException
4266 * @throws ForbiddenException
4267 * @throws InternalServerErrorException
4269 function api_fr_photoalbum_update($type)
4271 if (api_user() === false) {
4272 throw new ForbiddenException();
4275 $album = $_REQUEST['album'] ?? '';
4276 $album_new = $_REQUEST['album_new'] ?? '';
4278 // we do not allow calls without album string
4280 throw new BadRequestException("no albumname specified");
4282 if ($album_new == "") {
4283 throw new BadRequestException("no new albumname specified");
4285 // check if album is existing
4286 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4287 throw new BadRequestException("album not available");
4289 // now let's update all photos to the albumname
4290 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4292 // return success of updating or error message
4294 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4295 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4297 throw new InternalServerErrorException("unknown error - updating in database failed");
4303 * @brief list all photos of the authenticated user
4305 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4306 * @return string|array
4307 * @throws ForbiddenException
4308 * @throws InternalServerErrorException
4310 function api_fr_photos_list($type)
4312 if (api_user() === false) {
4313 throw new ForbiddenException();
4316 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4317 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4318 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4319 intval(local_user())
4322 'image/jpeg' => 'jpg',
4323 'image/png' => 'png',
4324 'image/gif' => 'gif'
4326 $data = ['photo'=>[]];
4327 if (DBA::isResult($r)) {
4328 foreach ($r as $rr) {
4330 $photo['id'] = $rr['resource-id'];
4331 $photo['album'] = $rr['album'];
4332 $photo['filename'] = $rr['filename'];
4333 $photo['type'] = $rr['type'];
4334 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4335 $photo['created'] = $rr['created'];
4336 $photo['edited'] = $rr['edited'];
4337 $photo['desc'] = $rr['desc'];
4339 if ($type == "xml") {
4340 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4342 $photo['thumb'] = $thumb;
4343 $data['photo'][] = $photo;
4347 return api_format_data("photos", $type, $data);
4351 * @brief upload a new photo or change an existing photo
4353 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4354 * @return string|array
4355 * @throws BadRequestException
4356 * @throws ForbiddenException
4357 * @throws ImagickException
4358 * @throws InternalServerErrorException
4359 * @throws NotFoundException
4361 function api_fr_photo_create_update($type)
4363 if (api_user() === false) {
4364 throw new ForbiddenException();
4367 $photo_id = $_REQUEST['photo_id'] ?? null;
4368 $desc = $_REQUEST['desc'] ?? null;
4369 $album = $_REQUEST['album'] ?? null;
4370 $album_new = $_REQUEST['album_new'] ?? null;
4371 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4372 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4373 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4374 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4375 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4377 // do several checks on input parameters
4378 // we do not allow calls without album string
4379 if ($album == null) {
4380 throw new BadRequestException("no albumname specified");
4382 // if photo_id == null --> we are uploading a new photo
4383 if ($photo_id == null) {
4386 // error if no media posted in create-mode
4387 if (empty($_FILES['media'])) {
4389 throw new BadRequestException("no media data submitted");
4392 // album_new will be ignored in create-mode
4397 // check if photo is existing in databasei
4398 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4399 throw new BadRequestException("photo not available");
4403 // checks on acl strings provided by clients
4404 $acl_input_error = false;
4405 $acl_input_error |= check_acl_input($allow_cid);
4406 $acl_input_error |= check_acl_input($deny_cid);
4407 $acl_input_error |= check_acl_input($allow_gid);
4408 $acl_input_error |= check_acl_input($deny_gid);
4409 if ($acl_input_error) {
4410 throw new BadRequestException("acl data invalid");
4412 // now let's upload the new media in create-mode
4413 if ($mode == "create") {
4414 $media = $_FILES['media'];
4415 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4417 // return success of updating or error message
4418 if (!is_null($data)) {
4419 return api_format_data("photo_create", $type, $data);
4421 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4425 // now let's do the changes in update-mode
4426 if ($mode == "update") {
4427 $updated_fields = [];
4429 if (!is_null($desc)) {
4430 $updated_fields['desc'] = $desc;
4433 if (!is_null($album_new)) {
4434 $updated_fields['album'] = $album_new;
4437 if (!is_null($allow_cid)) {
4438 $allow_cid = trim($allow_cid);
4439 $updated_fields['allow_cid'] = $allow_cid;
4442 if (!is_null($deny_cid)) {
4443 $deny_cid = trim($deny_cid);
4444 $updated_fields['deny_cid'] = $deny_cid;
4447 if (!is_null($allow_gid)) {
4448 $allow_gid = trim($allow_gid);
4449 $updated_fields['allow_gid'] = $allow_gid;
4452 if (!is_null($deny_gid)) {
4453 $deny_gid = trim($deny_gid);
4454 $updated_fields['deny_gid'] = $deny_gid;
4458 if (count($updated_fields) > 0) {
4459 $nothingtodo = false;
4460 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4462 $nothingtodo = true;
4465 if (!empty($_FILES['media'])) {
4466 $nothingtodo = false;
4467 $media = $_FILES['media'];
4468 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4469 if (!is_null($data)) {
4470 return api_format_data("photo_update", $type, $data);
4474 // return success of updating or error message
4476 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4477 return api_format_data("photo_update", $type, ['$result' => $answer]);
4480 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4481 return api_format_data("photo_update", $type, ['$result' => $answer]);
4483 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4486 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4490 * @brief delete a single photo from the database through api
4492 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4493 * @return string|array
4494 * @throws BadRequestException
4495 * @throws ForbiddenException
4496 * @throws InternalServerErrorException
4498 function api_fr_photo_delete($type)
4500 if (api_user() === false) {
4501 throw new ForbiddenException();
4505 $photo_id = $_REQUEST['photo_id'] ?? null;
4507 // do several checks on input parameters
4508 // we do not allow calls without photo id
4509 if ($photo_id == null) {
4510 throw new BadRequestException("no photo_id specified");
4513 // check if photo is existing in database
4514 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4515 throw new BadRequestException("photo not available");
4518 // now we can perform on the deletion of the photo
4519 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4521 // return success of deletion or error message
4523 // retrieve the id of the parent element (the photo element)
4524 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4525 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4527 if (!DBA::isResult($photo_item)) {
4528 throw new InternalServerErrorException("problem with deleting items occured");
4530 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4531 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4532 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4534 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4535 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4537 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4543 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4545 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4546 * @return string|array
4547 * @throws BadRequestException
4548 * @throws ForbiddenException
4549 * @throws InternalServerErrorException
4550 * @throws NotFoundException
4552 function api_fr_photo_detail($type)
4554 if (api_user() === false) {
4555 throw new ForbiddenException();
4557 if (empty($_REQUEST['photo_id'])) {
4558 throw new BadRequestException("No photo id.");
4561 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4562 $photo_id = $_REQUEST['photo_id'];
4564 // prepare json/xml output with data from database for the requested photo
4565 $data = prepare_photo_data($type, $scale, $photo_id);
4567 return api_format_data("photo_detail", $type, $data);
4572 * Updates the user’s profile image.
4574 * @brief updates the profile image for the user (either a specified profile or the default profile)
4576 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4578 * @return string|array
4579 * @throws BadRequestException
4580 * @throws ForbiddenException
4581 * @throws ImagickException
4582 * @throws InternalServerErrorException
4583 * @throws NotFoundException
4584 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4586 function api_account_update_profile_image($type)
4588 if (api_user() === false) {
4589 throw new ForbiddenException();
4592 $profile_id = $_REQUEST['profile_id'] ?? 0;
4594 // error if image data is missing
4595 if (empty($_FILES['image'])) {
4596 throw new BadRequestException("no media data submitted");
4599 // check if specified profile id is valid
4600 if ($profile_id != 0) {
4601 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4602 // error message if specified profile id is not in database
4603 if (!DBA::isResult($profile)) {
4604 throw new BadRequestException("profile_id not available");
4606 $is_default_profile = $profile['is-default'];
4608 $is_default_profile = 1;
4611 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4613 if (!empty($_FILES['image'])) {
4614 $media = $_FILES['image'];
4615 } elseif (!empty($_FILES['media'])) {
4616 $media = $_FILES['media'];
4618 // save new profile image
4619 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4622 if (is_array($media['type'])) {
4623 $filetype = $media['type'][0];
4625 $filetype = $media['type'];
4627 if ($filetype == "image/jpeg") {
4629 } elseif ($filetype == "image/png") {
4632 throw new InternalServerErrorException('Unsupported filetype');
4635 // change specified profile or all profiles to the new resource-id
4636 if ($is_default_profile) {
4637 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4638 Photo::update(['profile' => false], $condition);
4640 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4641 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4642 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4645 Contact::updateSelfFromUserID(api_user(), true);
4647 // Update global directory in background
4648 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4649 if ($url && strlen(Config::get('system', 'directory'))) {
4650 Worker::add(PRIORITY_LOW, "Directory", $url);
4653 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4655 // output for client
4657 return api_account_verify_credentials($type);
4659 // SaveMediaToDatabase failed for some reason
4660 throw new InternalServerErrorException("image upload failed");
4664 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4665 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4666 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4667 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4668 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4669 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4670 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4671 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4672 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4675 * Update user profile
4677 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4679 * @return array|string
4680 * @throws BadRequestException
4681 * @throws ForbiddenException
4682 * @throws ImagickException
4683 * @throws InternalServerErrorException
4684 * @throws UnauthorizedException
4686 function api_account_update_profile($type)
4688 $local_user = api_user();
4689 $api_user = api_get_user(DI::app());
4691 if (!empty($_POST['name'])) {
4692 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4693 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4694 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4695 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4698 if (isset($_POST['description'])) {
4699 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4700 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4701 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4704 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4705 // Update global directory in background
4706 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4707 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4710 return api_account_verify_credentials($type);
4713 /// @TODO move to top of file or somewhere better
4714 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4718 * @param string $acl_string
4722 function check_acl_input($acl_string)
4724 if (empty($acl_string)) {
4728 $contact_not_found = false;
4730 // split <x><y><z> into array of cid's
4731 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4733 // check for each cid if it is available on server
4734 $cid_array = $array[0];
4735 foreach ($cid_array as $cid) {
4736 $cid = str_replace("<", "", $cid);
4737 $cid = str_replace(">", "", $cid);
4738 $condition = ['id' => $cid, 'uid' => api_user()];
4739 $contact_not_found |= !DBA::exists('contact', $condition);
4741 return $contact_not_found;
4745 * @param string $mediatype
4746 * @param array $media
4747 * @param string $type
4748 * @param string $album
4749 * @param string $allow_cid
4750 * @param string $deny_cid
4751 * @param string $allow_gid
4752 * @param string $deny_gid
4753 * @param string $desc
4754 * @param integer $profile
4755 * @param boolean $visibility
4756 * @param string $photo_id
4758 * @throws BadRequestException
4759 * @throws ForbiddenException
4760 * @throws ImagickException
4761 * @throws InternalServerErrorException
4762 * @throws NotFoundException
4763 * @throws UnauthorizedException
4765 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)
4773 if (is_array($media)) {
4774 if (is_array($media['tmp_name'])) {
4775 $src = $media['tmp_name'][0];
4777 $src = $media['tmp_name'];
4779 if (is_array($media['name'])) {
4780 $filename = basename($media['name'][0]);
4782 $filename = basename($media['name']);
4784 if (is_array($media['size'])) {
4785 $filesize = intval($media['size'][0]);
4787 $filesize = intval($media['size']);
4789 if (is_array($media['type'])) {
4790 $filetype = $media['type'][0];
4792 $filetype = $media['type'];
4796 if ($filetype == "") {
4797 $filetype = Images::guessType($filename);
4799 $imagedata = @getimagesize($src);
4801 $filetype = $imagedata['mime'];
4804 "File upload src: " . $src . " - filename: " . $filename .
4805 " - size: " . $filesize . " - type: " . $filetype,
4809 // check if there was a php upload error
4810 if ($filesize == 0 && $media['error'] == 1) {
4811 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4813 // check against max upload size within Friendica instance
4814 $maximagesize = Config::get('system', 'maximagesize');
4815 if ($maximagesize && ($filesize > $maximagesize)) {
4816 $formattedBytes = Strings::formatBytes($maximagesize);
4817 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4820 // create Photo instance with the data of the image
4821 $imagedata = @file_get_contents($src);
4822 $Image = new Image($imagedata, $filetype);
4823 if (!$Image->isValid()) {
4824 throw new InternalServerErrorException("unable to process image data");
4827 // check orientation of image
4828 $Image->orient($src);
4831 // check max length of images on server
4832 $max_length = Config::get('system', 'max_image_length');
4834 $max_length = MAX_IMAGE_LENGTH;
4836 if ($max_length > 0) {
4837 $Image->scaleDown($max_length);
4838 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4840 $width = $Image->getWidth();
4841 $height = $Image->getHeight();
4843 // create a new resource-id if not already provided
4844 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4846 if ($mediatype == "photo") {
4847 // upload normal image (scales 0, 1, 2)
4848 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4850 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4852 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4854 if ($width > 640 || $height > 640) {
4855 $Image->scaleDown(640);
4856 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4858 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4862 if ($width > 320 || $height > 320) {
4863 $Image->scaleDown(320);
4864 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4866 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4869 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4870 } elseif ($mediatype == "profileimage") {
4871 // upload profile image (scales 4, 5, 6)
4872 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4874 if ($width > 300 || $height > 300) {
4875 $Image->scaleDown(300);
4876 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4878 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4882 if ($width > 80 || $height > 80) {
4883 $Image->scaleDown(80);
4884 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4886 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4890 if ($width > 48 || $height > 48) {
4891 $Image->scaleDown(48);
4892 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4894 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4897 $Image->__destruct();
4898 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4901 if (isset($r) && $r) {
4902 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4903 if ($photo_id == null && $mediatype == "photo") {
4904 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4906 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4907 return prepare_photo_data($type, false, $resource_id);
4909 throw new InternalServerErrorException("image upload failed");
4915 * @param string $hash
4916 * @param string $allow_cid
4917 * @param string $deny_cid
4918 * @param string $allow_gid
4919 * @param string $deny_gid
4920 * @param string $filetype
4921 * @param boolean $visibility
4922 * @throws InternalServerErrorException
4924 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4926 // get data about the api authenticated user
4927 $uri = Item::newURI(intval(api_user()));
4928 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4931 $arr['guid'] = System::createUUID();
4932 $arr['uid'] = intval(api_user());
4934 $arr['parent-uri'] = $uri;
4935 $arr['type'] = 'photo';
4937 $arr['resource-id'] = $hash;
4938 $arr['contact-id'] = $owner_record['id'];
4939 $arr['owner-name'] = $owner_record['name'];
4940 $arr['owner-link'] = $owner_record['url'];
4941 $arr['owner-avatar'] = $owner_record['thumb'];
4942 $arr['author-name'] = $owner_record['name'];
4943 $arr['author-link'] = $owner_record['url'];
4944 $arr['author-avatar'] = $owner_record['thumb'];
4946 $arr['allow_cid'] = $allow_cid;
4947 $arr['allow_gid'] = $allow_gid;
4948 $arr['deny_cid'] = $deny_cid;
4949 $arr['deny_gid'] = $deny_gid;
4950 $arr['visible'] = $visibility;
4954 'image/jpeg' => 'jpg',
4955 'image/png' => 'png',
4956 'image/gif' => 'gif'
4959 // adds link to the thumbnail scale photo
4960 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4961 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4964 // do the magic for storing the item in the database and trigger the federation to other contacts
4970 * @param string $type
4972 * @param string $photo_id
4975 * @throws BadRequestException
4976 * @throws ForbiddenException
4977 * @throws ImagickException
4978 * @throws InternalServerErrorException
4979 * @throws NotFoundException
4980 * @throws UnauthorizedException
4982 function prepare_photo_data($type, $scale, $photo_id)
4985 $user_info = api_get_user($a);
4987 if ($user_info === false) {
4988 throw new ForbiddenException();
4991 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4992 $data_sql = ($scale === false ? "" : "data, ");
4994 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4995 // clients needs to convert this in their way for further processing
4997 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4998 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4999 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
5000 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
5001 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
5002 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
5004 intval(local_user()),
5005 DBA::escape($photo_id),
5010 'image/jpeg' => 'jpg',
5011 'image/png' => 'png',
5012 'image/gif' => 'gif'
5015 // prepare output data for photo
5016 if (DBA::isResult($r)) {
5017 $data = ['photo' => $r[0]];
5018 $data['photo']['id'] = $data['photo']['resource-id'];
5019 if ($scale !== false) {
5020 $data['photo']['data'] = base64_encode($data['photo']['data']);
5022 unset($data['photo']['datasize']); //needed only with scale param
5024 if ($type == "xml") {
5025 $data['photo']['links'] = [];
5026 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5027 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5029 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5032 $data['photo']['link'] = [];
5033 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5035 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5036 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5040 unset($data['photo']['resource-id']);
5041 unset($data['photo']['minscale']);
5042 unset($data['photo']['maxscale']);
5044 throw new NotFoundException();
5047 // retrieve item element for getting activities (like, dislike etc.) related to photo
5048 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5049 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5051 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5053 // retrieve comments on photo
5054 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5055 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5057 $statuses = Item::selectForUser(api_user(), [], $condition);
5059 // prepare output of comments
5060 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5062 if ($type == "xml") {
5064 foreach ($commentData as $comment) {
5065 $comments[$k++ . ":comment"] = $comment;
5068 foreach ($commentData as $comment) {
5069 $comments[] = $comment;
5072 $data['photo']['friendica_comments'] = $comments;
5074 // include info if rights on photo and rights on item are mismatching
5075 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5076 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5077 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5078 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5079 $data['photo']['rights_mismatch'] = $rights_mismatch;
5086 * Similar as /mod/redir.php
5087 * redirect to 'url' after dfrn auth
5089 * Why this when there is mod/redir.php already?
5090 * This use api_user() and api_login()
5093 * c_url: url of remote contact to auth to
5094 * url: string, url to redirect after auth
5096 function api_friendica_remoteauth()
5098 $url = $_GET['url'] ?? '';
5099 $c_url = $_GET['c_url'] ?? '';
5101 if ($url === '' || $c_url === '') {
5102 throw new BadRequestException("Wrong parameters.");
5105 $c_url = Strings::normaliseLink($c_url);
5109 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5110 if (!DBA::isResult($contact)) {
5111 throw new BadRequestException("Unknown contact");
5114 $cid = $contact['id'];
5116 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5118 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5119 System::externalRedirect($url ?: $c_url);
5122 if ($contact['duplex'] && $contact['issued-id']) {
5123 $orig_id = $contact['issued-id'];
5124 $dfrn_id = '1:' . $orig_id;
5126 if ($contact['duplex'] && $contact['dfrn-id']) {
5127 $orig_id = $contact['dfrn-id'];
5128 $dfrn_id = '0:' . $orig_id;
5131 $sec = Strings::getRandomHex();
5133 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5134 'sec' => $sec, 'expire' => time() + 45];
5135 DBA::insert('profile_check', $fields);
5137 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5138 $dest = ($url ? '&destination_url=' . $url : '');
5140 System::externalRedirect(
5141 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5142 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5143 . '&type=profile&sec=' . $sec . $dest
5146 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5149 * Return an item with announcer data if it had been announced
5151 * @param array $item Item array
5152 * @return array Item array with announce data
5154 function api_get_announce($item)
5156 // Quit if the item already has got a different owner and author
5157 if ($item['owner-id'] != $item['author-id']) {
5161 // Don't change original or Diaspora posts
5162 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5166 // Quit if we do now the original author and it had been a post from a native network
5167 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5171 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5172 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5173 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5174 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5175 if (!DBA::isResult($announce)) {
5179 return array_merge($item, $announce);
5183 * @brief Return the item shared, if the item contains only the [share] tag
5185 * @param array $item Sharer item
5186 * @return array|false Shared item or false if not a reshare
5187 * @throws ImagickException
5188 * @throws InternalServerErrorException
5190 function api_share_as_retweet(&$item)
5192 $body = trim($item["body"]);
5194 if (Diaspora::isReshare($body, false) === false) {
5195 if ($item['author-id'] == $item['owner-id']) {
5198 // Reshares from OStatus, ActivityPub and Twitter
5199 $reshared_item = $item;
5200 $reshared_item['owner-id'] = $reshared_item['author-id'];
5201 $reshared_item['owner-link'] = $reshared_item['author-link'];
5202 $reshared_item['owner-name'] = $reshared_item['author-name'];
5203 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5204 return $reshared_item;
5208 $reshared = Item::getShareArray($item);
5209 if (empty($reshared)) {
5213 $reshared_item = $item;
5215 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5219 if (!empty($reshared['comment'])) {
5220 $item['body'] = $reshared['comment'];
5223 $reshared_item["share-pre-body"] = $reshared['comment'];
5224 $reshared_item["body"] = $reshared['shared'];
5225 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5226 $reshared_item["author-name"] = $reshared['author'];
5227 $reshared_item["author-link"] = $reshared['profile'];
5228 $reshared_item["author-avatar"] = $reshared['avatar'];
5229 $reshared_item["plink"] = $reshared['link'] ?? '';
5230 $reshared_item["created"] = $reshared['posted'];
5231 $reshared_item["edited"] = $reshared['posted'];
5233 // Try to fetch the original item
5234 if (!empty($reshared['guid'])) {
5235 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5236 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5237 $condition = ['id' => $original_id];
5242 if (!empty($condition)) {
5243 $original_item = Item::selectFirst([], $condition);
5244 if (DBA::isResult($original_item)) {
5245 $reshared_item = array_merge($reshared_item, $original_item);
5249 return $reshared_item;
5254 * @param array $item
5259 function api_in_reply_to($item)
5263 $in_reply_to['status_id'] = null;
5264 $in_reply_to['user_id'] = null;
5265 $in_reply_to['status_id_str'] = null;
5266 $in_reply_to['user_id_str'] = null;
5267 $in_reply_to['screen_name'] = null;
5269 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5270 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5271 if (DBA::isResult($parent)) {
5272 $in_reply_to['status_id'] = intval($parent['id']);
5274 $in_reply_to['status_id'] = intval($item['parent']);
5277 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5279 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5280 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5282 if (DBA::isResult($parent)) {
5283 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5284 $in_reply_to['user_id'] = intval($parent['author-id']);
5285 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5288 // There seems to be situation, where both fields are identical:
5289 // https://github.com/friendica/friendica/issues/1010
5290 // This is a bugfix for that.
5291 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5292 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']]);
5293 $in_reply_to['status_id'] = null;
5294 $in_reply_to['user_id'] = null;
5295 $in_reply_to['status_id_str'] = null;
5296 $in_reply_to['user_id_str'] = null;
5297 $in_reply_to['screen_name'] = null;
5301 return $in_reply_to;
5306 * @param string $text
5309 * @throws InternalServerErrorException
5311 function api_clean_plain_items($text)
5313 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5315 $text = BBCode::cleanPictureLinks($text);
5316 $URLSearchString = "^\[\]";
5318 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5320 if ($include_entities == "true") {
5321 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5324 // Simplify "attachment" element
5325 $text = BBCode::removeAttachment($text);
5332 * @param array $contacts
5336 function api_best_nickname(&$contacts)
5340 if (count($contacts) == 0) {
5344 foreach ($contacts as $contact) {
5345 if ($contact["network"] == "") {
5346 $contact["network"] = "dfrn";
5347 $best_contact = [$contact];
5351 if (sizeof($best_contact) == 0) {
5352 foreach ($contacts as $contact) {
5353 if ($contact["network"] == "dfrn") {
5354 $best_contact = [$contact];
5359 if (sizeof($best_contact) == 0) {
5360 foreach ($contacts as $contact) {
5361 if ($contact["network"] == "dspr") {
5362 $best_contact = [$contact];
5367 if (sizeof($best_contact) == 0) {
5368 foreach ($contacts as $contact) {
5369 if ($contact["network"] == "stat") {
5370 $best_contact = [$contact];
5375 if (sizeof($best_contact) == 0) {
5376 foreach ($contacts as $contact) {
5377 if ($contact["network"] == "pump") {
5378 $best_contact = [$contact];
5383 if (sizeof($best_contact) == 0) {
5384 foreach ($contacts as $contact) {
5385 if ($contact["network"] == "twit") {
5386 $best_contact = [$contact];
5391 if (sizeof($best_contact) == 1) {
5392 $contacts = $best_contact;
5394 $contacts = [$contacts[0]];
5399 * Return all or a specified group of the user with the containing contacts.
5401 * @param string $type Return type (atom, rss, xml, json)
5403 * @return array|string
5404 * @throws BadRequestException
5405 * @throws ForbiddenException
5406 * @throws ImagickException
5407 * @throws InternalServerErrorException
5408 * @throws UnauthorizedException
5410 function api_friendica_group_show($type)
5414 if (api_user() === false) {
5415 throw new ForbiddenException();
5419 $user_info = api_get_user($a);
5420 $gid = $_REQUEST['gid'] ?? 0;
5421 $uid = $user_info['uid'];
5423 // get data of the specified group id or all groups if not specified
5426 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5430 // error message if specified gid is not in database
5431 if (!DBA::isResult($r)) {
5432 throw new BadRequestException("gid not available");
5436 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5441 // loop through all groups and retrieve all members for adding data in the user array
5443 foreach ($r as $rr) {
5444 $members = Contact::getByGroupId($rr['id']);
5447 if ($type == "xml") {
5448 $user_element = "users";
5450 foreach ($members as $member) {
5451 $user = api_get_user($a, $member['nurl']);
5452 $users[$k++.":user"] = $user;
5455 $user_element = "user";
5456 foreach ($members as $member) {
5457 $user = api_get_user($a, $member['nurl']);
5461 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5463 return api_format_data("groups", $type, ['group' => $grps]);
5465 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5469 * Delete the specified group of the user.
5471 * @param string $type Return type (atom, rss, xml, json)
5473 * @return array|string
5474 * @throws BadRequestException
5475 * @throws ForbiddenException
5476 * @throws ImagickException
5477 * @throws InternalServerErrorException
5478 * @throws UnauthorizedException
5480 function api_friendica_group_delete($type)
5484 if (api_user() === false) {
5485 throw new ForbiddenException();
5489 $user_info = api_get_user($a);
5490 $gid = $_REQUEST['gid'] ?? 0;
5491 $name = $_REQUEST['name'] ?? '';
5492 $uid = $user_info['uid'];
5494 // error if no gid specified
5495 if ($gid == 0 || $name == "") {
5496 throw new BadRequestException('gid or name not specified');
5499 // get data of the specified group id
5501 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5505 // error message if specified gid is not in database
5506 if (!DBA::isResult($r)) {
5507 throw new BadRequestException('gid not available');
5510 // get data of the specified group id and group name
5512 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5517 // error message if specified gid is not in database
5518 if (!DBA::isResult($rname)) {
5519 throw new BadRequestException('wrong group name');
5523 $ret = Group::removeByName($uid, $name);
5526 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5527 return api_format_data("group_delete", $type, ['result' => $success]);
5529 throw new BadRequestException('other API error');
5532 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5537 * @param string $type Return type (atom, rss, xml, json)
5539 * @return array|string
5540 * @throws BadRequestException
5541 * @throws ForbiddenException
5542 * @throws ImagickException
5543 * @throws InternalServerErrorException
5544 * @throws UnauthorizedException
5545 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5547 function api_lists_destroy($type)
5551 if (api_user() === false) {
5552 throw new ForbiddenException();
5556 $user_info = api_get_user($a);
5557 $gid = $_REQUEST['list_id'] ?? 0;
5558 $uid = $user_info['uid'];
5560 // error if no gid specified
5562 throw new BadRequestException('gid not specified');
5565 // get data of the specified group id
5566 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5567 // error message if specified gid is not in database
5569 throw new BadRequestException('gid not available');
5572 if (Group::remove($gid)) {
5574 'name' => $group['name'],
5575 'id' => intval($gid),
5576 'id_str' => (string) $gid,
5577 'user' => $user_info
5580 return api_format_data("lists", $type, ['lists' => $list]);
5583 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5586 * Add a new group to the database.
5588 * @param string $name Group name
5589 * @param int $uid User ID
5590 * @param array $users List of users to add to the group
5593 * @throws BadRequestException
5595 function group_create($name, $uid, $users = [])
5597 // error if no name specified
5599 throw new BadRequestException('group name not specified');
5602 // get data of the specified group name
5604 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5608 // error message if specified group name already exists
5609 if (DBA::isResult($rname)) {
5610 throw new BadRequestException('group name already exists');
5613 // check if specified group name is a deleted group
5615 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5619 // error message if specified group name already exists
5620 if (DBA::isResult($rname)) {
5621 $reactivate_group = true;
5625 $ret = Group::create($uid, $name);
5627 $gid = Group::getIdByName($uid, $name);
5629 throw new BadRequestException('other API error');
5633 $erroraddinguser = false;
5635 foreach ($users as $user) {
5636 $cid = $user['cid'];
5637 // check if user really exists as contact
5639 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5643 if (count($contact)) {
5644 Group::addMember($gid, $cid);
5646 $erroraddinguser = true;
5647 $errorusers[] = $cid;
5651 // return success message incl. missing users in array
5652 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5654 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5658 * Create the specified group with the posted array of contacts.
5660 * @param string $type Return type (atom, rss, xml, json)
5662 * @return array|string
5663 * @throws BadRequestException
5664 * @throws ForbiddenException
5665 * @throws ImagickException
5666 * @throws InternalServerErrorException
5667 * @throws UnauthorizedException
5669 function api_friendica_group_create($type)
5673 if (api_user() === false) {
5674 throw new ForbiddenException();
5678 $user_info = api_get_user($a);
5679 $name = $_REQUEST['name'] ?? '';
5680 $uid = $user_info['uid'];
5681 $json = json_decode($_POST['json'], true);
5682 $users = $json['user'];
5684 $success = group_create($name, $uid, $users);
5686 return api_format_data("group_create", $type, ['result' => $success]);
5688 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5691 * Create a new group.
5693 * @param string $type Return type (atom, rss, xml, json)
5695 * @return array|string
5696 * @throws BadRequestException
5697 * @throws ForbiddenException
5698 * @throws ImagickException
5699 * @throws InternalServerErrorException
5700 * @throws UnauthorizedException
5701 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5703 function api_lists_create($type)
5707 if (api_user() === false) {
5708 throw new ForbiddenException();
5712 $user_info = api_get_user($a);
5713 $name = $_REQUEST['name'] ?? '';
5714 $uid = $user_info['uid'];
5716 $success = group_create($name, $uid);
5717 if ($success['success']) {
5719 'name' => $success['name'],
5720 'id' => intval($success['gid']),
5721 'id_str' => (string) $success['gid'],
5722 'user' => $user_info
5725 return api_format_data("lists", $type, ['lists'=>$grp]);
5728 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5731 * Update the specified group with the posted array of contacts.
5733 * @param string $type Return type (atom, rss, xml, json)
5735 * @return array|string
5736 * @throws BadRequestException
5737 * @throws ForbiddenException
5738 * @throws ImagickException
5739 * @throws InternalServerErrorException
5740 * @throws UnauthorizedException
5742 function api_friendica_group_update($type)
5746 if (api_user() === false) {
5747 throw new ForbiddenException();
5751 $user_info = api_get_user($a);
5752 $uid = $user_info['uid'];
5753 $gid = $_REQUEST['gid'] ?? 0;
5754 $name = $_REQUEST['name'] ?? '';
5755 $json = json_decode($_POST['json'], true);
5756 $users = $json['user'];
5758 // error if no name specified
5760 throw new BadRequestException('group name not specified');
5763 // error if no gid specified
5765 throw new BadRequestException('gid not specified');
5769 $members = Contact::getByGroupId($gid);
5770 foreach ($members as $member) {
5771 $cid = $member['id'];
5772 foreach ($users as $user) {
5773 $found = ($user['cid'] == $cid ? true : false);
5775 if (!isset($found) || !$found) {
5776 Group::removeMemberByName($uid, $name, $cid);
5781 $erroraddinguser = false;
5783 foreach ($users as $user) {
5784 $cid = $user['cid'];
5785 // check if user really exists as contact
5787 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5792 if (count($contact)) {
5793 Group::addMember($gid, $cid);
5795 $erroraddinguser = true;
5796 $errorusers[] = $cid;
5800 // return success message incl. missing users in array
5801 $status = ($erroraddinguser ? "missing user" : "ok");
5802 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5803 return api_format_data("group_update", $type, ['result' => $success]);
5806 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5809 * Update information about a group.
5811 * @param string $type Return type (atom, rss, xml, json)
5813 * @return array|string
5814 * @throws BadRequestException
5815 * @throws ForbiddenException
5816 * @throws ImagickException
5817 * @throws InternalServerErrorException
5818 * @throws UnauthorizedException
5819 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5821 function api_lists_update($type)
5825 if (api_user() === false) {
5826 throw new ForbiddenException();
5830 $user_info = api_get_user($a);
5831 $gid = $_REQUEST['list_id'] ?? 0;
5832 $name = $_REQUEST['name'] ?? '';
5833 $uid = $user_info['uid'];
5835 // error if no gid specified
5837 throw new BadRequestException('gid not specified');
5840 // get data of the specified group id
5841 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5842 // error message if specified gid is not in database
5844 throw new BadRequestException('gid not available');
5847 if (Group::update($gid, $name)) {
5850 'id' => intval($gid),
5851 'id_str' => (string) $gid,
5852 'user' => $user_info
5855 return api_format_data("lists", $type, ['lists' => $list]);
5859 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5863 * @param string $type Return type (atom, rss, xml, json)
5865 * @return array|string
5866 * @throws BadRequestException
5867 * @throws ForbiddenException
5868 * @throws ImagickException
5869 * @throws InternalServerErrorException
5871 function api_friendica_activity($type)
5875 if (api_user() === false) {
5876 throw new ForbiddenException();
5878 $verb = strtolower($a->argv[3]);
5879 $verb = preg_replace("|\..*$|", "", $verb);
5881 $id = $_REQUEST['id'] ?? 0;
5883 $res = Item::performLike($id, $verb);
5886 if ($type == "xml") {
5891 return api_format_data('ok', $type, ['ok' => $ok]);
5893 throw new BadRequestException('Error adding activity');
5897 /// @TODO move to top of file or somewhere better
5898 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5899 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5900 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5901 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5902 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5903 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5904 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5910 * @brief Returns notifications
5912 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5913 * @return string|array
5914 * @throws BadRequestException
5915 * @throws ForbiddenException
5916 * @throws InternalServerErrorException
5918 function api_friendica_notification($type)
5922 if (api_user() === false) {
5923 throw new ForbiddenException();
5926 throw new BadRequestException("Invalid argument count");
5928 $notes = DI::notify()->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5930 if ($type == "xml") {
5932 if (!empty($notes)) {
5933 foreach ($notes as $note) {
5934 $xmlnotes[] = ["@attributes" => $note];
5940 return api_format_data("notes", $type, ['note' => $notes]);
5944 * POST request with 'id' param as notification id
5946 * @brief Set notification as seen and returns associated item (if possible)
5948 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5949 * @return string|array
5950 * @throws BadRequestException
5951 * @throws ForbiddenException
5952 * @throws ImagickException
5953 * @throws InternalServerErrorException
5954 * @throws UnauthorizedException
5956 function api_friendica_notification_seen($type)
5959 $user_info = api_get_user($a);
5961 if (api_user() === false || $user_info === false) {
5962 throw new ForbiddenException();
5965 throw new BadRequestException("Invalid argument count");
5968 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5971 $note = $nm->getByID($id);
5972 if (is_null($note)) {
5973 throw new BadRequestException("Invalid argument");
5976 $nm->setSeen($note);
5977 if ($note['otype']=='item') {
5978 // would be really better with an ItemsManager and $im->getByID() :-P
5979 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5980 if (DBA::isResult($item)) {
5981 // we found the item, return it to the user
5982 $ret = api_format_items([$item], $user_info, false, $type);
5983 $data = ['status' => $ret];
5984 return api_format_data("status", $type, $data);
5986 // the item can't be found, but we set the note as seen, so we count this as a success
5988 return api_format_data('result', $type, ['result' => "success"]);
5991 /// @TODO move to top of file or somewhere better
5992 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5993 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5996 * @brief update a direct_message to seen state
5998 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5999 * @return string|array (success result=ok, error result=error with error message)
6000 * @throws BadRequestException
6001 * @throws ForbiddenException
6002 * @throws ImagickException
6003 * @throws InternalServerErrorException
6004 * @throws UnauthorizedException
6006 function api_friendica_direct_messages_setseen($type)
6009 if (api_user() === false) {
6010 throw new ForbiddenException();
6014 $user_info = api_get_user($a);
6015 $uid = $user_info['uid'];
6016 $id = $_REQUEST['id'] ?? 0;
6018 // return error if id is zero
6020 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6021 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6024 // error message if specified id is not in database
6025 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6026 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6027 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6030 // update seen indicator
6031 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6035 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6036 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6038 $answer = ['result' => 'error', 'message' => 'unknown error'];
6039 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6043 /// @TODO move to top of file or somewhere better
6044 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6047 * @brief search for direct_messages containing a searchstring through api
6049 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6050 * @param string $box
6051 * @return string|array (success: success=true if found and search_result contains found messages,
6052 * success=false if nothing was found, search_result='nothing found',
6053 * error: result=error with error message)
6054 * @throws BadRequestException
6055 * @throws ForbiddenException
6056 * @throws ImagickException
6057 * @throws InternalServerErrorException
6058 * @throws UnauthorizedException
6060 function api_friendica_direct_messages_search($type, $box = "")
6064 if (api_user() === false) {
6065 throw new ForbiddenException();
6069 $user_info = api_get_user($a);
6070 $searchstring = $_REQUEST['searchstring'] ?? '';
6071 $uid = $user_info['uid'];
6073 // error if no searchstring specified
6074 if ($searchstring == "") {
6075 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6076 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6079 // get data for the specified searchstring
6081 "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",
6083 DBA::escape('%'.$searchstring.'%')
6086 $profile_url = $user_info["url"];
6088 // message if nothing was found
6089 if (!DBA::isResult($r)) {
6090 $success = ['success' => false, 'search_results' => 'problem with query'];
6091 } elseif (count($r) == 0) {
6092 $success = ['success' => false, 'search_results' => 'nothing found'];
6095 foreach ($r as $item) {
6096 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6097 $recipient = $user_info;
6098 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6099 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6100 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6101 $sender = $user_info;
6104 if (isset($recipient) && isset($sender)) {
6105 $ret[] = api_format_messages($item, $recipient, $sender);
6108 $success = ['success' => true, 'search_results' => $ret];
6111 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6114 /// @TODO move to top of file or somewhere better
6115 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6118 * @brief return data of all the profiles a user has to the client
6120 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6121 * @return string|array
6122 * @throws BadRequestException
6123 * @throws ForbiddenException
6124 * @throws ImagickException
6125 * @throws InternalServerErrorException
6126 * @throws UnauthorizedException
6128 function api_friendica_profile_show($type)
6132 if (api_user() === false) {
6133 throw new ForbiddenException();
6137 $profile_id = $_REQUEST['profile_id'] ?? 0;
6139 // retrieve general information about profiles for user
6140 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6141 $directory = Config::get('system', 'directory');
6143 // get data of the specified profile id or all profiles of the user if not specified
6144 if ($profile_id != 0) {
6145 $r = Profile::getById(api_user(), $profile_id);
6146 // error message if specified gid is not in database
6147 if (!DBA::isResult($r)) {
6148 throw new BadRequestException("profile_id not available");
6151 $r = Profile::getListByUser(api_user());
6153 // loop through all returned profiles and retrieve data and users
6156 if (DBA::isResult($r)) {
6157 foreach ($r as $rr) {
6158 $profile = api_format_items_profiles($rr);
6160 // select all users from contact table, loop and prepare standard return for user data
6162 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6163 foreach ($nurls as $nurl) {
6164 $user = api_get_user($a, $nurl['nurl']);
6165 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6167 $profile['users'] = $users;
6169 // add prepared profile data to array for final return
6170 if ($type == "xml") {
6171 $profiles[$k++ . ":profile"] = $profile;
6173 $profiles[] = $profile;
6178 // return settings, authenticated user and profiles data
6179 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6181 $result = ['multi_profiles' => $multi_profiles ? true : false,
6182 'global_dir' => $directory,
6183 'friendica_owner' => api_get_user($a, $self['nurl']),
6184 'profiles' => $profiles];
6185 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6187 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6190 * Returns a list of saved searches.
6192 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6194 * @param string $type Return format: json or xml
6196 * @return string|array
6199 function api_saved_searches_list($type)
6201 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6204 while ($term = DBA::fetch($terms)) {
6206 'created_at' => api_date(time()),
6207 'id' => intval($term['id']),
6208 'id_str' => $term['id'],
6209 'name' => $term['term'],
6211 'query' => $term['term']
6217 return api_format_data("terms", $type, ['terms' => $result]);
6220 /// @TODO move to top of file or somewhere better
6221 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6224 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6226 * @brief Number of comments
6228 * @param object $data [Status, Status]
6232 function bindComments(&$data)
6234 if (count($data) == 0) {
6240 foreach ($data as $item) {
6241 $ids[] = $item['id'];
6244 $idStr = DBA::escape(implode(', ', $ids));
6245 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6246 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6247 $itemsData = DBA::toArray($items);
6249 foreach ($itemsData as $item) {
6250 $comments[$item['parent']] = $item['comments'];
6253 foreach ($data as $idx => $item) {
6255 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6260 @TODO Maybe open to implement?
6262 [pagename] => api/1.1/statuses/lookup.json
6263 [id] => 605138389168451584
6264 [include_cards] => true
6265 [cards_platform] => Android-12
6266 [include_entities] => true
6267 [include_my_retweet] => 1
6269 [include_reply_count] => true
6270 [include_descendent_reply_count] => true
6274 Not implemented by now:
6275 statuses/retweets_of_me
6280 account/update_location
6281 account/update_profile_background_image
6284 friendica/profile/update
6285 friendica/profile/create
6286 friendica/profile/delete
6288 Not implemented in status.net:
6289 statuses/retweeted_to_me
6290 statuses/retweeted_by_me
6291 direct_messages/destroy
6293 account/update_delivery_device
6294 notifications/follow