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 = DI::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 = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
740 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
741 $bgcolor = DI::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 |
2170 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2174 $query .= " AND `item`.`id` <= ?";
2175 $condition[] = $max_id;
2178 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2179 $condition[] = $start;
2180 $condition[] = $count;
2182 $useritems = DBA::p($query, $condition);
2184 while ($useritem = DBA::fetch($useritems)) {
2185 $itemids[] = $useritem['id'];
2187 DBA::close($useritems);
2189 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2190 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2192 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2194 $data = ['status' => $ret];
2199 $data = api_rss_extra($a, $data, $user_info);
2203 return api_format_data("statuses", $type, $data);
2206 /// @TODO move to top of file or somewhere better
2207 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2208 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2211 * Returns the most recent statuses posted by the user.
2213 * @brief Returns a user's public timeline
2215 * @param string $type Either "json" or "xml"
2216 * @return string|array
2217 * @throws BadRequestException
2218 * @throws ForbiddenException
2219 * @throws ImagickException
2220 * @throws InternalServerErrorException
2221 * @throws UnauthorizedException
2222 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2224 function api_statuses_user_timeline($type)
2227 $user_info = api_get_user($a);
2229 if (api_user() === false || $user_info === false) {
2230 throw new ForbiddenException();
2234 "api_statuses_user_timeline: api_user: ". api_user() .
2235 "\nuser_info: ".print_r($user_info, true) .
2236 "\n_REQUEST: ".print_r($_REQUEST, true),
2240 $since_id = $_REQUEST['since_id'] ?? 0;
2241 $max_id = $_REQUEST['max_id'] ?? 0;
2242 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2243 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2246 $count = $_REQUEST['count'] ?? 20;
2247 $page = $_REQUEST['page'] ?? 1;
2249 $start = max(0, ($page - 1) * $count);
2251 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2252 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2254 if ($user_info['self'] == 1) {
2255 $condition[0] .= ' AND `item`.`wall` ';
2258 if ($exclude_replies) {
2259 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2262 if ($conversation_id > 0) {
2263 $condition[0] .= " AND `item`.`parent` = ?";
2264 $condition[] = $conversation_id;
2268 $condition[0] .= " AND `item`.`id` <= ?";
2269 $condition[] = $max_id;
2272 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2273 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2275 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2279 $data = ['status' => $ret];
2284 $data = api_rss_extra($a, $data, $user_info);
2288 return api_format_data("statuses", $type, $data);
2291 /// @TODO move to top of file or somewhere better
2292 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2295 * Star/unstar an item.
2296 * param: id : id of the item
2298 * @param string $type Return type (atom, rss, xml, json)
2300 * @return array|string
2301 * @throws BadRequestException
2302 * @throws ForbiddenException
2303 * @throws ImagickException
2304 * @throws InternalServerErrorException
2305 * @throws UnauthorizedException
2306 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2308 function api_favorites_create_destroy($type)
2312 if (api_user() === false) {
2313 throw new ForbiddenException();
2316 // for versioned api.
2317 /// @TODO We need a better global soluton
2318 $action_argv_id = 2;
2319 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2320 $action_argv_id = 3;
2323 if ($a->argc <= $action_argv_id) {
2324 throw new BadRequestException("Invalid request.");
2326 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2327 if ($a->argc == $action_argv_id + 2) {
2328 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2330 $itemid = intval($_REQUEST['id'] ?? 0);
2333 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2335 if (!DBA::isResult($item)) {
2336 throw new BadRequestException("Invalid item.");
2341 $item['starred'] = 1;
2344 $item['starred'] = 0;
2347 throw new BadRequestException("Invalid action ".$action);
2350 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2353 throw new InternalServerErrorException("DB error");
2357 $user_info = api_get_user($a);
2358 $rets = api_format_items([$item], $user_info, false, $type);
2361 $data = ['status' => $ret];
2366 $data = api_rss_extra($a, $data, $user_info);
2370 return api_format_data("status", $type, $data);
2373 /// @TODO move to top of file or somewhere better
2374 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2375 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2378 * Returns the most recent favorite statuses.
2380 * @param string $type Return type (atom, rss, xml, json)
2382 * @return string|array
2383 * @throws BadRequestException
2384 * @throws ForbiddenException
2385 * @throws ImagickException
2386 * @throws InternalServerErrorException
2387 * @throws UnauthorizedException
2389 function api_favorites($type)
2394 $user_info = api_get_user($a);
2396 if (api_user() === false || $user_info === false) {
2397 throw new ForbiddenException();
2402 // in friendica starred item are private
2403 // return favorites only for self
2404 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2406 if ($user_info['self'] == 0) {
2410 $since_id = $_REQUEST['since_id'] ?? 0;
2411 $max_id = $_REQUEST['max_id'] ?? 0;
2412 $count = $_GET['count'] ?? 20;
2413 $page = $_REQUEST['page'] ?? 1;
2415 $start = max(0, ($page - 1) * $count);
2417 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2418 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2420 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2423 $condition[0] .= " AND `item`.`id` <= ?";
2424 $condition[] = $max_id;
2427 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2429 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2434 $data = ['status' => $ret];
2439 $data = api_rss_extra($a, $data, $user_info);
2443 return api_format_data("statuses", $type, $data);
2446 /// @TODO move to top of file or somewhere better
2447 api_register_func('api/favorites', 'api_favorites', true);
2451 * @param array $item
2452 * @param array $recipient
2453 * @param array $sender
2456 * @throws InternalServerErrorException
2458 function api_format_messages($item, $recipient, $sender)
2460 // standard meta information
2462 'id' => $item['id'],
2463 'sender_id' => $sender['id'],
2465 'recipient_id' => $recipient['id'],
2466 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2467 'sender_screen_name' => $sender['screen_name'],
2468 'recipient_screen_name' => $recipient['screen_name'],
2469 'sender' => $sender,
2470 'recipient' => $recipient,
2472 'friendica_seen' => $item['seen'] ?? 0,
2473 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2476 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2477 if (isset($ret['sender']['uid'])) {
2478 unset($ret['sender']['uid']);
2480 if (isset($ret['sender']['self'])) {
2481 unset($ret['sender']['self']);
2483 if (isset($ret['recipient']['uid'])) {
2484 unset($ret['recipient']['uid']);
2486 if (isset($ret['recipient']['self'])) {
2487 unset($ret['recipient']['self']);
2490 //don't send title to regular StatusNET requests to avoid confusing these apps
2491 if (!empty($_GET['getText'])) {
2492 $ret['title'] = $item['title'];
2493 if ($_GET['getText'] == 'html') {
2494 $ret['text'] = BBCode::convert($item['body'], false);
2495 } elseif ($_GET['getText'] == 'plain') {
2496 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2499 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2501 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2502 unset($ret['sender']);
2503 unset($ret['recipient']);
2511 * @param array $item
2514 * @throws InternalServerErrorException
2516 function api_convert_item($item)
2518 $body = $item['body'];
2519 $entities = api_get_entitities($statustext, $body);
2521 // Add pictures to the attachment array and remove them from the body
2522 $attachments = api_get_attachments($body);
2524 // Workaround for ostatus messages where the title is identically to the body
2525 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2526 $statusbody = trim(HTML::toPlaintext($html, 0));
2528 // handle data: images
2529 $statusbody = api_format_items_embeded_images($item, $statusbody);
2531 $statustitle = trim($item['title']);
2533 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2534 $statustext = trim($statusbody);
2536 $statustext = trim($statustitle."\n\n".$statusbody);
2539 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2540 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2543 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2545 // Workaround for clients with limited HTML parser functionality
2546 $search = ["<br>", "<blockquote>", "</blockquote>",
2547 "<h1>", "</h1>", "<h2>", "</h2>",
2548 "<h3>", "</h3>", "<h4>", "</h4>",
2549 "<h5>", "</h5>", "<h6>", "</h6>"];
2550 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2551 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2552 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2553 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2554 $statushtml = str_replace($search, $replace, $statushtml);
2556 if ($item['title'] != "") {
2557 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2561 $oldtext = $statushtml;
2562 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2563 } while ($oldtext != $statushtml);
2565 if (substr($statushtml, 0, 4) == '<br>') {
2566 $statushtml = substr($statushtml, 4);
2569 if (substr($statushtml, 0, -4) == '<br>') {
2570 $statushtml = substr($statushtml, -4);
2573 // feeds without body should contain the link
2574 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2575 $statushtml .= BBCode::convert($item['plink']);
2579 "text" => $statustext,
2580 "html" => $statushtml,
2581 "attachments" => $attachments,
2582 "entities" => $entities
2588 * @param string $body
2591 * @throws InternalServerErrorException
2593 function api_get_attachments(&$body)
2595 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2596 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2598 $URLSearchString = "^\[\]";
2599 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2603 // Remove all embedded pictures, since they are added as attachments
2604 foreach ($images[0] as $orig) {
2605 $body = str_replace($orig, '', $body);
2610 foreach ($images[1] as $image) {
2611 $imagedata = Images::getInfoFromURLCached($image);
2614 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2618 return $attachments;
2623 * @param string $text
2624 * @param string $bbcode
2627 * @throws InternalServerErrorException
2628 * @todo Links at the first character of the post
2630 function api_get_entitities(&$text, $bbcode)
2632 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2634 if ($include_entities != "true") {
2635 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2637 foreach ($images[1] as $image) {
2638 $replace = ProxyUtils::proxifyUrl($image);
2639 $text = str_replace($image, $replace, $text);
2644 $bbcode = BBCode::cleanPictureLinks($bbcode);
2646 // Change pure links in text to bbcode uris
2647 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2650 $entities["hashtags"] = [];
2651 $entities["symbols"] = [];
2652 $entities["urls"] = [];
2653 $entities["user_mentions"] = [];
2655 $URLSearchString = "^\[\]";
2657 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2659 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2660 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2662 $bbcode = preg_replace(
2663 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2664 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2667 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2669 $bbcode = preg_replace(
2670 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2671 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2674 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2676 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2678 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2681 foreach ($urls[1] as $id => $url) {
2682 $start = iconv_strpos($text, $url, 0, "UTF-8");
2683 if (!($start === false)) {
2684 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2688 ksort($ordered_urls);
2692 foreach ($ordered_urls as $url) {
2693 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2694 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2696 $display_url = $url["title"];
2698 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2699 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2701 if (strlen($display_url) > 26) {
2702 $display_url = substr($display_url, 0, 25)."…";
2706 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2707 if (!($start === false)) {
2708 $entities["urls"][] = ["url" => $url["url"],
2709 "expanded_url" => $url["url"],
2710 "display_url" => $display_url,
2711 "indices" => [$start, $start+strlen($url["url"])]];
2712 $offset = $start + 1;
2716 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2717 $ordered_images = [];
2718 foreach ($images as $image) {
2719 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2720 if (!($start === false)) {
2721 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2725 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2726 foreach ($images[1] as $image) {
2727 $start = iconv_strpos($text, $image, 0, "UTF-8");
2728 if (!($start === false)) {
2729 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2735 foreach ($ordered_images as $image) {
2736 $url = $image['url'];
2737 $ext_alt_text = $image['alt'];
2739 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2740 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2742 if (strlen($display_url) > 26) {
2743 $display_url = substr($display_url, 0, 25)."…";
2746 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2747 if (!($start === false)) {
2748 $image = Images::getInfoFromURLCached($url);
2750 // If image cache is activated, then use the following sizes:
2751 // thumb (150), small (340), medium (600) and large (1024)
2752 if (!Config::get("system", "proxy_disabled")) {
2753 $media_url = ProxyUtils::proxifyUrl($url);
2756 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2757 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2759 if (($image[0] > 150) || ($image[1] > 150)) {
2760 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2761 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2764 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2765 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2767 if (($image[0] > 600) || ($image[1] > 600)) {
2768 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2769 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2773 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2776 $entities["media"][] = [
2778 "id_str" => (string) ($start + 1),
2779 "indices" => [$start, $start+strlen($url)],
2780 "media_url" => Strings::normaliseLink($media_url),
2781 "media_url_https" => $media_url,
2783 "display_url" => $display_url,
2784 "expanded_url" => $url,
2785 "ext_alt_text" => $ext_alt_text,
2789 $offset = $start + 1;
2798 * @param array $item
2799 * @param string $text
2803 function api_format_items_embeded_images($item, $text)
2805 $text = preg_replace_callback(
2806 '|data:image/([^;]+)[^=]+=*|m',
2807 function () use ($item) {
2808 return DI::baseUrl() . '/display/' . $item['guid'];
2816 * @brief return <a href='url'>name</a> as array
2818 * @param string $txt text
2823 function api_contactlink_to_array($txt)
2826 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2827 if ($r && count($match)==3) {
2829 'name' => $match[2],
2843 * @brief return likes, dislikes and attend status for item
2845 * @param array $item array
2846 * @param string $type Return type (atom, rss, xml, json)
2849 * likes => int count,
2850 * dislikes => int count
2851 * @throws BadRequestException
2852 * @throws ImagickException
2853 * @throws InternalServerErrorException
2854 * @throws UnauthorizedException
2856 function api_format_items_activities($item, $type = "json")
2865 'attendmaybe' => [],
2869 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2870 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2872 while ($parent_item = Item::fetch($ret)) {
2873 // not used as result should be structured like other user data
2874 //builtin_activity_puller($i, $activities);
2876 // get user data and add it to the array of the activity
2877 $user = api_get_user($a, $parent_item['author-id']);
2878 switch ($parent_item['verb']) {
2879 case Activity::LIKE:
2880 $activities['like'][] = $user;
2882 case Activity::DISLIKE:
2883 $activities['dislike'][] = $user;
2885 case Activity::ATTEND:
2886 $activities['attendyes'][] = $user;
2888 case Activity::ATTENDNO:
2889 $activities['attendno'][] = $user;
2891 case Activity::ATTENDMAYBE:
2892 $activities['attendmaybe'][] = $user;
2894 case Activity::ANNOUNCE:
2895 $activities['announce'][] = $user;
2904 if ($type == "xml") {
2905 $xml_activities = [];
2906 foreach ($activities as $k => $v) {
2907 // change xml element from "like" to "friendica:like"
2908 $xml_activities["friendica:".$k] = $v;
2909 // add user data into xml output
2911 foreach ($v as $user) {
2912 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2915 $activities = $xml_activities;
2923 * @brief return data from profiles
2925 * @param array $profile_row array containing data from db table 'profile'
2927 * @throws InternalServerErrorException
2929 function api_format_items_profiles($profile_row)
2932 'profile_id' => $profile_row['id'],
2933 'profile_name' => $profile_row['profile-name'],
2934 'is_default' => $profile_row['is-default'] ? true : false,
2935 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2936 'profile_photo' => $profile_row['photo'],
2937 'profile_thumb' => $profile_row['thumb'],
2938 'publish' => $profile_row['publish'] ? true : false,
2939 'net_publish' => $profile_row['net-publish'] ? true : false,
2940 'description' => $profile_row['pdesc'],
2941 'date_of_birth' => $profile_row['dob'],
2942 'address' => $profile_row['address'],
2943 'city' => $profile_row['locality'],
2944 'region' => $profile_row['region'],
2945 'postal_code' => $profile_row['postal-code'],
2946 'country' => $profile_row['country-name'],
2947 'hometown' => $profile_row['hometown'],
2948 'gender' => $profile_row['gender'],
2949 'marital' => $profile_row['marital'],
2950 'marital_with' => $profile_row['with'],
2951 'marital_since' => $profile_row['howlong'],
2952 'sexual' => $profile_row['sexual'],
2953 'politic' => $profile_row['politic'],
2954 'religion' => $profile_row['religion'],
2955 'public_keywords' => $profile_row['pub_keywords'],
2956 'private_keywords' => $profile_row['prv_keywords'],
2957 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2958 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2959 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2960 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2961 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2962 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2963 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2964 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2965 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2966 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2967 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2968 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2969 'homepage' => $profile_row['homepage'],
2976 * @brief format items to be returned by api
2978 * @param array $items array of items
2979 * @param array $user_info
2980 * @param bool $filter_user filter items by $user_info
2981 * @param string $type Return type (atom, rss, xml, json)
2983 * @throws BadRequestException
2984 * @throws ImagickException
2985 * @throws InternalServerErrorException
2986 * @throws UnauthorizedException
2988 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2990 $a = Friendica\DI::app();
2994 foreach ((array)$items as $item) {
2995 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2997 // Look if the posts are matching if they should be filtered by user id
2998 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
3002 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
3011 * @param array $item Item record
3012 * @param string $type Return format (atom, rss, xml, json)
3013 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3014 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3015 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3016 * @return array API-formatted status
3017 * @throws BadRequestException
3018 * @throws ImagickException
3019 * @throws InternalServerErrorException
3020 * @throws UnauthorizedException
3022 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3024 $a = Friendica\DI::app();
3026 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3027 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3030 localize_item($item);
3032 $in_reply_to = api_in_reply_to($item);
3034 $converted = api_convert_item($item);
3036 if ($type == "xml") {
3037 $geo = "georss:point";
3043 'text' => $converted["text"],
3044 'truncated' => false,
3045 'created_at'=> api_date($item['created']),
3046 'in_reply_to_status_id' => $in_reply_to['status_id'],
3047 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3048 'source' => (($item['app']) ? $item['app'] : 'web'),
3049 'id' => intval($item['id']),
3050 'id_str' => (string) intval($item['id']),
3051 'in_reply_to_user_id' => $in_reply_to['user_id'],
3052 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3053 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3055 'favorited' => $item['starred'] ? true : false,
3056 'user' => $status_user,
3057 'friendica_author' => $author_user,
3058 'friendica_owner' => $owner_user,
3059 'friendica_private' => $item['private'] == 1,
3060 //'entities' => NULL,
3061 'statusnet_html' => $converted["html"],
3062 'statusnet_conversation_id' => $item['parent'],
3063 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3064 'friendica_activities' => api_format_items_activities($item, $type),
3065 'friendica_title' => $item['title'],
3066 'friendica_html' => BBCode::convert($item['body'], false)
3069 if (count($converted["attachments"]) > 0) {
3070 $status["attachments"] = $converted["attachments"];
3073 if (count($converted["entities"]) > 0) {
3074 $status["entities"] = $converted["entities"];
3077 if ($status["source"] == 'web') {
3078 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3079 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3080 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3083 $retweeted_item = [];
3086 if ($item["id"] == $item["parent"]) {
3087 $body = $item['body'];
3088 $retweeted_item = api_share_as_retweet($item);
3089 if ($body != $item['body']) {
3090 $quoted_item = $retweeted_item;
3091 $retweeted_item = [];
3095 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3096 $announce = api_get_announce($item);
3097 if (!empty($announce)) {
3098 $retweeted_item = $item;
3100 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3104 if (!empty($quoted_item)) {
3105 if ($quoted_item['id'] != $item['id']) {
3106 $quoted_status = api_format_item($quoted_item);
3107 /// @todo Only remove the attachments that are also contained in the quotes status
3108 unset($status['attachments']);
3109 unset($status['entities']);
3111 $conv_quoted = api_convert_item($quoted_item);
3112 $quoted_status = $status;
3113 unset($quoted_status['attachments']);
3114 unset($quoted_status['entities']);
3115 unset($quoted_status['statusnet_conversation_id']);
3116 $quoted_status['text'] = $conv_quoted['text'];
3117 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3119 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3120 } catch (BadRequestException $e) {
3121 // user not found. should be found?
3122 /// @todo check if the user should be always found
3123 $quoted_status["user"] = [];
3126 unset($quoted_status['friendica_author']);
3127 unset($quoted_status['friendica_owner']);
3128 unset($quoted_status['friendica_activities']);
3129 unset($quoted_status['friendica_private']);
3132 if (!empty($retweeted_item)) {
3133 $retweeted_status = $status;
3134 unset($retweeted_status['friendica_author']);
3135 unset($retweeted_status['friendica_owner']);
3136 unset($retweeted_status['friendica_activities']);
3137 unset($retweeted_status['friendica_private']);
3138 unset($retweeted_status['statusnet_conversation_id']);
3139 $status['user'] = $status['friendica_owner'];
3141 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3142 } catch (BadRequestException $e) {
3143 // user not found. should be found?
3144 /// @todo check if the user should be always found
3145 $retweeted_status["user"] = [];
3148 $rt_converted = api_convert_item($retweeted_item);
3150 $retweeted_status['text'] = $rt_converted["text"];
3151 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3152 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3154 if (!empty($quoted_status)) {
3155 $retweeted_status['quoted_status'] = $quoted_status;
3158 $status['friendica_author'] = $retweeted_status['user'];
3159 $status['retweeted_status'] = $retweeted_status;
3160 } elseif (!empty($quoted_status)) {
3161 $root_status = api_convert_item($item);
3163 $status['text'] = $root_status["text"];
3164 $status['statusnet_html'] = $root_status["html"];
3165 $status['quoted_status'] = $quoted_status;
3168 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3169 unset($status["user"]["uid"]);
3170 unset($status["user"]["self"]);
3172 if ($item["coord"] != "") {
3173 $coords = explode(' ', $item["coord"]);
3174 if (count($coords) == 2) {
3175 if ($type == "json") {
3176 $status["geo"] = ['type' => 'Point',
3177 'coordinates' => [(float) $coords[0],
3178 (float) $coords[1]]];
3179 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3180 $status["georss:point"] = $item["coord"];
3189 * Returns the remaining number of API requests available to the user before the API limit is reached.
3191 * @param string $type Return type (atom, rss, xml, json)
3193 * @return array|string
3196 function api_account_rate_limit_status($type)
3198 if ($type == "xml") {
3200 'remaining-hits' => '150',
3201 '@attributes' => ["type" => "integer"],
3202 'hourly-limit' => '150',
3203 '@attributes2' => ["type" => "integer"],
3204 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3205 '@attributes3' => ["type" => "datetime"],
3206 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3207 '@attributes4' => ["type" => "integer"],
3211 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3212 'remaining_hits' => '150',
3213 'hourly_limit' => '150',
3214 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3218 return api_format_data('hash', $type, ['hash' => $hash]);
3221 /// @TODO move to top of file or somewhere better
3222 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3225 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3227 * @param string $type Return type (atom, rss, xml, json)
3229 * @return array|string
3231 function api_help_test($type)
3233 if ($type == 'xml') {
3239 return api_format_data('ok', $type, ["ok" => $ok]);
3242 /// @TODO move to top of file or somewhere better
3243 api_register_func('api/help/test', 'api_help_test', false);
3246 * Returns all lists the user subscribes to.
3248 * @param string $type Return type (atom, rss, xml, json)
3250 * @return array|string
3251 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3253 function api_lists_list($type)
3256 /// @TODO $ret is not filled here?
3257 return api_format_data('lists', $type, ["lists_list" => $ret]);
3260 /// @TODO move to top of file or somewhere better
3261 api_register_func('api/lists/list', 'api_lists_list', true);
3262 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3265 * Returns all groups the user owns.
3267 * @param string $type Return type (atom, rss, xml, json)
3269 * @return array|string
3270 * @throws BadRequestException
3271 * @throws ForbiddenException
3272 * @throws ImagickException
3273 * @throws InternalServerErrorException
3274 * @throws UnauthorizedException
3275 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3277 function api_lists_ownerships($type)
3281 if (api_user() === false) {
3282 throw new ForbiddenException();
3286 $user_info = api_get_user($a);
3287 $uid = $user_info['uid'];
3289 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3291 // loop through all groups
3293 foreach ($groups as $group) {
3294 if ($group['visible']) {
3300 'name' => $group['name'],
3301 'id' => intval($group['id']),
3302 'id_str' => (string) $group['id'],
3303 'user' => $user_info,
3307 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3310 /// @TODO move to top of file or somewhere better
3311 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3314 * Returns recent statuses from users in the specified group.
3316 * @param string $type Return type (atom, rss, xml, json)
3318 * @return array|string
3319 * @throws BadRequestException
3320 * @throws ForbiddenException
3321 * @throws ImagickException
3322 * @throws InternalServerErrorException
3323 * @throws UnauthorizedException
3324 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3326 function api_lists_statuses($type)
3330 $user_info = api_get_user($a);
3331 if (api_user() === false || $user_info === false) {
3332 throw new ForbiddenException();
3335 unset($_REQUEST["user_id"]);
3336 unset($_GET["user_id"]);
3338 unset($_REQUEST["screen_name"]);
3339 unset($_GET["screen_name"]);
3341 if (empty($_REQUEST['list_id'])) {
3342 throw new BadRequestException('list_id not specified');
3346 $count = $_REQUEST['count'] ?? 20;
3347 $page = $_REQUEST['page'] ?? 1;
3348 $since_id = $_REQUEST['since_id'] ?? 0;
3349 $max_id = $_REQUEST['max_id'] ?? 0;
3350 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3351 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3353 $start = max(0, ($page - 1) * $count);
3355 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3356 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3359 $condition[0] .= " AND `item`.`id` <= ?";
3360 $condition[] = $max_id;
3362 if ($exclude_replies > 0) {
3363 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3365 if ($conversation_id > 0) {
3366 $condition[0] .= " AND `item`.`parent` = ?";
3367 $condition[] = $conversation_id;
3370 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3371 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3373 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3375 $data = ['status' => $items];
3380 $data = api_rss_extra($a, $data, $user_info);
3384 return api_format_data("statuses", $type, $data);
3387 /// @TODO move to top of file or somewhere better
3388 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3391 * Considers friends and followers lists to be private and won't return
3392 * anything if any user_id parameter is passed.
3394 * @brief Returns either the friends of the follower list
3396 * @param string $qtype Either "friends" or "followers"
3397 * @return boolean|array
3398 * @throws BadRequestException
3399 * @throws ForbiddenException
3400 * @throws ImagickException
3401 * @throws InternalServerErrorException
3402 * @throws UnauthorizedException
3404 function api_statuses_f($qtype)
3408 if (api_user() === false) {
3409 throw new ForbiddenException();
3413 $count = $_GET['count'] ?? 20;
3414 $page = $_GET['page'] ?? 1;
3416 $start = max(0, ($page - 1) * $count);
3418 $user_info = api_get_user($a);
3420 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3421 /* this is to stop Hotot to load friends multiple times
3422 * I'm not sure if I'm missing return something or
3423 * is a bug in hotot. Workaround, meantime
3427 return array('$users' => $ret);*/
3432 if ($qtype == 'friends') {
3433 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3434 } elseif ($qtype == 'followers') {
3435 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3438 // friends and followers only for self
3439 if ($user_info['self'] == 0) {
3440 $sql_extra = " AND false ";
3443 if ($qtype == 'blocks') {
3444 $sql_filter = 'AND `blocked` AND NOT `pending`';
3445 } elseif ($qtype == 'incoming') {
3446 $sql_filter = 'AND `pending`';
3448 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3466 foreach ($r as $cid) {
3467 $user = api_get_user($a, $cid['nurl']);
3468 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3469 unset($user["uid"]);
3470 unset($user["self"]);
3477 return ['user' => $ret];
3482 * Returns the user's friends.
3484 * @brief Returns the list of friends of the provided user
3486 * @deprecated By Twitter API in favor of friends/list
3488 * @param string $type Either "json" or "xml"
3489 * @return boolean|string|array
3490 * @throws BadRequestException
3491 * @throws ForbiddenException
3493 function api_statuses_friends($type)
3495 $data = api_statuses_f("friends");
3496 if ($data === false) {
3499 return api_format_data("users", $type, $data);
3503 * Returns the user's followers.
3505 * @brief Returns the list of followers of the provided user
3507 * @deprecated By Twitter API in favor of friends/list
3509 * @param string $type Either "json" or "xml"
3510 * @return boolean|string|array
3511 * @throws BadRequestException
3512 * @throws ForbiddenException
3514 function api_statuses_followers($type)
3516 $data = api_statuses_f("followers");
3517 if ($data === false) {
3520 return api_format_data("users", $type, $data);
3523 /// @TODO move to top of file or somewhere better
3524 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3525 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3528 * Returns the list of blocked users
3530 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3532 * @param string $type Either "json" or "xml"
3534 * @return boolean|string|array
3535 * @throws BadRequestException
3536 * @throws ForbiddenException
3538 function api_blocks_list($type)
3540 $data = api_statuses_f('blocks');
3541 if ($data === false) {
3544 return api_format_data("users", $type, $data);
3547 /// @TODO move to top of file or somewhere better
3548 api_register_func('api/blocks/list', 'api_blocks_list', true);
3551 * Returns the list of pending users IDs
3553 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3555 * @param string $type Either "json" or "xml"
3557 * @return boolean|string|array
3558 * @throws BadRequestException
3559 * @throws ForbiddenException
3561 function api_friendships_incoming($type)
3563 $data = api_statuses_f('incoming');
3564 if ($data === false) {
3569 foreach ($data['user'] as $user) {
3570 $ids[] = $user['id'];
3573 return api_format_data("ids", $type, ['id' => $ids]);
3576 /// @TODO move to top of file or somewhere better
3577 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3580 * Returns the instance's configuration information.
3582 * @param string $type Return type (atom, rss, xml, json)
3584 * @return array|string
3585 * @throws InternalServerErrorException
3587 function api_statusnet_config($type)
3589 $name = Config::get('config', 'sitename');
3590 $server = DI::baseUrl()->getHostname();
3591 $logo = DI::baseUrl() . '/images/friendica-64.png';
3592 $email = Config::get('config', 'admin_email');
3593 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3594 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3595 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3596 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3597 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3600 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3601 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3602 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3603 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3604 'shorturllength' => '30',
3606 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3607 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3608 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3609 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3614 return api_format_data('config', $type, ['config' => $config]);
3617 /// @TODO move to top of file or somewhere better
3618 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3619 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3623 * @param string $type Return type (atom, rss, xml, json)
3625 * @return array|string
3627 function api_statusnet_version($type)
3630 $fake_statusnet_version = "0.9.7";
3632 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3635 /// @TODO move to top of file or somewhere better
3636 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3637 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3641 * @param string $type Return type (atom, rss, xml, json)
3643 * @param int $rel A contact relationship constant
3644 * @return array|string|void
3645 * @throws BadRequestException
3646 * @throws ForbiddenException
3647 * @throws ImagickException
3648 * @throws InternalServerErrorException
3649 * @throws UnauthorizedException
3650 * @todo use api_format_data() to return data
3652 function api_ff_ids($type, int $rel)
3655 throw new ForbiddenException();
3662 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3664 $contacts = DBA::p("SELECT `pcontact`.`id`
3666 INNER JOIN `contact` AS `pcontact`
3667 ON `contact`.`nurl` = `pcontact`.`nurl`
3668 AND `pcontact`.`uid` = 0
3669 WHERE `contact`.`uid` = ?
3670 AND NOT `contact`.`self`
3671 AND `contact`.`rel` IN (?, ?)",
3678 foreach (DBA::toArray($contacts) as $contact) {
3679 if ($stringify_ids) {
3680 $ids[] = $contact['id'];
3682 $ids[] = intval($contact['id']);
3686 return api_format_data('ids', $type, ['id' => $ids]);
3690 * Returns the ID of every user the user is following.
3692 * @param string $type Return type (atom, rss, xml, json)
3694 * @return array|string
3695 * @throws BadRequestException
3696 * @throws ForbiddenException
3697 * @throws ImagickException
3698 * @throws InternalServerErrorException
3699 * @throws UnauthorizedException
3700 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3702 function api_friends_ids($type)
3704 return api_ff_ids($type, Contact::SHARING);
3708 * Returns the ID of every user following the user.
3710 * @param string $type Return type (atom, rss, xml, json)
3712 * @return array|string
3713 * @throws BadRequestException
3714 * @throws ForbiddenException
3715 * @throws ImagickException
3716 * @throws InternalServerErrorException
3717 * @throws UnauthorizedException
3718 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3720 function api_followers_ids($type)
3722 return api_ff_ids($type, Contact::FOLLOWER);
3725 /// @TODO move to top of file or somewhere better
3726 api_register_func('api/friends/ids', 'api_friends_ids', true);
3727 api_register_func('api/followers/ids', 'api_followers_ids', true);
3730 * Sends a new direct message.
3732 * @param string $type Return type (atom, rss, xml, json)
3734 * @return array|string
3735 * @throws BadRequestException
3736 * @throws ForbiddenException
3737 * @throws ImagickException
3738 * @throws InternalServerErrorException
3739 * @throws NotFoundException
3740 * @throws UnauthorizedException
3741 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3743 function api_direct_messages_new($type)
3747 if (api_user() === false) {
3748 throw new ForbiddenException();
3751 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3755 $sender = api_get_user($a);
3758 if (!empty($_POST['screen_name'])) {
3760 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3762 DBA::escape($_POST['screen_name'])
3765 if (DBA::isResult($r)) {
3766 // Selecting the id by priority, friendica first
3767 api_best_nickname($r);
3769 $recipient = api_get_user($a, $r[0]['nurl']);
3772 $recipient = api_get_user($a, $_POST['user_id']);
3775 if (empty($recipient)) {
3776 throw new NotFoundException('Recipient not found');
3780 if (!empty($_REQUEST['replyto'])) {
3782 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3784 intval($_REQUEST['replyto'])
3786 $replyto = $r[0]['parent-uri'];
3787 $sub = $r[0]['title'];
3789 if (!empty($_REQUEST['title'])) {
3790 $sub = $_REQUEST['title'];
3792 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3796 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3799 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3800 $ret = api_format_messages($r[0], $recipient, $sender);
3802 $ret = ["error"=>$id];
3805 $data = ['direct_message'=>$ret];
3811 $data = api_rss_extra($a, $data, $sender);
3815 return api_format_data("direct-messages", $type, $data);
3818 /// @TODO move to top of file or somewhere better
3819 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3822 * Destroys a direct message.
3824 * @brief delete a direct_message from mail table through api
3826 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3827 * @return string|array
3828 * @throws BadRequestException
3829 * @throws ForbiddenException
3830 * @throws ImagickException
3831 * @throws InternalServerErrorException
3832 * @throws UnauthorizedException
3833 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3835 function api_direct_messages_destroy($type)
3839 if (api_user() === false) {
3840 throw new ForbiddenException();
3844 $user_info = api_get_user($a);
3846 $id = $_REQUEST['id'] ?? 0;
3848 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3849 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3850 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3852 $uid = $user_info['uid'];
3853 // error if no id or parenturi specified (for clients posting parent-uri as well)
3854 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3855 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3856 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3859 // BadRequestException if no id specified (for clients using Twitter API)
3861 throw new BadRequestException('Message id not specified');
3864 // add parent-uri to sql command if specified by calling app
3865 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3867 // get data of the specified message id
3869 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3874 // error message if specified id is not in database
3875 if (!DBA::isResult($r)) {
3876 if ($verbose == "true") {
3877 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3878 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3880 /// @todo BadRequestException ok for Twitter API clients?
3881 throw new BadRequestException('message id not in database');
3886 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3891 if ($verbose == "true") {
3894 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3895 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3897 $answer = ['result' => 'error', 'message' => 'unknown error'];
3898 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3901 /// @todo return JSON data like Twitter API not yet implemented
3904 /// @TODO move to top of file or somewhere better
3905 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3910 * @brief unfollow contact
3912 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3913 * @return string|array
3914 * @throws BadRequestException
3915 * @throws ForbiddenException
3916 * @throws ImagickException
3917 * @throws InternalServerErrorException
3918 * @throws NotFoundException
3919 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3921 function api_friendships_destroy($type)
3925 if ($uid === false) {
3926 throw new ForbiddenException();
3929 $contact_id = $_REQUEST['user_id'] ?? 0;
3931 if (empty($contact_id)) {
3932 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3933 throw new BadRequestException("no user_id specified");
3936 // Get Contact by given id
3937 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3939 if(!DBA::isResult($contact)) {
3940 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3941 throw new NotFoundException("no contact found to given ID");
3944 $url = $contact["url"];
3946 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3947 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3948 Strings::normaliseLink($url), $url];
3949 $contact = DBA::selectFirst('contact', [], $condition);
3951 if (!DBA::isResult($contact)) {
3952 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3953 throw new NotFoundException("Not following Contact");
3956 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3957 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3958 throw new ExpectationFailedException("Not supported");
3961 $dissolve = ($contact['rel'] == Contact::SHARING);
3963 $owner = User::getOwnerDataById($uid);
3965 Contact::terminateFriendship($owner, $contact, $dissolve);
3968 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3969 throw new NotFoundException("Error Processing Request");
3972 // Sharing-only contacts get deleted as there no relationship any more
3974 Contact::remove($contact['id']);
3976 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3979 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3980 unset($contact["uid"]);
3981 unset($contact["self"]);
3983 // Set screen_name since Twidere requests it
3984 $contact["screen_name"] = $contact["nick"];
3986 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3988 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3992 * @param string $type Return type (atom, rss, xml, json)
3993 * @param string $box
3994 * @param string $verbose
3996 * @return array|string
3997 * @throws BadRequestException
3998 * @throws ForbiddenException
3999 * @throws ImagickException
4000 * @throws InternalServerErrorException
4001 * @throws UnauthorizedException
4003 function api_direct_messages_box($type, $box, $verbose)
4006 if (api_user() === false) {
4007 throw new ForbiddenException();
4010 $count = $_GET['count'] ?? 20;
4011 $page = $_REQUEST['page'] ?? 1;
4013 $since_id = $_REQUEST['since_id'] ?? 0;
4014 $max_id = $_REQUEST['max_id'] ?? 0;
4016 $user_id = $_REQUEST['user_id'] ?? '';
4017 $screen_name = $_REQUEST['screen_name'] ?? '';
4020 unset($_REQUEST["user_id"]);
4021 unset($_GET["user_id"]);
4023 unset($_REQUEST["screen_name"]);
4024 unset($_GET["screen_name"]);
4026 $user_info = api_get_user($a);
4027 if ($user_info === false) {
4028 throw new ForbiddenException();
4030 $profile_url = $user_info["url"];
4033 $start = max(0, ($page - 1) * $count);
4038 if ($box=="sentbox") {
4039 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4040 } elseif ($box == "conversation") {
4041 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4042 } elseif ($box == "all") {
4043 $sql_extra = "true";
4044 } elseif ($box == "inbox") {
4045 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4049 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4052 if ($user_id != "") {
4053 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4054 } elseif ($screen_name !="") {
4055 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4059 "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",
4065 if ($verbose == "true" && !DBA::isResult($r)) {
4066 $answer = ['result' => 'error', 'message' => 'no mails available'];
4067 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4071 foreach ($r as $item) {
4072 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4073 $recipient = $user_info;
4074 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4075 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4076 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4077 $sender = $user_info;
4080 if (isset($recipient) && isset($sender)) {
4081 $ret[] = api_format_messages($item, $recipient, $sender);
4086 $data = ['direct_message' => $ret];
4091 $data = api_rss_extra($a, $data, $user_info);
4095 return api_format_data("direct-messages", $type, $data);
4099 * Returns the most recent direct messages sent by the user.
4101 * @param string $type Return type (atom, rss, xml, json)
4103 * @return array|string
4104 * @throws BadRequestException
4105 * @throws ForbiddenException
4106 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4108 function api_direct_messages_sentbox($type)
4110 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4111 return api_direct_messages_box($type, "sentbox", $verbose);
4115 * Returns the most recent direct messages sent to the user.
4117 * @param string $type Return type (atom, rss, xml, json)
4119 * @return array|string
4120 * @throws BadRequestException
4121 * @throws ForbiddenException
4122 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4124 function api_direct_messages_inbox($type)
4126 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4127 return api_direct_messages_box($type, "inbox", $verbose);
4132 * @param string $type Return type (atom, rss, xml, json)
4134 * @return array|string
4135 * @throws BadRequestException
4136 * @throws ForbiddenException
4138 function api_direct_messages_all($type)
4140 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4141 return api_direct_messages_box($type, "all", $verbose);
4146 * @param string $type Return type (atom, rss, xml, json)
4148 * @return array|string
4149 * @throws BadRequestException
4150 * @throws ForbiddenException
4152 function api_direct_messages_conversation($type)
4154 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4155 return api_direct_messages_box($type, "conversation", $verbose);
4158 /// @TODO move to top of file or somewhere better
4159 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4160 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4161 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4162 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4165 * Returns an OAuth Request Token.
4167 * @see https://oauth.net/core/1.0/#auth_step1
4169 function api_oauth_request_token()
4171 $oauth1 = new FKOAuth1();
4173 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4174 } catch (Exception $e) {
4175 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4183 * Returns an OAuth Access Token.
4185 * @return array|string
4186 * @see https://oauth.net/core/1.0/#auth_step3
4188 function api_oauth_access_token()
4190 $oauth1 = new FKOAuth1();
4192 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4193 } catch (Exception $e) {
4194 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4201 /// @TODO move to top of file or somewhere better
4202 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4203 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4207 * @brief delete a complete photoalbum with all containing photos from database through api
4209 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4210 * @return string|array
4211 * @throws BadRequestException
4212 * @throws ForbiddenException
4213 * @throws InternalServerErrorException
4215 function api_fr_photoalbum_delete($type)
4217 if (api_user() === false) {
4218 throw new ForbiddenException();
4221 $album = $_REQUEST['album'] ?? '';
4223 // we do not allow calls without album string
4225 throw new BadRequestException("no albumname specified");
4227 // check if album is existing
4229 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4233 if (!DBA::isResult($r)) {
4234 throw new BadRequestException("album not available");
4237 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4238 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4239 foreach ($r as $rr) {
4240 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4241 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4243 if (!DBA::isResult($photo_item)) {
4244 throw new InternalServerErrorException("problem with deleting items occured");
4246 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4249 // now let's delete all photos from the album
4250 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4252 // return success of deletion or error message
4254 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4255 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4257 throw new InternalServerErrorException("unknown error - deleting from database failed");
4262 * @brief update the name of the album for all photos of an album
4264 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4265 * @return string|array
4266 * @throws BadRequestException
4267 * @throws ForbiddenException
4268 * @throws InternalServerErrorException
4270 function api_fr_photoalbum_update($type)
4272 if (api_user() === false) {
4273 throw new ForbiddenException();
4276 $album = $_REQUEST['album'] ?? '';
4277 $album_new = $_REQUEST['album_new'] ?? '';
4279 // we do not allow calls without album string
4281 throw new BadRequestException("no albumname specified");
4283 if ($album_new == "") {
4284 throw new BadRequestException("no new albumname specified");
4286 // check if album is existing
4287 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4288 throw new BadRequestException("album not available");
4290 // now let's update all photos to the albumname
4291 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4293 // return success of updating or error message
4295 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4296 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4298 throw new InternalServerErrorException("unknown error - updating in database failed");
4304 * @brief list all photos of the authenticated user
4306 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4307 * @return string|array
4308 * @throws ForbiddenException
4309 * @throws InternalServerErrorException
4311 function api_fr_photos_list($type)
4313 if (api_user() === false) {
4314 throw new ForbiddenException();
4317 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4318 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4319 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4320 intval(local_user())
4323 'image/jpeg' => 'jpg',
4324 'image/png' => 'png',
4325 'image/gif' => 'gif'
4327 $data = ['photo'=>[]];
4328 if (DBA::isResult($r)) {
4329 foreach ($r as $rr) {
4331 $photo['id'] = $rr['resource-id'];
4332 $photo['album'] = $rr['album'];
4333 $photo['filename'] = $rr['filename'];
4334 $photo['type'] = $rr['type'];
4335 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4336 $photo['created'] = $rr['created'];
4337 $photo['edited'] = $rr['edited'];
4338 $photo['desc'] = $rr['desc'];
4340 if ($type == "xml") {
4341 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4343 $photo['thumb'] = $thumb;
4344 $data['photo'][] = $photo;
4348 return api_format_data("photos", $type, $data);
4352 * @brief upload a new photo or change an existing photo
4354 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4355 * @return string|array
4356 * @throws BadRequestException
4357 * @throws ForbiddenException
4358 * @throws ImagickException
4359 * @throws InternalServerErrorException
4360 * @throws NotFoundException
4362 function api_fr_photo_create_update($type)
4364 if (api_user() === false) {
4365 throw new ForbiddenException();
4368 $photo_id = $_REQUEST['photo_id'] ?? null;
4369 $desc = $_REQUEST['desc'] ?? null;
4370 $album = $_REQUEST['album'] ?? null;
4371 $album_new = $_REQUEST['album_new'] ?? null;
4372 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4373 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4374 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4375 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4376 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4378 // do several checks on input parameters
4379 // we do not allow calls without album string
4380 if ($album == null) {
4381 throw new BadRequestException("no albumname specified");
4383 // if photo_id == null --> we are uploading a new photo
4384 if ($photo_id == null) {
4387 // error if no media posted in create-mode
4388 if (empty($_FILES['media'])) {
4390 throw new BadRequestException("no media data submitted");
4393 // album_new will be ignored in create-mode
4398 // check if photo is existing in databasei
4399 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4400 throw new BadRequestException("photo not available");
4404 // checks on acl strings provided by clients
4405 $acl_input_error = false;
4406 $acl_input_error |= check_acl_input($allow_cid);
4407 $acl_input_error |= check_acl_input($deny_cid);
4408 $acl_input_error |= check_acl_input($allow_gid);
4409 $acl_input_error |= check_acl_input($deny_gid);
4410 if ($acl_input_error) {
4411 throw new BadRequestException("acl data invalid");
4413 // now let's upload the new media in create-mode
4414 if ($mode == "create") {
4415 $media = $_FILES['media'];
4416 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4418 // return success of updating or error message
4419 if (!is_null($data)) {
4420 return api_format_data("photo_create", $type, $data);
4422 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4426 // now let's do the changes in update-mode
4427 if ($mode == "update") {
4428 $updated_fields = [];
4430 if (!is_null($desc)) {
4431 $updated_fields['desc'] = $desc;
4434 if (!is_null($album_new)) {
4435 $updated_fields['album'] = $album_new;
4438 if (!is_null($allow_cid)) {
4439 $allow_cid = trim($allow_cid);
4440 $updated_fields['allow_cid'] = $allow_cid;
4443 if (!is_null($deny_cid)) {
4444 $deny_cid = trim($deny_cid);
4445 $updated_fields['deny_cid'] = $deny_cid;
4448 if (!is_null($allow_gid)) {
4449 $allow_gid = trim($allow_gid);
4450 $updated_fields['allow_gid'] = $allow_gid;
4453 if (!is_null($deny_gid)) {
4454 $deny_gid = trim($deny_gid);
4455 $updated_fields['deny_gid'] = $deny_gid;
4459 if (count($updated_fields) > 0) {
4460 $nothingtodo = false;
4461 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4463 $nothingtodo = true;
4466 if (!empty($_FILES['media'])) {
4467 $nothingtodo = false;
4468 $media = $_FILES['media'];
4469 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4470 if (!is_null($data)) {
4471 return api_format_data("photo_update", $type, $data);
4475 // return success of updating or error message
4477 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4478 return api_format_data("photo_update", $type, ['$result' => $answer]);
4481 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4482 return api_format_data("photo_update", $type, ['$result' => $answer]);
4484 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4487 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4491 * @brief delete a single photo from the database through api
4493 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4494 * @return string|array
4495 * @throws BadRequestException
4496 * @throws ForbiddenException
4497 * @throws InternalServerErrorException
4499 function api_fr_photo_delete($type)
4501 if (api_user() === false) {
4502 throw new ForbiddenException();
4506 $photo_id = $_REQUEST['photo_id'] ?? null;
4508 // do several checks on input parameters
4509 // we do not allow calls without photo id
4510 if ($photo_id == null) {
4511 throw new BadRequestException("no photo_id specified");
4514 // check if photo is existing in database
4515 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4516 throw new BadRequestException("photo not available");
4519 // now we can perform on the deletion of the photo
4520 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4522 // return success of deletion or error message
4524 // retrieve the id of the parent element (the photo element)
4525 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4526 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4528 if (!DBA::isResult($photo_item)) {
4529 throw new InternalServerErrorException("problem with deleting items occured");
4531 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4532 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4533 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4535 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4536 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4538 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4544 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4546 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4547 * @return string|array
4548 * @throws BadRequestException
4549 * @throws ForbiddenException
4550 * @throws InternalServerErrorException
4551 * @throws NotFoundException
4553 function api_fr_photo_detail($type)
4555 if (api_user() === false) {
4556 throw new ForbiddenException();
4558 if (empty($_REQUEST['photo_id'])) {
4559 throw new BadRequestException("No photo id.");
4562 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4563 $photo_id = $_REQUEST['photo_id'];
4565 // prepare json/xml output with data from database for the requested photo
4566 $data = prepare_photo_data($type, $scale, $photo_id);
4568 return api_format_data("photo_detail", $type, $data);
4573 * Updates the user’s profile image.
4575 * @brief updates the profile image for the user (either a specified profile or the default profile)
4577 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4579 * @return string|array
4580 * @throws BadRequestException
4581 * @throws ForbiddenException
4582 * @throws ImagickException
4583 * @throws InternalServerErrorException
4584 * @throws NotFoundException
4585 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4587 function api_account_update_profile_image($type)
4589 if (api_user() === false) {
4590 throw new ForbiddenException();
4593 $profile_id = $_REQUEST['profile_id'] ?? 0;
4595 // error if image data is missing
4596 if (empty($_FILES['image'])) {
4597 throw new BadRequestException("no media data submitted");
4600 // check if specified profile id is valid
4601 if ($profile_id != 0) {
4602 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4603 // error message if specified profile id is not in database
4604 if (!DBA::isResult($profile)) {
4605 throw new BadRequestException("profile_id not available");
4607 $is_default_profile = $profile['is-default'];
4609 $is_default_profile = 1;
4612 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4614 if (!empty($_FILES['image'])) {
4615 $media = $_FILES['image'];
4616 } elseif (!empty($_FILES['media'])) {
4617 $media = $_FILES['media'];
4619 // save new profile image
4620 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4623 if (is_array($media['type'])) {
4624 $filetype = $media['type'][0];
4626 $filetype = $media['type'];
4628 if ($filetype == "image/jpeg") {
4630 } elseif ($filetype == "image/png") {
4633 throw new InternalServerErrorException('Unsupported filetype');
4636 // change specified profile or all profiles to the new resource-id
4637 if ($is_default_profile) {
4638 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4639 Photo::update(['profile' => false], $condition);
4641 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4642 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4643 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4646 Contact::updateSelfFromUserID(api_user(), true);
4648 // Update global directory in background
4649 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4650 if ($url && strlen(Config::get('system', 'directory'))) {
4651 Worker::add(PRIORITY_LOW, "Directory", $url);
4654 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4656 // output for client
4658 return api_account_verify_credentials($type);
4660 // SaveMediaToDatabase failed for some reason
4661 throw new InternalServerErrorException("image upload failed");
4665 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4666 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4667 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4668 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4669 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4670 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4671 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4672 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4673 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4676 * Update user profile
4678 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4680 * @return array|string
4681 * @throws BadRequestException
4682 * @throws ForbiddenException
4683 * @throws ImagickException
4684 * @throws InternalServerErrorException
4685 * @throws UnauthorizedException
4687 function api_account_update_profile($type)
4689 $local_user = api_user();
4690 $api_user = api_get_user(DI::app());
4692 if (!empty($_POST['name'])) {
4693 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4694 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4695 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4696 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4699 if (isset($_POST['description'])) {
4700 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4701 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4702 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4705 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4706 // Update global directory in background
4707 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4708 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4711 return api_account_verify_credentials($type);
4714 /// @TODO move to top of file or somewhere better
4715 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4719 * @param string $acl_string
4723 function check_acl_input($acl_string)
4725 if (empty($acl_string)) {
4729 $contact_not_found = false;
4731 // split <x><y><z> into array of cid's
4732 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4734 // check for each cid if it is available on server
4735 $cid_array = $array[0];
4736 foreach ($cid_array as $cid) {
4737 $cid = str_replace("<", "", $cid);
4738 $cid = str_replace(">", "", $cid);
4739 $condition = ['id' => $cid, 'uid' => api_user()];
4740 $contact_not_found |= !DBA::exists('contact', $condition);
4742 return $contact_not_found;
4746 * @param string $mediatype
4747 * @param array $media
4748 * @param string $type
4749 * @param string $album
4750 * @param string $allow_cid
4751 * @param string $deny_cid
4752 * @param string $allow_gid
4753 * @param string $deny_gid
4754 * @param string $desc
4755 * @param integer $profile
4756 * @param boolean $visibility
4757 * @param string $photo_id
4759 * @throws BadRequestException
4760 * @throws ForbiddenException
4761 * @throws ImagickException
4762 * @throws InternalServerErrorException
4763 * @throws NotFoundException
4764 * @throws UnauthorizedException
4766 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)
4774 if (is_array($media)) {
4775 if (is_array($media['tmp_name'])) {
4776 $src = $media['tmp_name'][0];
4778 $src = $media['tmp_name'];
4780 if (is_array($media['name'])) {
4781 $filename = basename($media['name'][0]);
4783 $filename = basename($media['name']);
4785 if (is_array($media['size'])) {
4786 $filesize = intval($media['size'][0]);
4788 $filesize = intval($media['size']);
4790 if (is_array($media['type'])) {
4791 $filetype = $media['type'][0];
4793 $filetype = $media['type'];
4797 if ($filetype == "") {
4798 $filetype = Images::guessType($filename);
4800 $imagedata = @getimagesize($src);
4802 $filetype = $imagedata['mime'];
4805 "File upload src: " . $src . " - filename: " . $filename .
4806 " - size: " . $filesize . " - type: " . $filetype,
4810 // check if there was a php upload error
4811 if ($filesize == 0 && $media['error'] == 1) {
4812 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4814 // check against max upload size within Friendica instance
4815 $maximagesize = Config::get('system', 'maximagesize');
4816 if ($maximagesize && ($filesize > $maximagesize)) {
4817 $formattedBytes = Strings::formatBytes($maximagesize);
4818 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4821 // create Photo instance with the data of the image
4822 $imagedata = @file_get_contents($src);
4823 $Image = new Image($imagedata, $filetype);
4824 if (!$Image->isValid()) {
4825 throw new InternalServerErrorException("unable to process image data");
4828 // check orientation of image
4829 $Image->orient($src);
4832 // check max length of images on server
4833 $max_length = Config::get('system', 'max_image_length');
4835 $max_length = MAX_IMAGE_LENGTH;
4837 if ($max_length > 0) {
4838 $Image->scaleDown($max_length);
4839 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4841 $width = $Image->getWidth();
4842 $height = $Image->getHeight();
4844 // create a new resource-id if not already provided
4845 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4847 if ($mediatype == "photo") {
4848 // upload normal image (scales 0, 1, 2)
4849 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4851 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4853 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4855 if ($width > 640 || $height > 640) {
4856 $Image->scaleDown(640);
4857 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4859 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4863 if ($width > 320 || $height > 320) {
4864 $Image->scaleDown(320);
4865 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4867 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4870 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4871 } elseif ($mediatype == "profileimage") {
4872 // upload profile image (scales 4, 5, 6)
4873 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4875 if ($width > 300 || $height > 300) {
4876 $Image->scaleDown(300);
4877 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4879 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4883 if ($width > 80 || $height > 80) {
4884 $Image->scaleDown(80);
4885 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4887 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4891 if ($width > 48 || $height > 48) {
4892 $Image->scaleDown(48);
4893 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4895 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4898 $Image->__destruct();
4899 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4902 if (isset($r) && $r) {
4903 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4904 if ($photo_id == null && $mediatype == "photo") {
4905 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4907 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4908 return prepare_photo_data($type, false, $resource_id);
4910 throw new InternalServerErrorException("image upload failed");
4916 * @param string $hash
4917 * @param string $allow_cid
4918 * @param string $deny_cid
4919 * @param string $allow_gid
4920 * @param string $deny_gid
4921 * @param string $filetype
4922 * @param boolean $visibility
4923 * @throws InternalServerErrorException
4925 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4927 // get data about the api authenticated user
4928 $uri = Item::newURI(intval(api_user()));
4929 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4932 $arr['guid'] = System::createUUID();
4933 $arr['uid'] = intval(api_user());
4935 $arr['parent-uri'] = $uri;
4936 $arr['type'] = 'photo';
4938 $arr['resource-id'] = $hash;
4939 $arr['contact-id'] = $owner_record['id'];
4940 $arr['owner-name'] = $owner_record['name'];
4941 $arr['owner-link'] = $owner_record['url'];
4942 $arr['owner-avatar'] = $owner_record['thumb'];
4943 $arr['author-name'] = $owner_record['name'];
4944 $arr['author-link'] = $owner_record['url'];
4945 $arr['author-avatar'] = $owner_record['thumb'];
4947 $arr['allow_cid'] = $allow_cid;
4948 $arr['allow_gid'] = $allow_gid;
4949 $arr['deny_cid'] = $deny_cid;
4950 $arr['deny_gid'] = $deny_gid;
4951 $arr['visible'] = $visibility;
4955 'image/jpeg' => 'jpg',
4956 'image/png' => 'png',
4957 'image/gif' => 'gif'
4960 // adds link to the thumbnail scale photo
4961 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4962 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4965 // do the magic for storing the item in the database and trigger the federation to other contacts
4971 * @param string $type
4973 * @param string $photo_id
4976 * @throws BadRequestException
4977 * @throws ForbiddenException
4978 * @throws ImagickException
4979 * @throws InternalServerErrorException
4980 * @throws NotFoundException
4981 * @throws UnauthorizedException
4983 function prepare_photo_data($type, $scale, $photo_id)
4986 $user_info = api_get_user($a);
4988 if ($user_info === false) {
4989 throw new ForbiddenException();
4992 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4993 $data_sql = ($scale === false ? "" : "data, ");
4995 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4996 // clients needs to convert this in their way for further processing
4998 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4999 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
5000 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
5001 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
5002 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
5003 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
5005 intval(local_user()),
5006 DBA::escape($photo_id),
5011 'image/jpeg' => 'jpg',
5012 'image/png' => 'png',
5013 'image/gif' => 'gif'
5016 // prepare output data for photo
5017 if (DBA::isResult($r)) {
5018 $data = ['photo' => $r[0]];
5019 $data['photo']['id'] = $data['photo']['resource-id'];
5020 if ($scale !== false) {
5021 $data['photo']['data'] = base64_encode($data['photo']['data']);
5023 unset($data['photo']['datasize']); //needed only with scale param
5025 if ($type == "xml") {
5026 $data['photo']['links'] = [];
5027 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5028 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5030 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5033 $data['photo']['link'] = [];
5034 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5036 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5037 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5041 unset($data['photo']['resource-id']);
5042 unset($data['photo']['minscale']);
5043 unset($data['photo']['maxscale']);
5045 throw new NotFoundException();
5048 // retrieve item element for getting activities (like, dislike etc.) related to photo
5049 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5050 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5052 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5054 // retrieve comments on photo
5055 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5056 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5058 $statuses = Item::selectForUser(api_user(), [], $condition);
5060 // prepare output of comments
5061 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5063 if ($type == "xml") {
5065 foreach ($commentData as $comment) {
5066 $comments[$k++ . ":comment"] = $comment;
5069 foreach ($commentData as $comment) {
5070 $comments[] = $comment;
5073 $data['photo']['friendica_comments'] = $comments;
5075 // include info if rights on photo and rights on item are mismatching
5076 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5077 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5078 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5079 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5080 $data['photo']['rights_mismatch'] = $rights_mismatch;
5087 * Similar as /mod/redir.php
5088 * redirect to 'url' after dfrn auth
5090 * Why this when there is mod/redir.php already?
5091 * This use api_user() and api_login()
5094 * c_url: url of remote contact to auth to
5095 * url: string, url to redirect after auth
5097 function api_friendica_remoteauth()
5099 $url = $_GET['url'] ?? '';
5100 $c_url = $_GET['c_url'] ?? '';
5102 if ($url === '' || $c_url === '') {
5103 throw new BadRequestException("Wrong parameters.");
5106 $c_url = Strings::normaliseLink($c_url);
5110 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5111 if (!DBA::isResult($contact)) {
5112 throw new BadRequestException("Unknown contact");
5115 $cid = $contact['id'];
5117 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5119 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5120 System::externalRedirect($url ?: $c_url);
5123 if ($contact['duplex'] && $contact['issued-id']) {
5124 $orig_id = $contact['issued-id'];
5125 $dfrn_id = '1:' . $orig_id;
5127 if ($contact['duplex'] && $contact['dfrn-id']) {
5128 $orig_id = $contact['dfrn-id'];
5129 $dfrn_id = '0:' . $orig_id;
5132 $sec = Strings::getRandomHex();
5134 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5135 'sec' => $sec, 'expire' => time() + 45];
5136 DBA::insert('profile_check', $fields);
5138 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5139 $dest = ($url ? '&destination_url=' . $url : '');
5141 System::externalRedirect(
5142 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5143 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5144 . '&type=profile&sec=' . $sec . $dest
5147 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5150 * Return an item with announcer data if it had been announced
5152 * @param array $item Item array
5153 * @return array Item array with announce data
5155 function api_get_announce($item)
5157 // Quit if the item already has got a different owner and author
5158 if ($item['owner-id'] != $item['author-id']) {
5162 // Don't change original or Diaspora posts
5163 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5167 // Quit if we do now the original author and it had been a post from a native network
5168 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5172 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5173 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5174 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5175 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5176 if (!DBA::isResult($announce)) {
5180 return array_merge($item, $announce);
5184 * @brief Return the item shared, if the item contains only the [share] tag
5186 * @param array $item Sharer item
5187 * @return array|false Shared item or false if not a reshare
5188 * @throws ImagickException
5189 * @throws InternalServerErrorException
5191 function api_share_as_retweet(&$item)
5193 $body = trim($item["body"]);
5195 if (Diaspora::isReshare($body, false) === false) {
5196 if ($item['author-id'] == $item['owner-id']) {
5199 // Reshares from OStatus, ActivityPub and Twitter
5200 $reshared_item = $item;
5201 $reshared_item['owner-id'] = $reshared_item['author-id'];
5202 $reshared_item['owner-link'] = $reshared_item['author-link'];
5203 $reshared_item['owner-name'] = $reshared_item['author-name'];
5204 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5205 return $reshared_item;
5209 $reshared = Item::getShareArray($item);
5210 if (empty($reshared)) {
5214 $reshared_item = $item;
5216 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5220 if (!empty($reshared['comment'])) {
5221 $item['body'] = $reshared['comment'];
5224 $reshared_item["share-pre-body"] = $reshared['comment'];
5225 $reshared_item["body"] = $reshared['shared'];
5226 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5227 $reshared_item["author-name"] = $reshared['author'];
5228 $reshared_item["author-link"] = $reshared['profile'];
5229 $reshared_item["author-avatar"] = $reshared['avatar'];
5230 $reshared_item["plink"] = $reshared['link'] ?? '';
5231 $reshared_item["created"] = $reshared['posted'];
5232 $reshared_item["edited"] = $reshared['posted'];
5234 // Try to fetch the original item
5235 if (!empty($reshared['guid'])) {
5236 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5237 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5238 $condition = ['id' => $original_id];
5243 if (!empty($condition)) {
5244 $original_item = Item::selectFirst([], $condition);
5245 if (DBA::isResult($original_item)) {
5246 $reshared_item = array_merge($reshared_item, $original_item);
5250 return $reshared_item;
5255 * @param array $item
5260 function api_in_reply_to($item)
5264 $in_reply_to['status_id'] = null;
5265 $in_reply_to['user_id'] = null;
5266 $in_reply_to['status_id_str'] = null;
5267 $in_reply_to['user_id_str'] = null;
5268 $in_reply_to['screen_name'] = null;
5270 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5271 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5272 if (DBA::isResult($parent)) {
5273 $in_reply_to['status_id'] = intval($parent['id']);
5275 $in_reply_to['status_id'] = intval($item['parent']);
5278 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5280 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5281 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5283 if (DBA::isResult($parent)) {
5284 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5285 $in_reply_to['user_id'] = intval($parent['author-id']);
5286 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5289 // There seems to be situation, where both fields are identical:
5290 // https://github.com/friendica/friendica/issues/1010
5291 // This is a bugfix for that.
5292 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5293 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']]);
5294 $in_reply_to['status_id'] = null;
5295 $in_reply_to['user_id'] = null;
5296 $in_reply_to['status_id_str'] = null;
5297 $in_reply_to['user_id_str'] = null;
5298 $in_reply_to['screen_name'] = null;
5302 return $in_reply_to;
5307 * @param string $text
5310 * @throws InternalServerErrorException
5312 function api_clean_plain_items($text)
5314 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5316 $text = BBCode::cleanPictureLinks($text);
5317 $URLSearchString = "^\[\]";
5319 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5321 if ($include_entities == "true") {
5322 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5325 // Simplify "attachment" element
5326 $text = BBCode::removeAttachment($text);
5333 * @param array $contacts
5337 function api_best_nickname(&$contacts)
5341 if (count($contacts) == 0) {
5345 foreach ($contacts as $contact) {
5346 if ($contact["network"] == "") {
5347 $contact["network"] = "dfrn";
5348 $best_contact = [$contact];
5352 if (sizeof($best_contact) == 0) {
5353 foreach ($contacts as $contact) {
5354 if ($contact["network"] == "dfrn") {
5355 $best_contact = [$contact];
5360 if (sizeof($best_contact) == 0) {
5361 foreach ($contacts as $contact) {
5362 if ($contact["network"] == "dspr") {
5363 $best_contact = [$contact];
5368 if (sizeof($best_contact) == 0) {
5369 foreach ($contacts as $contact) {
5370 if ($contact["network"] == "stat") {
5371 $best_contact = [$contact];
5376 if (sizeof($best_contact) == 0) {
5377 foreach ($contacts as $contact) {
5378 if ($contact["network"] == "pump") {
5379 $best_contact = [$contact];
5384 if (sizeof($best_contact) == 0) {
5385 foreach ($contacts as $contact) {
5386 if ($contact["network"] == "twit") {
5387 $best_contact = [$contact];
5392 if (sizeof($best_contact) == 1) {
5393 $contacts = $best_contact;
5395 $contacts = [$contacts[0]];
5400 * Return all or a specified group of the user with the containing contacts.
5402 * @param string $type Return type (atom, rss, xml, json)
5404 * @return array|string
5405 * @throws BadRequestException
5406 * @throws ForbiddenException
5407 * @throws ImagickException
5408 * @throws InternalServerErrorException
5409 * @throws UnauthorizedException
5411 function api_friendica_group_show($type)
5415 if (api_user() === false) {
5416 throw new ForbiddenException();
5420 $user_info = api_get_user($a);
5421 $gid = $_REQUEST['gid'] ?? 0;
5422 $uid = $user_info['uid'];
5424 // get data of the specified group id or all groups if not specified
5427 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5431 // error message if specified gid is not in database
5432 if (!DBA::isResult($r)) {
5433 throw new BadRequestException("gid not available");
5437 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5442 // loop through all groups and retrieve all members for adding data in the user array
5444 foreach ($r as $rr) {
5445 $members = Contact::getByGroupId($rr['id']);
5448 if ($type == "xml") {
5449 $user_element = "users";
5451 foreach ($members as $member) {
5452 $user = api_get_user($a, $member['nurl']);
5453 $users[$k++.":user"] = $user;
5456 $user_element = "user";
5457 foreach ($members as $member) {
5458 $user = api_get_user($a, $member['nurl']);
5462 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5464 return api_format_data("groups", $type, ['group' => $grps]);
5466 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5470 * Delete the specified group of the user.
5472 * @param string $type Return type (atom, rss, xml, json)
5474 * @return array|string
5475 * @throws BadRequestException
5476 * @throws ForbiddenException
5477 * @throws ImagickException
5478 * @throws InternalServerErrorException
5479 * @throws UnauthorizedException
5481 function api_friendica_group_delete($type)
5485 if (api_user() === false) {
5486 throw new ForbiddenException();
5490 $user_info = api_get_user($a);
5491 $gid = $_REQUEST['gid'] ?? 0;
5492 $name = $_REQUEST['name'] ?? '';
5493 $uid = $user_info['uid'];
5495 // error if no gid specified
5496 if ($gid == 0 || $name == "") {
5497 throw new BadRequestException('gid or name not specified');
5500 // get data of the specified group id
5502 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5506 // error message if specified gid is not in database
5507 if (!DBA::isResult($r)) {
5508 throw new BadRequestException('gid not available');
5511 // get data of the specified group id and group name
5513 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5518 // error message if specified gid is not in database
5519 if (!DBA::isResult($rname)) {
5520 throw new BadRequestException('wrong group name');
5524 $ret = Group::removeByName($uid, $name);
5527 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5528 return api_format_data("group_delete", $type, ['result' => $success]);
5530 throw new BadRequestException('other API error');
5533 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5538 * @param string $type Return type (atom, rss, xml, json)
5540 * @return array|string
5541 * @throws BadRequestException
5542 * @throws ForbiddenException
5543 * @throws ImagickException
5544 * @throws InternalServerErrorException
5545 * @throws UnauthorizedException
5546 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5548 function api_lists_destroy($type)
5552 if (api_user() === false) {
5553 throw new ForbiddenException();
5557 $user_info = api_get_user($a);
5558 $gid = $_REQUEST['list_id'] ?? 0;
5559 $uid = $user_info['uid'];
5561 // error if no gid specified
5563 throw new BadRequestException('gid not specified');
5566 // get data of the specified group id
5567 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5568 // error message if specified gid is not in database
5570 throw new BadRequestException('gid not available');
5573 if (Group::remove($gid)) {
5575 'name' => $group['name'],
5576 'id' => intval($gid),
5577 'id_str' => (string) $gid,
5578 'user' => $user_info
5581 return api_format_data("lists", $type, ['lists' => $list]);
5584 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5587 * Add a new group to the database.
5589 * @param string $name Group name
5590 * @param int $uid User ID
5591 * @param array $users List of users to add to the group
5594 * @throws BadRequestException
5596 function group_create($name, $uid, $users = [])
5598 // error if no name specified
5600 throw new BadRequestException('group name not specified');
5603 // get data of the specified group name
5605 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5609 // error message if specified group name already exists
5610 if (DBA::isResult($rname)) {
5611 throw new BadRequestException('group name already exists');
5614 // check if specified group name is a deleted group
5616 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5620 // error message if specified group name already exists
5621 if (DBA::isResult($rname)) {
5622 $reactivate_group = true;
5626 $ret = Group::create($uid, $name);
5628 $gid = Group::getIdByName($uid, $name);
5630 throw new BadRequestException('other API error');
5634 $erroraddinguser = false;
5636 foreach ($users as $user) {
5637 $cid = $user['cid'];
5638 // check if user really exists as contact
5640 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5644 if (count($contact)) {
5645 Group::addMember($gid, $cid);
5647 $erroraddinguser = true;
5648 $errorusers[] = $cid;
5652 // return success message incl. missing users in array
5653 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5655 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5659 * Create the specified group with the posted array of contacts.
5661 * @param string $type Return type (atom, rss, xml, json)
5663 * @return array|string
5664 * @throws BadRequestException
5665 * @throws ForbiddenException
5666 * @throws ImagickException
5667 * @throws InternalServerErrorException
5668 * @throws UnauthorizedException
5670 function api_friendica_group_create($type)
5674 if (api_user() === false) {
5675 throw new ForbiddenException();
5679 $user_info = api_get_user($a);
5680 $name = $_REQUEST['name'] ?? '';
5681 $uid = $user_info['uid'];
5682 $json = json_decode($_POST['json'], true);
5683 $users = $json['user'];
5685 $success = group_create($name, $uid, $users);
5687 return api_format_data("group_create", $type, ['result' => $success]);
5689 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5692 * Create a new group.
5694 * @param string $type Return type (atom, rss, xml, json)
5696 * @return array|string
5697 * @throws BadRequestException
5698 * @throws ForbiddenException
5699 * @throws ImagickException
5700 * @throws InternalServerErrorException
5701 * @throws UnauthorizedException
5702 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5704 function api_lists_create($type)
5708 if (api_user() === false) {
5709 throw new ForbiddenException();
5713 $user_info = api_get_user($a);
5714 $name = $_REQUEST['name'] ?? '';
5715 $uid = $user_info['uid'];
5717 $success = group_create($name, $uid);
5718 if ($success['success']) {
5720 'name' => $success['name'],
5721 'id' => intval($success['gid']),
5722 'id_str' => (string) $success['gid'],
5723 'user' => $user_info
5726 return api_format_data("lists", $type, ['lists'=>$grp]);
5729 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5732 * Update the specified group with the posted array of contacts.
5734 * @param string $type Return type (atom, rss, xml, json)
5736 * @return array|string
5737 * @throws BadRequestException
5738 * @throws ForbiddenException
5739 * @throws ImagickException
5740 * @throws InternalServerErrorException
5741 * @throws UnauthorizedException
5743 function api_friendica_group_update($type)
5747 if (api_user() === false) {
5748 throw new ForbiddenException();
5752 $user_info = api_get_user($a);
5753 $uid = $user_info['uid'];
5754 $gid = $_REQUEST['gid'] ?? 0;
5755 $name = $_REQUEST['name'] ?? '';
5756 $json = json_decode($_POST['json'], true);
5757 $users = $json['user'];
5759 // error if no name specified
5761 throw new BadRequestException('group name not specified');
5764 // error if no gid specified
5766 throw new BadRequestException('gid not specified');
5770 $members = Contact::getByGroupId($gid);
5771 foreach ($members as $member) {
5772 $cid = $member['id'];
5773 foreach ($users as $user) {
5774 $found = ($user['cid'] == $cid ? true : false);
5776 if (!isset($found) || !$found) {
5777 Group::removeMemberByName($uid, $name, $cid);
5782 $erroraddinguser = false;
5784 foreach ($users as $user) {
5785 $cid = $user['cid'];
5786 // check if user really exists as contact
5788 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5793 if (count($contact)) {
5794 Group::addMember($gid, $cid);
5796 $erroraddinguser = true;
5797 $errorusers[] = $cid;
5801 // return success message incl. missing users in array
5802 $status = ($erroraddinguser ? "missing user" : "ok");
5803 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5804 return api_format_data("group_update", $type, ['result' => $success]);
5807 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5810 * Update information about a group.
5812 * @param string $type Return type (atom, rss, xml, json)
5814 * @return array|string
5815 * @throws BadRequestException
5816 * @throws ForbiddenException
5817 * @throws ImagickException
5818 * @throws InternalServerErrorException
5819 * @throws UnauthorizedException
5820 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5822 function api_lists_update($type)
5826 if (api_user() === false) {
5827 throw new ForbiddenException();
5831 $user_info = api_get_user($a);
5832 $gid = $_REQUEST['list_id'] ?? 0;
5833 $name = $_REQUEST['name'] ?? '';
5834 $uid = $user_info['uid'];
5836 // error if no gid specified
5838 throw new BadRequestException('gid not specified');
5841 // get data of the specified group id
5842 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5843 // error message if specified gid is not in database
5845 throw new BadRequestException('gid not available');
5848 if (Group::update($gid, $name)) {
5851 'id' => intval($gid),
5852 'id_str' => (string) $gid,
5853 'user' => $user_info
5856 return api_format_data("lists", $type, ['lists' => $list]);
5860 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5864 * @param string $type Return type (atom, rss, xml, json)
5866 * @return array|string
5867 * @throws BadRequestException
5868 * @throws ForbiddenException
5869 * @throws ImagickException
5870 * @throws InternalServerErrorException
5872 function api_friendica_activity($type)
5876 if (api_user() === false) {
5877 throw new ForbiddenException();
5879 $verb = strtolower($a->argv[3]);
5880 $verb = preg_replace("|\..*$|", "", $verb);
5882 $id = $_REQUEST['id'] ?? 0;
5884 $res = Item::performLike($id, $verb);
5887 if ($type == "xml") {
5892 return api_format_data('ok', $type, ['ok' => $ok]);
5894 throw new BadRequestException('Error adding activity');
5898 /// @TODO move to top of file or somewhere better
5899 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5900 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5901 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5902 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5903 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5904 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5905 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5906 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5907 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5908 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5911 * @brief Returns notifications
5913 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5914 * @return string|array
5915 * @throws BadRequestException
5916 * @throws ForbiddenException
5917 * @throws InternalServerErrorException
5919 function api_friendica_notification($type)
5923 if (api_user() === false) {
5924 throw new ForbiddenException();
5927 throw new BadRequestException("Invalid argument count");
5929 $notes = DI::notify()->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
5931 if ($type == "xml") {
5933 if (!empty($notes)) {
5934 foreach ($notes as $note) {
5935 $xmlnotes[] = ["@attributes" => $note];
5941 return api_format_data("notes", $type, ['note' => $notes]);
5945 * POST request with 'id' param as notification id
5947 * @brief Set notification as seen and returns associated item (if possible)
5949 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5950 * @return string|array
5951 * @throws BadRequestException
5952 * @throws ForbiddenException
5953 * @throws ImagickException
5954 * @throws InternalServerErrorException
5955 * @throws UnauthorizedException
5957 function api_friendica_notification_seen($type)
5960 $user_info = api_get_user($a);
5962 if (api_user() === false || $user_info === false) {
5963 throw new ForbiddenException();
5966 throw new BadRequestException("Invalid argument count");
5969 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5972 $note = $nm->getByID($id);
5973 if (is_null($note)) {
5974 throw new BadRequestException("Invalid argument");
5977 $nm->setSeen($note);
5978 if ($note['otype']=='item') {
5979 // would be really better with an ItemsManager and $im->getByID() :-P
5980 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
5981 if (DBA::isResult($item)) {
5982 // we found the item, return it to the user
5983 $ret = api_format_items([$item], $user_info, false, $type);
5984 $data = ['status' => $ret];
5985 return api_format_data("status", $type, $data);
5987 // the item can't be found, but we set the note as seen, so we count this as a success
5989 return api_format_data('result', $type, ['result' => "success"]);
5992 /// @TODO move to top of file or somewhere better
5993 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5994 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5997 * @brief update a direct_message to seen state
5999 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6000 * @return string|array (success result=ok, error result=error with error message)
6001 * @throws BadRequestException
6002 * @throws ForbiddenException
6003 * @throws ImagickException
6004 * @throws InternalServerErrorException
6005 * @throws UnauthorizedException
6007 function api_friendica_direct_messages_setseen($type)
6010 if (api_user() === false) {
6011 throw new ForbiddenException();
6015 $user_info = api_get_user($a);
6016 $uid = $user_info['uid'];
6017 $id = $_REQUEST['id'] ?? 0;
6019 // return error if id is zero
6021 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6022 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6025 // error message if specified id is not in database
6026 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6027 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6028 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6031 // update seen indicator
6032 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6036 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6037 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6039 $answer = ['result' => 'error', 'message' => 'unknown error'];
6040 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6044 /// @TODO move to top of file or somewhere better
6045 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6048 * @brief search for direct_messages containing a searchstring through api
6050 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6051 * @param string $box
6052 * @return string|array (success: success=true if found and search_result contains found messages,
6053 * success=false if nothing was found, search_result='nothing found',
6054 * error: result=error with error message)
6055 * @throws BadRequestException
6056 * @throws ForbiddenException
6057 * @throws ImagickException
6058 * @throws InternalServerErrorException
6059 * @throws UnauthorizedException
6061 function api_friendica_direct_messages_search($type, $box = "")
6065 if (api_user() === false) {
6066 throw new ForbiddenException();
6070 $user_info = api_get_user($a);
6071 $searchstring = $_REQUEST['searchstring'] ?? '';
6072 $uid = $user_info['uid'];
6074 // error if no searchstring specified
6075 if ($searchstring == "") {
6076 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6077 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6080 // get data for the specified searchstring
6082 "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",
6084 DBA::escape('%'.$searchstring.'%')
6087 $profile_url = $user_info["url"];
6089 // message if nothing was found
6090 if (!DBA::isResult($r)) {
6091 $success = ['success' => false, 'search_results' => 'problem with query'];
6092 } elseif (count($r) == 0) {
6093 $success = ['success' => false, 'search_results' => 'nothing found'];
6096 foreach ($r as $item) {
6097 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6098 $recipient = $user_info;
6099 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6100 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6101 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6102 $sender = $user_info;
6105 if (isset($recipient) && isset($sender)) {
6106 $ret[] = api_format_messages($item, $recipient, $sender);
6109 $success = ['success' => true, 'search_results' => $ret];
6112 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6115 /// @TODO move to top of file or somewhere better
6116 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6119 * @brief return data of all the profiles a user has to the client
6121 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6122 * @return string|array
6123 * @throws BadRequestException
6124 * @throws ForbiddenException
6125 * @throws ImagickException
6126 * @throws InternalServerErrorException
6127 * @throws UnauthorizedException
6129 function api_friendica_profile_show($type)
6133 if (api_user() === false) {
6134 throw new ForbiddenException();
6138 $profile_id = $_REQUEST['profile_id'] ?? 0;
6140 // retrieve general information about profiles for user
6141 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6142 $directory = Config::get('system', 'directory');
6144 // get data of the specified profile id or all profiles of the user if not specified
6145 if ($profile_id != 0) {
6146 $r = Profile::getById(api_user(), $profile_id);
6147 // error message if specified gid is not in database
6148 if (!DBA::isResult($r)) {
6149 throw new BadRequestException("profile_id not available");
6152 $r = Profile::getListByUser(api_user());
6154 // loop through all returned profiles and retrieve data and users
6157 if (DBA::isResult($r)) {
6158 foreach ($r as $rr) {
6159 $profile = api_format_items_profiles($rr);
6161 // select all users from contact table, loop and prepare standard return for user data
6163 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6164 foreach ($nurls as $nurl) {
6165 $user = api_get_user($a, $nurl['nurl']);
6166 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6168 $profile['users'] = $users;
6170 // add prepared profile data to array for final return
6171 if ($type == "xml") {
6172 $profiles[$k++ . ":profile"] = $profile;
6174 $profiles[] = $profile;
6179 // return settings, authenticated user and profiles data
6180 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6182 $result = ['multi_profiles' => $multi_profiles ? true : false,
6183 'global_dir' => $directory,
6184 'friendica_owner' => api_get_user($a, $self['nurl']),
6185 'profiles' => $profiles];
6186 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6188 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6191 * Returns a list of saved searches.
6193 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6195 * @param string $type Return format: json or xml
6197 * @return string|array
6200 function api_saved_searches_list($type)
6202 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6205 while ($term = DBA::fetch($terms)) {
6207 'created_at' => api_date(time()),
6208 'id' => intval($term['id']),
6209 'id_str' => $term['id'],
6210 'name' => $term['term'],
6212 'query' => $term['term']
6218 return api_format_data("terms", $type, ['terms' => $result]);
6221 /// @TODO move to top of file or somewhere better
6222 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6225 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6227 * @brief Number of comments
6229 * @param object $data [Status, Status]
6233 function bindComments(&$data)
6235 if (count($data) == 0) {
6241 foreach ($data as $item) {
6242 $ids[] = $item['id'];
6245 $idStr = DBA::escape(implode(', ', $ids));
6246 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6247 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6248 $itemsData = DBA::toArray($items);
6250 foreach ($itemsData as $item) {
6251 $comments[$item['parent']] = $item['comments'];
6254 foreach ($data as $idx => $item) {
6256 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6261 @TODO Maybe open to implement?
6263 [pagename] => api/1.1/statuses/lookup.json
6264 [id] => 605138389168451584
6265 [include_cards] => true
6266 [cards_platform] => Android-12
6267 [include_entities] => true
6268 [include_my_retweet] => 1
6270 [include_reply_count] => true
6271 [include_descendent_reply_count] => true
6275 Not implemented by now:
6276 statuses/retweets_of_me
6281 account/update_location
6282 account/update_profile_background_image
6285 friendica/profile/update
6286 friendica/profile/create
6287 friendica/profile/delete
6289 Not implemented in status.net:
6290 statuses/retweeted_to_me
6291 statuses/retweeted_by_me
6292 direct_messages/destroy
6294 account/update_delivery_device
6295 notifications/follow