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\BaseObject;
11 use Friendica\Content\ContactSelector;
12 use Friendica\Content\Feature;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 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\Notify;
30 use Friendica\Model\Photo;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
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 System::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 Session::setAuthenticatedForUser($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 * @return string|array API call result
290 function api_call(App $a)
292 global $API, $called_api;
295 if (strpos($a->query_string, ".xml") > 0) {
298 if (strpos($a->query_string, ".json") > 0) {
301 if (strpos($a->query_string, ".rss") > 0) {
304 if (strpos($a->query_string, ".atom") > 0) {
309 foreach ($API as $p => $info) {
310 if (strpos($a->query_string, $p) === 0) {
311 if (!api_check_method($info['method'])) {
312 throw new MethodNotAllowedException();
315 $called_api = explode("/", $p);
316 //unset($_SERVER['PHP_AUTH_USER']);
318 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
319 if (!empty($info['auth']) && api_user() === false) {
323 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
324 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
326 $stamp = microtime(true);
327 $return = call_user_func($info['func'], $type);
328 $duration = floatval(microtime(true) - $stamp);
330 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
332 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
334 if (false === $return) {
336 * api function returned false withour throw an
337 * exception. This should not happend, throw a 500
339 throw new InternalServerErrorException();
344 header("Content-Type: text/xml");
347 header("Content-Type: application/json");
348 if (!empty($return)) {
349 $json = json_encode(end($return));
350 if (!empty($_GET['callback'])) {
351 $json = $_GET['callback'] . "(" . $json . ")";
357 header("Content-Type: application/rss+xml");
358 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
361 header("Content-Type: application/atom+xml");
362 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
369 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
370 throw new NotImplementedException();
371 } catch (HTTPException $e) {
372 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
373 return api_error($type, $e);
378 * @brief Format API error string
380 * @param string $type Return type (xml, json, rss, as)
381 * @param object $e HTTPException Error object
382 * @return string|array error message formatted as $type
384 function api_error($type, $e)
388 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
389 /// @TODO: https://dev.twitter.com/overview/api/response-codes
391 $error = ["error" => $error,
392 "code" => $e->getCode() . " " . $e->httpdesc,
393 "request" => $a->query_string];
395 $return = api_format_data('status', $type, ['status' => $error]);
399 header("Content-Type: text/xml");
402 header("Content-Type: application/json");
403 $return = json_encode($return);
406 header("Content-Type: application/rss+xml");
409 header("Content-Type: application/atom+xml");
417 * @brief Set values for RSS template
420 * @param array $arr Array to be passed to template
421 * @param array $user_info User info
423 * @throws BadRequestException
424 * @throws ImagickException
425 * @throws InternalServerErrorException
426 * @throws UnauthorizedException
427 * @todo find proper type-hints
429 function api_rss_extra(App $a, $arr, $user_info)
431 if (is_null($user_info)) {
432 $user_info = api_get_user($a);
435 $arr['$user'] = $user_info;
437 'alternate' => $user_info['url'],
438 'self' => System::baseUrl() . "/" . $a->query_string,
439 'base' => System::baseUrl(),
440 'updated' => api_date(null),
441 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
442 'language' => $user_info['lang'],
443 'logo' => System::baseUrl() . "/images/friendica-32.png",
451 * @brief Unique contact to contact url.
453 * @param int $id Contact id
454 * @return bool|string
455 * Contact url or False if contact id is unknown
458 function api_unique_id_to_nurl($id)
460 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
462 if (DBA::isResult($r)) {
470 * @brief Get user info array.
473 * @param int|string $contact_id Contact ID or URL
475 * @throws BadRequestException
476 * @throws ImagickException
477 * @throws InternalServerErrorException
478 * @throws UnauthorizedException
480 function api_get_user(App $a, $contact_id = null)
488 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
490 // Searching for contact URL
491 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
492 $user = DBA::escape(Strings::normaliseLink($contact_id));
494 $extra_query = "AND `contact`.`nurl` = '%s' ";
495 if (api_user() !== false) {
496 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
500 // Searching for contact id with uid = 0
501 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
502 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
505 throw new BadRequestException("User ID ".$contact_id." not found.");
509 $extra_query = "AND `contact`.`nurl` = '%s' ";
510 if (api_user() !== false) {
511 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
515 if (is_null($user) && !empty($_GET['user_id'])) {
516 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
519 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
523 $extra_query = "AND `contact`.`nurl` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && !empty($_GET['screen_name'])) {
529 $user = DBA::escape($_GET['screen_name']);
530 $extra_query = "AND `contact`.`nick` = '%s' ";
531 if (api_user() !== false) {
532 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
536 if (is_null($user) && !empty($_GET['profileurl'])) {
537 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
538 $extra_query = "AND `contact`.`nurl` = '%s' ";
539 if (api_user() !== false) {
540 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
544 // $called_api is the API path exploded on / and is expected to have at least 2 elements
545 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
546 $argid = count($called_api);
547 if (!empty($a->argv[$argid])) {
548 $data = explode(".", $a->argv[$argid]);
549 if (count($data) > 1) {
550 list($user, $null) = $data;
553 if (is_numeric($user)) {
554 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
558 $extra_query = "AND `contact`.`nurl` = '%s' ";
559 if (api_user() !== false) {
560 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
564 $user = DBA::escape($user);
565 $extra_query = "AND `contact`.`nick` = '%s' ";
566 if (api_user() !== false) {
567 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
572 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
575 if (api_user() === false) {
579 $user = $_SESSION['uid'];
580 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
584 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
588 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
594 // Selecting the id by priority, friendica first
595 if (is_array($uinfo)) {
596 api_best_nickname($uinfo);
599 // if the contact wasn't found, fetch it from the contacts with uid = 0
600 if (!DBA::isResult($uinfo)) {
602 throw new BadRequestException("User not found.");
605 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
607 if (DBA::isResult($contact)) {
608 // If no nick where given, extract it from the address
609 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
610 $contact['nick'] = api_get_nick($contact["url"]);
614 'id' => $contact["id"],
615 'id_str' => (string) $contact["id"],
616 'name' => $contact["name"],
617 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
618 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
619 'description' => BBCode::toPlaintext($contact["about"]),
620 'profile_image_url' => $contact["micro"],
621 'profile_image_url_https' => $contact["micro"],
622 'profile_image_url_profile_size' => $contact["thumb"],
623 'profile_image_url_large' => $contact["photo"],
624 'url' => $contact["url"],
625 'protected' => false,
626 'followers_count' => 0,
627 'friends_count' => 0,
629 'created_at' => api_date($contact["created"]),
630 'favourites_count' => 0,
632 'time_zone' => 'UTC',
633 'geo_enabled' => false,
635 'statuses_count' => 0,
637 'contributors_enabled' => false,
638 'is_translator' => false,
639 'is_translation_enabled' => false,
640 'following' => false,
641 'follow_request_sent' => false,
642 'statusnet_blocking' => false,
643 'notifications' => false,
644 'statusnet_profile_url' => $contact["url"],
646 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
647 'pid' => Contact::getIdForURL($contact["url"], 0, true),
649 'network' => $contact["network"],
654 throw new BadRequestException("User ".$url." not found.");
658 if ($uinfo[0]['self']) {
659 if ($uinfo[0]['network'] == "") {
660 $uinfo[0]['network'] = Protocol::DFRN;
663 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
664 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
671 // Add a nick if it isn't present there
672 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
673 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
676 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
678 if (!empty($profile['about'])) {
679 $description = $profile['about'];
681 $description = $uinfo[0]["about"];
684 if (!empty($usr['default-location'])) {
685 $location = $usr['default-location'];
686 } elseif (!empty($uinfo[0]["location"])) {
687 $location = $uinfo[0]["location"];
689 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
693 'id' => intval($pcontact_id),
694 'id_str' => (string) intval($pcontact_id),
695 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
696 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
697 'location' => $location,
698 'description' => BBCode::toPlaintext($description),
699 'profile_image_url' => $uinfo[0]['micro'],
700 'profile_image_url_https' => $uinfo[0]['micro'],
701 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
702 'profile_image_url_large' => $uinfo[0]["photo"],
703 'url' => $uinfo[0]['url'],
704 'protected' => false,
705 'followers_count' => intval($countfollowers),
706 'friends_count' => intval($countfriends),
708 'created_at' => api_date($uinfo[0]['created']),
709 'favourites_count' => intval($starred),
711 'time_zone' => 'UTC',
712 'geo_enabled' => false,
714 'statuses_count' => intval($countitems),
716 'contributors_enabled' => false,
717 'is_translator' => false,
718 'is_translation_enabled' => false,
719 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
720 'follow_request_sent' => false,
721 'statusnet_blocking' => false,
722 'notifications' => false,
724 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
725 'statusnet_profile_url' => $uinfo[0]['url'],
726 'uid' => intval($uinfo[0]['uid']),
727 'cid' => intval($uinfo[0]['cid']),
728 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
729 'self' => $uinfo[0]['self'],
730 'network' => $uinfo[0]['network'],
733 // If this is a local user and it uses Frio, we can get its color preferences.
735 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
736 if ($theme_info['theme'] === 'frio') {
737 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
739 if ($schema && ($schema != '---')) {
740 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
741 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
742 require_once $schemefile;
745 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
746 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
747 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
749 if (empty($nav_bg)) {
752 if (empty($link_color)) {
753 $link_color = "#6fdbe8";
755 if (empty($bgcolor)) {
756 $bgcolor = "#ededed";
759 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
760 $ret['profile_link_color'] = str_replace('#', '', $link_color);
761 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
769 * @brief return api-formatted array for item's author and owner
772 * @param array $item item from db
773 * @return array(array:author, array:owner)
774 * @throws BadRequestException
775 * @throws ImagickException
776 * @throws InternalServerErrorException
777 * @throws UnauthorizedException
779 function api_item_get_user(App $a, $item)
781 $status_user = api_get_user($a, $item['author-id'] ?? null);
783 $author_user = $status_user;
785 $status_user["protected"] = $item['private'] ?? 0;
787 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
788 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
790 $owner_user = $author_user;
793 return ([$status_user, $author_user, $owner_user]);
797 * @brief walks recursively through an array with the possibility to change value and key
799 * @param array $array The array to walk through
800 * @param callable $callback The callback function
802 * @return array the transformed array
804 function api_walk_recursive(array &$array, callable $callback)
808 foreach ($array as $k => $v) {
810 if ($callback($v, $k)) {
811 $new_array[$k] = api_walk_recursive($v, $callback);
814 if ($callback($v, $k)) {
825 * @brief Callback function to transform the array in an array that can be transformed in a XML file
827 * @param mixed $item Array item value
828 * @param string $key Array key
830 * @return boolean Should the array item be deleted?
832 function api_reformat_xml(&$item, &$key)
834 if (is_bool($item)) {
835 $item = ($item ? "true" : "false");
838 if (substr($key, 0, 10) == "statusnet_") {
839 $key = "statusnet:".substr($key, 10);
840 } elseif (substr($key, 0, 10) == "friendica_") {
841 $key = "friendica:".substr($key, 10);
843 /// @TODO old-lost code?
845 // $key = "default:".$key;
851 * @brief Creates the XML from a JSON style array
853 * @param array $data JSON style array
854 * @param string $root_element Name of the root element
856 * @return string The XML data
858 function api_create_xml(array $data, $root_element)
860 $childname = key($data);
861 $data2 = array_pop($data);
863 $namespaces = ["" => "http://api.twitter.com",
864 "statusnet" => "http://status.net/schema/api/1/",
865 "friendica" => "http://friendi.ca/schema/api/1/",
866 "georss" => "http://www.georss.org/georss"];
868 /// @todo Auto detection of needed namespaces
869 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
873 if (is_array($data2)) {
875 api_walk_recursive($data2, "api_reformat_xml");
881 foreach ($data2 as $item) {
882 $data4[$i++ . ":" . $childname] = $item;
889 $data3 = [$root_element => $data2];
891 $ret = XML::fromArray($data3, $xml, false, $namespaces);
896 * @brief Formats the data according to the data type
898 * @param string $root_element Name of the root element
899 * @param string $type Return type (atom, rss, xml, json)
900 * @param array $data JSON style array
902 * @return array|string (string|array) XML data or JSON data
904 function api_format_data($root_element, $type, $data)
910 $ret = api_create_xml($data, $root_element);
925 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
926 * returns a 401 status code and an error message if not.
928 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
930 * @param string $type Return type (atom, rss, xml, json)
931 * @return array|string
932 * @throws BadRequestException
933 * @throws ForbiddenException
934 * @throws ImagickException
935 * @throws InternalServerErrorException
936 * @throws UnauthorizedException
938 function api_account_verify_credentials($type)
942 if (api_user() === false) {
943 throw new ForbiddenException();
946 unset($_REQUEST["user_id"]);
947 unset($_GET["user_id"]);
949 unset($_REQUEST["screen_name"]);
950 unset($_GET["screen_name"]);
952 $skip_status = $_REQUEST['skip_status'] ?? false;
954 $user_info = api_get_user($a);
956 // "verified" isn't used here in the standard
957 unset($user_info["verified"]);
959 // - Adding last status
961 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
963 $user_info['status'] = api_format_item($item, $type);
967 // "uid" and "self" are only needed for some internal stuff, so remove it from here
968 unset($user_info["uid"]);
969 unset($user_info["self"]);
971 return api_format_data("user", $type, ['user' => $user_info]);
974 /// @TODO move to top of file or somewhere better
975 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
978 * Get data from $_POST or $_GET
983 function requestdata($k)
985 if (!empty($_POST[$k])) {
988 if (!empty($_GET[$k])) {
995 * Deprecated function to upload media.
997 * @param string $type Return type (atom, rss, xml, json)
999 * @return array|string
1000 * @throws BadRequestException
1001 * @throws ForbiddenException
1002 * @throws ImagickException
1003 * @throws InternalServerErrorException
1004 * @throws UnauthorizedException
1006 function api_statuses_mediap($type)
1010 if (api_user() === false) {
1011 Logger::log('api_statuses_update: no user');
1012 throw new ForbiddenException();
1014 $user_info = api_get_user($a);
1016 $_REQUEST['profile_uid'] = api_user();
1017 $_REQUEST['api_source'] = true;
1018 $txt = requestdata('status');
1019 /// @TODO old-lost code?
1020 //$txt = urldecode(requestdata('status'));
1022 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1023 $txt = HTML::toBBCodeVideo($txt);
1024 $config = HTMLPurifier_Config::createDefault();
1025 $config->set('Cache.DefinitionImpl', null);
1026 $purifier = new HTMLPurifier($config);
1027 $txt = $purifier->purify($txt);
1029 $txt = HTML::toBBCode($txt);
1031 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1033 $picture = wall_upload_post($a, false);
1035 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1036 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1037 $item_id = item_post($a);
1039 // output the post that we just posted.
1040 return api_status_show($type, $item_id);
1043 /// @TODO move this to top of file or somewhere better!
1044 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1047 * Updates the user’s current status.
1049 * @param string $type Return type (atom, rss, xml, json)
1051 * @return array|string
1052 * @throws BadRequestException
1053 * @throws ForbiddenException
1054 * @throws ImagickException
1055 * @throws InternalServerErrorException
1056 * @throws TooManyRequestsException
1057 * @throws UnauthorizedException
1058 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1060 function api_statuses_update($type)
1064 if (api_user() === false) {
1065 Logger::log('api_statuses_update: no user');
1066 throw new ForbiddenException();
1071 // convert $_POST array items to the form we use for web posts.
1072 if (requestdata('htmlstatus')) {
1073 $txt = requestdata('htmlstatus');
1074 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1075 $txt = HTML::toBBCodeVideo($txt);
1077 $config = HTMLPurifier_Config::createDefault();
1078 $config->set('Cache.DefinitionImpl', null);
1080 $purifier = new HTMLPurifier($config);
1081 $txt = $purifier->purify($txt);
1083 $_REQUEST['body'] = HTML::toBBCode($txt);
1086 $_REQUEST['body'] = requestdata('status');
1089 $_REQUEST['title'] = requestdata('title');
1091 $parent = requestdata('in_reply_to_status_id');
1093 // Twidere sends "-1" if it is no reply ...
1094 if ($parent == -1) {
1098 if (ctype_digit($parent)) {
1099 $_REQUEST['parent'] = $parent;
1101 $_REQUEST['parent_uri'] = $parent;
1104 if (requestdata('lat') && requestdata('long')) {
1105 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1107 $_REQUEST['profile_uid'] = api_user();
1110 // Check for throttling (maximum posts per day, week and month)
1111 $throttle_day = Config::get('system', 'throttle_limit_day');
1112 if ($throttle_day > 0) {
1113 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1115 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1116 $posts_day = DBA::count('thread', $condition);
1118 if ($posts_day > $throttle_day) {
1119 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1120 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1121 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));
1125 $throttle_week = Config::get('system', 'throttle_limit_week');
1126 if ($throttle_week > 0) {
1127 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1129 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1130 $posts_week = DBA::count('thread', $condition);
1132 if ($posts_week > $throttle_week) {
1133 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1134 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1135 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));
1139 $throttle_month = Config::get('system', 'throttle_limit_month');
1140 if ($throttle_month > 0) {
1141 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1143 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1144 $posts_month = DBA::count('thread', $condition);
1146 if ($posts_month > $throttle_month) {
1147 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1148 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1149 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));
1154 if (!empty($_FILES['media'])) {
1155 // upload the image if we have one
1156 $picture = wall_upload_post($a, false);
1157 if (is_array($picture)) {
1158 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1162 if (requestdata('media_ids')) {
1163 $ids = explode(',', requestdata('media_ids'));
1164 foreach ($ids as $id) {
1166 "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",
1170 if (DBA::isResult($r)) {
1171 $phototypes = Images::supportedTypes();
1172 $ext = $phototypes[$r[0]['type']];
1173 $description = $r[0]['desc'] ?? '';
1174 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1175 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1180 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1182 $_REQUEST['api_source'] = true;
1184 if (empty($_REQUEST['source'])) {
1185 $_REQUEST["source"] = api_source();
1188 // call out normal post function
1189 $item_id = item_post($a);
1191 // output the post that we just posted.
1192 return api_status_show($type, $item_id);
1195 /// @TODO move to top of file or somewhere better
1196 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1197 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1200 * Uploads an image to Friendica.
1203 * @throws BadRequestException
1204 * @throws ForbiddenException
1205 * @throws ImagickException
1206 * @throws InternalServerErrorException
1207 * @throws UnauthorizedException
1208 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1210 function api_media_upload()
1214 if (api_user() === false) {
1215 Logger::log('no user');
1216 throw new ForbiddenException();
1221 if (empty($_FILES['media'])) {
1223 throw new BadRequestException("No media.");
1226 $media = wall_upload_post($a, false);
1229 throw new InternalServerErrorException();
1233 $returndata["media_id"] = $media["id"];
1234 $returndata["media_id_string"] = (string)$media["id"];
1235 $returndata["size"] = $media["size"];
1236 $returndata["image"] = ["w" => $media["width"],
1237 "h" => $media["height"],
1238 "image_type" => $media["type"],
1239 "friendica_preview_url" => $media["preview"]];
1241 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1243 return ["media" => $returndata];
1246 /// @TODO move to top of file or somewhere better
1247 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1250 * Updates media meta data (picture descriptions)
1252 * @param string $type Return type (atom, rss, xml, json)
1254 * @return array|string
1255 * @throws BadRequestException
1256 * @throws ForbiddenException
1257 * @throws ImagickException
1258 * @throws InternalServerErrorException
1259 * @throws TooManyRequestsException
1260 * @throws UnauthorizedException
1261 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1263 * @todo Compare the corresponding Twitter function for correct return values
1265 function api_media_metadata_create($type)
1269 if (api_user() === false) {
1270 Logger::info('no user');
1271 throw new ForbiddenException();
1276 $postdata = Network::postdata();
1278 if (empty($postdata)) {
1279 throw new BadRequestException("No post data");
1282 $data = json_decode($postdata, true);
1284 throw new BadRequestException("Invalid post data");
1287 if (empty($data['media_id']) || empty($data['alt_text'])) {
1288 throw new BadRequestException("Missing post data values");
1291 if (empty($data['alt_text']['text'])) {
1292 throw new BadRequestException("No alt text.");
1295 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1297 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1298 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1299 if (!DBA::isResult($photo)) {
1300 throw new BadRequestException("Metadata not found.");
1303 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1306 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1309 * @param string $type Return format (atom, rss, xml, json)
1310 * @param int $item_id
1314 function api_status_show($type, $item_id)
1316 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1320 $item = api_get_item(['id' => $item_id]);
1321 if (!empty($item)) {
1322 $status_info = api_format_item($item, $type);
1325 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1327 return api_format_data('statuses', $type, ['status' => $status_info]);
1331 * Retrieves the last public status of the provided user info
1333 * @param int $ownerId Public contact Id
1334 * @param int $uid User Id
1338 function api_get_last_status($ownerId, $uid)
1341 'author-id'=> $ownerId,
1343 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1347 $item = api_get_item($condition);
1353 * Retrieves a single item record based on the provided condition and converts it for API use.
1355 * @param array $condition Item table condition array
1359 function api_get_item(array $condition)
1361 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1367 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1368 * The author's most recent status will be returned inline.
1370 * @param string $type Return type (atom, rss, xml, json)
1371 * @return array|string
1372 * @throws BadRequestException
1373 * @throws ImagickException
1374 * @throws InternalServerErrorException
1375 * @throws UnauthorizedException
1376 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1378 function api_users_show($type)
1380 $a = BaseObject::getApp();
1382 $user_info = api_get_user($a);
1384 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1385 if (!empty($item)) {
1386 $user_info['status'] = api_format_item($item, $type);
1389 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1390 unset($user_info['uid']);
1391 unset($user_info['self']);
1393 return api_format_data('user', $type, ['user' => $user_info]);
1396 /// @TODO move to top of file or somewhere better
1397 api_register_func('api/users/show', 'api_users_show');
1398 api_register_func('api/externalprofile/show', 'api_users_show');
1401 * Search a public user account.
1403 * @param string $type Return type (atom, rss, xml, json)
1405 * @return array|string
1406 * @throws BadRequestException
1407 * @throws ImagickException
1408 * @throws InternalServerErrorException
1409 * @throws UnauthorizedException
1410 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1412 function api_users_search($type)
1418 if (!empty($_GET['q'])) {
1419 $contacts = Contact::selectToArray(
1422 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1430 if (DBA::isResult($contacts)) {
1432 foreach ($contacts as $contact) {
1433 $user_info = api_get_user($a, $contact['id']);
1435 if ($type == 'xml') {
1436 $userlist[$k++ . ':user'] = $user_info;
1438 $userlist[] = $user_info;
1441 $userlist = ['users' => $userlist];
1443 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1446 throw new BadRequestException('No search term specified.');
1449 return api_format_data('users', $type, $userlist);
1452 /// @TODO move to top of file or somewhere better
1453 api_register_func('api/users/search', 'api_users_search');
1456 * Return user objects
1458 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1460 * @param string $type Return format: json or xml
1462 * @return array|string
1463 * @throws BadRequestException
1464 * @throws ImagickException
1465 * @throws InternalServerErrorException
1466 * @throws NotFoundException if the results are empty.
1467 * @throws UnauthorizedException
1469 function api_users_lookup($type)
1473 if (!empty($_REQUEST['user_id'])) {
1474 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1476 $users[] = api_get_user(get_app(), $id);
1481 if (empty($users)) {
1482 throw new NotFoundException;
1485 return api_format_data("users", $type, ['users' => $users]);
1488 /// @TODO move to top of file or somewhere better
1489 api_register_func('api/users/lookup', 'api_users_lookup', true);
1492 * Returns statuses that match a specified query.
1494 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1496 * @param string $type Return format: json, xml, atom, rss
1498 * @return array|string
1499 * @throws BadRequestException if the "q" parameter is missing.
1500 * @throws ForbiddenException
1501 * @throws ImagickException
1502 * @throws InternalServerErrorException
1503 * @throws UnauthorizedException
1505 function api_search($type)
1508 $user_info = api_get_user($a);
1510 if (api_user() === false || $user_info === false) {
1511 throw new ForbiddenException();
1514 if (empty($_REQUEST['q'])) {
1515 throw new BadRequestException('q parameter is required.');
1518 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1521 $data['status'] = [];
1523 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1524 if (!empty($_REQUEST['rpp'])) {
1525 $count = $_REQUEST['rpp'];
1526 } elseif (!empty($_REQUEST['count'])) {
1527 $count = $_REQUEST['count'];
1530 $since_id = $_REQUEST['since_id'] ?? 0;
1531 $max_id = $_REQUEST['max_id'] ?? 0;
1532 $page = $_REQUEST['page'] ?? 1;
1534 $start = max(0, ($page - 1) * $count);
1536 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1537 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1538 $searchTerm = $matches[1];
1539 $condition = ["`oid` > ?
1540 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1541 AND `otype` = ? AND `type` = ? AND `term` = ?",
1542 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1544 $condition[0] .= ' AND `oid` <= ?';
1545 $condition[] = $max_id;
1547 $terms = DBA::select('term', ['oid'], $condition, []);
1549 while ($term = DBA::fetch($terms)) {
1550 $itemIds[] = $term['oid'];
1554 if (empty($itemIds)) {
1555 return api_format_data('statuses', $type, $data);
1558 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1559 if ($exclude_replies) {
1560 $preCondition[] = '`id` = `parent`';
1563 $condition = [implode(' AND ', $preCondition)];
1565 $condition = ["`id` > ?
1566 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1567 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1568 AND `body` LIKE CONCAT('%',?,'%')",
1569 $since_id, api_user(), $_REQUEST['q']];
1571 $condition[0] .= ' AND `id` <= ?';
1572 $condition[] = $max_id;
1578 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1579 $id = Item::fetchByLink($searchTerm, api_user());
1582 $id = Item::fetchByLink($searchTerm);
1586 $statuses = Item::select([], ['id' => $id]);
1590 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1592 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1594 bindComments($data['status']);
1596 return api_format_data('statuses', $type, $data);
1599 /// @TODO move to top of file or somewhere better
1600 api_register_func('api/search/tweets', 'api_search', true);
1601 api_register_func('api/search', 'api_search', true);
1604 * Returns the most recent statuses posted by the user and the users they follow.
1606 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1608 * @param string $type Return type (atom, rss, xml, json)
1610 * @return array|string
1611 * @throws BadRequestException
1612 * @throws ForbiddenException
1613 * @throws ImagickException
1614 * @throws InternalServerErrorException
1615 * @throws UnauthorizedException
1616 * @todo Optional parameters
1617 * @todo Add reply info
1619 function api_statuses_home_timeline($type)
1622 $user_info = api_get_user($a);
1624 if (api_user() === false || $user_info === false) {
1625 throw new ForbiddenException();
1628 unset($_REQUEST["user_id"]);
1629 unset($_GET["user_id"]);
1631 unset($_REQUEST["screen_name"]);
1632 unset($_GET["screen_name"]);
1634 // get last network messages
1637 $count = $_REQUEST['count'] ?? 20;
1638 $page = $_REQUEST['page']?? 0;
1639 $since_id = $_REQUEST['since_id'] ?? 0;
1640 $max_id = $_REQUEST['max_id'] ?? 0;
1641 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1642 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1644 $start = max(0, ($page - 1) * $count);
1646 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1647 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1650 $condition[0] .= " AND `item`.`id` <= ?";
1651 $condition[] = $max_id;
1653 if ($exclude_replies) {
1654 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1656 if ($conversation_id > 0) {
1657 $condition[0] .= " AND `item`.`parent` = ?";
1658 $condition[] = $conversation_id;
1661 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1662 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1664 $items = Item::inArray($statuses);
1666 $ret = api_format_items($items, $user_info, false, $type);
1668 // Set all posts from the query above to seen
1670 foreach ($items as $item) {
1671 $idarray[] = intval($item["id"]);
1674 if (!empty($idarray)) {
1675 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1677 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1683 $data = ['status' => $ret];
1688 $data = api_rss_extra($a, $data, $user_info);
1692 return api_format_data("statuses", $type, $data);
1696 /// @TODO move to top of file or somewhere better
1697 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1698 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1701 * Returns the most recent statuses from public users.
1703 * @param string $type Return type (atom, rss, xml, json)
1705 * @return array|string
1706 * @throws BadRequestException
1707 * @throws ForbiddenException
1708 * @throws ImagickException
1709 * @throws InternalServerErrorException
1710 * @throws UnauthorizedException
1712 function api_statuses_public_timeline($type)
1715 $user_info = api_get_user($a);
1717 if (api_user() === false || $user_info === false) {
1718 throw new ForbiddenException();
1721 // get last network messages
1724 $count = $_REQUEST['count'] ?? 20;
1725 $page = $_REQUEST['page'] ?? 1;
1726 $since_id = $_REQUEST['since_id'] ?? 0;
1727 $max_id = $_REQUEST['max_id'] ?? 0;
1728 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1729 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1731 $start = max(0, ($page - 1) * $count);
1733 if ($exclude_replies && !$conversation_id) {
1734 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1735 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1738 $condition[0] .= " AND `thread`.`iid` <= ?";
1739 $condition[] = $max_id;
1742 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1743 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1745 $r = Item::inArray($statuses);
1747 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1748 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1751 $condition[0] .= " AND `item`.`id` <= ?";
1752 $condition[] = $max_id;
1754 if ($conversation_id > 0) {
1755 $condition[0] .= " AND `item`.`parent` = ?";
1756 $condition[] = $conversation_id;
1759 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1760 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1762 $r = Item::inArray($statuses);
1765 $ret = api_format_items($r, $user_info, false, $type);
1769 $data = ['status' => $ret];
1774 $data = api_rss_extra($a, $data, $user_info);
1778 return api_format_data("statuses", $type, $data);
1781 /// @TODO move to top of file or somewhere better
1782 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1785 * Returns the most recent statuses posted by users this node knows about.
1787 * @brief Returns the list of public federated posts this node knows about
1789 * @param string $type Return format: json, xml, atom, rss
1790 * @return array|string
1791 * @throws BadRequestException
1792 * @throws ForbiddenException
1793 * @throws ImagickException
1794 * @throws InternalServerErrorException
1795 * @throws UnauthorizedException
1797 function api_statuses_networkpublic_timeline($type)
1800 $user_info = api_get_user($a);
1802 if (api_user() === false || $user_info === false) {
1803 throw new ForbiddenException();
1806 $since_id = $_REQUEST['since_id'] ?? 0;
1807 $max_id = $_REQUEST['max_id'] ?? 0;
1810 $count = $_REQUEST['count'] ?? 20;
1811 $page = $_REQUEST['page'] ?? 1;
1813 $start = max(0, ($page - 1) * $count);
1815 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1816 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1819 $condition[0] .= " AND `thread`.`iid` <= ?";
1820 $condition[] = $max_id;
1823 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1824 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1826 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1830 $data = ['status' => $ret];
1835 $data = api_rss_extra($a, $data, $user_info);
1839 return api_format_data("statuses", $type, $data);
1842 /// @TODO move to top of file or somewhere better
1843 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1846 * Returns a single status.
1848 * @param string $type Return type (atom, rss, xml, json)
1850 * @return array|string
1851 * @throws BadRequestException
1852 * @throws ForbiddenException
1853 * @throws ImagickException
1854 * @throws InternalServerErrorException
1855 * @throws UnauthorizedException
1856 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1858 function api_statuses_show($type)
1861 $user_info = api_get_user($a);
1863 if (api_user() === false || $user_info === false) {
1864 throw new ForbiddenException();
1868 $id = intval($a->argv[3] ?? 0);
1871 $id = intval($_REQUEST['id'] ?? 0);
1876 $id = intval($a->argv[4] ?? 0);
1879 Logger::log('API: api_statuses_show: ' . $id);
1881 $conversation = !empty($_REQUEST['conversation']);
1883 // try to fetch the item for the local user - or the public item, if there is no local one
1884 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1885 if (!DBA::isResult($uri_item)) {
1886 throw new BadRequestException("There is no status with this id.");
1889 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1890 if (!DBA::isResult($item)) {
1891 throw new BadRequestException("There is no status with this id.");
1896 if ($conversation) {
1897 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1898 $params = ['order' => ['id' => true]];
1900 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1904 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1906 /// @TODO How about copying this to above methods which don't check $r ?
1907 if (!DBA::isResult($statuses)) {
1908 throw new BadRequestException("There is no status with this id.");
1911 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1913 if ($conversation) {
1914 $data = ['status' => $ret];
1915 return api_format_data("statuses", $type, $data);
1917 $data = ['status' => $ret[0]];
1918 return api_format_data("status", $type, $data);
1922 /// @TODO move to top of file or somewhere better
1923 api_register_func('api/statuses/show', 'api_statuses_show', true);
1927 * @param string $type Return type (atom, rss, xml, json)
1929 * @return array|string
1930 * @throws BadRequestException
1931 * @throws ForbiddenException
1932 * @throws ImagickException
1933 * @throws InternalServerErrorException
1934 * @throws UnauthorizedException
1935 * @todo nothing to say?
1937 function api_conversation_show($type)
1940 $user_info = api_get_user($a);
1942 if (api_user() === false || $user_info === false) {
1943 throw new ForbiddenException();
1947 $id = intval($a->argv[3] ?? 0);
1948 $since_id = intval($_REQUEST['since_id'] ?? 0);
1949 $max_id = intval($_REQUEST['max_id'] ?? 0);
1950 $count = intval($_REQUEST['count'] ?? 20);
1951 $page = intval($_REQUEST['page'] ?? 1);
1953 $start = max(0, ($page - 1) * $count);
1956 $id = intval($_REQUEST['id'] ?? 0);
1961 $id = intval($a->argv[4] ?? 0);
1964 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1966 // try to fetch the item for the local user - or the public item, if there is no local one
1967 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1968 if (!DBA::isResult($item)) {
1969 throw new BadRequestException("There is no status with this id.");
1972 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1973 if (!DBA::isResult($parent)) {
1974 throw new BadRequestException("There is no status with this id.");
1977 $id = $parent['id'];
1979 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1980 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1983 $condition[0] .= " AND `item`.`id` <= ?";
1984 $condition[] = $max_id;
1987 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1988 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1990 if (!DBA::isResult($statuses)) {
1991 throw new BadRequestException("There is no status with id $id.");
1994 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1996 $data = ['status' => $ret];
1997 return api_format_data("statuses", $type, $data);
2000 /// @TODO move to top of file or somewhere better
2001 api_register_func('api/conversation/show', 'api_conversation_show', true);
2002 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2007 * @param string $type Return type (atom, rss, xml, json)
2009 * @return array|string
2010 * @throws BadRequestException
2011 * @throws ForbiddenException
2012 * @throws ImagickException
2013 * @throws InternalServerErrorException
2014 * @throws UnauthorizedException
2015 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2017 function api_statuses_repeat($type)
2023 if (api_user() === false) {
2024 throw new ForbiddenException();
2030 $id = intval($a->argv[3] ?? 0);
2033 $id = intval($_REQUEST['id'] ?? 0);
2038 $id = intval($a->argv[4] ?? 0);
2041 Logger::log('API: api_statuses_repeat: '.$id);
2043 $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2044 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2046 if (DBA::isResult($item) && $item['body'] != "") {
2047 if (strpos($item['body'], "[/share]") !== false) {
2048 $pos = strpos($item['body'], "[share");
2049 $post = substr($item['body'], $pos);
2051 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2053 if (!empty($item['title'])) {
2054 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2057 $post .= $item['body'];
2058 $post .= "[/share]";
2060 $_REQUEST['body'] = $post;
2061 $_REQUEST['tag'] = $item['tag'];
2062 $_REQUEST['attach'] = $item['attach'];
2063 $_REQUEST['profile_uid'] = api_user();
2064 $_REQUEST['api_source'] = true;
2066 if (empty($_REQUEST['source'])) {
2067 $_REQUEST["source"] = api_source();
2070 $item_id = item_post($a);
2072 throw new ForbiddenException();
2075 // output the post that we just posted.
2077 return api_status_show($type, $item_id);
2080 /// @TODO move to top of file or somewhere better
2081 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2084 * Destroys a specific status.
2086 * @param string $type Return type (atom, rss, xml, json)
2088 * @return array|string
2089 * @throws BadRequestException
2090 * @throws ForbiddenException
2091 * @throws ImagickException
2092 * @throws InternalServerErrorException
2093 * @throws UnauthorizedException
2094 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2096 function api_statuses_destroy($type)
2100 if (api_user() === false) {
2101 throw new ForbiddenException();
2107 $id = intval($a->argv[3] ?? 0);
2110 $id = intval($_REQUEST['id'] ?? 0);
2115 $id = intval($a->argv[4] ?? 0);
2118 Logger::log('API: api_statuses_destroy: '.$id);
2120 $ret = api_statuses_show($type);
2122 Item::deleteForUser(['id' => $id], api_user());
2127 /// @TODO move to top of file or somewhere better
2128 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2131 * Returns the most recent mentions.
2133 * @param string $type Return type (atom, rss, xml, json)
2135 * @return array|string
2136 * @throws BadRequestException
2137 * @throws ForbiddenException
2138 * @throws ImagickException
2139 * @throws InternalServerErrorException
2140 * @throws UnauthorizedException
2141 * @see http://developer.twitter.com/doc/get/statuses/mentions
2143 function api_statuses_mentions($type)
2146 $user_info = api_get_user($a);
2148 if (api_user() === false || $user_info === false) {
2149 throw new ForbiddenException();
2152 unset($_REQUEST["user_id"]);
2153 unset($_GET["user_id"]);
2155 unset($_REQUEST["screen_name"]);
2156 unset($_GET["screen_name"]);
2158 // get last network messages
2161 $since_id = $_REQUEST['since_id'] ?? 0;
2162 $max_id = $_REQUEST['max_id'] ?? 0;
2163 $count = $_REQUEST['count'] ?? 20;
2164 $page = $_REQUEST['page'] ?? 1;
2166 $start = max(0, ($page - 1) * $count);
2168 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ? AND `mention`
2169 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND NOT `thread`.`ignored`)",
2170 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2173 $condition[0] .= " AND `item`.`id` <= ?";
2174 $condition[] = $max_id;
2177 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2178 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2180 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2182 $data = ['status' => $ret];
2187 $data = api_rss_extra($a, $data, $user_info);
2191 return api_format_data("statuses", $type, $data);
2194 /// @TODO move to top of file or somewhere better
2195 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2196 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2199 * Returns the most recent statuses posted by the user.
2201 * @brief Returns a user's public timeline
2203 * @param string $type Either "json" or "xml"
2204 * @return string|array
2205 * @throws BadRequestException
2206 * @throws ForbiddenException
2207 * @throws ImagickException
2208 * @throws InternalServerErrorException
2209 * @throws UnauthorizedException
2210 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2212 function api_statuses_user_timeline($type)
2215 $user_info = api_get_user($a);
2217 if (api_user() === false || $user_info === false) {
2218 throw new ForbiddenException();
2222 "api_statuses_user_timeline: api_user: ". api_user() .
2223 "\nuser_info: ".print_r($user_info, true) .
2224 "\n_REQUEST: ".print_r($_REQUEST, true),
2228 $since_id = $_REQUEST['since_id'] ?? 0;
2229 $max_id = $_REQUEST['max_id'] ?? 0;
2230 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2231 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2234 $count = $_REQUEST['count'] ?? 20;
2235 $page = $_REQUEST['page'] ?? 1;
2237 $start = max(0, ($page - 1) * $count);
2239 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2240 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2242 if ($user_info['self'] == 1) {
2243 $condition[0] .= ' AND `item`.`wall` ';
2246 if ($exclude_replies) {
2247 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2250 if ($conversation_id > 0) {
2251 $condition[0] .= " AND `item`.`parent` = ?";
2252 $condition[] = $conversation_id;
2256 $condition[0] .= " AND `item`.`id` <= ?";
2257 $condition[] = $max_id;
2260 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2261 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2263 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2267 $data = ['status' => $ret];
2272 $data = api_rss_extra($a, $data, $user_info);
2276 return api_format_data("statuses", $type, $data);
2279 /// @TODO move to top of file or somewhere better
2280 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2283 * Star/unstar an item.
2284 * param: id : id of the item
2286 * @param string $type Return type (atom, rss, xml, json)
2288 * @return array|string
2289 * @throws BadRequestException
2290 * @throws ForbiddenException
2291 * @throws ImagickException
2292 * @throws InternalServerErrorException
2293 * @throws UnauthorizedException
2294 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2296 function api_favorites_create_destroy($type)
2300 if (api_user() === false) {
2301 throw new ForbiddenException();
2304 // for versioned api.
2305 /// @TODO We need a better global soluton
2306 $action_argv_id = 2;
2307 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2308 $action_argv_id = 3;
2311 if ($a->argc <= $action_argv_id) {
2312 throw new BadRequestException("Invalid request.");
2314 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2315 if ($a->argc == $action_argv_id + 2) {
2316 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2318 $itemid = intval($_REQUEST['id'] ?? 0);
2321 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2323 if (!DBA::isResult($item)) {
2324 throw new BadRequestException("Invalid item.");
2329 $item['starred'] = 1;
2332 $item['starred'] = 0;
2335 throw new BadRequestException("Invalid action ".$action);
2338 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2341 throw new InternalServerErrorException("DB error");
2345 $user_info = api_get_user($a);
2346 $rets = api_format_items([$item], $user_info, false, $type);
2349 $data = ['status' => $ret];
2354 $data = api_rss_extra($a, $data, $user_info);
2358 return api_format_data("status", $type, $data);
2361 /// @TODO move to top of file or somewhere better
2362 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2363 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2366 * Returns the most recent favorite statuses.
2368 * @param string $type Return type (atom, rss, xml, json)
2370 * @return string|array
2371 * @throws BadRequestException
2372 * @throws ForbiddenException
2373 * @throws ImagickException
2374 * @throws InternalServerErrorException
2375 * @throws UnauthorizedException
2377 function api_favorites($type)
2382 $user_info = api_get_user($a);
2384 if (api_user() === false || $user_info === false) {
2385 throw new ForbiddenException();
2390 // in friendica starred item are private
2391 // return favorites only for self
2392 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2394 if ($user_info['self'] == 0) {
2398 $since_id = $_REQUEST['since_id'] ?? 0;
2399 $max_id = $_REQUEST['max_id'] ?? 0;
2400 $count = $_GET['count'] ?? 20;
2401 $page = $_REQUEST['page'] ?? 1;
2403 $start = max(0, ($page - 1) * $count);
2405 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2406 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2408 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2411 $condition[0] .= " AND `item`.`id` <= ?";
2412 $condition[] = $max_id;
2415 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2417 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2422 $data = ['status' => $ret];
2427 $data = api_rss_extra($a, $data, $user_info);
2431 return api_format_data("statuses", $type, $data);
2434 /// @TODO move to top of file or somewhere better
2435 api_register_func('api/favorites', 'api_favorites', true);
2439 * @param array $item
2440 * @param array $recipient
2441 * @param array $sender
2444 * @throws InternalServerErrorException
2446 function api_format_messages($item, $recipient, $sender)
2448 // standard meta information
2450 'id' => $item['id'],
2451 'sender_id' => $sender['id'],
2453 'recipient_id' => $recipient['id'],
2454 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2455 'sender_screen_name' => $sender['screen_name'],
2456 'recipient_screen_name' => $recipient['screen_name'],
2457 'sender' => $sender,
2458 'recipient' => $recipient,
2460 'friendica_seen' => $item['seen'] ?? 0,
2461 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2464 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2465 if (isset($ret['sender']['uid'])) {
2466 unset($ret['sender']['uid']);
2468 if (isset($ret['sender']['self'])) {
2469 unset($ret['sender']['self']);
2471 if (isset($ret['recipient']['uid'])) {
2472 unset($ret['recipient']['uid']);
2474 if (isset($ret['recipient']['self'])) {
2475 unset($ret['recipient']['self']);
2478 //don't send title to regular StatusNET requests to avoid confusing these apps
2479 if (!empty($_GET['getText'])) {
2480 $ret['title'] = $item['title'];
2481 if ($_GET['getText'] == 'html') {
2482 $ret['text'] = BBCode::convert($item['body'], false);
2483 } elseif ($_GET['getText'] == 'plain') {
2484 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2487 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2489 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2490 unset($ret['sender']);
2491 unset($ret['recipient']);
2499 * @param array $item
2502 * @throws InternalServerErrorException
2504 function api_convert_item($item)
2506 $body = $item['body'];
2507 $entities = api_get_entitities($statustext, $body);
2509 // Add pictures to the attachment array and remove them from the body
2510 $attachments = api_get_attachments($body);
2512 // Workaround for ostatus messages where the title is identically to the body
2513 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2514 $statusbody = trim(HTML::toPlaintext($html, 0));
2516 // handle data: images
2517 $statusbody = api_format_items_embeded_images($item, $statusbody);
2519 $statustitle = trim($item['title']);
2521 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2522 $statustext = trim($statusbody);
2524 $statustext = trim($statustitle."\n\n".$statusbody);
2527 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2528 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2531 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2533 // Workaround for clients with limited HTML parser functionality
2534 $search = ["<br>", "<blockquote>", "</blockquote>",
2535 "<h1>", "</h1>", "<h2>", "</h2>",
2536 "<h3>", "</h3>", "<h4>", "</h4>",
2537 "<h5>", "</h5>", "<h6>", "</h6>"];
2538 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2539 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2540 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2541 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2542 $statushtml = str_replace($search, $replace, $statushtml);
2544 if ($item['title'] != "") {
2545 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2549 $oldtext = $statushtml;
2550 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2551 } while ($oldtext != $statushtml);
2553 if (substr($statushtml, 0, 4) == '<br>') {
2554 $statushtml = substr($statushtml, 4);
2557 if (substr($statushtml, 0, -4) == '<br>') {
2558 $statushtml = substr($statushtml, -4);
2561 // feeds without body should contain the link
2562 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2563 $statushtml .= BBCode::convert($item['plink']);
2567 "text" => $statustext,
2568 "html" => $statushtml,
2569 "attachments" => $attachments,
2570 "entities" => $entities
2576 * @param string $body
2579 * @throws InternalServerErrorException
2581 function api_get_attachments(&$body)
2583 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2584 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2586 $URLSearchString = "^\[\]";
2587 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2591 // Remove all embedded pictures, since they are added as attachments
2592 foreach ($images[0] as $orig) {
2593 $body = str_replace($orig, '', $body);
2598 foreach ($images[1] as $image) {
2599 $imagedata = Images::getInfoFromURLCached($image);
2602 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2606 return $attachments;
2611 * @param string $text
2612 * @param string $bbcode
2615 * @throws InternalServerErrorException
2616 * @todo Links at the first character of the post
2618 function api_get_entitities(&$text, $bbcode)
2620 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2622 if ($include_entities != "true") {
2623 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2625 foreach ($images[1] as $image) {
2626 $replace = ProxyUtils::proxifyUrl($image);
2627 $text = str_replace($image, $replace, $text);
2632 $bbcode = BBCode::cleanPictureLinks($bbcode);
2634 // Change pure links in text to bbcode uris
2635 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2638 $entities["hashtags"] = [];
2639 $entities["symbols"] = [];
2640 $entities["urls"] = [];
2641 $entities["user_mentions"] = [];
2643 $URLSearchString = "^\[\]";
2645 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2647 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2648 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2650 $bbcode = preg_replace(
2651 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2652 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2655 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2657 $bbcode = preg_replace(
2658 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2659 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2662 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2664 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2666 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2669 foreach ($urls[1] as $id => $url) {
2670 $start = iconv_strpos($text, $url, 0, "UTF-8");
2671 if (!($start === false)) {
2672 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2676 ksort($ordered_urls);
2680 foreach ($ordered_urls as $url) {
2681 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2682 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2684 $display_url = $url["title"];
2686 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2687 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2689 if (strlen($display_url) > 26) {
2690 $display_url = substr($display_url, 0, 25)."…";
2694 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2695 if (!($start === false)) {
2696 $entities["urls"][] = ["url" => $url["url"],
2697 "expanded_url" => $url["url"],
2698 "display_url" => $display_url,
2699 "indices" => [$start, $start+strlen($url["url"])]];
2700 $offset = $start + 1;
2704 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2705 $ordered_images = [];
2706 foreach ($images as $image) {
2707 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2708 if (!($start === false)) {
2709 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2713 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2714 foreach ($images[1] as $image) {
2715 $start = iconv_strpos($text, $image, 0, "UTF-8");
2716 if (!($start === false)) {
2717 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2723 foreach ($ordered_images as $image) {
2724 $url = $image['url'];
2725 $ext_alt_text = $image['alt'];
2727 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2728 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2730 if (strlen($display_url) > 26) {
2731 $display_url = substr($display_url, 0, 25)."…";
2734 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2735 if (!($start === false)) {
2736 $image = Images::getInfoFromURLCached($url);
2738 // If image cache is activated, then use the following sizes:
2739 // thumb (150), small (340), medium (600) and large (1024)
2740 if (!Config::get("system", "proxy_disabled")) {
2741 $media_url = ProxyUtils::proxifyUrl($url);
2744 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2745 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2747 if (($image[0] > 150) || ($image[1] > 150)) {
2748 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2749 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2752 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2753 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2755 if (($image[0] > 600) || ($image[1] > 600)) {
2756 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2757 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2761 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2764 $entities["media"][] = [
2766 "id_str" => (string) ($start + 1),
2767 "indices" => [$start, $start+strlen($url)],
2768 "media_url" => Strings::normaliseLink($media_url),
2769 "media_url_https" => $media_url,
2771 "display_url" => $display_url,
2772 "expanded_url" => $url,
2773 "ext_alt_text" => $ext_alt_text,
2777 $offset = $start + 1;
2786 * @param array $item
2787 * @param string $text
2791 function api_format_items_embeded_images($item, $text)
2793 $text = preg_replace_callback(
2794 '|data:image/([^;]+)[^=]+=*|m',
2795 function () use ($item) {
2796 return System::baseUrl() . '/display/' . $item['guid'];
2804 * @brief return <a href='url'>name</a> as array
2806 * @param string $txt text
2811 function api_contactlink_to_array($txt)
2814 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2815 if ($r && count($match)==3) {
2817 'name' => $match[2],
2831 * @brief return likes, dislikes and attend status for item
2833 * @param array $item array
2834 * @param string $type Return type (atom, rss, xml, json)
2837 * likes => int count,
2838 * dislikes => int count
2839 * @throws BadRequestException
2840 * @throws ImagickException
2841 * @throws InternalServerErrorException
2842 * @throws UnauthorizedException
2844 function api_format_items_activities($item, $type = "json")
2853 'attendmaybe' => [],
2857 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2858 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2860 while ($parent_item = Item::fetch($ret)) {
2861 // not used as result should be structured like other user data
2862 //builtin_activity_puller($i, $activities);
2864 // get user data and add it to the array of the activity
2865 $user = api_get_user($a, $parent_item['author-id']);
2866 switch ($parent_item['verb']) {
2867 case Activity::LIKE:
2868 $activities['like'][] = $user;
2870 case Activity::DISLIKE:
2871 $activities['dislike'][] = $user;
2873 case Activity::ATTEND:
2874 $activities['attendyes'][] = $user;
2876 case Activity::ATTENDNO:
2877 $activities['attendno'][] = $user;
2879 case Activity::ATTENDMAYBE:
2880 $activities['attendmaybe'][] = $user;
2882 case Activity::ANNOUNCE:
2883 $activities['announce'][] = $user;
2892 if ($type == "xml") {
2893 $xml_activities = [];
2894 foreach ($activities as $k => $v) {
2895 // change xml element from "like" to "friendica:like"
2896 $xml_activities["friendica:".$k] = $v;
2897 // add user data into xml output
2899 foreach ($v as $user) {
2900 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2903 $activities = $xml_activities;
2911 * @brief return data from profiles
2913 * @param array $profile_row array containing data from db table 'profile'
2915 * @throws InternalServerErrorException
2917 function api_format_items_profiles($profile_row)
2920 'profile_id' => $profile_row['id'],
2921 'profile_name' => $profile_row['profile-name'],
2922 'is_default' => $profile_row['is-default'] ? true : false,
2923 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2924 'profile_photo' => $profile_row['photo'],
2925 'profile_thumb' => $profile_row['thumb'],
2926 'publish' => $profile_row['publish'] ? true : false,
2927 'net_publish' => $profile_row['net-publish'] ? true : false,
2928 'description' => $profile_row['pdesc'],
2929 'date_of_birth' => $profile_row['dob'],
2930 'address' => $profile_row['address'],
2931 'city' => $profile_row['locality'],
2932 'region' => $profile_row['region'],
2933 'postal_code' => $profile_row['postal-code'],
2934 'country' => $profile_row['country-name'],
2935 'hometown' => $profile_row['hometown'],
2936 'gender' => $profile_row['gender'],
2937 'marital' => $profile_row['marital'],
2938 'marital_with' => $profile_row['with'],
2939 'marital_since' => $profile_row['howlong'],
2940 'sexual' => $profile_row['sexual'],
2941 'politic' => $profile_row['politic'],
2942 'religion' => $profile_row['religion'],
2943 'public_keywords' => $profile_row['pub_keywords'],
2944 'private_keywords' => $profile_row['prv_keywords'],
2945 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2946 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2947 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2948 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2949 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2950 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2951 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2952 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2953 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2954 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2955 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2956 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2957 'homepage' => $profile_row['homepage'],
2964 * @brief format items to be returned by api
2966 * @param array $items array of items
2967 * @param array $user_info
2968 * @param bool $filter_user filter items by $user_info
2969 * @param string $type Return type (atom, rss, xml, json)
2971 * @throws BadRequestException
2972 * @throws ImagickException
2973 * @throws InternalServerErrorException
2974 * @throws UnauthorizedException
2976 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2978 $a = BaseObject::getApp();
2982 foreach ((array)$items as $item) {
2983 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2985 // Look if the posts are matching if they should be filtered by user id
2986 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2990 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2999 * @param array $item Item record
3000 * @param string $type Return format (atom, rss, xml, json)
3001 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
3002 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
3003 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
3004 * @return array API-formatted status
3005 * @throws BadRequestException
3006 * @throws ImagickException
3007 * @throws InternalServerErrorException
3008 * @throws UnauthorizedException
3010 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
3012 $a = BaseObject::getApp();
3014 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3015 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3018 localize_item($item);
3020 $in_reply_to = api_in_reply_to($item);
3022 $converted = api_convert_item($item);
3024 if ($type == "xml") {
3025 $geo = "georss:point";
3031 'text' => $converted["text"],
3032 'truncated' => false,
3033 'created_at'=> api_date($item['created']),
3034 'in_reply_to_status_id' => $in_reply_to['status_id'],
3035 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3036 'source' => (($item['app']) ? $item['app'] : 'web'),
3037 'id' => intval($item['id']),
3038 'id_str' => (string) intval($item['id']),
3039 'in_reply_to_user_id' => $in_reply_to['user_id'],
3040 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3041 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3043 'favorited' => $item['starred'] ? true : false,
3044 'user' => $status_user,
3045 'friendica_author' => $author_user,
3046 'friendica_owner' => $owner_user,
3047 'friendica_private' => $item['private'] == 1,
3048 //'entities' => NULL,
3049 'statusnet_html' => $converted["html"],
3050 'statusnet_conversation_id' => $item['parent'],
3051 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3052 'friendica_activities' => api_format_items_activities($item, $type),
3053 'friendica_title' => $item['title'],
3054 'friendica_html' => BBCode::convert($item['body'], false)
3057 if (count($converted["attachments"]) > 0) {
3058 $status["attachments"] = $converted["attachments"];
3061 if (count($converted["entities"]) > 0) {
3062 $status["entities"] = $converted["entities"];
3065 if ($status["source"] == 'web') {
3066 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3067 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3068 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3071 $retweeted_item = [];
3074 if ($item["id"] == $item["parent"]) {
3075 $body = $item['body'];
3076 $retweeted_item = api_share_as_retweet($item);
3077 if ($body != $item['body']) {
3078 $quoted_item = $retweeted_item;
3079 $retweeted_item = [];
3083 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3084 $announce = api_get_announce($item);
3085 if (!empty($announce)) {
3086 $retweeted_item = $item;
3088 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3092 if (!empty($quoted_item)) {
3093 if ($quoted_item['id'] != $item['id']) {
3094 $quoted_status = api_format_item($quoted_item);
3095 /// @todo Only remove the attachments that are also contained in the quotes status
3096 unset($status['attachments']);
3097 unset($status['entities']);
3099 $conv_quoted = api_convert_item($quoted_item);
3100 $quoted_status = $status;
3101 unset($quoted_status['attachments']);
3102 unset($quoted_status['entities']);
3103 unset($quoted_status['statusnet_conversation_id']);
3104 $quoted_status['text'] = $conv_quoted['text'];
3105 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3107 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3108 } catch (BadRequestException $e) {
3109 // user not found. should be found?
3110 /// @todo check if the user should be always found
3111 $quoted_status["user"] = [];
3114 unset($quoted_status['friendica_author']);
3115 unset($quoted_status['friendica_owner']);
3116 unset($quoted_status['friendica_activities']);
3117 unset($quoted_status['friendica_private']);
3120 if (!empty($retweeted_item)) {
3121 $retweeted_status = $status;
3122 unset($retweeted_status['friendica_author']);
3123 unset($retweeted_status['friendica_owner']);
3124 unset($retweeted_status['friendica_activities']);
3125 unset($retweeted_status['friendica_private']);
3126 unset($retweeted_status['statusnet_conversation_id']);
3127 $status['user'] = $status['friendica_owner'];
3129 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3130 } catch (BadRequestException $e) {
3131 // user not found. should be found?
3132 /// @todo check if the user should be always found
3133 $retweeted_status["user"] = [];
3136 $rt_converted = api_convert_item($retweeted_item);
3138 $retweeted_status['text'] = $rt_converted["text"];
3139 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3140 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3142 if (!empty($quoted_status)) {
3143 $retweeted_status['quoted_status'] = $quoted_status;
3146 $status['friendica_author'] = $retweeted_status['user'];
3147 $status['retweeted_status'] = $retweeted_status;
3148 } elseif (!empty($quoted_status)) {
3149 $root_status = api_convert_item($item);
3151 $status['text'] = $root_status["text"];
3152 $status['statusnet_html'] = $root_status["html"];
3153 $status['quoted_status'] = $quoted_status;
3156 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3157 unset($status["user"]["uid"]);
3158 unset($status["user"]["self"]);
3160 if ($item["coord"] != "") {
3161 $coords = explode(' ', $item["coord"]);
3162 if (count($coords) == 2) {
3163 if ($type == "json") {
3164 $status["geo"] = ['type' => 'Point',
3165 'coordinates' => [(float) $coords[0],
3166 (float) $coords[1]]];
3167 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3168 $status["georss:point"] = $item["coord"];
3177 * Returns the remaining number of API requests available to the user before the API limit is reached.
3179 * @param string $type Return type (atom, rss, xml, json)
3181 * @return array|string
3184 function api_account_rate_limit_status($type)
3186 if ($type == "xml") {
3188 'remaining-hits' => '150',
3189 '@attributes' => ["type" => "integer"],
3190 'hourly-limit' => '150',
3191 '@attributes2' => ["type" => "integer"],
3192 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3193 '@attributes3' => ["type" => "datetime"],
3194 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3195 '@attributes4' => ["type" => "integer"],
3199 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3200 'remaining_hits' => '150',
3201 'hourly_limit' => '150',
3202 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3206 return api_format_data('hash', $type, ['hash' => $hash]);
3209 /// @TODO move to top of file or somewhere better
3210 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3213 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3215 * @param string $type Return type (atom, rss, xml, json)
3217 * @return array|string
3219 function api_help_test($type)
3221 if ($type == 'xml') {
3227 return api_format_data('ok', $type, ["ok" => $ok]);
3230 /// @TODO move to top of file or somewhere better
3231 api_register_func('api/help/test', 'api_help_test', false);
3234 * Returns all lists the user subscribes to.
3236 * @param string $type Return type (atom, rss, xml, json)
3238 * @return array|string
3239 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3241 function api_lists_list($type)
3244 /// @TODO $ret is not filled here?
3245 return api_format_data('lists', $type, ["lists_list" => $ret]);
3248 /// @TODO move to top of file or somewhere better
3249 api_register_func('api/lists/list', 'api_lists_list', true);
3250 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3253 * Returns all groups the user owns.
3255 * @param string $type Return type (atom, rss, xml, json)
3257 * @return array|string
3258 * @throws BadRequestException
3259 * @throws ForbiddenException
3260 * @throws ImagickException
3261 * @throws InternalServerErrorException
3262 * @throws UnauthorizedException
3263 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3265 function api_lists_ownerships($type)
3269 if (api_user() === false) {
3270 throw new ForbiddenException();
3274 $user_info = api_get_user($a);
3275 $uid = $user_info['uid'];
3277 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3279 // loop through all groups
3281 foreach ($groups as $group) {
3282 if ($group['visible']) {
3288 'name' => $group['name'],
3289 'id' => intval($group['id']),
3290 'id_str' => (string) $group['id'],
3291 'user' => $user_info,
3295 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3298 /// @TODO move to top of file or somewhere better
3299 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3302 * Returns recent statuses from users in the specified group.
3304 * @param string $type Return type (atom, rss, xml, json)
3306 * @return array|string
3307 * @throws BadRequestException
3308 * @throws ForbiddenException
3309 * @throws ImagickException
3310 * @throws InternalServerErrorException
3311 * @throws UnauthorizedException
3312 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3314 function api_lists_statuses($type)
3318 $user_info = api_get_user($a);
3319 if (api_user() === false || $user_info === false) {
3320 throw new ForbiddenException();
3323 unset($_REQUEST["user_id"]);
3324 unset($_GET["user_id"]);
3326 unset($_REQUEST["screen_name"]);
3327 unset($_GET["screen_name"]);
3329 if (empty($_REQUEST['list_id'])) {
3330 throw new BadRequestException('list_id not specified');
3334 $count = $_REQUEST['count'] ?? 20;
3335 $page = $_REQUEST['page'] ?? 1;
3336 $since_id = $_REQUEST['since_id'] ?? 0;
3337 $max_id = $_REQUEST['max_id'] ?? 0;
3338 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3339 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3341 $start = max(0, ($page - 1) * $count);
3343 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3344 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3347 $condition[0] .= " AND `item`.`id` <= ?";
3348 $condition[] = $max_id;
3350 if ($exclude_replies > 0) {
3351 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3353 if ($conversation_id > 0) {
3354 $condition[0] .= " AND `item`.`parent` = ?";
3355 $condition[] = $conversation_id;
3358 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3359 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3361 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3363 $data = ['status' => $items];
3368 $data = api_rss_extra($a, $data, $user_info);
3372 return api_format_data("statuses", $type, $data);
3375 /// @TODO move to top of file or somewhere better
3376 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3379 * Considers friends and followers lists to be private and won't return
3380 * anything if any user_id parameter is passed.
3382 * @brief Returns either the friends of the follower list
3384 * @param string $qtype Either "friends" or "followers"
3385 * @return boolean|array
3386 * @throws BadRequestException
3387 * @throws ForbiddenException
3388 * @throws ImagickException
3389 * @throws InternalServerErrorException
3390 * @throws UnauthorizedException
3392 function api_statuses_f($qtype)
3396 if (api_user() === false) {
3397 throw new ForbiddenException();
3401 $count = $_GET['count'] ?? 20;
3402 $page = $_GET['page'] ?? 1;
3404 $start = max(0, ($page - 1) * $count);
3406 $user_info = api_get_user($a);
3408 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3409 /* this is to stop Hotot to load friends multiple times
3410 * I'm not sure if I'm missing return something or
3411 * is a bug in hotot. Workaround, meantime
3415 return array('$users' => $ret);*/
3420 if ($qtype == 'friends') {
3421 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3422 } elseif ($qtype == 'followers') {
3423 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3426 // friends and followers only for self
3427 if ($user_info['self'] == 0) {
3428 $sql_extra = " AND false ";
3431 if ($qtype == 'blocks') {
3432 $sql_filter = 'AND `blocked` AND NOT `pending`';
3433 } elseif ($qtype == 'incoming') {
3434 $sql_filter = 'AND `pending`';
3436 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3454 foreach ($r as $cid) {
3455 $user = api_get_user($a, $cid['nurl']);
3456 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3457 unset($user["uid"]);
3458 unset($user["self"]);
3465 return ['user' => $ret];
3470 * Returns the user's friends.
3472 * @brief Returns the list of friends of the provided user
3474 * @deprecated By Twitter API in favor of friends/list
3476 * @param string $type Either "json" or "xml"
3477 * @return boolean|string|array
3478 * @throws BadRequestException
3479 * @throws ForbiddenException
3481 function api_statuses_friends($type)
3483 $data = api_statuses_f("friends");
3484 if ($data === false) {
3487 return api_format_data("users", $type, $data);
3491 * Returns the user's followers.
3493 * @brief Returns the list of followers of the provided user
3495 * @deprecated By Twitter API in favor of friends/list
3497 * @param string $type Either "json" or "xml"
3498 * @return boolean|string|array
3499 * @throws BadRequestException
3500 * @throws ForbiddenException
3502 function api_statuses_followers($type)
3504 $data = api_statuses_f("followers");
3505 if ($data === false) {
3508 return api_format_data("users", $type, $data);
3511 /// @TODO move to top of file or somewhere better
3512 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3513 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3516 * Returns the list of blocked users
3518 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3520 * @param string $type Either "json" or "xml"
3522 * @return boolean|string|array
3523 * @throws BadRequestException
3524 * @throws ForbiddenException
3526 function api_blocks_list($type)
3528 $data = api_statuses_f('blocks');
3529 if ($data === false) {
3532 return api_format_data("users", $type, $data);
3535 /// @TODO move to top of file or somewhere better
3536 api_register_func('api/blocks/list', 'api_blocks_list', true);
3539 * Returns the list of pending users IDs
3541 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3543 * @param string $type Either "json" or "xml"
3545 * @return boolean|string|array
3546 * @throws BadRequestException
3547 * @throws ForbiddenException
3549 function api_friendships_incoming($type)
3551 $data = api_statuses_f('incoming');
3552 if ($data === false) {
3557 foreach ($data['user'] as $user) {
3558 $ids[] = $user['id'];
3561 return api_format_data("ids", $type, ['id' => $ids]);
3564 /// @TODO move to top of file or somewhere better
3565 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3568 * Returns the instance's configuration information.
3570 * @param string $type Return type (atom, rss, xml, json)
3572 * @return array|string
3573 * @throws InternalServerErrorException
3575 function api_statusnet_config($type)
3579 $name = Config::get('config', 'sitename');
3580 $server = $a->getHostName();
3581 $logo = System::baseUrl() . '/images/friendica-64.png';
3582 $email = Config::get('config', 'admin_email');
3583 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3584 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3585 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3586 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3587 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3590 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3591 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3592 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3593 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3594 'shorturllength' => '30',
3596 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3597 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3598 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3599 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3604 return api_format_data('config', $type, ['config' => $config]);
3607 /// @TODO move to top of file or somewhere better
3608 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3609 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3613 * @param string $type Return type (atom, rss, xml, json)
3615 * @return array|string
3617 function api_statusnet_version($type)
3620 $fake_statusnet_version = "0.9.7";
3622 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3625 /// @TODO move to top of file or somewhere better
3626 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3627 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3631 * @param string $type Return type (atom, rss, xml, json)
3633 * @param int $rel A contact relationship constant
3634 * @return array|string|void
3635 * @throws BadRequestException
3636 * @throws ForbiddenException
3637 * @throws ImagickException
3638 * @throws InternalServerErrorException
3639 * @throws UnauthorizedException
3640 * @todo use api_format_data() to return data
3642 function api_ff_ids($type, int $rel)
3645 throw new ForbiddenException();
3652 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3654 $contacts = DBA::p("SELECT `pcontact`.`id`
3656 INNER JOIN `contact` AS `pcontact`
3657 ON `contact`.`nurl` = `pcontact`.`nurl`
3658 AND `pcontact`.`uid` = 0
3659 WHERE `contact`.`uid` = ?
3660 AND NOT `contact`.`self`
3661 AND `contact`.`rel` IN (?, ?)",
3668 foreach (DBA::toArray($contacts) as $contact) {
3669 if ($stringify_ids) {
3670 $ids[] = $contact['id'];
3672 $ids[] = intval($contact['id']);
3676 return api_format_data('ids', $type, ['id' => $ids]);
3680 * Returns the ID of every user the user is following.
3682 * @param string $type Return type (atom, rss, xml, json)
3684 * @return array|string
3685 * @throws BadRequestException
3686 * @throws ForbiddenException
3687 * @throws ImagickException
3688 * @throws InternalServerErrorException
3689 * @throws UnauthorizedException
3690 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3692 function api_friends_ids($type)
3694 return api_ff_ids($type, Contact::SHARING);
3698 * Returns the ID of every user following the user.
3700 * @param string $type Return type (atom, rss, xml, json)
3702 * @return array|string
3703 * @throws BadRequestException
3704 * @throws ForbiddenException
3705 * @throws ImagickException
3706 * @throws InternalServerErrorException
3707 * @throws UnauthorizedException
3708 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3710 function api_followers_ids($type)
3712 return api_ff_ids($type, Contact::FOLLOWER);
3715 /// @TODO move to top of file or somewhere better
3716 api_register_func('api/friends/ids', 'api_friends_ids', true);
3717 api_register_func('api/followers/ids', 'api_followers_ids', true);
3720 * Sends a new direct message.
3722 * @param string $type Return type (atom, rss, xml, json)
3724 * @return array|string
3725 * @throws BadRequestException
3726 * @throws ForbiddenException
3727 * @throws ImagickException
3728 * @throws InternalServerErrorException
3729 * @throws NotFoundException
3730 * @throws UnauthorizedException
3731 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3733 function api_direct_messages_new($type)
3737 if (api_user() === false) {
3738 throw new ForbiddenException();
3741 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3745 $sender = api_get_user($a);
3748 if (!empty($_POST['screen_name'])) {
3750 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3752 DBA::escape($_POST['screen_name'])
3755 if (DBA::isResult($r)) {
3756 // Selecting the id by priority, friendica first
3757 api_best_nickname($r);
3759 $recipient = api_get_user($a, $r[0]['nurl']);
3762 $recipient = api_get_user($a, $_POST['user_id']);
3765 if (empty($recipient)) {
3766 throw new NotFoundException('Recipient not found');
3770 if (!empty($_REQUEST['replyto'])) {
3772 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3774 intval($_REQUEST['replyto'])
3776 $replyto = $r[0]['parent-uri'];
3777 $sub = $r[0]['title'];
3779 if (!empty($_REQUEST['title'])) {
3780 $sub = $_REQUEST['title'];
3782 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3786 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3789 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3790 $ret = api_format_messages($r[0], $recipient, $sender);
3792 $ret = ["error"=>$id];
3795 $data = ['direct_message'=>$ret];
3801 $data = api_rss_extra($a, $data, $sender);
3805 return api_format_data("direct-messages", $type, $data);
3808 /// @TODO move to top of file or somewhere better
3809 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3812 * Destroys a direct message.
3814 * @brief delete a direct_message from mail table through api
3816 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3817 * @return string|array
3818 * @throws BadRequestException
3819 * @throws ForbiddenException
3820 * @throws ImagickException
3821 * @throws InternalServerErrorException
3822 * @throws UnauthorizedException
3823 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3825 function api_direct_messages_destroy($type)
3829 if (api_user() === false) {
3830 throw new ForbiddenException();
3834 $user_info = api_get_user($a);
3836 $id = $_REQUEST['id'] ?? 0;
3838 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3839 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3840 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3842 $uid = $user_info['uid'];
3843 // error if no id or parenturi specified (for clients posting parent-uri as well)
3844 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3845 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3846 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3849 // BadRequestException if no id specified (for clients using Twitter API)
3851 throw new BadRequestException('Message id not specified');
3854 // add parent-uri to sql command if specified by calling app
3855 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3857 // get data of the specified message id
3859 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3864 // error message if specified id is not in database
3865 if (!DBA::isResult($r)) {
3866 if ($verbose == "true") {
3867 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3868 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3870 /// @todo BadRequestException ok for Twitter API clients?
3871 throw new BadRequestException('message id not in database');
3876 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3881 if ($verbose == "true") {
3884 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3885 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3887 $answer = ['result' => 'error', 'message' => 'unknown error'];
3888 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3891 /// @todo return JSON data like Twitter API not yet implemented
3894 /// @TODO move to top of file or somewhere better
3895 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3900 * @brief unfollow contact
3902 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3903 * @return string|array
3904 * @throws BadRequestException
3905 * @throws ForbiddenException
3906 * @throws ImagickException
3907 * @throws InternalServerErrorException
3908 * @throws NotFoundException
3909 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3911 function api_friendships_destroy($type)
3915 if ($uid === false) {
3916 throw new ForbiddenException();
3919 $contact_id = $_REQUEST['user_id'] ?? 0;
3921 if (empty($contact_id)) {
3922 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3923 throw new BadRequestException("no user_id specified");
3926 // Get Contact by given id
3927 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3929 if(!DBA::isResult($contact)) {
3930 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3931 throw new NotFoundException("no contact found to given ID");
3934 $url = $contact["url"];
3936 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3937 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3938 Strings::normaliseLink($url), $url];
3939 $contact = DBA::selectFirst('contact', [], $condition);
3941 if (!DBA::isResult($contact)) {
3942 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3943 throw new NotFoundException("Not following Contact");
3946 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3947 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3948 throw new ExpectationFailedException("Not supported");
3951 $dissolve = ($contact['rel'] == Contact::SHARING);
3953 $owner = User::getOwnerDataById($uid);
3955 Contact::terminateFriendship($owner, $contact, $dissolve);
3958 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3959 throw new NotFoundException("Error Processing Request");
3962 // Sharing-only contacts get deleted as there no relationship any more
3964 Contact::remove($contact['id']);
3966 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3969 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3970 unset($contact["uid"]);
3971 unset($contact["self"]);
3973 // Set screen_name since Twidere requests it
3974 $contact["screen_name"] = $contact["nick"];
3976 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3978 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3982 * @param string $type Return type (atom, rss, xml, json)
3983 * @param string $box
3984 * @param string $verbose
3986 * @return array|string
3987 * @throws BadRequestException
3988 * @throws ForbiddenException
3989 * @throws ImagickException
3990 * @throws InternalServerErrorException
3991 * @throws UnauthorizedException
3993 function api_direct_messages_box($type, $box, $verbose)
3996 if (api_user() === false) {
3997 throw new ForbiddenException();
4000 $count = $_GET['count'] ?? 20;
4001 $page = $_REQUEST['page'] ?? 1;
4003 $since_id = $_REQUEST['since_id'] ?? 0;
4004 $max_id = $_REQUEST['max_id'] ?? 0;
4006 $user_id = $_REQUEST['user_id'] ?? '';
4007 $screen_name = $_REQUEST['screen_name'] ?? '';
4010 unset($_REQUEST["user_id"]);
4011 unset($_GET["user_id"]);
4013 unset($_REQUEST["screen_name"]);
4014 unset($_GET["screen_name"]);
4016 $user_info = api_get_user($a);
4017 if ($user_info === false) {
4018 throw new ForbiddenException();
4020 $profile_url = $user_info["url"];
4023 $start = max(0, ($page - 1) * $count);
4028 if ($box=="sentbox") {
4029 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
4030 } elseif ($box == "conversation") {
4031 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
4032 } elseif ($box == "all") {
4033 $sql_extra = "true";
4034 } elseif ($box == "inbox") {
4035 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
4039 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
4042 if ($user_id != "") {
4043 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4044 } elseif ($screen_name !="") {
4045 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4049 "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",
4055 if ($verbose == "true" && !DBA::isResult($r)) {
4056 $answer = ['result' => 'error', 'message' => 'no mails available'];
4057 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4061 foreach ($r as $item) {
4062 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4063 $recipient = $user_info;
4064 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4065 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4066 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4067 $sender = $user_info;
4070 if (isset($recipient) && isset($sender)) {
4071 $ret[] = api_format_messages($item, $recipient, $sender);
4076 $data = ['direct_message' => $ret];
4081 $data = api_rss_extra($a, $data, $user_info);
4085 return api_format_data("direct-messages", $type, $data);
4089 * Returns the most recent direct messages sent by the user.
4091 * @param string $type Return type (atom, rss, xml, json)
4093 * @return array|string
4094 * @throws BadRequestException
4095 * @throws ForbiddenException
4096 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4098 function api_direct_messages_sentbox($type)
4100 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4101 return api_direct_messages_box($type, "sentbox", $verbose);
4105 * Returns the most recent direct messages sent to the user.
4107 * @param string $type Return type (atom, rss, xml, json)
4109 * @return array|string
4110 * @throws BadRequestException
4111 * @throws ForbiddenException
4112 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4114 function api_direct_messages_inbox($type)
4116 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4117 return api_direct_messages_box($type, "inbox", $verbose);
4122 * @param string $type Return type (atom, rss, xml, json)
4124 * @return array|string
4125 * @throws BadRequestException
4126 * @throws ForbiddenException
4128 function api_direct_messages_all($type)
4130 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4131 return api_direct_messages_box($type, "all", $verbose);
4136 * @param string $type Return type (atom, rss, xml, json)
4138 * @return array|string
4139 * @throws BadRequestException
4140 * @throws ForbiddenException
4142 function api_direct_messages_conversation($type)
4144 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4145 return api_direct_messages_box($type, "conversation", $verbose);
4148 /// @TODO move to top of file or somewhere better
4149 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4150 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4151 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4152 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4155 * Returns an OAuth Request Token.
4157 * @see https://oauth.net/core/1.0/#auth_step1
4159 function api_oauth_request_token()
4161 $oauth1 = new FKOAuth1();
4163 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4164 } catch (Exception $e) {
4165 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4173 * Returns an OAuth Access Token.
4175 * @return array|string
4176 * @see https://oauth.net/core/1.0/#auth_step3
4178 function api_oauth_access_token()
4180 $oauth1 = new FKOAuth1();
4182 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4183 } catch (Exception $e) {
4184 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4191 /// @TODO move to top of file or somewhere better
4192 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4193 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4197 * @brief delete a complete photoalbum with all containing photos from database through api
4199 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4200 * @return string|array
4201 * @throws BadRequestException
4202 * @throws ForbiddenException
4203 * @throws InternalServerErrorException
4205 function api_fr_photoalbum_delete($type)
4207 if (api_user() === false) {
4208 throw new ForbiddenException();
4211 $album = $_REQUEST['album'] ?? '';
4213 // we do not allow calls without album string
4215 throw new BadRequestException("no albumname specified");
4217 // check if album is existing
4219 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4223 if (!DBA::isResult($r)) {
4224 throw new BadRequestException("album not available");
4227 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4228 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4229 foreach ($r as $rr) {
4230 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4231 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4233 if (!DBA::isResult($photo_item)) {
4234 throw new InternalServerErrorException("problem with deleting items occured");
4236 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4239 // now let's delete all photos from the album
4240 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4242 // return success of deletion or error message
4244 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4245 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4247 throw new InternalServerErrorException("unknown error - deleting from database failed");
4252 * @brief update the name of the album for all photos of an album
4254 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4255 * @return string|array
4256 * @throws BadRequestException
4257 * @throws ForbiddenException
4258 * @throws InternalServerErrorException
4260 function api_fr_photoalbum_update($type)
4262 if (api_user() === false) {
4263 throw new ForbiddenException();
4266 $album = $_REQUEST['album'] ?? '';
4267 $album_new = $_REQUEST['album_new'] ?? '';
4269 // we do not allow calls without album string
4271 throw new BadRequestException("no albumname specified");
4273 if ($album_new == "") {
4274 throw new BadRequestException("no new albumname specified");
4276 // check if album is existing
4277 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4278 throw new BadRequestException("album not available");
4280 // now let's update all photos to the albumname
4281 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4283 // return success of updating or error message
4285 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4286 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4288 throw new InternalServerErrorException("unknown error - updating in database failed");
4294 * @brief list all photos of the authenticated user
4296 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4297 * @return string|array
4298 * @throws ForbiddenException
4299 * @throws InternalServerErrorException
4301 function api_fr_photos_list($type)
4303 if (api_user() === false) {
4304 throw new ForbiddenException();
4307 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4308 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4309 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4310 intval(local_user())
4313 'image/jpeg' => 'jpg',
4314 'image/png' => 'png',
4315 'image/gif' => 'gif'
4317 $data = ['photo'=>[]];
4318 if (DBA::isResult($r)) {
4319 foreach ($r as $rr) {
4321 $photo['id'] = $rr['resource-id'];
4322 $photo['album'] = $rr['album'];
4323 $photo['filename'] = $rr['filename'];
4324 $photo['type'] = $rr['type'];
4325 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4326 $photo['created'] = $rr['created'];
4327 $photo['edited'] = $rr['edited'];
4328 $photo['desc'] = $rr['desc'];
4330 if ($type == "xml") {
4331 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4333 $photo['thumb'] = $thumb;
4334 $data['photo'][] = $photo;
4338 return api_format_data("photos", $type, $data);
4342 * @brief upload a new photo or change an existing photo
4344 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4345 * @return string|array
4346 * @throws BadRequestException
4347 * @throws ForbiddenException
4348 * @throws ImagickException
4349 * @throws InternalServerErrorException
4350 * @throws NotFoundException
4352 function api_fr_photo_create_update($type)
4354 if (api_user() === false) {
4355 throw new ForbiddenException();
4358 $photo_id = $_REQUEST['photo_id'] ?? null;
4359 $desc = $_REQUEST['desc'] ?? null;
4360 $album = $_REQUEST['album'] ?? null;
4361 $album_new = $_REQUEST['album_new'] ?? null;
4362 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4363 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4364 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4365 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4366 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4368 // do several checks on input parameters
4369 // we do not allow calls without album string
4370 if ($album == null) {
4371 throw new BadRequestException("no albumname specified");
4373 // if photo_id == null --> we are uploading a new photo
4374 if ($photo_id == null) {
4377 // error if no media posted in create-mode
4378 if (empty($_FILES['media'])) {
4380 throw new BadRequestException("no media data submitted");
4383 // album_new will be ignored in create-mode
4388 // check if photo is existing in databasei
4389 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4390 throw new BadRequestException("photo not available");
4394 // checks on acl strings provided by clients
4395 $acl_input_error = false;
4396 $acl_input_error |= check_acl_input($allow_cid);
4397 $acl_input_error |= check_acl_input($deny_cid);
4398 $acl_input_error |= check_acl_input($allow_gid);
4399 $acl_input_error |= check_acl_input($deny_gid);
4400 if ($acl_input_error) {
4401 throw new BadRequestException("acl data invalid");
4403 // now let's upload the new media in create-mode
4404 if ($mode == "create") {
4405 $media = $_FILES['media'];
4406 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4408 // return success of updating or error message
4409 if (!is_null($data)) {
4410 return api_format_data("photo_create", $type, $data);
4412 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4416 // now let's do the changes in update-mode
4417 if ($mode == "update") {
4418 $updated_fields = [];
4420 if (!is_null($desc)) {
4421 $updated_fields['desc'] = $desc;
4424 if (!is_null($album_new)) {
4425 $updated_fields['album'] = $album_new;
4428 if (!is_null($allow_cid)) {
4429 $allow_cid = trim($allow_cid);
4430 $updated_fields['allow_cid'] = $allow_cid;
4433 if (!is_null($deny_cid)) {
4434 $deny_cid = trim($deny_cid);
4435 $updated_fields['deny_cid'] = $deny_cid;
4438 if (!is_null($allow_gid)) {
4439 $allow_gid = trim($allow_gid);
4440 $updated_fields['allow_gid'] = $allow_gid;
4443 if (!is_null($deny_gid)) {
4444 $deny_gid = trim($deny_gid);
4445 $updated_fields['deny_gid'] = $deny_gid;
4449 if (count($updated_fields) > 0) {
4450 $nothingtodo = false;
4451 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4453 $nothingtodo = true;
4456 if (!empty($_FILES['media'])) {
4457 $nothingtodo = false;
4458 $media = $_FILES['media'];
4459 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4460 if (!is_null($data)) {
4461 return api_format_data("photo_update", $type, $data);
4465 // return success of updating or error message
4467 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4468 return api_format_data("photo_update", $type, ['$result' => $answer]);
4471 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4472 return api_format_data("photo_update", $type, ['$result' => $answer]);
4474 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4477 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4481 * @brief delete a single photo from the database through api
4483 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4484 * @return string|array
4485 * @throws BadRequestException
4486 * @throws ForbiddenException
4487 * @throws InternalServerErrorException
4489 function api_fr_photo_delete($type)
4491 if (api_user() === false) {
4492 throw new ForbiddenException();
4496 $photo_id = $_REQUEST['photo_id'] ?? null;
4498 // do several checks on input parameters
4499 // we do not allow calls without photo id
4500 if ($photo_id == null) {
4501 throw new BadRequestException("no photo_id specified");
4504 // check if photo is existing in database
4505 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4506 throw new BadRequestException("photo not available");
4509 // now we can perform on the deletion of the photo
4510 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4512 // return success of deletion or error message
4514 // retrieve the id of the parent element (the photo element)
4515 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4516 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4518 if (!DBA::isResult($photo_item)) {
4519 throw new InternalServerErrorException("problem with deleting items occured");
4521 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4522 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4523 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4525 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4526 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4528 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4534 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4536 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4537 * @return string|array
4538 * @throws BadRequestException
4539 * @throws ForbiddenException
4540 * @throws InternalServerErrorException
4541 * @throws NotFoundException
4543 function api_fr_photo_detail($type)
4545 if (api_user() === false) {
4546 throw new ForbiddenException();
4548 if (empty($_REQUEST['photo_id'])) {
4549 throw new BadRequestException("No photo id.");
4552 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4553 $photo_id = $_REQUEST['photo_id'];
4555 // prepare json/xml output with data from database for the requested photo
4556 $data = prepare_photo_data($type, $scale, $photo_id);
4558 return api_format_data("photo_detail", $type, $data);
4563 * Updates the user’s profile image.
4565 * @brief updates the profile image for the user (either a specified profile or the default profile)
4567 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4569 * @return string|array
4570 * @throws BadRequestException
4571 * @throws ForbiddenException
4572 * @throws ImagickException
4573 * @throws InternalServerErrorException
4574 * @throws NotFoundException
4575 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4577 function api_account_update_profile_image($type)
4579 if (api_user() === false) {
4580 throw new ForbiddenException();
4583 $profile_id = $_REQUEST['profile_id'] ?? 0;
4585 // error if image data is missing
4586 if (empty($_FILES['image'])) {
4587 throw new BadRequestException("no media data submitted");
4590 // check if specified profile id is valid
4591 if ($profile_id != 0) {
4592 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4593 // error message if specified profile id is not in database
4594 if (!DBA::isResult($profile)) {
4595 throw new BadRequestException("profile_id not available");
4597 $is_default_profile = $profile['is-default'];
4599 $is_default_profile = 1;
4602 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4604 if (!empty($_FILES['image'])) {
4605 $media = $_FILES['image'];
4606 } elseif (!empty($_FILES['media'])) {
4607 $media = $_FILES['media'];
4609 // save new profile image
4610 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4613 if (is_array($media['type'])) {
4614 $filetype = $media['type'][0];
4616 $filetype = $media['type'];
4618 if ($filetype == "image/jpeg") {
4620 } elseif ($filetype == "image/png") {
4623 throw new InternalServerErrorException('Unsupported filetype');
4626 // change specified profile or all profiles to the new resource-id
4627 if ($is_default_profile) {
4628 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4629 Photo::update(['profile' => false], $condition);
4631 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4632 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4633 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4636 Contact::updateSelfFromUserID(api_user(), true);
4638 // Update global directory in background
4639 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4640 if ($url && strlen(Config::get('system', 'directory'))) {
4641 Worker::add(PRIORITY_LOW, "Directory", $url);
4644 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4646 // output for client
4648 return api_account_verify_credentials($type);
4650 // SaveMediaToDatabase failed for some reason
4651 throw new InternalServerErrorException("image upload failed");
4655 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4656 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4657 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4658 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4659 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4660 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4661 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4662 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4663 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4666 * Update user profile
4668 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4670 * @return array|string
4671 * @throws BadRequestException
4672 * @throws ForbiddenException
4673 * @throws ImagickException
4674 * @throws InternalServerErrorException
4675 * @throws UnauthorizedException
4677 function api_account_update_profile($type)
4679 $local_user = api_user();
4680 $api_user = api_get_user(get_app());
4682 if (!empty($_POST['name'])) {
4683 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4684 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4685 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4686 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4689 if (isset($_POST['description'])) {
4690 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4691 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4692 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4695 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4696 // Update global directory in background
4697 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4698 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4701 return api_account_verify_credentials($type);
4704 /// @TODO move to top of file or somewhere better
4705 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4709 * @param string $acl_string
4713 function check_acl_input($acl_string)
4715 if (empty($acl_string)) {
4719 $contact_not_found = false;
4721 // split <x><y><z> into array of cid's
4722 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4724 // check for each cid if it is available on server
4725 $cid_array = $array[0];
4726 foreach ($cid_array as $cid) {
4727 $cid = str_replace("<", "", $cid);
4728 $cid = str_replace(">", "", $cid);
4729 $condition = ['id' => $cid, 'uid' => api_user()];
4730 $contact_not_found |= !DBA::exists('contact', $condition);
4732 return $contact_not_found;
4736 * @param string $mediatype
4737 * @param array $media
4738 * @param string $type
4739 * @param string $album
4740 * @param string $allow_cid
4741 * @param string $deny_cid
4742 * @param string $allow_gid
4743 * @param string $deny_gid
4744 * @param string $desc
4745 * @param integer $profile
4746 * @param boolean $visibility
4747 * @param string $photo_id
4749 * @throws BadRequestException
4750 * @throws ForbiddenException
4751 * @throws ImagickException
4752 * @throws InternalServerErrorException
4753 * @throws NotFoundException
4754 * @throws UnauthorizedException
4756 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)
4764 if (is_array($media)) {
4765 if (is_array($media['tmp_name'])) {
4766 $src = $media['tmp_name'][0];
4768 $src = $media['tmp_name'];
4770 if (is_array($media['name'])) {
4771 $filename = basename($media['name'][0]);
4773 $filename = basename($media['name']);
4775 if (is_array($media['size'])) {
4776 $filesize = intval($media['size'][0]);
4778 $filesize = intval($media['size']);
4780 if (is_array($media['type'])) {
4781 $filetype = $media['type'][0];
4783 $filetype = $media['type'];
4787 if ($filetype == "") {
4788 $filetype = Images::guessType($filename);
4790 $imagedata = @getimagesize($src);
4792 $filetype = $imagedata['mime'];
4795 "File upload src: " . $src . " - filename: " . $filename .
4796 " - size: " . $filesize . " - type: " . $filetype,
4800 // check if there was a php upload error
4801 if ($filesize == 0 && $media['error'] == 1) {
4802 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4804 // check against max upload size within Friendica instance
4805 $maximagesize = Config::get('system', 'maximagesize');
4806 if ($maximagesize && ($filesize > $maximagesize)) {
4807 $formattedBytes = Strings::formatBytes($maximagesize);
4808 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4811 // create Photo instance with the data of the image
4812 $imagedata = @file_get_contents($src);
4813 $Image = new Image($imagedata, $filetype);
4814 if (!$Image->isValid()) {
4815 throw new InternalServerErrorException("unable to process image data");
4818 // check orientation of image
4819 $Image->orient($src);
4822 // check max length of images on server
4823 $max_length = Config::get('system', 'max_image_length');
4825 $max_length = MAX_IMAGE_LENGTH;
4827 if ($max_length > 0) {
4828 $Image->scaleDown($max_length);
4829 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4831 $width = $Image->getWidth();
4832 $height = $Image->getHeight();
4834 // create a new resource-id if not already provided
4835 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4837 if ($mediatype == "photo") {
4838 // upload normal image (scales 0, 1, 2)
4839 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4841 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4843 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4845 if ($width > 640 || $height > 640) {
4846 $Image->scaleDown(640);
4847 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4849 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4853 if ($width > 320 || $height > 320) {
4854 $Image->scaleDown(320);
4855 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4857 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4860 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4861 } elseif ($mediatype == "profileimage") {
4862 // upload profile image (scales 4, 5, 6)
4863 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4865 if ($width > 300 || $height > 300) {
4866 $Image->scaleDown(300);
4867 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4869 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4873 if ($width > 80 || $height > 80) {
4874 $Image->scaleDown(80);
4875 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4877 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4881 if ($width > 48 || $height > 48) {
4882 $Image->scaleDown(48);
4883 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4885 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4888 $Image->__destruct();
4889 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4892 if (isset($r) && $r) {
4893 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4894 if ($photo_id == null && $mediatype == "photo") {
4895 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4897 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4898 return prepare_photo_data($type, false, $resource_id);
4900 throw new InternalServerErrorException("image upload failed");
4906 * @param string $hash
4907 * @param string $allow_cid
4908 * @param string $deny_cid
4909 * @param string $allow_gid
4910 * @param string $deny_gid
4911 * @param string $filetype
4912 * @param boolean $visibility
4913 * @throws InternalServerErrorException
4915 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4917 // get data about the api authenticated user
4918 $uri = Item::newURI(intval(api_user()));
4919 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4922 $arr['guid'] = System::createUUID();
4923 $arr['uid'] = intval(api_user());
4925 $arr['parent-uri'] = $uri;
4926 $arr['type'] = 'photo';
4928 $arr['resource-id'] = $hash;
4929 $arr['contact-id'] = $owner_record['id'];
4930 $arr['owner-name'] = $owner_record['name'];
4931 $arr['owner-link'] = $owner_record['url'];
4932 $arr['owner-avatar'] = $owner_record['thumb'];
4933 $arr['author-name'] = $owner_record['name'];
4934 $arr['author-link'] = $owner_record['url'];
4935 $arr['author-avatar'] = $owner_record['thumb'];
4937 $arr['allow_cid'] = $allow_cid;
4938 $arr['allow_gid'] = $allow_gid;
4939 $arr['deny_cid'] = $deny_cid;
4940 $arr['deny_gid'] = $deny_gid;
4941 $arr['visible'] = $visibility;
4945 'image/jpeg' => 'jpg',
4946 'image/png' => 'png',
4947 'image/gif' => 'gif'
4950 // adds link to the thumbnail scale photo
4951 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4952 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4955 // do the magic for storing the item in the database and trigger the federation to other contacts
4961 * @param string $type
4963 * @param string $photo_id
4966 * @throws BadRequestException
4967 * @throws ForbiddenException
4968 * @throws ImagickException
4969 * @throws InternalServerErrorException
4970 * @throws NotFoundException
4971 * @throws UnauthorizedException
4973 function prepare_photo_data($type, $scale, $photo_id)
4976 $user_info = api_get_user($a);
4978 if ($user_info === false) {
4979 throw new ForbiddenException();
4982 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4983 $data_sql = ($scale === false ? "" : "data, ");
4985 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4986 // clients needs to convert this in their way for further processing
4988 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4989 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4990 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4991 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4992 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4993 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4995 intval(local_user()),
4996 DBA::escape($photo_id),
5001 'image/jpeg' => 'jpg',
5002 'image/png' => 'png',
5003 'image/gif' => 'gif'
5006 // prepare output data for photo
5007 if (DBA::isResult($r)) {
5008 $data = ['photo' => $r[0]];
5009 $data['photo']['id'] = $data['photo']['resource-id'];
5010 if ($scale !== false) {
5011 $data['photo']['data'] = base64_encode($data['photo']['data']);
5013 unset($data['photo']['datasize']); //needed only with scale param
5015 if ($type == "xml") {
5016 $data['photo']['links'] = [];
5017 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5018 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
5020 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
5023 $data['photo']['link'] = [];
5024 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
5026 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
5027 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
5031 unset($data['photo']['resource-id']);
5032 unset($data['photo']['minscale']);
5033 unset($data['photo']['maxscale']);
5035 throw new NotFoundException();
5038 // retrieve item element for getting activities (like, dislike etc.) related to photo
5039 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
5040 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
5042 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5044 // retrieve comments on photo
5045 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5046 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5048 $statuses = Item::selectForUser(api_user(), [], $condition);
5050 // prepare output of comments
5051 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5053 if ($type == "xml") {
5055 foreach ($commentData as $comment) {
5056 $comments[$k++ . ":comment"] = $comment;
5059 foreach ($commentData as $comment) {
5060 $comments[] = $comment;
5063 $data['photo']['friendica_comments'] = $comments;
5065 // include info if rights on photo and rights on item are mismatching
5066 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5067 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5068 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5069 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5070 $data['photo']['rights_mismatch'] = $rights_mismatch;
5077 * Similar as /mod/redir.php
5078 * redirect to 'url' after dfrn auth
5080 * Why this when there is mod/redir.php already?
5081 * This use api_user() and api_login()
5084 * c_url: url of remote contact to auth to
5085 * url: string, url to redirect after auth
5087 function api_friendica_remoteauth()
5089 $url = $_GET['url'] ?? '';
5090 $c_url = $_GET['c_url'] ?? '';
5092 if ($url === '' || $c_url === '') {
5093 throw new BadRequestException("Wrong parameters.");
5096 $c_url = Strings::normaliseLink($c_url);
5100 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5102 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5103 throw new BadRequestException("Unknown contact");
5106 $cid = $contact['id'];
5108 $dfrn_id = $contact['issued-id'] ?? $contact['dfrn-id'];
5110 if ($contact['duplex'] && $contact['issued-id']) {
5111 $orig_id = $contact['issued-id'];
5112 $dfrn_id = '1:' . $orig_id;
5114 if ($contact['duplex'] && $contact['dfrn-id']) {
5115 $orig_id = $contact['dfrn-id'];
5116 $dfrn_id = '0:' . $orig_id;
5119 $sec = Strings::getRandomHex();
5121 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5122 'sec' => $sec, 'expire' => time() + 45];
5123 DBA::insert('profile_check', $fields);
5125 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5126 $dest = ($url ? '&destination_url=' . $url : '');
5128 System::externalRedirect(
5129 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5130 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5131 . '&type=profile&sec=' . $sec . $dest
5134 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5137 * Return an item with announcer data if it had been announced
5139 * @param array $item Item array
5140 * @return array Item array with announce data
5142 function api_get_announce($item)
5144 // Quit if the item already has got a different owner and author
5145 if ($item['owner-id'] != $item['author-id']) {
5149 // Don't change original or Diaspora posts
5150 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5154 // Quit if we do now the original author and it had been a post from a native network
5155 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5159 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5160 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5161 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5162 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5163 if (!DBA::isResult($announce)) {
5167 return array_merge($item, $announce);
5171 * @brief Return the item shared, if the item contains only the [share] tag
5173 * @param array $item Sharer item
5174 * @return array|false Shared item or false if not a reshare
5175 * @throws ImagickException
5176 * @throws InternalServerErrorException
5178 function api_share_as_retweet(&$item)
5180 $body = trim($item["body"]);
5182 if (Diaspora::isReshare($body, false) === false) {
5183 if ($item['author-id'] == $item['owner-id']) {
5186 // Reshares from OStatus, ActivityPub and Twitter
5187 $reshared_item = $item;
5188 $reshared_item['owner-id'] = $reshared_item['author-id'];
5189 $reshared_item['owner-link'] = $reshared_item['author-link'];
5190 $reshared_item['owner-name'] = $reshared_item['author-name'];
5191 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5192 return $reshared_item;
5196 $reshared = Item::getShareArray($item);
5197 if (empty($reshared)) {
5201 $reshared_item = $item;
5203 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5207 if (!empty($reshared['comment'])) {
5208 $item['body'] = $reshared['comment'];
5211 $reshared_item["share-pre-body"] = $reshared['comment'];
5212 $reshared_item["body"] = $reshared['shared'];
5213 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5214 $reshared_item["author-name"] = $reshared['author'];
5215 $reshared_item["author-link"] = $reshared['profile'];
5216 $reshared_item["author-avatar"] = $reshared['avatar'];
5217 $reshared_item["plink"] = $reshared['link'] ?? '';
5218 $reshared_item["created"] = $reshared['posted'];
5219 $reshared_item["edited"] = $reshared['posted'];
5221 // Try to fetch the original item
5222 if (!empty($reshared['guid'])) {
5223 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5224 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5225 $condition = ['id' => $original_id];
5230 if (!empty($condition)) {
5231 $original_item = Item::selectFirst([], $condition);
5232 if (DBA::isResult($original_item)) {
5233 $reshared_item = array_merge($reshared_item, $original_item);
5237 return $reshared_item;
5242 * @param string $profile
5244 * @return string|false
5245 * @throws InternalServerErrorException
5246 * @todo remove trailing junk from profile url
5247 * @todo pump.io check has to check the website
5249 function api_get_nick($profile)
5254 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5255 DBA::escape(Strings::normaliseLink($profile))
5258 if (DBA::isResult($r)) {
5259 $nick = $r[0]["nick"];
5264 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5265 DBA::escape(Strings::normaliseLink($profile))
5268 if (DBA::isResult($r)) {
5269 $nick = $r[0]["nick"];
5274 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5275 if ($friendica != $profile) {
5281 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5282 if ($diaspora != $profile) {
5288 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5289 if ($twitter != $profile) {
5296 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5297 if ($StatusnetHost != $profile) {
5298 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5299 if ($StatusnetUser != $profile) {
5300 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5301 $user = json_decode($UserData);
5303 $nick = $user->screen_name;
5309 // To-Do: look at the page if its really a pumpio site
5310 //if (!$nick == "") {
5311 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5312 // if ($pumpio != $profile)
5314 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5327 * @param array $item
5332 function api_in_reply_to($item)
5336 $in_reply_to['status_id'] = null;
5337 $in_reply_to['user_id'] = null;
5338 $in_reply_to['status_id_str'] = null;
5339 $in_reply_to['user_id_str'] = null;
5340 $in_reply_to['screen_name'] = null;
5342 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5343 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5344 if (DBA::isResult($parent)) {
5345 $in_reply_to['status_id'] = intval($parent['id']);
5347 $in_reply_to['status_id'] = intval($item['parent']);
5350 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5352 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5353 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5355 if (DBA::isResult($parent)) {
5356 if ($parent['author-nick'] == "") {
5357 $parent['author-nick'] = api_get_nick($parent['author-link']);
5360 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5361 $in_reply_to['user_id'] = intval($parent['author-id']);
5362 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5365 // There seems to be situation, where both fields are identical:
5366 // https://github.com/friendica/friendica/issues/1010
5367 // This is a bugfix for that.
5368 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5369 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']]);
5370 $in_reply_to['status_id'] = null;
5371 $in_reply_to['user_id'] = null;
5372 $in_reply_to['status_id_str'] = null;
5373 $in_reply_to['user_id_str'] = null;
5374 $in_reply_to['screen_name'] = null;
5378 return $in_reply_to;
5383 * @param string $text
5386 * @throws InternalServerErrorException
5388 function api_clean_plain_items($text)
5390 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5392 $text = BBCode::cleanPictureLinks($text);
5393 $URLSearchString = "^\[\]";
5395 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5397 if ($include_entities == "true") {
5398 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5401 // Simplify "attachment" element
5402 $text = BBCode::removeAttachment($text);
5409 * @param array $contacts
5413 function api_best_nickname(&$contacts)
5417 if (count($contacts) == 0) {
5421 foreach ($contacts as $contact) {
5422 if ($contact["network"] == "") {
5423 $contact["network"] = "dfrn";
5424 $best_contact = [$contact];
5428 if (sizeof($best_contact) == 0) {
5429 foreach ($contacts as $contact) {
5430 if ($contact["network"] == "dfrn") {
5431 $best_contact = [$contact];
5436 if (sizeof($best_contact) == 0) {
5437 foreach ($contacts as $contact) {
5438 if ($contact["network"] == "dspr") {
5439 $best_contact = [$contact];
5444 if (sizeof($best_contact) == 0) {
5445 foreach ($contacts as $contact) {
5446 if ($contact["network"] == "stat") {
5447 $best_contact = [$contact];
5452 if (sizeof($best_contact) == 0) {
5453 foreach ($contacts as $contact) {
5454 if ($contact["network"] == "pump") {
5455 $best_contact = [$contact];
5460 if (sizeof($best_contact) == 0) {
5461 foreach ($contacts as $contact) {
5462 if ($contact["network"] == "twit") {
5463 $best_contact = [$contact];
5468 if (sizeof($best_contact) == 1) {
5469 $contacts = $best_contact;
5471 $contacts = [$contacts[0]];
5476 * Return all or a specified group of the user with the containing contacts.
5478 * @param string $type Return type (atom, rss, xml, json)
5480 * @return array|string
5481 * @throws BadRequestException
5482 * @throws ForbiddenException
5483 * @throws ImagickException
5484 * @throws InternalServerErrorException
5485 * @throws UnauthorizedException
5487 function api_friendica_group_show($type)
5491 if (api_user() === false) {
5492 throw new ForbiddenException();
5496 $user_info = api_get_user($a);
5497 $gid = $_REQUEST['gid'] ?? 0;
5498 $uid = $user_info['uid'];
5500 // get data of the specified group id or all groups if not specified
5503 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5507 // error message if specified gid is not in database
5508 if (!DBA::isResult($r)) {
5509 throw new BadRequestException("gid not available");
5513 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5518 // loop through all groups and retrieve all members for adding data in the user array
5520 foreach ($r as $rr) {
5521 $members = Contact::getByGroupId($rr['id']);
5524 if ($type == "xml") {
5525 $user_element = "users";
5527 foreach ($members as $member) {
5528 $user = api_get_user($a, $member['nurl']);
5529 $users[$k++.":user"] = $user;
5532 $user_element = "user";
5533 foreach ($members as $member) {
5534 $user = api_get_user($a, $member['nurl']);
5538 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5540 return api_format_data("groups", $type, ['group' => $grps]);
5542 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5546 * Delete the specified group of the user.
5548 * @param string $type Return type (atom, rss, xml, json)
5550 * @return array|string
5551 * @throws BadRequestException
5552 * @throws ForbiddenException
5553 * @throws ImagickException
5554 * @throws InternalServerErrorException
5555 * @throws UnauthorizedException
5557 function api_friendica_group_delete($type)
5561 if (api_user() === false) {
5562 throw new ForbiddenException();
5566 $user_info = api_get_user($a);
5567 $gid = $_REQUEST['gid'] ?? 0;
5568 $name = $_REQUEST['name'] ?? '';
5569 $uid = $user_info['uid'];
5571 // error if no gid specified
5572 if ($gid == 0 || $name == "") {
5573 throw new BadRequestException('gid or name not specified');
5576 // get data of the specified group id
5578 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5582 // error message if specified gid is not in database
5583 if (!DBA::isResult($r)) {
5584 throw new BadRequestException('gid not available');
5587 // get data of the specified group id and group name
5589 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5594 // error message if specified gid is not in database
5595 if (!DBA::isResult($rname)) {
5596 throw new BadRequestException('wrong group name');
5600 $ret = Group::removeByName($uid, $name);
5603 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5604 return api_format_data("group_delete", $type, ['result' => $success]);
5606 throw new BadRequestException('other API error');
5609 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5614 * @param string $type Return type (atom, rss, xml, json)
5616 * @return array|string
5617 * @throws BadRequestException
5618 * @throws ForbiddenException
5619 * @throws ImagickException
5620 * @throws InternalServerErrorException
5621 * @throws UnauthorizedException
5622 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5624 function api_lists_destroy($type)
5628 if (api_user() === false) {
5629 throw new ForbiddenException();
5633 $user_info = api_get_user($a);
5634 $gid = $_REQUEST['list_id'] ?? 0;
5635 $uid = $user_info['uid'];
5637 // error if no gid specified
5639 throw new BadRequestException('gid not specified');
5642 // get data of the specified group id
5643 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5644 // error message if specified gid is not in database
5646 throw new BadRequestException('gid not available');
5649 if (Group::remove($gid)) {
5651 'name' => $group['name'],
5652 'id' => intval($gid),
5653 'id_str' => (string) $gid,
5654 'user' => $user_info
5657 return api_format_data("lists", $type, ['lists' => $list]);
5660 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5663 * Add a new group to the database.
5665 * @param string $name Group name
5666 * @param int $uid User ID
5667 * @param array $users List of users to add to the group
5670 * @throws BadRequestException
5672 function group_create($name, $uid, $users = [])
5674 // error if no name specified
5676 throw new BadRequestException('group name not specified');
5679 // get data of the specified group name
5681 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5685 // error message if specified group name already exists
5686 if (DBA::isResult($rname)) {
5687 throw new BadRequestException('group name already exists');
5690 // check if specified group name is a deleted group
5692 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5696 // error message if specified group name already exists
5697 if (DBA::isResult($rname)) {
5698 $reactivate_group = true;
5702 $ret = Group::create($uid, $name);
5704 $gid = Group::getIdByName($uid, $name);
5706 throw new BadRequestException('other API error');
5710 $erroraddinguser = false;
5712 foreach ($users as $user) {
5713 $cid = $user['cid'];
5714 // check if user really exists as contact
5716 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5720 if (count($contact)) {
5721 Group::addMember($gid, $cid);
5723 $erroraddinguser = true;
5724 $errorusers[] = $cid;
5728 // return success message incl. missing users in array
5729 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5731 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5735 * Create the specified group with the posted array of contacts.
5737 * @param string $type Return type (atom, rss, xml, json)
5739 * @return array|string
5740 * @throws BadRequestException
5741 * @throws ForbiddenException
5742 * @throws ImagickException
5743 * @throws InternalServerErrorException
5744 * @throws UnauthorizedException
5746 function api_friendica_group_create($type)
5750 if (api_user() === false) {
5751 throw new ForbiddenException();
5755 $user_info = api_get_user($a);
5756 $name = $_REQUEST['name'] ?? '';
5757 $uid = $user_info['uid'];
5758 $json = json_decode($_POST['json'], true);
5759 $users = $json['user'];
5761 $success = group_create($name, $uid, $users);
5763 return api_format_data("group_create", $type, ['result' => $success]);
5765 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5768 * Create a new group.
5770 * @param string $type Return type (atom, rss, xml, json)
5772 * @return array|string
5773 * @throws BadRequestException
5774 * @throws ForbiddenException
5775 * @throws ImagickException
5776 * @throws InternalServerErrorException
5777 * @throws UnauthorizedException
5778 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5780 function api_lists_create($type)
5784 if (api_user() === false) {
5785 throw new ForbiddenException();
5789 $user_info = api_get_user($a);
5790 $name = $_REQUEST['name'] ?? '';
5791 $uid = $user_info['uid'];
5793 $success = group_create($name, $uid);
5794 if ($success['success']) {
5796 'name' => $success['name'],
5797 'id' => intval($success['gid']),
5798 'id_str' => (string) $success['gid'],
5799 'user' => $user_info
5802 return api_format_data("lists", $type, ['lists'=>$grp]);
5805 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5808 * Update the specified group with the posted array of contacts.
5810 * @param string $type Return type (atom, rss, xml, json)
5812 * @return array|string
5813 * @throws BadRequestException
5814 * @throws ForbiddenException
5815 * @throws ImagickException
5816 * @throws InternalServerErrorException
5817 * @throws UnauthorizedException
5819 function api_friendica_group_update($type)
5823 if (api_user() === false) {
5824 throw new ForbiddenException();
5828 $user_info = api_get_user($a);
5829 $uid = $user_info['uid'];
5830 $gid = $_REQUEST['gid'] ?? 0;
5831 $name = $_REQUEST['name'] ?? '';
5832 $json = json_decode($_POST['json'], true);
5833 $users = $json['user'];
5835 // error if no name specified
5837 throw new BadRequestException('group name not specified');
5840 // error if no gid specified
5842 throw new BadRequestException('gid not specified');
5846 $members = Contact::getByGroupId($gid);
5847 foreach ($members as $member) {
5848 $cid = $member['id'];
5849 foreach ($users as $user) {
5850 $found = ($user['cid'] == $cid ? true : false);
5852 if (!isset($found) || !$found) {
5853 Group::removeMemberByName($uid, $name, $cid);
5858 $erroraddinguser = false;
5860 foreach ($users as $user) {
5861 $cid = $user['cid'];
5862 // check if user really exists as contact
5864 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5869 if (count($contact)) {
5870 Group::addMember($gid, $cid);
5872 $erroraddinguser = true;
5873 $errorusers[] = $cid;
5877 // return success message incl. missing users in array
5878 $status = ($erroraddinguser ? "missing user" : "ok");
5879 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5880 return api_format_data("group_update", $type, ['result' => $success]);
5883 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5886 * Update information about a group.
5888 * @param string $type Return type (atom, rss, xml, json)
5890 * @return array|string
5891 * @throws BadRequestException
5892 * @throws ForbiddenException
5893 * @throws ImagickException
5894 * @throws InternalServerErrorException
5895 * @throws UnauthorizedException
5896 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5898 function api_lists_update($type)
5902 if (api_user() === false) {
5903 throw new ForbiddenException();
5907 $user_info = api_get_user($a);
5908 $gid = $_REQUEST['list_id'] ?? 0;
5909 $name = $_REQUEST['name'] ?? '';
5910 $uid = $user_info['uid'];
5912 // error if no gid specified
5914 throw new BadRequestException('gid not specified');
5917 // get data of the specified group id
5918 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5919 // error message if specified gid is not in database
5921 throw new BadRequestException('gid not available');
5924 if (Group::update($gid, $name)) {
5927 'id' => intval($gid),
5928 'id_str' => (string) $gid,
5929 'user' => $user_info
5932 return api_format_data("lists", $type, ['lists' => $list]);
5936 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5940 * @param string $type Return type (atom, rss, xml, json)
5942 * @return array|string
5943 * @throws BadRequestException
5944 * @throws ForbiddenException
5945 * @throws ImagickException
5946 * @throws InternalServerErrorException
5948 function api_friendica_activity($type)
5952 if (api_user() === false) {
5953 throw new ForbiddenException();
5955 $verb = strtolower($a->argv[3]);
5956 $verb = preg_replace("|\..*$|", "", $verb);
5958 $id = $_REQUEST['id'] ?? 0;
5960 $res = Item::performLike($id, $verb);
5963 if ($type == "xml") {
5968 return api_format_data('ok', $type, ['ok' => $ok]);
5970 throw new BadRequestException('Error adding activity');
5974 /// @TODO move to top of file or somewhere better
5975 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5976 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5977 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5978 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5979 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5980 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5981 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5982 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5983 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5984 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5987 * @brief Returns notifications
5989 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5990 * @return string|array
5991 * @throws BadRequestException
5992 * @throws ForbiddenException
5993 * @throws InternalServerErrorException
5995 function api_friendica_notification($type)
5999 if (api_user() === false) {
6000 throw new ForbiddenException();
6003 throw new BadRequestException("Invalid argument count");
6005 /** @var Notify $nm */
6006 $nm = BaseObject::getClass(Notify::class);
6008 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6010 if ($type == "xml") {
6012 if (!empty($notes)) {
6013 foreach ($notes as $note) {
6014 $xmlnotes[] = ["@attributes" => $note];
6020 return api_format_data("notes", $type, ['note' => $notes]);
6024 * POST request with 'id' param as notification id
6026 * @brief Set notification as seen and returns associated item (if possible)
6028 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6029 * @return string|array
6030 * @throws BadRequestException
6031 * @throws ForbiddenException
6032 * @throws ImagickException
6033 * @throws InternalServerErrorException
6034 * @throws UnauthorizedException
6036 function api_friendica_notification_seen($type)
6039 $user_info = api_get_user($a);
6041 if (api_user() === false || $user_info === false) {
6042 throw new ForbiddenException();
6045 throw new BadRequestException("Invalid argument count");
6048 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6050 /** @var Notify $nm */
6051 $nm = BaseObject::getClass(Notify::class);
6052 $note = $nm->getByID($id);
6053 if (is_null($note)) {
6054 throw new BadRequestException("Invalid argument");
6057 $nm->setSeen($note);
6058 if ($note['otype']=='item') {
6059 // would be really better with an ItemsManager and $im->getByID() :-P
6060 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6061 if (DBA::isResult($item)) {
6062 // we found the item, return it to the user
6063 $ret = api_format_items([$item], $user_info, false, $type);
6064 $data = ['status' => $ret];
6065 return api_format_data("status", $type, $data);
6067 // the item can't be found, but we set the note as seen, so we count this as a success
6069 return api_format_data('result', $type, ['result' => "success"]);
6072 /// @TODO move to top of file or somewhere better
6073 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6074 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6077 * @brief update a direct_message to seen state
6079 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6080 * @return string|array (success result=ok, error result=error with error message)
6081 * @throws BadRequestException
6082 * @throws ForbiddenException
6083 * @throws ImagickException
6084 * @throws InternalServerErrorException
6085 * @throws UnauthorizedException
6087 function api_friendica_direct_messages_setseen($type)
6090 if (api_user() === false) {
6091 throw new ForbiddenException();
6095 $user_info = api_get_user($a);
6096 $uid = $user_info['uid'];
6097 $id = $_REQUEST['id'] ?? 0;
6099 // return error if id is zero
6101 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6102 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6105 // error message if specified id is not in database
6106 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6107 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6108 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6111 // update seen indicator
6112 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6116 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6117 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6119 $answer = ['result' => 'error', 'message' => 'unknown error'];
6120 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6124 /// @TODO move to top of file or somewhere better
6125 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6128 * @brief search for direct_messages containing a searchstring through api
6130 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6131 * @param string $box
6132 * @return string|array (success: success=true if found and search_result contains found messages,
6133 * success=false if nothing was found, search_result='nothing found',
6134 * error: result=error with error message)
6135 * @throws BadRequestException
6136 * @throws ForbiddenException
6137 * @throws ImagickException
6138 * @throws InternalServerErrorException
6139 * @throws UnauthorizedException
6141 function api_friendica_direct_messages_search($type, $box = "")
6145 if (api_user() === false) {
6146 throw new ForbiddenException();
6150 $user_info = api_get_user($a);
6151 $searchstring = $_REQUEST['searchstring'] ?? '';
6152 $uid = $user_info['uid'];
6154 // error if no searchstring specified
6155 if ($searchstring == "") {
6156 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6157 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6160 // get data for the specified searchstring
6162 "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",
6164 DBA::escape('%'.$searchstring.'%')
6167 $profile_url = $user_info["url"];
6169 // message if nothing was found
6170 if (!DBA::isResult($r)) {
6171 $success = ['success' => false, 'search_results' => 'problem with query'];
6172 } elseif (count($r) == 0) {
6173 $success = ['success' => false, 'search_results' => 'nothing found'];
6176 foreach ($r as $item) {
6177 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6178 $recipient = $user_info;
6179 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6180 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6181 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6182 $sender = $user_info;
6185 if (isset($recipient) && isset($sender)) {
6186 $ret[] = api_format_messages($item, $recipient, $sender);
6189 $success = ['success' => true, 'search_results' => $ret];
6192 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6195 /// @TODO move to top of file or somewhere better
6196 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6199 * @brief return data of all the profiles a user has to the client
6201 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6202 * @return string|array
6203 * @throws BadRequestException
6204 * @throws ForbiddenException
6205 * @throws ImagickException
6206 * @throws InternalServerErrorException
6207 * @throws UnauthorizedException
6209 function api_friendica_profile_show($type)
6213 if (api_user() === false) {
6214 throw new ForbiddenException();
6218 $profile_id = $_REQUEST['profile_id'] ?? 0;
6220 // retrieve general information about profiles for user
6221 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6222 $directory = Config::get('system', 'directory');
6224 // get data of the specified profile id or all profiles of the user if not specified
6225 if ($profile_id != 0) {
6226 $r = Profile::getById(api_user(), $profile_id);
6227 // error message if specified gid is not in database
6228 if (!DBA::isResult($r)) {
6229 throw new BadRequestException("profile_id not available");
6232 $r = Profile::getListByUser(api_user());
6234 // loop through all returned profiles and retrieve data and users
6237 if (DBA::isResult($r)) {
6238 foreach ($r as $rr) {
6239 $profile = api_format_items_profiles($rr);
6241 // select all users from contact table, loop and prepare standard return for user data
6243 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6244 foreach ($nurls as $nurl) {
6245 $user = api_get_user($a, $nurl['nurl']);
6246 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6248 $profile['users'] = $users;
6250 // add prepared profile data to array for final return
6251 if ($type == "xml") {
6252 $profiles[$k++ . ":profile"] = $profile;
6254 $profiles[] = $profile;
6259 // return settings, authenticated user and profiles data
6260 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6262 $result = ['multi_profiles' => $multi_profiles ? true : false,
6263 'global_dir' => $directory,
6264 'friendica_owner' => api_get_user($a, $self['nurl']),
6265 'profiles' => $profiles];
6266 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6268 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6271 * Returns a list of saved searches.
6273 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6275 * @param string $type Return format: json or xml
6277 * @return string|array
6280 function api_saved_searches_list($type)
6282 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6285 while ($term = DBA::fetch($terms)) {
6287 'created_at' => api_date(time()),
6288 'id' => intval($term['id']),
6289 'id_str' => $term['id'],
6290 'name' => $term['term'],
6292 'query' => $term['term']
6298 return api_format_data("terms", $type, ['terms' => $result]);
6301 /// @TODO move to top of file or somewhere better
6302 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6305 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6307 * @brief Number of comments
6309 * @param object $data [Status, Status]
6313 function bindComments(&$data)
6315 if (count($data) == 0) {
6321 foreach ($data as $item) {
6322 $ids[] = $item['id'];
6325 $idStr = DBA::escape(implode(', ', $ids));
6326 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6327 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6328 $itemsData = DBA::toArray($items);
6330 foreach ($itemsData as $item) {
6331 $comments[$item['parent']] = $item['comments'];
6334 foreach ($data as $idx => $item) {
6336 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6341 @TODO Maybe open to implement?
6343 [pagename] => api/1.1/statuses/lookup.json
6344 [id] => 605138389168451584
6345 [include_cards] => true
6346 [cards_platform] => Android-12
6347 [include_entities] => true
6348 [include_my_retweet] => 1
6350 [include_reply_count] => true
6351 [include_descendent_reply_count] => true
6355 Not implemented by now:
6356 statuses/retweets_of_me
6361 account/update_location
6362 account/update_profile_background_image
6365 friendica/profile/update
6366 friendica/profile/create
6367 friendica/profile/delete
6369 Not implemented in status.net:
6370 statuses/retweeted_to_me
6371 statuses/retweeted_by_me
6372 direct_messages/destroy
6374 account/update_delivery_device
6375 notifications/follow