3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\Content\ContactSelector;
11 use Friendica\Content\Feature;
12 use Friendica\Content\Text\BBCode;
13 use Friendica\Content\Text\HTML;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\NotificationsManager;
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\Photo;
30 use Friendica\Model\Profile;
31 use Friendica\Model\User;
32 use Friendica\Network\FKOAuth1;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPException\BadRequestException;
35 use Friendica\Network\HTTPException\ExpectationFailedException;
36 use Friendica\Network\HTTPException\ForbiddenException;
37 use Friendica\Network\HTTPException\InternalServerErrorException;
38 use Friendica\Network\HTTPException\MethodNotAllowedException;
39 use Friendica\Network\HTTPException\NotFoundException;
40 use Friendica\Network\HTTPException\NotImplementedException;
41 use Friendica\Network\HTTPException\TooManyRequestsException;
42 use Friendica\Network\HTTPException\UnauthorizedException;
43 use Friendica\Object\Image;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy as ProxyUtils;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
51 require_once __DIR__ . '/../mod/share.php';
52 require_once __DIR__ . '/../mod/item.php';
53 require_once __DIR__ . '/../mod/wall_upload.php';
55 define('API_METHOD_ANY', '*');
56 define('API_METHOD_GET', 'GET');
57 define('API_METHOD_POST', 'POST,PUT');
58 define('API_METHOD_DELETE', 'POST,DELETE');
60 define('API_LOG_PREFIX', 'API {action} - ');
66 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
67 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
68 * into a page, and visitors will post something without noticing it).
70 * @brief Auth API user
74 if (!empty($_SESSION['allow_api'])) {
82 * Clients can send 'source' parameter to be show in post metadata
83 * as "sent via <source>".
84 * Some clients doesn't send a source param, we support ones we know
87 * @brief Get source name from API client
90 * Client source name, default to "api" if unset/unknown
95 if (requestdata('source')) {
96 return requestdata('source');
99 // Support for known clients that doesn't send a source name
100 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
101 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
105 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
107 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
114 * @brief Format date for API
116 * @param string $str Source date, as UTC
117 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
120 function api_date($str)
122 // Wed May 23 06:01:13 +0000 2007
123 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
127 * Register a function to be the endpoint for defined API path.
129 * @brief Register API endpoint
131 * @param string $path API URL path, relative to System::baseUrl()
132 * @param string $func Function name to call on path request
133 * @param bool $auth API need logged user
134 * @param string $method HTTP method reqiured to call this endpoint.
135 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
136 * Default to API_METHOD_ANY
138 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
148 // Workaround for hotot
149 $path = str_replace("api/", "api/1.1/", $path);
159 * Log in user via OAuth1 or Simple HTTP Auth.
160 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
162 * @brief Login API user
165 * @throws ForbiddenException
166 * @throws InternalServerErrorException
167 * @throws UnauthorizedException
168 * @hook 'authenticate'
170 * 'username' => username from login form
171 * 'password' => password from login form
172 * 'authenticated' => return status,
173 * 'user_record' => return authenticated user record
175 function api_login(App $a)
177 $oauth1 = new FKOAuth1();
180 $request = OAuthRequest::from_request();
181 list($consumer, $token) = $oauth1->verify_request($request);
182 if (!is_null($token)) {
183 $oauth1->loginUser($token->uid);
184 Session::set('allow_api', true);
187 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
188 var_dump($consumer, $token);
190 } catch (Exception $e) {
191 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
194 // workaround for HTTP-auth in CGI mode
195 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
196 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
197 if (strlen($userpass)) {
198 list($name, $password) = explode(':', $userpass);
199 $_SERVER['PHP_AUTH_USER'] = $name;
200 $_SERVER['PHP_AUTH_PW'] = $password;
204 if (empty($_SERVER['PHP_AUTH_USER'])) {
205 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
206 header('WWW-Authenticate: Basic realm="Friendica"');
207 throw new UnauthorizedException("This API requires login");
210 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
211 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
213 // allow "user@server" login (but ignore 'server' part)
214 $at = strstr($user, "@", true);
219 // next code from mod/auth.php. needs better solution
223 'username' => trim($user),
224 'password' => trim($password),
225 'authenticated' => 0,
226 'user_record' => null,
230 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
231 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
232 * and later addons should not interfere with an earlier one that succeeded.
234 Hook::callAll('authenticate', $addon_auth);
236 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
237 $record = $addon_auth['user_record'];
239 $user_id = User::authenticate(trim($user), trim($password), true);
240 if ($user_id !== false) {
241 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
245 if (!DBA::isResult($record)) {
246 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
247 header('WWW-Authenticate: Basic realm="Friendica"');
248 //header('HTTP/1.0 401 Unauthorized');
249 //die('This api requires login');
250 throw new UnauthorizedException("This API requires login");
253 Session::setAuthenticatedForUser($a, $record);
255 $_SESSION["allow_api"] = true;
257 Hook::callAll('logged_in', $a->user);
261 * API endpoints can define which HTTP method to accept when called.
262 * This function check the current HTTP method agains endpoint
265 * @brief Check HTTP method of called API
267 * @param string $method Required methods, uppercase, separated by comma
270 function api_check_method($method)
272 if ($method == "*") {
275 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
279 * Authenticate user, call registered API function, set HTTP headers
281 * @brief Main API entry point
284 * @return string|array API call result
287 function api_call(App $a)
289 global $API, $called_api;
292 if (strpos($a->query_string, ".xml") > 0) {
295 if (strpos($a->query_string, ".json") > 0) {
298 if (strpos($a->query_string, ".rss") > 0) {
301 if (strpos($a->query_string, ".atom") > 0) {
306 foreach ($API as $p => $info) {
307 if (strpos($a->query_string, $p) === 0) {
308 if (!api_check_method($info['method'])) {
309 throw new MethodNotAllowedException();
312 $called_api = explode("/", $p);
313 //unset($_SERVER['PHP_AUTH_USER']);
315 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
316 if (!empty($info['auth']) && api_user() === false) {
320 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
321 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
323 $stamp = microtime(true);
324 $return = call_user_func($info['func'], $type);
325 $duration = floatval(microtime(true) - $stamp);
327 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
329 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
331 if (false === $return) {
333 * api function returned false withour throw an
334 * exception. This should not happend, throw a 500
336 throw new InternalServerErrorException();
341 header("Content-Type: text/xml");
344 header("Content-Type: application/json");
345 if (!empty($return)) {
346 $json = json_encode(end($return));
347 if (!empty($_GET['callback'])) {
348 $json = $_GET['callback'] . "(" . $json . ")";
354 header("Content-Type: application/rss+xml");
355 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
358 header("Content-Type: application/atom+xml");
359 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
366 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
367 throw new NotImplementedException();
368 } catch (HTTPException $e) {
369 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
370 return api_error($type, $e);
375 * @brief Format API error string
377 * @param string $type Return type (xml, json, rss, as)
378 * @param object $e HTTPException Error object
379 * @return string|array error message formatted as $type
381 function api_error($type, $e)
385 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
386 /// @TODO: https://dev.twitter.com/overview/api/response-codes
388 $error = ["error" => $error,
389 "code" => $e->getCode() . " " . $e->httpdesc,
390 "request" => $a->query_string];
392 $return = api_format_data('status', $type, ['status' => $error]);
396 header("Content-Type: text/xml");
399 header("Content-Type: application/json");
400 $return = json_encode($return);
403 header("Content-Type: application/rss+xml");
406 header("Content-Type: application/atom+xml");
414 * @brief Set values for RSS template
417 * @param array $arr Array to be passed to template
418 * @param array $user_info User info
420 * @throws BadRequestException
421 * @throws ImagickException
422 * @throws InternalServerErrorException
423 * @throws UnauthorizedException
424 * @todo find proper type-hints
426 function api_rss_extra(App $a, $arr, $user_info)
428 if (is_null($user_info)) {
429 $user_info = api_get_user($a);
432 $arr['$user'] = $user_info;
434 'alternate' => $user_info['url'],
435 'self' => System::baseUrl() . "/" . $a->query_string,
436 'base' => System::baseUrl(),
437 'updated' => api_date(null),
438 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
439 'language' => $user_info['lang'],
440 'logo' => System::baseUrl() . "/images/friendica-32.png",
448 * @brief Unique contact to contact url.
450 * @param int $id Contact id
451 * @return bool|string
452 * Contact url or False if contact id is unknown
455 function api_unique_id_to_nurl($id)
457 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
459 if (DBA::isResult($r)) {
467 * @brief Get user info array.
470 * @param int|string $contact_id Contact ID or URL
472 * @throws BadRequestException
473 * @throws ImagickException
474 * @throws InternalServerErrorException
475 * @throws UnauthorizedException
477 function api_get_user(App $a, $contact_id = null)
485 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
487 // Searching for contact URL
488 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
489 $user = DBA::escape(Strings::normaliseLink($contact_id));
491 $extra_query = "AND `contact`.`nurl` = '%s' ";
492 if (api_user() !== false) {
493 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
497 // Searching for contact id with uid = 0
498 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
499 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
502 throw new BadRequestException("User ID ".$contact_id." not found.");
506 $extra_query = "AND `contact`.`nurl` = '%s' ";
507 if (api_user() !== false) {
508 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
512 if (is_null($user) && !empty($_GET['user_id'])) {
513 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
516 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
520 $extra_query = "AND `contact`.`nurl` = '%s' ";
521 if (api_user() !== false) {
522 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
525 if (is_null($user) && !empty($_GET['screen_name'])) {
526 $user = DBA::escape($_GET['screen_name']);
527 $extra_query = "AND `contact`.`nick` = '%s' ";
528 if (api_user() !== false) {
529 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
533 if (is_null($user) && !empty($_GET['profileurl'])) {
534 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
535 $extra_query = "AND `contact`.`nurl` = '%s' ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
541 // $called_api is the API path exploded on / and is expected to have at least 2 elements
542 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
543 $argid = count($called_api);
544 if (!empty($a->argv[$argid])) {
545 $data = explode(".", $a->argv[$argid]);
546 if (count($data) > 1) {
547 list($user, $null) = $data;
550 if (is_numeric($user)) {
551 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
555 $extra_query = "AND `contact`.`nurl` = '%s' ";
556 if (api_user() !== false) {
557 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
561 $user = DBA::escape($user);
562 $extra_query = "AND `contact`.`nick` = '%s' ";
563 if (api_user() !== false) {
564 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
569 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
572 if (api_user() === false) {
576 $user = $_SESSION['uid'];
577 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
581 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
585 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
591 // Selecting the id by priority, friendica first
592 if (is_array($uinfo)) {
593 api_best_nickname($uinfo);
596 // if the contact wasn't found, fetch it from the contacts with uid = 0
597 if (!DBA::isResult($uinfo)) {
599 throw new BadRequestException("User not found.");
602 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
604 if (DBA::isResult($contact)) {
605 // If no nick where given, extract it from the address
606 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
607 $contact['nick'] = api_get_nick($contact["url"]);
611 'id' => $contact["id"],
612 'id_str' => (string) $contact["id"],
613 'name' => $contact["name"],
614 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
615 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
616 'description' => BBCode::toPlaintext($contact["about"]),
617 'profile_image_url' => $contact["micro"],
618 'profile_image_url_https' => $contact["micro"],
619 'profile_image_url_profile_size' => $contact["thumb"],
620 'profile_image_url_large' => $contact["photo"],
621 'url' => $contact["url"],
622 'protected' => false,
623 'followers_count' => 0,
624 'friends_count' => 0,
626 'created_at' => api_date($contact["created"]),
627 'favourites_count' => 0,
629 'time_zone' => 'UTC',
630 'geo_enabled' => false,
632 'statuses_count' => 0,
634 'contributors_enabled' => false,
635 'is_translator' => false,
636 'is_translation_enabled' => false,
637 'following' => false,
638 'follow_request_sent' => false,
639 'statusnet_blocking' => false,
640 'notifications' => false,
641 'statusnet_profile_url' => $contact["url"],
643 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
644 'pid' => Contact::getIdForURL($contact["url"], 0, true),
646 'network' => $contact["network"],
651 throw new BadRequestException("User ".$url." not found.");
655 if ($uinfo[0]['self']) {
656 if ($uinfo[0]['network'] == "") {
657 $uinfo[0]['network'] = Protocol::DFRN;
660 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
661 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
668 // Add a nick if it isn't present there
669 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
670 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
673 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
675 if (!empty($profile['about'])) {
676 $description = $profile['about'];
678 $description = $uinfo[0]["about"];
681 if (!empty($usr['default-location'])) {
682 $location = $usr['default-location'];
683 } elseif (!empty($uinfo[0]["location"])) {
684 $location = $uinfo[0]["location"];
686 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
690 'id' => intval($pcontact_id),
691 'id_str' => (string) intval($pcontact_id),
692 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
693 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
694 'location' => $location,
695 'description' => BBCode::toPlaintext($description),
696 'profile_image_url' => $uinfo[0]['micro'],
697 'profile_image_url_https' => $uinfo[0]['micro'],
698 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
699 'profile_image_url_large' => $uinfo[0]["photo"],
700 'url' => $uinfo[0]['url'],
701 'protected' => false,
702 'followers_count' => intval($countfollowers),
703 'friends_count' => intval($countfriends),
705 'created_at' => api_date($uinfo[0]['created']),
706 'favourites_count' => intval($starred),
708 'time_zone' => 'UTC',
709 'geo_enabled' => false,
711 'statuses_count' => intval($countitems),
713 'contributors_enabled' => false,
714 'is_translator' => false,
715 'is_translation_enabled' => false,
716 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
717 'follow_request_sent' => false,
718 'statusnet_blocking' => false,
719 'notifications' => false,
721 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
722 'statusnet_profile_url' => $uinfo[0]['url'],
723 'uid' => intval($uinfo[0]['uid']),
724 'cid' => intval($uinfo[0]['cid']),
725 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
726 'self' => $uinfo[0]['self'],
727 'network' => $uinfo[0]['network'],
730 // If this is a local user and it uses Frio, we can get its color preferences.
732 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
733 if ($theme_info['theme'] === 'frio') {
734 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
736 if ($schema && ($schema != '---')) {
737 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
738 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
739 require_once $schemefile;
742 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
743 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
744 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
746 if (empty($nav_bg)) {
749 if (empty($link_color)) {
750 $link_color = "#6fdbe8";
752 if (empty($bgcolor)) {
753 $bgcolor = "#ededed";
756 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
757 $ret['profile_link_color'] = str_replace('#', '', $link_color);
758 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
766 * @brief return api-formatted array for item's author and owner
769 * @param array $item item from db
770 * @return array(array:author, array:owner)
771 * @throws BadRequestException
772 * @throws ImagickException
773 * @throws InternalServerErrorException
774 * @throws UnauthorizedException
776 function api_item_get_user(App $a, $item)
778 $status_user = api_get_user($a, $item['author-id'] ?? null);
780 $author_user = $status_user;
782 $status_user["protected"] = $item['private'] ?? 0;
784 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
785 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
787 $owner_user = $author_user;
790 return ([$status_user, $author_user, $owner_user]);
794 * @brief walks recursively through an array with the possibility to change value and key
796 * @param array $array The array to walk through
797 * @param callable $callback The callback function
799 * @return array the transformed array
801 function api_walk_recursive(array &$array, callable $callback)
805 foreach ($array as $k => $v) {
807 if ($callback($v, $k)) {
808 $new_array[$k] = api_walk_recursive($v, $callback);
811 if ($callback($v, $k)) {
822 * @brief Callback function to transform the array in an array that can be transformed in a XML file
824 * @param mixed $item Array item value
825 * @param string $key Array key
827 * @return boolean Should the array item be deleted?
829 function api_reformat_xml(&$item, &$key)
831 if (is_bool($item)) {
832 $item = ($item ? "true" : "false");
835 if (substr($key, 0, 10) == "statusnet_") {
836 $key = "statusnet:".substr($key, 10);
837 } elseif (substr($key, 0, 10) == "friendica_") {
838 $key = "friendica:".substr($key, 10);
840 /// @TODO old-lost code?
842 // $key = "default:".$key;
848 * @brief Creates the XML from a JSON style array
850 * @param array $data JSON style array
851 * @param string $root_element Name of the root element
853 * @return string The XML data
855 function api_create_xml(array $data, $root_element)
857 $childname = key($data);
858 $data2 = array_pop($data);
860 $namespaces = ["" => "http://api.twitter.com",
861 "statusnet" => "http://status.net/schema/api/1/",
862 "friendica" => "http://friendi.ca/schema/api/1/",
863 "georss" => "http://www.georss.org/georss"];
865 /// @todo Auto detection of needed namespaces
866 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
870 if (is_array($data2)) {
872 api_walk_recursive($data2, "api_reformat_xml");
878 foreach ($data2 as $item) {
879 $data4[$i++ . ":" . $childname] = $item;
886 $data3 = [$root_element => $data2];
888 $ret = XML::fromArray($data3, $xml, false, $namespaces);
893 * @brief Formats the data according to the data type
895 * @param string $root_element Name of the root element
896 * @param string $type Return type (atom, rss, xml, json)
897 * @param array $data JSON style array
899 * @return array|string (string|array) XML data or JSON data
901 function api_format_data($root_element, $type, $data)
907 $ret = api_create_xml($data, $root_element);
922 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
923 * returns a 401 status code and an error message if not.
925 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
927 * @param string $type Return type (atom, rss, xml, json)
928 * @return array|string
929 * @throws BadRequestException
930 * @throws ForbiddenException
931 * @throws ImagickException
932 * @throws InternalServerErrorException
933 * @throws UnauthorizedException
935 function api_account_verify_credentials($type)
939 if (api_user() === false) {
940 throw new ForbiddenException();
943 unset($_REQUEST["user_id"]);
944 unset($_GET["user_id"]);
946 unset($_REQUEST["screen_name"]);
947 unset($_GET["screen_name"]);
949 $skip_status = $_REQUEST['skip_status'] ?? false;
951 $user_info = api_get_user($a);
953 // "verified" isn't used here in the standard
954 unset($user_info["verified"]);
956 // - Adding last status
958 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
960 $user_info['status'] = api_format_item($item, $type);
964 // "uid" and "self" are only needed for some internal stuff, so remove it from here
965 unset($user_info["uid"]);
966 unset($user_info["self"]);
968 return api_format_data("user", $type, ['user' => $user_info]);
971 /// @TODO move to top of file or somewhere better
972 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
975 * Get data from $_POST or $_GET
980 function requestdata($k)
982 if (!empty($_POST[$k])) {
985 if (!empty($_GET[$k])) {
992 * Deprecated function to upload media.
994 * @param string $type Return type (atom, rss, xml, json)
996 * @return array|string
997 * @throws BadRequestException
998 * @throws ForbiddenException
999 * @throws ImagickException
1000 * @throws InternalServerErrorException
1001 * @throws UnauthorizedException
1003 function api_statuses_mediap($type)
1007 if (api_user() === false) {
1008 Logger::log('api_statuses_update: no user');
1009 throw new ForbiddenException();
1011 $user_info = api_get_user($a);
1013 $_REQUEST['profile_uid'] = api_user();
1014 $_REQUEST['api_source'] = true;
1015 $txt = requestdata('status');
1016 /// @TODO old-lost code?
1017 //$txt = urldecode(requestdata('status'));
1019 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1020 $txt = HTML::toBBCodeVideo($txt);
1021 $config = HTMLPurifier_Config::createDefault();
1022 $config->set('Cache.DefinitionImpl', null);
1023 $purifier = new HTMLPurifier($config);
1024 $txt = $purifier->purify($txt);
1026 $txt = HTML::toBBCode($txt);
1028 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1030 $picture = wall_upload_post($a, false);
1032 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1033 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1034 $item_id = item_post($a);
1036 // output the post that we just posted.
1037 return api_status_show($type, $item_id);
1040 /// @TODO move this to top of file or somewhere better!
1041 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1044 * Updates the user’s current status.
1046 * @param string $type Return type (atom, rss, xml, json)
1048 * @return array|string
1049 * @throws BadRequestException
1050 * @throws ForbiddenException
1051 * @throws ImagickException
1052 * @throws InternalServerErrorException
1053 * @throws TooManyRequestsException
1054 * @throws UnauthorizedException
1055 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1057 function api_statuses_update($type)
1061 if (api_user() === false) {
1062 Logger::log('api_statuses_update: no user');
1063 throw new ForbiddenException();
1068 // convert $_POST array items to the form we use for web posts.
1069 if (requestdata('htmlstatus')) {
1070 $txt = requestdata('htmlstatus');
1071 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1072 $txt = HTML::toBBCodeVideo($txt);
1074 $config = HTMLPurifier_Config::createDefault();
1075 $config->set('Cache.DefinitionImpl', null);
1077 $purifier = new HTMLPurifier($config);
1078 $txt = $purifier->purify($txt);
1080 $_REQUEST['body'] = HTML::toBBCode($txt);
1083 $_REQUEST['body'] = requestdata('status');
1086 $_REQUEST['title'] = requestdata('title');
1088 $parent = requestdata('in_reply_to_status_id');
1090 // Twidere sends "-1" if it is no reply ...
1091 if ($parent == -1) {
1095 if (ctype_digit($parent)) {
1096 $_REQUEST['parent'] = $parent;
1098 $_REQUEST['parent_uri'] = $parent;
1101 if (requestdata('lat') && requestdata('long')) {
1102 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1104 $_REQUEST['profile_uid'] = api_user();
1107 // Check for throttling (maximum posts per day, week and month)
1108 $throttle_day = Config::get('system', 'throttle_limit_day');
1109 if ($throttle_day > 0) {
1110 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1112 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1113 $posts_day = DBA::count('thread', $condition);
1115 if ($posts_day > $throttle_day) {
1116 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1117 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1118 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));
1122 $throttle_week = Config::get('system', 'throttle_limit_week');
1123 if ($throttle_week > 0) {
1124 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1126 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1127 $posts_week = DBA::count('thread', $condition);
1129 if ($posts_week > $throttle_week) {
1130 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1131 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1132 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));
1136 $throttle_month = Config::get('system', 'throttle_limit_month');
1137 if ($throttle_month > 0) {
1138 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1140 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1141 $posts_month = DBA::count('thread', $condition);
1143 if ($posts_month > $throttle_month) {
1144 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1145 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1146 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));
1151 if (!empty($_FILES['media'])) {
1152 // upload the image if we have one
1153 $picture = wall_upload_post($a, false);
1154 if (is_array($picture)) {
1155 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1159 if (requestdata('media_ids')) {
1160 $ids = explode(',', requestdata('media_ids'));
1161 foreach ($ids as $id) {
1163 "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",
1167 if (DBA::isResult($r)) {
1168 $phototypes = Image::supportedTypes();
1169 $ext = $phototypes[$r[0]['type']];
1170 $description = $r[0]['desc'] ?? '';
1171 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1172 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1177 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1179 $_REQUEST['api_source'] = true;
1181 if (empty($_REQUEST['source'])) {
1182 $_REQUEST["source"] = api_source();
1185 // call out normal post function
1186 $item_id = item_post($a);
1188 // output the post that we just posted.
1189 return api_status_show($type, $item_id);
1192 /// @TODO move to top of file or somewhere better
1193 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1194 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1197 * Uploads an image to Friendica.
1200 * @throws BadRequestException
1201 * @throws ForbiddenException
1202 * @throws ImagickException
1203 * @throws InternalServerErrorException
1204 * @throws UnauthorizedException
1205 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1207 function api_media_upload()
1211 if (api_user() === false) {
1212 Logger::log('no user');
1213 throw new ForbiddenException();
1218 if (empty($_FILES['media'])) {
1220 throw new BadRequestException("No media.");
1223 $media = wall_upload_post($a, false);
1226 throw new InternalServerErrorException();
1230 $returndata["media_id"] = $media["id"];
1231 $returndata["media_id_string"] = (string)$media["id"];
1232 $returndata["size"] = $media["size"];
1233 $returndata["image"] = ["w" => $media["width"],
1234 "h" => $media["height"],
1235 "image_type" => $media["type"],
1236 "friendica_preview_url" => $media["preview"]];
1238 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1240 return ["media" => $returndata];
1243 /// @TODO move to top of file or somewhere better
1244 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1247 * Updates media meta data (picture descriptions)
1249 * @param string $type Return type (atom, rss, xml, json)
1251 * @return array|string
1252 * @throws BadRequestException
1253 * @throws ForbiddenException
1254 * @throws ImagickException
1255 * @throws InternalServerErrorException
1256 * @throws TooManyRequestsException
1257 * @throws UnauthorizedException
1258 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1260 * @todo Compare the corresponding Twitter function for correct return values
1262 function api_media_metadata_create($type)
1266 if (api_user() === false) {
1267 Logger::info('no user');
1268 throw new ForbiddenException();
1273 $postdata = Network::postdata();
1275 if (empty($postdata)) {
1276 throw new BadRequestException("No post data");
1279 $data = json_decode($postdata, true);
1281 throw new BadRequestException("Invalid post data");
1284 if (empty($data['media_id']) || empty($data['alt_text'])) {
1285 throw new BadRequestException("Missing post data values");
1288 if (empty($data['alt_text']['text'])) {
1289 throw new BadRequestException("No alt text.");
1292 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1294 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1295 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1296 if (!DBA::isResult($photo)) {
1297 throw new BadRequestException("Metadata not found.");
1300 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1303 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1306 * @param string $type Return format (atom, rss, xml, json)
1307 * @param int $item_id
1311 function api_status_show($type, $item_id)
1313 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1317 $item = api_get_item(['id' => $item_id]);
1319 $status_info = api_format_item($item, $type);
1322 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1324 return api_format_data('statuses', $type, ['status' => $status_info]);
1328 * Retrieves the last public status of the provided user info
1330 * @param int $ownerId Public contact Id
1331 * @param int $uid User Id
1335 function api_get_last_status($ownerId, $uid)
1338 'author-id'=> $ownerId,
1340 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1344 $item = api_get_item($condition);
1350 * Retrieves a single item record based on the provided condition and converts it for API use.
1352 * @param array $condition Item table condition array
1356 function api_get_item(array $condition)
1358 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1364 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1365 * The author's most recent status will be returned inline.
1367 * @param string $type Return type (atom, rss, xml, json)
1368 * @return array|string
1369 * @throws BadRequestException
1370 * @throws ImagickException
1371 * @throws InternalServerErrorException
1372 * @throws UnauthorizedException
1373 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1375 function api_users_show($type)
1377 $a = \Friendica\BaseObject::getApp();
1379 $user_info = api_get_user($a);
1381 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1383 $user_info['status'] = api_format_item($item, $type);
1386 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1387 unset($user_info['uid']);
1388 unset($user_info['self']);
1390 return api_format_data('user', $type, ['user' => $user_info]);
1393 /// @TODO move to top of file or somewhere better
1394 api_register_func('api/users/show', 'api_users_show');
1395 api_register_func('api/externalprofile/show', 'api_users_show');
1398 * Search a public user account.
1400 * @param string $type Return type (atom, rss, xml, json)
1402 * @return array|string
1403 * @throws BadRequestException
1404 * @throws ImagickException
1405 * @throws InternalServerErrorException
1406 * @throws UnauthorizedException
1407 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1409 function api_users_search($type)
1415 if (!empty($_GET['q'])) {
1416 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1418 if (!DBA::isResult($r)) {
1419 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1422 if (DBA::isResult($r)) {
1424 foreach ($r as $user) {
1425 $user_info = api_get_user($a, $user["id"]);
1427 if ($type == "xml") {
1428 $userlist[$k++.":user"] = $user_info;
1430 $userlist[] = $user_info;
1433 $userlist = ["users" => $userlist];
1435 throw new BadRequestException("User ".$_GET["q"]." not found.");
1438 throw new BadRequestException("No user specified.");
1441 return api_format_data("users", $type, $userlist);
1444 /// @TODO move to top of file or somewhere better
1445 api_register_func('api/users/search', 'api_users_search');
1448 * Return user objects
1450 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1452 * @param string $type Return format: json or xml
1454 * @return array|string
1455 * @throws BadRequestException
1456 * @throws ImagickException
1457 * @throws InternalServerErrorException
1458 * @throws NotFoundException if the results are empty.
1459 * @throws UnauthorizedException
1461 function api_users_lookup($type)
1465 if (!empty($_REQUEST['user_id'])) {
1466 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1468 $users[] = api_get_user(get_app(), $id);
1473 if (empty($users)) {
1474 throw new NotFoundException;
1477 return api_format_data("users", $type, ['users' => $users]);
1480 /// @TODO move to top of file or somewhere better
1481 api_register_func('api/users/lookup', 'api_users_lookup', true);
1484 * Returns statuses that match a specified query.
1486 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1488 * @param string $type Return format: json, xml, atom, rss
1490 * @return array|string
1491 * @throws BadRequestException if the "q" parameter is missing.
1492 * @throws ForbiddenException
1493 * @throws ImagickException
1494 * @throws InternalServerErrorException
1495 * @throws UnauthorizedException
1497 function api_search($type)
1500 $user_info = api_get_user($a);
1502 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1504 if (empty($_REQUEST['q'])) {
1505 throw new BadRequestException('q parameter is required.');
1508 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1511 $data['status'] = [];
1513 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1514 if (!empty($_REQUEST['rpp'])) {
1515 $count = $_REQUEST['rpp'];
1516 } elseif (!empty($_REQUEST['count'])) {
1517 $count = $_REQUEST['count'];
1520 $since_id = $_REQUEST['since_id'] ?? 0;
1521 $max_id = $_REQUEST['max_id'] ?? 0;
1522 $page = $_REQUEST['page'] ?? 1;
1524 $start = max(0, ($page - 1) * $count);
1526 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1527 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1528 $searchTerm = $matches[1];
1529 $condition = ["`oid` > ?
1530 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1531 AND `otype` = ? AND `type` = ? AND `term` = ?",
1532 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1534 $condition[0] .= ' AND `oid` <= ?';
1535 $condition[] = $max_id;
1537 $terms = DBA::select('term', ['oid'], $condition, []);
1539 while ($term = DBA::fetch($terms)) {
1540 $itemIds[] = $term['oid'];
1544 if (empty($itemIds)) {
1545 return api_format_data('statuses', $type, $data);
1548 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1549 if ($exclude_replies) {
1550 $preCondition[] = '`id` = `parent`';
1553 $condition = [implode(' AND ', $preCondition)];
1555 $condition = ["`id` > ?
1556 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1557 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1558 AND `body` LIKE CONCAT('%',?,'%')",
1559 $since_id, api_user(), $_REQUEST['q']];
1561 $condition[0] .= ' AND `id` <= ?';
1562 $condition[] = $max_id;
1566 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1568 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1570 bindComments($data['status']);
1572 return api_format_data('statuses', $type, $data);
1575 /// @TODO move to top of file or somewhere better
1576 api_register_func('api/search/tweets', 'api_search', true);
1577 api_register_func('api/search', 'api_search', true);
1580 * Returns the most recent statuses posted by the user and the users they follow.
1582 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1584 * @param string $type Return type (atom, rss, xml, json)
1586 * @return array|string
1587 * @throws BadRequestException
1588 * @throws ForbiddenException
1589 * @throws ImagickException
1590 * @throws InternalServerErrorException
1591 * @throws UnauthorizedException
1592 * @todo Optional parameters
1593 * @todo Add reply info
1595 function api_statuses_home_timeline($type)
1598 $user_info = api_get_user($a);
1600 if (api_user() === false || $user_info === false) {
1601 throw new ForbiddenException();
1604 unset($_REQUEST["user_id"]);
1605 unset($_GET["user_id"]);
1607 unset($_REQUEST["screen_name"]);
1608 unset($_GET["screen_name"]);
1610 // get last network messages
1613 $count = $_REQUEST['count'] ?? 20;
1614 $page = $_REQUEST['page']?? 0;
1615 $since_id = $_REQUEST['since_id'] ?? 0;
1616 $max_id = $_REQUEST['max_id'] ?? 0;
1617 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1618 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1620 $start = max(0, ($page - 1) * $count);
1622 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1623 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1626 $condition[0] .= " AND `item`.`id` <= ?";
1627 $condition[] = $max_id;
1629 if ($exclude_replies) {
1630 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1632 if ($conversation_id > 0) {
1633 $condition[0] .= " AND `item`.`parent` = ?";
1634 $condition[] = $conversation_id;
1637 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1638 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1640 $items = Item::inArray($statuses);
1642 $ret = api_format_items($items, $user_info, false, $type);
1644 // Set all posts from the query above to seen
1646 foreach ($items as $item) {
1647 $idarray[] = intval($item["id"]);
1650 if (!empty($idarray)) {
1651 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1653 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1659 $data = ['status' => $ret];
1664 $data = api_rss_extra($a, $data, $user_info);
1668 return api_format_data("statuses", $type, $data);
1672 /// @TODO move to top of file or somewhere better
1673 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1674 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1677 * Returns the most recent statuses from public users.
1679 * @param string $type Return type (atom, rss, xml, json)
1681 * @return array|string
1682 * @throws BadRequestException
1683 * @throws ForbiddenException
1684 * @throws ImagickException
1685 * @throws InternalServerErrorException
1686 * @throws UnauthorizedException
1688 function api_statuses_public_timeline($type)
1691 $user_info = api_get_user($a);
1693 if (api_user() === false || $user_info === false) {
1694 throw new ForbiddenException();
1697 // get last network messages
1700 $count = $_REQUEST['count'] ?? 20;
1701 $page = $_REQUEST['page'] ?? 1;
1702 $since_id = $_REQUEST['since_id'] ?? 0;
1703 $max_id = $_REQUEST['max_id'] ?? 0;
1704 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1705 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1707 $start = max(0, ($page - 1) * $count);
1709 if ($exclude_replies && !$conversation_id) {
1710 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1711 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1714 $condition[0] .= " AND `thread`.`iid` <= ?";
1715 $condition[] = $max_id;
1718 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1719 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1721 $r = Item::inArray($statuses);
1723 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1724 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1727 $condition[0] .= " AND `item`.`id` <= ?";
1728 $condition[] = $max_id;
1730 if ($conversation_id > 0) {
1731 $condition[0] .= " AND `item`.`parent` = ?";
1732 $condition[] = $conversation_id;
1735 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1736 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1738 $r = Item::inArray($statuses);
1741 $ret = api_format_items($r, $user_info, false, $type);
1745 $data = ['status' => $ret];
1750 $data = api_rss_extra($a, $data, $user_info);
1754 return api_format_data("statuses", $type, $data);
1757 /// @TODO move to top of file or somewhere better
1758 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1761 * Returns the most recent statuses posted by users this node knows about.
1763 * @brief Returns the list of public federated posts this node knows about
1765 * @param string $type Return format: json, xml, atom, rss
1766 * @return array|string
1767 * @throws BadRequestException
1768 * @throws ForbiddenException
1769 * @throws ImagickException
1770 * @throws InternalServerErrorException
1771 * @throws UnauthorizedException
1773 function api_statuses_networkpublic_timeline($type)
1776 $user_info = api_get_user($a);
1778 if (api_user() === false || $user_info === false) {
1779 throw new ForbiddenException();
1782 $since_id = $_REQUEST['since_id'] ?? 0;
1783 $max_id = $_REQUEST['max_id'] ?? 0;
1786 $count = $_REQUEST['count'] ?? 20;
1787 $page = $_REQUEST['page'] ?? 1;
1789 $start = max(0, ($page - 1) * $count);
1791 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1792 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1795 $condition[0] .= " AND `thread`.`iid` <= ?";
1796 $condition[] = $max_id;
1799 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1800 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1802 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1806 $data = ['status' => $ret];
1811 $data = api_rss_extra($a, $data, $user_info);
1815 return api_format_data("statuses", $type, $data);
1818 /// @TODO move to top of file or somewhere better
1819 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1822 * Returns a single status.
1824 * @param string $type Return type (atom, rss, xml, json)
1826 * @return array|string
1827 * @throws BadRequestException
1828 * @throws ForbiddenException
1829 * @throws ImagickException
1830 * @throws InternalServerErrorException
1831 * @throws UnauthorizedException
1832 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1834 function api_statuses_show($type)
1837 $user_info = api_get_user($a);
1839 if (api_user() === false || $user_info === false) {
1840 throw new ForbiddenException();
1844 $id = intval($a->argv[3] ?? 0);
1847 $id = intval($_REQUEST['id'] ?? 0);
1852 $id = intval($a->argv[4] ?? 0);
1855 Logger::log('API: api_statuses_show: ' . $id);
1857 $conversation = !empty($_REQUEST['conversation']);
1859 // try to fetch the item for the local user - or the public item, if there is no local one
1860 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1861 if (!DBA::isResult($uri_item)) {
1862 throw new BadRequestException("There is no status with this id.");
1865 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1866 if (!DBA::isResult($item)) {
1867 throw new BadRequestException("There is no status with this id.");
1872 if ($conversation) {
1873 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1874 $params = ['order' => ['id' => true]];
1876 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1880 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1882 /// @TODO How about copying this to above methods which don't check $r ?
1883 if (!DBA::isResult($statuses)) {
1884 throw new BadRequestException("There is no status with this id.");
1887 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1889 if ($conversation) {
1890 $data = ['status' => $ret];
1891 return api_format_data("statuses", $type, $data);
1893 $data = ['status' => $ret[0]];
1894 return api_format_data("status", $type, $data);
1898 /// @TODO move to top of file or somewhere better
1899 api_register_func('api/statuses/show', 'api_statuses_show', true);
1903 * @param string $type Return type (atom, rss, xml, json)
1905 * @return array|string
1906 * @throws BadRequestException
1907 * @throws ForbiddenException
1908 * @throws ImagickException
1909 * @throws InternalServerErrorException
1910 * @throws UnauthorizedException
1911 * @todo nothing to say?
1913 function api_conversation_show($type)
1916 $user_info = api_get_user($a);
1918 if (api_user() === false || $user_info === false) {
1919 throw new ForbiddenException();
1923 $id = intval($a->argv[3] ?? 0);
1924 $since_id = intval($_REQUEST['since_id'] ?? 0);
1925 $max_id = intval($_REQUEST['max_id'] ?? 0);
1926 $count = intval($_REQUEST['count'] ?? 20);
1927 $page = intval($_REQUEST['page'] ?? 1);
1929 $start = max(0, ($page - 1) * $count);
1932 $id = intval($_REQUEST['id'] ?? 0);
1937 $id = intval($a->argv[4] ?? 0);
1940 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1942 // try to fetch the item for the local user - or the public item, if there is no local one
1943 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1944 if (!DBA::isResult($item)) {
1945 throw new BadRequestException("There is no status with this id.");
1948 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1949 if (!DBA::isResult($parent)) {
1950 throw new BadRequestException("There is no status with this id.");
1953 $id = $parent['id'];
1955 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1956 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1959 $condition[0] .= " AND `item`.`id` <= ?";
1960 $condition[] = $max_id;
1963 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1964 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1966 if (!DBA::isResult($statuses)) {
1967 throw new BadRequestException("There is no status with id $id.");
1970 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1972 $data = ['status' => $ret];
1973 return api_format_data("statuses", $type, $data);
1976 /// @TODO move to top of file or somewhere better
1977 api_register_func('api/conversation/show', 'api_conversation_show', true);
1978 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1983 * @param string $type Return type (atom, rss, xml, json)
1985 * @return array|string
1986 * @throws BadRequestException
1987 * @throws ForbiddenException
1988 * @throws ImagickException
1989 * @throws InternalServerErrorException
1990 * @throws UnauthorizedException
1991 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1993 function api_statuses_repeat($type)
1999 if (api_user() === false) {
2000 throw new ForbiddenException();
2006 $id = intval($a->argv[3] ?? 0);
2009 $id = intval($_REQUEST['id'] ?? 0);
2014 $id = intval($a->argv[4] ?? 0);
2017 Logger::log('API: api_statuses_repeat: '.$id);
2019 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2020 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2022 if (DBA::isResult($item) && $item['body'] != "") {
2023 if (strpos($item['body'], "[/share]") !== false) {
2024 $pos = strpos($item['body'], "[share");
2025 $post = substr($item['body'], $pos);
2027 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2029 $post .= $item['body'];
2030 $post .= "[/share]";
2032 $_REQUEST['body'] = $post;
2033 $_REQUEST['profile_uid'] = api_user();
2034 $_REQUEST['api_source'] = true;
2036 if (empty($_REQUEST['source'])) {
2037 $_REQUEST["source"] = api_source();
2040 $item_id = item_post($a);
2042 throw new ForbiddenException();
2045 // output the post that we just posted.
2047 return api_status_show($type, $item_id);
2050 /// @TODO move to top of file or somewhere better
2051 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2054 * Destroys a specific status.
2056 * @param string $type Return type (atom, rss, xml, json)
2058 * @return array|string
2059 * @throws BadRequestException
2060 * @throws ForbiddenException
2061 * @throws ImagickException
2062 * @throws InternalServerErrorException
2063 * @throws UnauthorizedException
2064 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2066 function api_statuses_destroy($type)
2070 if (api_user() === false) {
2071 throw new ForbiddenException();
2077 $id = intval($a->argv[3] ?? 0);
2080 $id = intval($_REQUEST['id'] ?? 0);
2085 $id = intval($a->argv[4] ?? 0);
2088 Logger::log('API: api_statuses_destroy: '.$id);
2090 $ret = api_statuses_show($type);
2092 Item::deleteForUser(['id' => $id], api_user());
2097 /// @TODO move to top of file or somewhere better
2098 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2101 * Returns the most recent mentions.
2103 * @param string $type Return type (atom, rss, xml, json)
2105 * @return array|string
2106 * @throws BadRequestException
2107 * @throws ForbiddenException
2108 * @throws ImagickException
2109 * @throws InternalServerErrorException
2110 * @throws UnauthorizedException
2111 * @see http://developer.twitter.com/doc/get/statuses/mentions
2113 function api_statuses_mentions($type)
2116 $user_info = api_get_user($a);
2118 if (api_user() === false || $user_info === false) {
2119 throw new ForbiddenException();
2122 unset($_REQUEST["user_id"]);
2123 unset($_GET["user_id"]);
2125 unset($_REQUEST["screen_name"]);
2126 unset($_GET["screen_name"]);
2128 // get last network messages
2131 $since_id = $_REQUEST['since_id'] ?? 0;
2132 $max_id = $_REQUEST['max_id'] ?? 0;
2133 $count = $_REQUEST['count'] ?? 20;
2134 $page = $_REQUEST['page'] ?? 1;
2136 $start = max(0, ($page - 1) * $count);
2138 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2139 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2140 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2143 $condition[0] .= " AND `item`.`id` <= ?";
2144 $condition[] = $max_id;
2147 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2148 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2150 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2152 $data = ['status' => $ret];
2157 $data = api_rss_extra($a, $data, $user_info);
2161 return api_format_data("statuses", $type, $data);
2164 /// @TODO move to top of file or somewhere better
2165 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2166 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2169 * Returns the most recent statuses posted by the user.
2171 * @brief Returns a user's public timeline
2173 * @param string $type Either "json" or "xml"
2174 * @return string|array
2175 * @throws BadRequestException
2176 * @throws ForbiddenException
2177 * @throws ImagickException
2178 * @throws InternalServerErrorException
2179 * @throws UnauthorizedException
2180 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2182 function api_statuses_user_timeline($type)
2185 $user_info = api_get_user($a);
2187 if (api_user() === false || $user_info === false) {
2188 throw new ForbiddenException();
2192 "api_statuses_user_timeline: api_user: ". api_user() .
2193 "\nuser_info: ".print_r($user_info, true) .
2194 "\n_REQUEST: ".print_r($_REQUEST, true),
2198 $since_id = $_REQUEST['since_id'] ?? 0;
2199 $max_id = $_REQUEST['max_id'] ?? 0;
2200 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2201 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2204 $count = $_REQUEST['count'] ?? 20;
2205 $page = $_REQUEST['page'] ?? 1;
2207 $start = max(0, ($page - 1) * $count);
2209 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2210 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2212 if ($user_info['self'] == 1) {
2213 $condition[0] .= ' AND `item`.`wall` ';
2216 if ($exclude_replies) {
2217 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2220 if ($conversation_id > 0) {
2221 $condition[0] .= " AND `item`.`parent` = ?";
2222 $condition[] = $conversation_id;
2226 $condition[0] .= " AND `item`.`id` <= ?";
2227 $condition[] = $max_id;
2230 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2231 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2233 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2237 $data = ['status' => $ret];
2242 $data = api_rss_extra($a, $data, $user_info);
2246 return api_format_data("statuses", $type, $data);
2249 /// @TODO move to top of file or somewhere better
2250 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2253 * Star/unstar an item.
2254 * param: id : id of the item
2256 * @param string $type Return type (atom, rss, xml, json)
2258 * @return array|string
2259 * @throws BadRequestException
2260 * @throws ForbiddenException
2261 * @throws ImagickException
2262 * @throws InternalServerErrorException
2263 * @throws UnauthorizedException
2264 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2266 function api_favorites_create_destroy($type)
2270 if (api_user() === false) {
2271 throw new ForbiddenException();
2274 // for versioned api.
2275 /// @TODO We need a better global soluton
2276 $action_argv_id = 2;
2277 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2278 $action_argv_id = 3;
2281 if ($a->argc <= $action_argv_id) {
2282 throw new BadRequestException("Invalid request.");
2284 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2285 if ($a->argc == $action_argv_id + 2) {
2286 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2288 $itemid = intval($_REQUEST['id'] ?? 0);
2291 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2293 if (!DBA::isResult($item)) {
2294 throw new BadRequestException("Invalid item.");
2299 $item['starred'] = 1;
2302 $item['starred'] = 0;
2305 throw new BadRequestException("Invalid action ".$action);
2308 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2311 throw new InternalServerErrorException("DB error");
2315 $user_info = api_get_user($a);
2316 $rets = api_format_items([$item], $user_info, false, $type);
2319 $data = ['status' => $ret];
2324 $data = api_rss_extra($a, $data, $user_info);
2328 return api_format_data("status", $type, $data);
2331 /// @TODO move to top of file or somewhere better
2332 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2333 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2336 * Returns the most recent favorite statuses.
2338 * @param string $type Return type (atom, rss, xml, json)
2340 * @return string|array
2341 * @throws BadRequestException
2342 * @throws ForbiddenException
2343 * @throws ImagickException
2344 * @throws InternalServerErrorException
2345 * @throws UnauthorizedException
2347 function api_favorites($type)
2352 $user_info = api_get_user($a);
2354 if (api_user() === false || $user_info === false) {
2355 throw new ForbiddenException();
2360 // in friendica starred item are private
2361 // return favorites only for self
2362 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2364 if ($user_info['self'] == 0) {
2368 $since_id = $_REQUEST['since_id'] ?? 0;
2369 $max_id = $_REQUEST['max_id'] ?? 0;
2370 $count = $_GET['count'] ?? 20;
2371 $page = $_REQUEST['page'] ?? 1;
2373 $start = max(0, ($page - 1) * $count);
2375 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2376 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2378 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2381 $condition[0] .= " AND `item`.`id` <= ?";
2382 $condition[] = $max_id;
2385 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2387 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2392 $data = ['status' => $ret];
2397 $data = api_rss_extra($a, $data, $user_info);
2401 return api_format_data("statuses", $type, $data);
2404 /// @TODO move to top of file or somewhere better
2405 api_register_func('api/favorites', 'api_favorites', true);
2409 * @param array $item
2410 * @param array $recipient
2411 * @param array $sender
2414 * @throws InternalServerErrorException
2416 function api_format_messages($item, $recipient, $sender)
2418 // standard meta information
2420 'id' => $item['id'],
2421 'sender_id' => $sender['id'],
2423 'recipient_id' => $recipient['id'],
2424 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2425 'sender_screen_name' => $sender['screen_name'],
2426 'recipient_screen_name' => $recipient['screen_name'],
2427 'sender' => $sender,
2428 'recipient' => $recipient,
2430 'friendica_seen' => $item['seen'] ?? 0,
2431 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2434 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2435 if (isset($ret['sender']['uid'])) {
2436 unset($ret['sender']['uid']);
2438 if (isset($ret['sender']['self'])) {
2439 unset($ret['sender']['self']);
2441 if (isset($ret['recipient']['uid'])) {
2442 unset($ret['recipient']['uid']);
2444 if (isset($ret['recipient']['self'])) {
2445 unset($ret['recipient']['self']);
2448 //don't send title to regular StatusNET requests to avoid confusing these apps
2449 if (!empty($_GET['getText'])) {
2450 $ret['title'] = $item['title'];
2451 if ($_GET['getText'] == 'html') {
2452 $ret['text'] = BBCode::convert($item['body'], false);
2453 } elseif ($_GET['getText'] == 'plain') {
2454 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2457 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2459 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2460 unset($ret['sender']);
2461 unset($ret['recipient']);
2469 * @param array $item
2472 * @throws InternalServerErrorException
2474 function api_convert_item($item)
2476 $body = $item['body'];
2477 $attachments = api_get_attachments($body);
2479 // Workaround for ostatus messages where the title is identically to the body
2480 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2481 $statusbody = trim(HTML::toPlaintext($html, 0));
2483 // handle data: images
2484 $statusbody = api_format_items_embeded_images($item, $statusbody);
2486 $statustitle = trim($item['title']);
2488 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2489 $statustext = trim($statusbody);
2491 $statustext = trim($statustitle."\n\n".$statusbody);
2494 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2495 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2498 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2500 // Workaround for clients with limited HTML parser functionality
2501 $search = ["<br>", "<blockquote>", "</blockquote>",
2502 "<h1>", "</h1>", "<h2>", "</h2>",
2503 "<h3>", "</h3>", "<h4>", "</h4>",
2504 "<h5>", "</h5>", "<h6>", "</h6>"];
2505 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2506 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2507 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2508 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2509 $statushtml = str_replace($search, $replace, $statushtml);
2511 if ($item['title'] != "") {
2512 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2516 $oldtext = $statushtml;
2517 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2518 } while ($oldtext != $statushtml);
2520 if (substr($statushtml, 0, 4) == '<br>') {
2521 $statushtml = substr($statushtml, 4);
2524 if (substr($statushtml, 0, -4) == '<br>') {
2525 $statushtml = substr($statushtml, -4);
2528 // feeds without body should contain the link
2529 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2530 $statushtml .= BBCode::convert($item['plink']);
2533 $entities = api_get_entitities($statustext, $body);
2536 "text" => $statustext,
2537 "html" => $statushtml,
2538 "attachments" => $attachments,
2539 "entities" => $entities
2545 * @param string $body
2548 * @throws InternalServerErrorException
2550 function api_get_attachments(&$body)
2553 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2555 $URLSearchString = "^\[\]";
2556 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2564 foreach ($images[1] as $image) {
2565 $imagedata = Image::getInfoFromURL($image);
2568 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2572 if (strstr($_SERVER['HTTP_USER_AGENT'] ?? '', 'AndStatus')) {
2573 foreach ($images[0] as $orig) {
2574 $body = str_replace($orig, "", $body);
2578 return $attachments;
2583 * @param string $text
2584 * @param string $bbcode
2587 * @throws InternalServerErrorException
2588 * @todo Links at the first character of the post
2590 function api_get_entitities(&$text, $bbcode)
2592 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2594 if ($include_entities != "true") {
2595 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2597 foreach ($images[1] as $image) {
2598 $replace = ProxyUtils::proxifyUrl($image);
2599 $text = str_replace($image, $replace, $text);
2604 $bbcode = BBCode::cleanPictureLinks($bbcode);
2606 // Change pure links in text to bbcode uris
2607 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2610 $entities["hashtags"] = [];
2611 $entities["symbols"] = [];
2612 $entities["urls"] = [];
2613 $entities["user_mentions"] = [];
2615 $URLSearchString = "^\[\]";
2617 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2619 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2620 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2621 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2623 $bbcode = preg_replace(
2624 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2625 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2628 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2630 $bbcode = preg_replace(
2631 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2632 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2635 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2637 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2639 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2640 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2643 foreach ($urls[1] as $id => $url) {
2644 //$start = strpos($text, $url, $offset);
2645 $start = iconv_strpos($text, $url, 0, "UTF-8");
2646 if (!($start === false)) {
2647 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2651 ksort($ordered_urls);
2654 //foreach ($urls[1] AS $id=>$url) {
2655 foreach ($ordered_urls as $url) {
2656 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2657 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2659 $display_url = $url["title"];
2661 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2662 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2664 if (strlen($display_url) > 26) {
2665 $display_url = substr($display_url, 0, 25)."…";
2669 //$start = strpos($text, $url, $offset);
2670 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2671 if (!($start === false)) {
2672 $entities["urls"][] = ["url" => $url["url"],
2673 "expanded_url" => $url["url"],
2674 "display_url" => $display_url,
2675 "indices" => [$start, $start+strlen($url["url"])]];
2676 $offset = $start + 1;
2680 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2681 $ordered_images = [];
2682 foreach ($images as $image) {
2683 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2684 if (!($start === false)) {
2685 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2689 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2690 foreach ($images[1] as $image) {
2691 $start = iconv_strpos($text, $image, 0, "UTF-8");
2692 if (!($start === false)) {
2693 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2696 //$entities["media"] = array();
2699 foreach ($ordered_images as $image) {
2700 $url = $image['url'];
2701 $ext_alt_text = $image['alt'];
2703 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2704 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2706 if (strlen($display_url) > 26) {
2707 $display_url = substr($display_url, 0, 25)."…";
2710 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2711 if (!($start === false)) {
2712 $image = Image::getInfoFromURL($url);
2714 // If image cache is activated, then use the following sizes:
2715 // thumb (150), small (340), medium (600) and large (1024)
2716 if (!Config::get("system", "proxy_disabled")) {
2717 $media_url = ProxyUtils::proxifyUrl($url);
2720 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2721 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2723 if (($image[0] > 150) || ($image[1] > 150)) {
2724 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2725 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2728 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2729 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2731 if (($image[0] > 600) || ($image[1] > 600)) {
2732 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2733 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2737 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2740 $entities["media"][] = [
2742 "id_str" => (string) ($start + 1),
2743 "indices" => [$start, $start+strlen($url)],
2744 "media_url" => Strings::normaliseLink($media_url),
2745 "media_url_https" => $media_url,
2747 "display_url" => $display_url,
2748 "expanded_url" => $url,
2749 "ext_alt_text" => $ext_alt_text,
2753 $offset = $start + 1;
2762 * @param array $item
2763 * @param string $text
2767 function api_format_items_embeded_images($item, $text)
2769 $text = preg_replace_callback(
2770 '|data:image/([^;]+)[^=]+=*|m',
2771 function () use ($item) {
2772 return System::baseUrl() . '/display/' . $item['guid'];
2780 * @brief return <a href='url'>name</a> as array
2782 * @param string $txt text
2787 function api_contactlink_to_array($txt)
2790 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2791 if ($r && count($match)==3) {
2793 'name' => $match[2],
2807 * @brief return likes, dislikes and attend status for item
2809 * @param array $item array
2810 * @param string $type Return type (atom, rss, xml, json)
2813 * likes => int count,
2814 * dislikes => int count
2815 * @throws BadRequestException
2816 * @throws ImagickException
2817 * @throws InternalServerErrorException
2818 * @throws UnauthorizedException
2820 function api_format_items_activities($item, $type = "json")
2829 'attendmaybe' => [],
2832 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2833 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2835 while ($parent_item = Item::fetch($ret)) {
2836 // not used as result should be structured like other user data
2837 //builtin_activity_puller($i, $activities);
2839 // get user data and add it to the array of the activity
2840 $user = api_get_user($a, $parent_item['author-id']);
2841 switch ($parent_item['verb']) {
2843 $activities['like'][] = $user;
2845 case ACTIVITY_DISLIKE:
2846 $activities['dislike'][] = $user;
2848 case ACTIVITY_ATTEND:
2849 $activities['attendyes'][] = $user;
2851 case ACTIVITY_ATTENDNO:
2852 $activities['attendno'][] = $user;
2854 case ACTIVITY_ATTENDMAYBE:
2855 $activities['attendmaybe'][] = $user;
2864 if ($type == "xml") {
2865 $xml_activities = [];
2866 foreach ($activities as $k => $v) {
2867 // change xml element from "like" to "friendica:like"
2868 $xml_activities["friendica:".$k] = $v;
2869 // add user data into xml output
2871 foreach ($v as $user) {
2872 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2875 $activities = $xml_activities;
2883 * @brief return data from profiles
2885 * @param array $profile_row array containing data from db table 'profile'
2887 * @throws InternalServerErrorException
2889 function api_format_items_profiles($profile_row)
2892 'profile_id' => $profile_row['id'],
2893 'profile_name' => $profile_row['profile-name'],
2894 'is_default' => $profile_row['is-default'] ? true : false,
2895 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2896 'profile_photo' => $profile_row['photo'],
2897 'profile_thumb' => $profile_row['thumb'],
2898 'publish' => $profile_row['publish'] ? true : false,
2899 'net_publish' => $profile_row['net-publish'] ? true : false,
2900 'description' => $profile_row['pdesc'],
2901 'date_of_birth' => $profile_row['dob'],
2902 'address' => $profile_row['address'],
2903 'city' => $profile_row['locality'],
2904 'region' => $profile_row['region'],
2905 'postal_code' => $profile_row['postal-code'],
2906 'country' => $profile_row['country-name'],
2907 'hometown' => $profile_row['hometown'],
2908 'gender' => $profile_row['gender'],
2909 'marital' => $profile_row['marital'],
2910 'marital_with' => $profile_row['with'],
2911 'marital_since' => $profile_row['howlong'],
2912 'sexual' => $profile_row['sexual'],
2913 'politic' => $profile_row['politic'],
2914 'religion' => $profile_row['religion'],
2915 'public_keywords' => $profile_row['pub_keywords'],
2916 'private_keywords' => $profile_row['prv_keywords'],
2917 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2918 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2919 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2920 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2921 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2922 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2923 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2924 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2925 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2926 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2927 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2928 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2929 'homepage' => $profile_row['homepage'],
2936 * @brief format items to be returned by api
2938 * @param array $items array of items
2939 * @param array $user_info
2940 * @param bool $filter_user filter items by $user_info
2941 * @param string $type Return type (atom, rss, xml, json)
2943 * @throws BadRequestException
2944 * @throws ImagickException
2945 * @throws InternalServerErrorException
2946 * @throws UnauthorizedException
2948 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2950 $a = \Friendica\BaseObject::getApp();
2954 foreach ((array)$items as $item) {
2955 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2957 // Look if the posts are matching if they should be filtered by user id
2958 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2962 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2971 * @param array $item Item record
2972 * @param string $type Return format (atom, rss, xml, json)
2973 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2974 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2975 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2976 * @return array API-formatted status
2977 * @throws BadRequestException
2978 * @throws ImagickException
2979 * @throws InternalServerErrorException
2980 * @throws UnauthorizedException
2982 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2984 $a = \Friendica\BaseObject::getApp();
2986 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2987 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2990 localize_item($item);
2992 $in_reply_to = api_in_reply_to($item);
2994 $converted = api_convert_item($item);
2996 if ($type == "xml") {
2997 $geo = "georss:point";
3003 'text' => $converted["text"],
3004 'truncated' => false,
3005 'created_at'=> api_date($item['created']),
3006 'in_reply_to_status_id' => $in_reply_to['status_id'],
3007 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3008 'source' => (($item['app']) ? $item['app'] : 'web'),
3009 'id' => intval($item['id']),
3010 'id_str' => (string) intval($item['id']),
3011 'in_reply_to_user_id' => $in_reply_to['user_id'],
3012 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3013 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3015 'favorited' => $item['starred'] ? true : false,
3016 'user' => $status_user,
3017 'friendica_author' => $author_user,
3018 'friendica_owner' => $owner_user,
3019 'friendica_private' => $item['private'] == 1,
3020 //'entities' => NULL,
3021 'statusnet_html' => $converted["html"],
3022 'statusnet_conversation_id' => $item['parent'],
3023 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3024 'friendica_activities' => api_format_items_activities($item, $type),
3025 'friendica_title' => $item['title'],
3026 'friendica_html' => BBCode::convert($item['body'], false)
3029 if (count($converted["attachments"]) > 0) {
3030 $status["attachments"] = $converted["attachments"];
3033 if (count($converted["entities"]) > 0) {
3034 $status["entities"] = $converted["entities"];
3037 if ($status["source"] == 'web') {
3038 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3039 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3040 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3043 $retweeted_item = [];
3046 if ($item["id"] == $item["parent"]) {
3047 $body = $item['body'];
3048 $retweeted_item = api_share_as_retweet($item);
3049 if ($body != $item['body']) {
3050 $quoted_item = $retweeted_item;
3051 $retweeted_item = [];
3055 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3056 $announce = api_get_announce($item);
3057 if (!empty($announce)) {
3058 $retweeted_item = $item;
3060 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3064 if (!empty($quoted_item)) {
3065 $conv_quoted = api_convert_item($quoted_item);
3066 $quoted_status = $status;
3067 unset($quoted_status['friendica_author']);
3068 unset($quoted_status['friendica_owner']);
3069 unset($quoted_status['friendica_activities']);
3070 unset($quoted_status['friendica_private']);
3071 unset($quoted_status['statusnet_conversation_id']);
3072 $quoted_status['text'] = $conv_quoted['text'];
3073 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3075 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3076 } catch (BadRequestException $e) {
3077 // user not found. should be found?
3078 /// @todo check if the user should be always found
3079 $quoted_status["user"] = [];
3083 if (!empty($retweeted_item)) {
3084 $retweeted_status = $status;
3085 unset($retweeted_status['friendica_author']);
3086 unset($retweeted_status['friendica_owner']);
3087 unset($retweeted_status['friendica_activities']);
3088 unset($retweeted_status['friendica_private']);
3089 unset($retweeted_status['statusnet_conversation_id']);
3090 $status['user'] = $status['friendica_owner'];
3092 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3093 } catch (BadRequestException $e) {
3094 // user not found. should be found?
3095 /// @todo check if the user should be always found
3096 $retweeted_status["user"] = [];
3099 $rt_converted = api_convert_item($retweeted_item);
3101 $retweeted_status['text'] = $rt_converted["text"];
3102 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3103 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3105 if (!empty($quoted_status)) {
3106 $retweeted_status['quoted_status'] = $quoted_status;
3109 $status['friendica_author'] = $retweeted_status['user'];
3110 $status['retweeted_status'] = $retweeted_status;
3111 } elseif (!empty($quoted_status)) {
3112 $root_status = api_convert_item($item);
3114 $status['text'] = $root_status["text"];
3115 $status['statusnet_html'] = $root_status["html"];
3116 $status['quoted_status'] = $quoted_status;
3119 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3120 unset($status["user"]["uid"]);
3121 unset($status["user"]["self"]);
3123 if ($item["coord"] != "") {
3124 $coords = explode(' ', $item["coord"]);
3125 if (count($coords) == 2) {
3126 if ($type == "json") {
3127 $status["geo"] = ['type' => 'Point',
3128 'coordinates' => [(float) $coords[0],
3129 (float) $coords[1]]];
3130 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3131 $status["georss:point"] = $item["coord"];
3140 * Returns the remaining number of API requests available to the user before the API limit is reached.
3142 * @param string $type Return type (atom, rss, xml, json)
3144 * @return array|string
3147 function api_account_rate_limit_status($type)
3149 if ($type == "xml") {
3151 'remaining-hits' => '150',
3152 '@attributes' => ["type" => "integer"],
3153 'hourly-limit' => '150',
3154 '@attributes2' => ["type" => "integer"],
3155 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3156 '@attributes3' => ["type" => "datetime"],
3157 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3158 '@attributes4' => ["type" => "integer"],
3162 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3163 'remaining_hits' => '150',
3164 'hourly_limit' => '150',
3165 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3169 return api_format_data('hash', $type, ['hash' => $hash]);
3172 /// @TODO move to top of file or somewhere better
3173 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3176 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3178 * @param string $type Return type (atom, rss, xml, json)
3180 * @return array|string
3182 function api_help_test($type)
3184 if ($type == 'xml') {
3190 return api_format_data('ok', $type, ["ok" => $ok]);
3193 /// @TODO move to top of file or somewhere better
3194 api_register_func('api/help/test', 'api_help_test', false);
3197 * Returns all lists the user subscribes to.
3199 * @param string $type Return type (atom, rss, xml, json)
3201 * @return array|string
3202 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3204 function api_lists_list($type)
3207 /// @TODO $ret is not filled here?
3208 return api_format_data('lists', $type, ["lists_list" => $ret]);
3211 /// @TODO move to top of file or somewhere better
3212 api_register_func('api/lists/list', 'api_lists_list', true);
3213 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3216 * Returns all groups the user owns.
3218 * @param string $type Return type (atom, rss, xml, json)
3220 * @return array|string
3221 * @throws BadRequestException
3222 * @throws ForbiddenException
3223 * @throws ImagickException
3224 * @throws InternalServerErrorException
3225 * @throws UnauthorizedException
3226 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3228 function api_lists_ownerships($type)
3232 if (api_user() === false) {
3233 throw new ForbiddenException();
3237 $user_info = api_get_user($a);
3238 $uid = $user_info['uid'];
3240 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3242 // loop through all groups
3244 foreach ($groups as $group) {
3245 if ($group['visible']) {
3251 'name' => $group['name'],
3252 'id' => intval($group['id']),
3253 'id_str' => (string) $group['id'],
3254 'user' => $user_info,
3258 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3261 /// @TODO move to top of file or somewhere better
3262 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3265 * Returns recent statuses from users in the specified group.
3267 * @param string $type Return type (atom, rss, xml, json)
3269 * @return array|string
3270 * @throws BadRequestException
3271 * @throws ForbiddenException
3272 * @throws ImagickException
3273 * @throws InternalServerErrorException
3274 * @throws UnauthorizedException
3275 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3277 function api_lists_statuses($type)
3281 $user_info = api_get_user($a);
3282 if (api_user() === false || $user_info === false) {
3283 throw new ForbiddenException();
3286 unset($_REQUEST["user_id"]);
3287 unset($_GET["user_id"]);
3289 unset($_REQUEST["screen_name"]);
3290 unset($_GET["screen_name"]);
3292 if (empty($_REQUEST['list_id'])) {
3293 throw new BadRequestException('list_id not specified');
3297 $count = $_REQUEST['count'] ?? 20;
3298 $page = $_REQUEST['page'] ?? 1;
3299 $since_id = $_REQUEST['since_id'] ?? 0;
3300 $max_id = $_REQUEST['max_id'] ?? 0;
3301 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3302 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3304 $start = max(0, ($page - 1) * $count);
3306 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3307 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3310 $condition[0] .= " AND `item`.`id` <= ?";
3311 $condition[] = $max_id;
3313 if ($exclude_replies > 0) {
3314 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3316 if ($conversation_id > 0) {
3317 $condition[0] .= " AND `item`.`parent` = ?";
3318 $condition[] = $conversation_id;
3321 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3322 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3324 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3326 $data = ['status' => $items];
3331 $data = api_rss_extra($a, $data, $user_info);
3335 return api_format_data("statuses", $type, $data);
3338 /// @TODO move to top of file or somewhere better
3339 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3342 * Considers friends and followers lists to be private and won't return
3343 * anything if any user_id parameter is passed.
3345 * @brief Returns either the friends of the follower list
3347 * @param string $qtype Either "friends" or "followers"
3348 * @return boolean|array
3349 * @throws BadRequestException
3350 * @throws ForbiddenException
3351 * @throws ImagickException
3352 * @throws InternalServerErrorException
3353 * @throws UnauthorizedException
3355 function api_statuses_f($qtype)
3359 if (api_user() === false) {
3360 throw new ForbiddenException();
3364 $count = $_GET['count'] ?? 20;
3365 $page = $_GET['page'] ?? 1;
3367 $start = max(0, ($page - 1) * $count);
3369 $user_info = api_get_user($a);
3371 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3372 /* this is to stop Hotot to load friends multiple times
3373 * I'm not sure if I'm missing return something or
3374 * is a bug in hotot. Workaround, meantime
3378 return array('$users' => $ret);*/
3383 if ($qtype == 'friends') {
3384 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3385 } elseif ($qtype == 'followers') {
3386 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3389 // friends and followers only for self
3390 if ($user_info['self'] == 0) {
3391 $sql_extra = " AND false ";
3394 if ($qtype == 'blocks') {
3395 $sql_filter = 'AND `blocked` AND NOT `pending`';
3396 } elseif ($qtype == 'incoming') {
3397 $sql_filter = 'AND `pending`';
3399 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3417 foreach ($r as $cid) {
3418 $user = api_get_user($a, $cid['nurl']);
3419 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3420 unset($user["uid"]);
3421 unset($user["self"]);
3428 return ['user' => $ret];
3433 * Returns the user's friends.
3435 * @brief Returns the list of friends of the provided user
3437 * @deprecated By Twitter API in favor of friends/list
3439 * @param string $type Either "json" or "xml"
3440 * @return boolean|string|array
3441 * @throws BadRequestException
3442 * @throws ForbiddenException
3444 function api_statuses_friends($type)
3446 $data = api_statuses_f("friends");
3447 if ($data === false) {
3450 return api_format_data("users", $type, $data);
3454 * Returns the user's followers.
3456 * @brief Returns the list of followers of the provided user
3458 * @deprecated By Twitter API in favor of friends/list
3460 * @param string $type Either "json" or "xml"
3461 * @return boolean|string|array
3462 * @throws BadRequestException
3463 * @throws ForbiddenException
3465 function api_statuses_followers($type)
3467 $data = api_statuses_f("followers");
3468 if ($data === false) {
3471 return api_format_data("users", $type, $data);
3474 /// @TODO move to top of file or somewhere better
3475 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3476 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3479 * Returns the list of blocked users
3481 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3483 * @param string $type Either "json" or "xml"
3485 * @return boolean|string|array
3486 * @throws BadRequestException
3487 * @throws ForbiddenException
3489 function api_blocks_list($type)
3491 $data = api_statuses_f('blocks');
3492 if ($data === false) {
3495 return api_format_data("users", $type, $data);
3498 /// @TODO move to top of file or somewhere better
3499 api_register_func('api/blocks/list', 'api_blocks_list', true);
3502 * Returns the list of pending users IDs
3504 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3506 * @param string $type Either "json" or "xml"
3508 * @return boolean|string|array
3509 * @throws BadRequestException
3510 * @throws ForbiddenException
3512 function api_friendships_incoming($type)
3514 $data = api_statuses_f('incoming');
3515 if ($data === false) {
3520 foreach ($data['user'] as $user) {
3521 $ids[] = $user['id'];
3524 return api_format_data("ids", $type, ['id' => $ids]);
3527 /// @TODO move to top of file or somewhere better
3528 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3531 * Returns the instance's configuration information.
3533 * @param string $type Return type (atom, rss, xml, json)
3535 * @return array|string
3536 * @throws InternalServerErrorException
3538 function api_statusnet_config($type)
3542 $name = Config::get('config', 'sitename');
3543 $server = $a->getHostName();
3544 $logo = System::baseUrl() . '/images/friendica-64.png';
3545 $email = Config::get('config', 'admin_email');
3546 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3547 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3548 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3549 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3550 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3553 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3554 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3555 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3556 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3557 'shorturllength' => '30',
3559 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3560 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3561 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3562 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3567 return api_format_data('config', $type, ['config' => $config]);
3570 /// @TODO move to top of file or somewhere better
3571 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3572 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3576 * @param string $type Return type (atom, rss, xml, json)
3578 * @return array|string
3580 function api_statusnet_version($type)
3583 $fake_statusnet_version = "0.9.7";
3585 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3588 /// @TODO move to top of file or somewhere better
3589 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3590 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3594 * @param string $type Return type (atom, rss, xml, json)
3596 * @return array|string|void
3597 * @throws BadRequestException
3598 * @throws ForbiddenException
3599 * @throws ImagickException
3600 * @throws InternalServerErrorException
3601 * @throws UnauthorizedException
3602 * @todo use api_format_data() to return data
3604 function api_ff_ids($type)
3607 throw new ForbiddenException();
3614 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3617 "SELECT `pcontact`.`id` FROM `contact`
3618 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3619 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3622 if (!DBA::isResult($r)) {
3627 foreach ($r as $rr) {
3628 if ($stringify_ids) {
3631 $ids[] = intval($rr['id']);
3635 return api_format_data("ids", $type, ['id' => $ids]);
3639 * Returns the ID of every user the user is following.
3641 * @param string $type Return type (atom, rss, xml, json)
3643 * @return array|string
3644 * @throws BadRequestException
3645 * @throws ForbiddenException
3646 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3648 function api_friends_ids($type)
3650 return api_ff_ids($type);
3654 * Returns the ID of every user following the user.
3656 * @param string $type Return type (atom, rss, xml, json)
3658 * @return array|string
3659 * @throws BadRequestException
3660 * @throws ForbiddenException
3661 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3663 function api_followers_ids($type)
3665 return api_ff_ids($type);
3668 /// @TODO move to top of file or somewhere better
3669 api_register_func('api/friends/ids', 'api_friends_ids', true);
3670 api_register_func('api/followers/ids', 'api_followers_ids', true);
3673 * Sends a new direct message.
3675 * @param string $type Return type (atom, rss, xml, json)
3677 * @return array|string
3678 * @throws BadRequestException
3679 * @throws ForbiddenException
3680 * @throws ImagickException
3681 * @throws InternalServerErrorException
3682 * @throws NotFoundException
3683 * @throws UnauthorizedException
3684 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3686 function api_direct_messages_new($type)
3690 if (api_user() === false) {
3691 throw new ForbiddenException();
3694 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3698 $sender = api_get_user($a);
3701 if (!empty($_POST['screen_name'])) {
3703 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3705 DBA::escape($_POST['screen_name'])
3708 if (DBA::isResult($r)) {
3709 // Selecting the id by priority, friendica first
3710 api_best_nickname($r);
3712 $recipient = api_get_user($a, $r[0]['nurl']);
3715 $recipient = api_get_user($a, $_POST['user_id']);
3718 if (empty($recipient)) {
3719 throw new NotFoundException('Recipient not found');
3723 if (!empty($_REQUEST['replyto'])) {
3725 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3727 intval($_REQUEST['replyto'])
3729 $replyto = $r[0]['parent-uri'];
3730 $sub = $r[0]['title'];
3732 if (!empty($_REQUEST['title'])) {
3733 $sub = $_REQUEST['title'];
3735 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3739 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3742 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3743 $ret = api_format_messages($r[0], $recipient, $sender);
3745 $ret = ["error"=>$id];
3748 $data = ['direct_message'=>$ret];
3754 $data = api_rss_extra($a, $data, $sender);
3758 return api_format_data("direct-messages", $type, $data);
3761 /// @TODO move to top of file or somewhere better
3762 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3765 * Destroys a direct message.
3767 * @brief delete a direct_message from mail table through api
3769 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3770 * @return string|array
3771 * @throws BadRequestException
3772 * @throws ForbiddenException
3773 * @throws ImagickException
3774 * @throws InternalServerErrorException
3775 * @throws UnauthorizedException
3776 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3778 function api_direct_messages_destroy($type)
3782 if (api_user() === false) {
3783 throw new ForbiddenException();
3787 $user_info = api_get_user($a);
3789 $id = $_REQUEST['id'] ?? 0;
3791 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3792 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3793 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3795 $uid = $user_info['uid'];
3796 // error if no id or parenturi specified (for clients posting parent-uri as well)
3797 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3798 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3799 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3802 // BadRequestException if no id specified (for clients using Twitter API)
3804 throw new BadRequestException('Message id not specified');
3807 // add parent-uri to sql command if specified by calling app
3808 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3810 // get data of the specified message id
3812 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3817 // error message if specified id is not in database
3818 if (!DBA::isResult($r)) {
3819 if ($verbose == "true") {
3820 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3821 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3823 /// @todo BadRequestException ok for Twitter API clients?
3824 throw new BadRequestException('message id not in database');
3829 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3834 if ($verbose == "true") {
3837 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3838 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3840 $answer = ['result' => 'error', 'message' => 'unknown error'];
3841 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3844 /// @todo return JSON data like Twitter API not yet implemented
3847 /// @TODO move to top of file or somewhere better
3848 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3853 * @brief unfollow contact
3855 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3856 * @return string|array
3857 * @throws BadRequestException
3858 * @throws ForbiddenException
3859 * @throws ImagickException
3860 * @throws InternalServerErrorException
3861 * @throws NotFoundException
3862 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3864 function api_friendships_destroy($type)
3868 if ($uid === false) {
3869 throw new ForbiddenException();
3872 $contact_id = $_REQUEST['user_id'] ?? 0;
3874 if (empty($contact_id)) {
3875 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3876 throw new BadRequestException("no user_id specified");
3879 // Get Contact by given id
3880 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3882 if(!DBA::isResult($contact)) {
3883 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3884 throw new NotFoundException("no contact found to given ID");
3887 $url = $contact["url"];
3889 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3890 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3891 Strings::normaliseLink($url), $url];
3892 $contact = DBA::selectFirst('contact', [], $condition);
3894 if (!DBA::isResult($contact)) {
3895 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3896 throw new NotFoundException("Not following Contact");
3899 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3900 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3901 throw new ExpectationFailedException("Not supported");
3904 $dissolve = ($contact['rel'] == Contact::SHARING);
3906 $owner = User::getOwnerDataById($uid);
3908 Contact::terminateFriendship($owner, $contact, $dissolve);
3911 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3912 throw new NotFoundException("Error Processing Request");
3915 // Sharing-only contacts get deleted as there no relationship any more
3917 Contact::remove($contact['id']);
3919 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3922 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3923 unset($contact["uid"]);
3924 unset($contact["self"]);
3926 // Set screen_name since Twidere requests it
3927 $contact["screen_name"] = $contact["nick"];
3929 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3931 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3935 * @param string $type Return type (atom, rss, xml, json)
3936 * @param string $box
3937 * @param string $verbose
3939 * @return array|string
3940 * @throws BadRequestException
3941 * @throws ForbiddenException
3942 * @throws ImagickException
3943 * @throws InternalServerErrorException
3944 * @throws UnauthorizedException
3946 function api_direct_messages_box($type, $box, $verbose)
3949 if (api_user() === false) {
3950 throw new ForbiddenException();
3953 $count = $_GET['count'] ?? 20;
3954 $page = $_REQUEST['page'] ?? 1;
3956 $since_id = $_REQUEST['since_id'] ?? 0;
3957 $max_id = $_REQUEST['max_id'] ?? 0;
3959 $user_id = $_REQUEST['user_id'] ?? '';
3960 $screen_name = $_REQUEST['screen_name'] ?? '';
3963 unset($_REQUEST["user_id"]);
3964 unset($_GET["user_id"]);
3966 unset($_REQUEST["screen_name"]);
3967 unset($_GET["screen_name"]);
3969 $user_info = api_get_user($a);
3970 if ($user_info === false) {
3971 throw new ForbiddenException();
3973 $profile_url = $user_info["url"];
3976 $start = max(0, ($page - 1) * $count);
3981 if ($box=="sentbox") {
3982 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3983 } elseif ($box == "conversation") {
3984 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3985 } elseif ($box == "all") {
3986 $sql_extra = "true";
3987 } elseif ($box == "inbox") {
3988 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3992 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3995 if ($user_id != "") {
3996 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3997 } elseif ($screen_name !="") {
3998 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4002 "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",
4008 if ($verbose == "true" && !DBA::isResult($r)) {
4009 $answer = ['result' => 'error', 'message' => 'no mails available'];
4010 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4014 foreach ($r as $item) {
4015 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4016 $recipient = $user_info;
4017 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4018 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4019 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4020 $sender = $user_info;
4023 if (isset($recipient) && isset($sender)) {
4024 $ret[] = api_format_messages($item, $recipient, $sender);
4029 $data = ['direct_message' => $ret];
4034 $data = api_rss_extra($a, $data, $user_info);
4038 return api_format_data("direct-messages", $type, $data);
4042 * Returns the most recent direct messages sent by the user.
4044 * @param string $type Return type (atom, rss, xml, json)
4046 * @return array|string
4047 * @throws BadRequestException
4048 * @throws ForbiddenException
4049 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4051 function api_direct_messages_sentbox($type)
4053 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4054 return api_direct_messages_box($type, "sentbox", $verbose);
4058 * Returns the most recent direct messages sent to the user.
4060 * @param string $type Return type (atom, rss, xml, json)
4062 * @return array|string
4063 * @throws BadRequestException
4064 * @throws ForbiddenException
4065 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4067 function api_direct_messages_inbox($type)
4069 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4070 return api_direct_messages_box($type, "inbox", $verbose);
4075 * @param string $type Return type (atom, rss, xml, json)
4077 * @return array|string
4078 * @throws BadRequestException
4079 * @throws ForbiddenException
4081 function api_direct_messages_all($type)
4083 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4084 return api_direct_messages_box($type, "all", $verbose);
4089 * @param string $type Return type (atom, rss, xml, json)
4091 * @return array|string
4092 * @throws BadRequestException
4093 * @throws ForbiddenException
4095 function api_direct_messages_conversation($type)
4097 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4098 return api_direct_messages_box($type, "conversation", $verbose);
4101 /// @TODO move to top of file or somewhere better
4102 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4103 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4104 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4105 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4108 * Returns an OAuth Request Token.
4110 * @see https://oauth.net/core/1.0/#auth_step1
4112 function api_oauth_request_token()
4114 $oauth1 = new FKOAuth1();
4116 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4117 } catch (Exception $e) {
4118 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4126 * Returns an OAuth Access Token.
4128 * @return array|string
4129 * @see https://oauth.net/core/1.0/#auth_step3
4131 function api_oauth_access_token()
4133 $oauth1 = new FKOAuth1();
4135 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4136 } catch (Exception $e) {
4137 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4144 /// @TODO move to top of file or somewhere better
4145 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4146 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4150 * @brief delete a complete photoalbum with all containing photos from database through api
4152 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4153 * @return string|array
4154 * @throws BadRequestException
4155 * @throws ForbiddenException
4156 * @throws InternalServerErrorException
4158 function api_fr_photoalbum_delete($type)
4160 if (api_user() === false) {
4161 throw new ForbiddenException();
4164 $album = $_REQUEST['album'] ?? '';
4166 // we do not allow calls without album string
4168 throw new BadRequestException("no albumname specified");
4170 // check if album is existing
4172 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4176 if (!DBA::isResult($r)) {
4177 throw new BadRequestException("album not available");
4180 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4181 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4182 foreach ($r as $rr) {
4183 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4184 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4186 if (!DBA::isResult($photo_item)) {
4187 throw new InternalServerErrorException("problem with deleting items occured");
4189 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4192 // now let's delete all photos from the album
4193 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4195 // return success of deletion or error message
4197 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4198 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4200 throw new InternalServerErrorException("unknown error - deleting from database failed");
4205 * @brief update the name of the album for all photos of an album
4207 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4208 * @return string|array
4209 * @throws BadRequestException
4210 * @throws ForbiddenException
4211 * @throws InternalServerErrorException
4213 function api_fr_photoalbum_update($type)
4215 if (api_user() === false) {
4216 throw new ForbiddenException();
4219 $album = $_REQUEST['album'] ?? '';
4220 $album_new = $_REQUEST['album_new'] ?? '';
4222 // we do not allow calls without album string
4224 throw new BadRequestException("no albumname specified");
4226 if ($album_new == "") {
4227 throw new BadRequestException("no new albumname specified");
4229 // check if album is existing
4230 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4231 throw new BadRequestException("album not available");
4233 // now let's update all photos to the albumname
4234 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4236 // return success of updating or error message
4238 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4239 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4241 throw new InternalServerErrorException("unknown error - updating in database failed");
4247 * @brief list all photos of the authenticated user
4249 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4250 * @return string|array
4251 * @throws ForbiddenException
4252 * @throws InternalServerErrorException
4254 function api_fr_photos_list($type)
4256 if (api_user() === false) {
4257 throw new ForbiddenException();
4260 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4261 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4262 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4263 intval(local_user())
4266 'image/jpeg' => 'jpg',
4267 'image/png' => 'png',
4268 'image/gif' => 'gif'
4270 $data = ['photo'=>[]];
4271 if (DBA::isResult($r)) {
4272 foreach ($r as $rr) {
4274 $photo['id'] = $rr['resource-id'];
4275 $photo['album'] = $rr['album'];
4276 $photo['filename'] = $rr['filename'];
4277 $photo['type'] = $rr['type'];
4278 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4279 $photo['created'] = $rr['created'];
4280 $photo['edited'] = $rr['edited'];
4281 $photo['desc'] = $rr['desc'];
4283 if ($type == "xml") {
4284 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4286 $photo['thumb'] = $thumb;
4287 $data['photo'][] = $photo;
4291 return api_format_data("photos", $type, $data);
4295 * @brief upload a new photo or change an existing photo
4297 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4298 * @return string|array
4299 * @throws BadRequestException
4300 * @throws ForbiddenException
4301 * @throws ImagickException
4302 * @throws InternalServerErrorException
4303 * @throws NotFoundException
4305 function api_fr_photo_create_update($type)
4307 if (api_user() === false) {
4308 throw new ForbiddenException();
4311 $photo_id = $_REQUEST['photo_id'] ?? null;
4312 $desc = $_REQUEST['desc'] ?? null;
4313 $album = $_REQUEST['album'] ?? null;
4314 $album_new = $_REQUEST['album_new'] ?? null;
4315 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4316 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4317 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4318 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4319 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4321 // do several checks on input parameters
4322 // we do not allow calls without album string
4323 if ($album == null) {
4324 throw new BadRequestException("no albumname specified");
4326 // if photo_id == null --> we are uploading a new photo
4327 if ($photo_id == null) {
4330 // error if no media posted in create-mode
4331 if (empty($_FILES['media'])) {
4333 throw new BadRequestException("no media data submitted");
4336 // album_new will be ignored in create-mode
4341 // check if photo is existing in databasei
4342 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4343 throw new BadRequestException("photo not available");
4347 // checks on acl strings provided by clients
4348 $acl_input_error = false;
4349 $acl_input_error |= check_acl_input($allow_cid);
4350 $acl_input_error |= check_acl_input($deny_cid);
4351 $acl_input_error |= check_acl_input($allow_gid);
4352 $acl_input_error |= check_acl_input($deny_gid);
4353 if ($acl_input_error) {
4354 throw new BadRequestException("acl data invalid");
4356 // now let's upload the new media in create-mode
4357 if ($mode == "create") {
4358 $media = $_FILES['media'];
4359 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4361 // return success of updating or error message
4362 if (!is_null($data)) {
4363 return api_format_data("photo_create", $type, $data);
4365 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4369 // now let's do the changes in update-mode
4370 if ($mode == "update") {
4371 $updated_fields = [];
4373 if (!is_null($desc)) {
4374 $updated_fields['desc'] = $desc;
4377 if (!is_null($album_new)) {
4378 $updated_fields['album'] = $album_new;
4381 if (!is_null($allow_cid)) {
4382 $allow_cid = trim($allow_cid);
4383 $updated_fields['allow_cid'] = $allow_cid;
4386 if (!is_null($deny_cid)) {
4387 $deny_cid = trim($deny_cid);
4388 $updated_fields['deny_cid'] = $deny_cid;
4391 if (!is_null($allow_gid)) {
4392 $allow_gid = trim($allow_gid);
4393 $updated_fields['allow_gid'] = $allow_gid;
4396 if (!is_null($deny_gid)) {
4397 $deny_gid = trim($deny_gid);
4398 $updated_fields['deny_gid'] = $deny_gid;
4402 if (count($updated_fields) > 0) {
4403 $nothingtodo = false;
4404 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4406 $nothingtodo = true;
4409 if (!empty($_FILES['media'])) {
4410 $nothingtodo = false;
4411 $media = $_FILES['media'];
4412 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4413 if (!is_null($data)) {
4414 return api_format_data("photo_update", $type, $data);
4418 // return success of updating or error message
4420 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4421 return api_format_data("photo_update", $type, ['$result' => $answer]);
4424 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4425 return api_format_data("photo_update", $type, ['$result' => $answer]);
4427 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4430 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4434 * @brief delete a single photo from the database through api
4436 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4437 * @return string|array
4438 * @throws BadRequestException
4439 * @throws ForbiddenException
4440 * @throws InternalServerErrorException
4442 function api_fr_photo_delete($type)
4444 if (api_user() === false) {
4445 throw new ForbiddenException();
4449 $photo_id = $_REQUEST['photo_id'] ?? null;
4451 // do several checks on input parameters
4452 // we do not allow calls without photo id
4453 if ($photo_id == null) {
4454 throw new BadRequestException("no photo_id specified");
4457 // check if photo is existing in database
4458 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4459 throw new BadRequestException("photo not available");
4462 // now we can perform on the deletion of the photo
4463 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4465 // return success of deletion or error message
4467 // retrieve the id of the parent element (the photo element)
4468 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4469 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4471 if (!DBA::isResult($photo_item)) {
4472 throw new InternalServerErrorException("problem with deleting items occured");
4474 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4475 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4476 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4478 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4479 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4481 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4487 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4489 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4490 * @return string|array
4491 * @throws BadRequestException
4492 * @throws ForbiddenException
4493 * @throws InternalServerErrorException
4494 * @throws NotFoundException
4496 function api_fr_photo_detail($type)
4498 if (api_user() === false) {
4499 throw new ForbiddenException();
4501 if (empty($_REQUEST['photo_id'])) {
4502 throw new BadRequestException("No photo id.");
4505 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4506 $photo_id = $_REQUEST['photo_id'];
4508 // prepare json/xml output with data from database for the requested photo
4509 $data = prepare_photo_data($type, $scale, $photo_id);
4511 return api_format_data("photo_detail", $type, $data);
4516 * Updates the user’s profile image.
4518 * @brief updates the profile image for the user (either a specified profile or the default profile)
4520 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4522 * @return string|array
4523 * @throws BadRequestException
4524 * @throws ForbiddenException
4525 * @throws ImagickException
4526 * @throws InternalServerErrorException
4527 * @throws NotFoundException
4528 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4530 function api_account_update_profile_image($type)
4532 if (api_user() === false) {
4533 throw new ForbiddenException();
4536 $profile_id = $_REQUEST['profile_id'] ?? 0;
4538 // error if image data is missing
4539 if (empty($_FILES['image'])) {
4540 throw new BadRequestException("no media data submitted");
4543 // check if specified profile id is valid
4544 if ($profile_id != 0) {
4545 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4546 // error message if specified profile id is not in database
4547 if (!DBA::isResult($profile)) {
4548 throw new BadRequestException("profile_id not available");
4550 $is_default_profile = $profile['is-default'];
4552 $is_default_profile = 1;
4555 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4557 if (!empty($_FILES['image'])) {
4558 $media = $_FILES['image'];
4559 } elseif (!empty($_FILES['media'])) {
4560 $media = $_FILES['media'];
4562 // save new profile image
4563 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4566 if (is_array($media['type'])) {
4567 $filetype = $media['type'][0];
4569 $filetype = $media['type'];
4571 if ($filetype == "image/jpeg") {
4573 } elseif ($filetype == "image/png") {
4576 throw new InternalServerErrorException('Unsupported filetype');
4579 // change specified profile or all profiles to the new resource-id
4580 if ($is_default_profile) {
4581 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4582 Photo::update(['profile' => false], $condition);
4584 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4585 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4586 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4589 Contact::updateSelfFromUserID(api_user(), true);
4591 // Update global directory in background
4592 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4593 if ($url && strlen(Config::get('system', 'directory'))) {
4594 Worker::add(PRIORITY_LOW, "Directory", $url);
4597 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4599 // output for client
4601 return api_account_verify_credentials($type);
4603 // SaveMediaToDatabase failed for some reason
4604 throw new InternalServerErrorException("image upload failed");
4608 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4609 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4610 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4611 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4612 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4613 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4614 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4615 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4616 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4619 * Update user profile
4621 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4623 * @return array|string
4624 * @throws BadRequestException
4625 * @throws ForbiddenException
4626 * @throws ImagickException
4627 * @throws InternalServerErrorException
4628 * @throws UnauthorizedException
4630 function api_account_update_profile($type)
4632 $local_user = api_user();
4633 $api_user = api_get_user(get_app());
4635 if (!empty($_POST['name'])) {
4636 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4637 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4638 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4639 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4642 if (isset($_POST['description'])) {
4643 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4644 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4645 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4648 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4649 // Update global directory in background
4650 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4651 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4654 return api_account_verify_credentials($type);
4657 /// @TODO move to top of file or somewhere better
4658 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4662 * @param string $acl_string
4666 function check_acl_input($acl_string)
4668 if (empty($acl_string)) {
4672 $contact_not_found = false;
4674 // split <x><y><z> into array of cid's
4675 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4677 // check for each cid if it is available on server
4678 $cid_array = $array[0];
4679 foreach ($cid_array as $cid) {
4680 $cid = str_replace("<", "", $cid);
4681 $cid = str_replace(">", "", $cid);
4682 $condition = ['id' => $cid, 'uid' => api_user()];
4683 $contact_not_found |= !DBA::exists('contact', $condition);
4685 return $contact_not_found;
4689 * @param string $mediatype
4690 * @param array $media
4691 * @param string $type
4692 * @param string $album
4693 * @param string $allow_cid
4694 * @param string $deny_cid
4695 * @param string $allow_gid
4696 * @param string $deny_gid
4697 * @param string $desc
4698 * @param integer $profile
4699 * @param boolean $visibility
4700 * @param string $photo_id
4702 * @throws BadRequestException
4703 * @throws ForbiddenException
4704 * @throws ImagickException
4705 * @throws InternalServerErrorException
4706 * @throws NotFoundException
4707 * @throws UnauthorizedException
4709 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)
4717 if (is_array($media)) {
4718 if (is_array($media['tmp_name'])) {
4719 $src = $media['tmp_name'][0];
4721 $src = $media['tmp_name'];
4723 if (is_array($media['name'])) {
4724 $filename = basename($media['name'][0]);
4726 $filename = basename($media['name']);
4728 if (is_array($media['size'])) {
4729 $filesize = intval($media['size'][0]);
4731 $filesize = intval($media['size']);
4733 if (is_array($media['type'])) {
4734 $filetype = $media['type'][0];
4736 $filetype = $media['type'];
4740 if ($filetype == "") {
4741 $filetype=Image::guessType($filename);
4743 $imagedata = @getimagesize($src);
4745 $filetype = $imagedata['mime'];
4748 "File upload src: " . $src . " - filename: " . $filename .
4749 " - size: " . $filesize . " - type: " . $filetype,
4753 // check if there was a php upload error
4754 if ($filesize == 0 && $media['error'] == 1) {
4755 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4757 // check against max upload size within Friendica instance
4758 $maximagesize = Config::get('system', 'maximagesize');
4759 if ($maximagesize && ($filesize > $maximagesize)) {
4760 $formattedBytes = Strings::formatBytes($maximagesize);
4761 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4764 // create Photo instance with the data of the image
4765 $imagedata = @file_get_contents($src);
4766 $Image = new Image($imagedata, $filetype);
4767 if (!$Image->isValid()) {
4768 throw new InternalServerErrorException("unable to process image data");
4771 // check orientation of image
4772 $Image->orient($src);
4775 // check max length of images on server
4776 $max_length = Config::get('system', 'max_image_length');
4778 $max_length = MAX_IMAGE_LENGTH;
4780 if ($max_length > 0) {
4781 $Image->scaleDown($max_length);
4782 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4784 $width = $Image->getWidth();
4785 $height = $Image->getHeight();
4787 // create a new resource-id if not already provided
4788 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4790 if ($mediatype == "photo") {
4791 // upload normal image (scales 0, 1, 2)
4792 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4794 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4796 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4798 if ($width > 640 || $height > 640) {
4799 $Image->scaleDown(640);
4800 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4802 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4806 if ($width > 320 || $height > 320) {
4807 $Image->scaleDown(320);
4808 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4810 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4813 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4814 } elseif ($mediatype == "profileimage") {
4815 // upload profile image (scales 4, 5, 6)
4816 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4818 if ($width > 300 || $height > 300) {
4819 $Image->scaleDown(300);
4820 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4822 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4826 if ($width > 80 || $height > 80) {
4827 $Image->scaleDown(80);
4828 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4830 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4834 if ($width > 48 || $height > 48) {
4835 $Image->scaleDown(48);
4836 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4838 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4841 $Image->__destruct();
4842 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4845 if (isset($r) && $r) {
4846 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4847 if ($photo_id == null && $mediatype == "photo") {
4848 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4850 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4851 return prepare_photo_data($type, false, $hash);
4853 throw new InternalServerErrorException("image upload failed");
4859 * @param string $hash
4860 * @param string $allow_cid
4861 * @param string $deny_cid
4862 * @param string $allow_gid
4863 * @param string $deny_gid
4864 * @param string $filetype
4865 * @param boolean $visibility
4866 * @throws InternalServerErrorException
4868 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4870 // get data about the api authenticated user
4871 $uri = Item::newURI(intval(api_user()));
4872 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4875 $arr['guid'] = System::createUUID();
4876 $arr['uid'] = intval(api_user());
4878 $arr['parent-uri'] = $uri;
4879 $arr['type'] = 'photo';
4881 $arr['resource-id'] = $hash;
4882 $arr['contact-id'] = $owner_record['id'];
4883 $arr['owner-name'] = $owner_record['name'];
4884 $arr['owner-link'] = $owner_record['url'];
4885 $arr['owner-avatar'] = $owner_record['thumb'];
4886 $arr['author-name'] = $owner_record['name'];
4887 $arr['author-link'] = $owner_record['url'];
4888 $arr['author-avatar'] = $owner_record['thumb'];
4890 $arr['allow_cid'] = $allow_cid;
4891 $arr['allow_gid'] = $allow_gid;
4892 $arr['deny_cid'] = $deny_cid;
4893 $arr['deny_gid'] = $deny_gid;
4894 $arr['visible'] = $visibility;
4898 'image/jpeg' => 'jpg',
4899 'image/png' => 'png',
4900 'image/gif' => 'gif'
4903 // adds link to the thumbnail scale photo
4904 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4905 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4908 // do the magic for storing the item in the database and trigger the federation to other contacts
4914 * @param string $type
4916 * @param string $photo_id
4919 * @throws BadRequestException
4920 * @throws ForbiddenException
4921 * @throws ImagickException
4922 * @throws InternalServerErrorException
4923 * @throws NotFoundException
4924 * @throws UnauthorizedException
4926 function prepare_photo_data($type, $scale, $photo_id)
4929 $user_info = api_get_user($a);
4931 if ($user_info === false) {
4932 throw new ForbiddenException();
4935 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4936 $data_sql = ($scale === false ? "" : "data, ");
4938 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4939 // clients needs to convert this in their way for further processing
4941 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4942 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4943 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4944 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4945 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4946 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4948 intval(local_user()),
4949 DBA::escape($photo_id),
4954 'image/jpeg' => 'jpg',
4955 'image/png' => 'png',
4956 'image/gif' => 'gif'
4959 // prepare output data for photo
4960 if (DBA::isResult($r)) {
4961 $data = ['photo' => $r[0]];
4962 $data['photo']['id'] = $data['photo']['resource-id'];
4963 if ($scale !== false) {
4964 $data['photo']['data'] = base64_encode($data['photo']['data']);
4966 unset($data['photo']['datasize']); //needed only with scale param
4968 if ($type == "xml") {
4969 $data['photo']['links'] = [];
4970 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4971 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4973 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4976 $data['photo']['link'] = [];
4977 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4979 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4980 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4984 unset($data['photo']['resource-id']);
4985 unset($data['photo']['minscale']);
4986 unset($data['photo']['maxscale']);
4988 throw new NotFoundException();
4991 // retrieve item element for getting activities (like, dislike etc.) related to photo
4992 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4993 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4995 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4997 // retrieve comments on photo
4998 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4999 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5001 $statuses = Item::selectForUser(api_user(), [], $condition);
5003 // prepare output of comments
5004 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5006 if ($type == "xml") {
5008 foreach ($commentData as $comment) {
5009 $comments[$k++ . ":comment"] = $comment;
5012 foreach ($commentData as $comment) {
5013 $comments[] = $comment;
5016 $data['photo']['friendica_comments'] = $comments;
5018 // include info if rights on photo and rights on item are mismatching
5019 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5020 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5021 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5022 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5023 $data['photo']['rights_mismatch'] = $rights_mismatch;
5030 * Similar as /mod/redir.php
5031 * redirect to 'url' after dfrn auth
5033 * Why this when there is mod/redir.php already?
5034 * This use api_user() and api_login()
5037 * c_url: url of remote contact to auth to
5038 * url: string, url to redirect after auth
5040 function api_friendica_remoteauth()
5042 $url = $_GET['url'] ?? '';
5043 $c_url = $_GET['c_url'] ?? '';
5045 if ($url === '' || $c_url === '') {
5046 throw new BadRequestException("Wrong parameters.");
5049 $c_url = Strings::normaliseLink($c_url);
5053 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5055 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5056 throw new BadRequestException("Unknown contact");
5059 $cid = $contact['id'];
5061 $dfrn_id = $contact['issued-id'] ?? $contact['dfrn-id'];
5063 if ($contact['duplex'] && $contact['issued-id']) {
5064 $orig_id = $contact['issued-id'];
5065 $dfrn_id = '1:' . $orig_id;
5067 if ($contact['duplex'] && $contact['dfrn-id']) {
5068 $orig_id = $contact['dfrn-id'];
5069 $dfrn_id = '0:' . $orig_id;
5072 $sec = Strings::getRandomHex();
5074 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5075 'sec' => $sec, 'expire' => time() + 45];
5076 DBA::insert('profile_check', $fields);
5078 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5079 $dest = ($url ? '&destination_url=' . $url : '');
5081 System::externalRedirect(
5082 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5083 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5084 . '&type=profile&sec=' . $sec . $dest
5087 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5090 * Return an item with announcer data if it had been announced
5092 * @param array $item Item array
5093 * @return array Item array with announce data
5095 function api_get_announce($item)
5097 // Quit if the item already has got a different owner and author
5098 if ($item['owner-id'] != $item['author-id']) {
5102 // Don't change original or Diaspora posts
5103 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5107 // Quit if we do now the original author and it had been a post from a native network
5108 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5112 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5113 $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE);
5114 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5115 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5116 if (!DBA::isResult($announce)) {
5120 return array_merge($item, $announce);
5124 * @brief Return the item shared, if the item contains only the [share] tag
5126 * @param array $item Sharer item
5127 * @return array|false Shared item or false if not a reshare
5128 * @throws ImagickException
5129 * @throws InternalServerErrorException
5131 function api_share_as_retweet(&$item)
5133 $body = trim($item["body"]);
5135 if (Diaspora::isReshare($body, false) === false) {
5136 if ($item['author-id'] == $item['owner-id']) {
5139 // Reshares from OStatus, ActivityPub and Twitter
5140 $reshared_item = $item;
5141 $reshared_item['owner-id'] = $reshared_item['author-id'];
5142 $reshared_item['owner-link'] = $reshared_item['author-link'];
5143 $reshared_item['owner-name'] = $reshared_item['author-name'];
5144 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5145 return $reshared_item;
5149 /// @TODO "$1" should maybe mean '$1' ?
5150 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5152 * Skip if there is no shared message in there
5153 * we already checked this in diaspora::isReshare()
5154 * but better one more than one less...
5156 if (($body == $attributes) || empty($attributes)) {
5160 // build the fake reshared item
5161 $reshared_item = $item;
5164 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5165 if (!empty($matches[1])) {
5166 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5169 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5170 if (!empty($matches[1])) {
5171 $author = $matches[1];
5175 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5176 if (!empty($matches[1])) {
5177 $profile = $matches[1];
5180 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5181 if (!empty($matches[1])) {
5182 $profile = $matches[1];
5186 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5187 if (!empty($matches[1])) {
5188 $avatar = $matches[1];
5191 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5192 if (!empty($matches[1])) {
5193 $avatar = $matches[1];
5197 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5198 if (!empty($matches[1])) {
5199 $link = $matches[1];
5202 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5203 if (!empty($matches[1])) {
5204 $link = $matches[1];
5208 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5209 if (!empty($matches[1])) {
5210 $posted = $matches[1];
5213 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5214 if (!empty($matches[1])) {
5215 $posted = $matches[1];
5218 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5222 $pre_body = trim($matches[1]);
5223 if ($pre_body != '') {
5224 $item['body'] = $pre_body;
5227 $shared_body = trim($matches[2]);
5229 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5233 $reshared_item["share-pre-body"] = $pre_body;
5234 $reshared_item["body"] = $shared_body;
5235 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5236 $reshared_item["author-name"] = $author;
5237 $reshared_item["author-link"] = $profile;
5238 $reshared_item["author-avatar"] = $avatar;
5239 $reshared_item["plink"] = $link;
5240 $reshared_item["created"] = $posted;
5241 $reshared_item["edited"] = $posted;
5243 return $reshared_item;
5248 * @param string $profile
5250 * @return string|false
5251 * @throws InternalServerErrorException
5252 * @todo remove trailing junk from profile url
5253 * @todo pump.io check has to check the website
5255 function api_get_nick($profile)
5260 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5261 DBA::escape(Strings::normaliseLink($profile))
5264 if (DBA::isResult($r)) {
5265 $nick = $r[0]["nick"];
5270 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5271 DBA::escape(Strings::normaliseLink($profile))
5274 if (DBA::isResult($r)) {
5275 $nick = $r[0]["nick"];
5280 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5281 if ($friendica != $profile) {
5287 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5288 if ($diaspora != $profile) {
5294 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5295 if ($twitter != $profile) {
5302 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5303 if ($StatusnetHost != $profile) {
5304 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5305 if ($StatusnetUser != $profile) {
5306 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5307 $user = json_decode($UserData);
5309 $nick = $user->screen_name;
5315 // To-Do: look at the page if its really a pumpio site
5316 //if (!$nick == "") {
5317 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5318 // if ($pumpio != $profile)
5320 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5333 * @param array $item
5338 function api_in_reply_to($item)
5342 $in_reply_to['status_id'] = null;
5343 $in_reply_to['user_id'] = null;
5344 $in_reply_to['status_id_str'] = null;
5345 $in_reply_to['user_id_str'] = null;
5346 $in_reply_to['screen_name'] = null;
5348 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5349 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5350 if (DBA::isResult($parent)) {
5351 $in_reply_to['status_id'] = intval($parent['id']);
5353 $in_reply_to['status_id'] = intval($item['parent']);
5356 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5358 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5359 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5361 if (DBA::isResult($parent)) {
5362 if ($parent['author-nick'] == "") {
5363 $parent['author-nick'] = api_get_nick($parent['author-link']);
5366 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5367 $in_reply_to['user_id'] = intval($parent['author-id']);
5368 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5371 // There seems to be situation, where both fields are identical:
5372 // https://github.com/friendica/friendica/issues/1010
5373 // This is a bugfix for that.
5374 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5375 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']]);
5376 $in_reply_to['status_id'] = null;
5377 $in_reply_to['user_id'] = null;
5378 $in_reply_to['status_id_str'] = null;
5379 $in_reply_to['user_id_str'] = null;
5380 $in_reply_to['screen_name'] = null;
5384 return $in_reply_to;
5389 * @param string $text
5392 * @throws InternalServerErrorException
5394 function api_clean_plain_items($text)
5396 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5398 $text = BBCode::cleanPictureLinks($text);
5399 $URLSearchString = "^\[\]";
5401 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5403 if ($include_entities == "true") {
5404 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5407 // Simplify "attachment" element
5408 $text = api_clean_attachments($text);
5414 * @brief Removes most sharing information for API text export
5416 * @param string $body The original body
5418 * @return string Cleaned body
5419 * @throws InternalServerErrorException
5421 function api_clean_attachments($body)
5423 $data = BBCode::getAttachmentData($body);
5430 if (isset($data["text"])) {
5431 $body = $data["text"];
5433 if (($body == "") && isset($data["title"])) {
5434 $body = $data["title"];
5436 if (isset($data["url"])) {
5437 $body .= "\n".$data["url"];
5439 $body .= $data["after"];
5446 * @param array $contacts
5450 function api_best_nickname(&$contacts)
5454 if (count($contacts) == 0) {
5458 foreach ($contacts as $contact) {
5459 if ($contact["network"] == "") {
5460 $contact["network"] = "dfrn";
5461 $best_contact = [$contact];
5465 if (sizeof($best_contact) == 0) {
5466 foreach ($contacts as $contact) {
5467 if ($contact["network"] == "dfrn") {
5468 $best_contact = [$contact];
5473 if (sizeof($best_contact) == 0) {
5474 foreach ($contacts as $contact) {
5475 if ($contact["network"] == "dspr") {
5476 $best_contact = [$contact];
5481 if (sizeof($best_contact) == 0) {
5482 foreach ($contacts as $contact) {
5483 if ($contact["network"] == "stat") {
5484 $best_contact = [$contact];
5489 if (sizeof($best_contact) == 0) {
5490 foreach ($contacts as $contact) {
5491 if ($contact["network"] == "pump") {
5492 $best_contact = [$contact];
5497 if (sizeof($best_contact) == 0) {
5498 foreach ($contacts as $contact) {
5499 if ($contact["network"] == "twit") {
5500 $best_contact = [$contact];
5505 if (sizeof($best_contact) == 1) {
5506 $contacts = $best_contact;
5508 $contacts = [$contacts[0]];
5513 * Return all or a specified group of the user with the containing contacts.
5515 * @param string $type Return type (atom, rss, xml, json)
5517 * @return array|string
5518 * @throws BadRequestException
5519 * @throws ForbiddenException
5520 * @throws ImagickException
5521 * @throws InternalServerErrorException
5522 * @throws UnauthorizedException
5524 function api_friendica_group_show($type)
5528 if (api_user() === false) {
5529 throw new ForbiddenException();
5533 $user_info = api_get_user($a);
5534 $gid = $_REQUEST['gid'] ?? 0;
5535 $uid = $user_info['uid'];
5537 // get data of the specified group id or all groups if not specified
5540 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5544 // error message if specified gid is not in database
5545 if (!DBA::isResult($r)) {
5546 throw new BadRequestException("gid not available");
5550 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5555 // loop through all groups and retrieve all members for adding data in the user array
5557 foreach ($r as $rr) {
5558 $members = Contact::getByGroupId($rr['id']);
5561 if ($type == "xml") {
5562 $user_element = "users";
5564 foreach ($members as $member) {
5565 $user = api_get_user($a, $member['nurl']);
5566 $users[$k++.":user"] = $user;
5569 $user_element = "user";
5570 foreach ($members as $member) {
5571 $user = api_get_user($a, $member['nurl']);
5575 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5577 return api_format_data("groups", $type, ['group' => $grps]);
5579 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5583 * Delete the specified group of the user.
5585 * @param string $type Return type (atom, rss, xml, json)
5587 * @return array|string
5588 * @throws BadRequestException
5589 * @throws ForbiddenException
5590 * @throws ImagickException
5591 * @throws InternalServerErrorException
5592 * @throws UnauthorizedException
5594 function api_friendica_group_delete($type)
5598 if (api_user() === false) {
5599 throw new ForbiddenException();
5603 $user_info = api_get_user($a);
5604 $gid = $_REQUEST['gid'] ?? 0;
5605 $name = $_REQUEST['name'] ?? '';
5606 $uid = $user_info['uid'];
5608 // error if no gid specified
5609 if ($gid == 0 || $name == "") {
5610 throw new BadRequestException('gid or name not specified');
5613 // get data of the specified group id
5615 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5619 // error message if specified gid is not in database
5620 if (!DBA::isResult($r)) {
5621 throw new BadRequestException('gid not available');
5624 // get data of the specified group id and group name
5626 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5631 // error message if specified gid is not in database
5632 if (!DBA::isResult($rname)) {
5633 throw new BadRequestException('wrong group name');
5637 $ret = Group::removeByName($uid, $name);
5640 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5641 return api_format_data("group_delete", $type, ['result' => $success]);
5643 throw new BadRequestException('other API error');
5646 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5651 * @param string $type Return type (atom, rss, xml, json)
5653 * @return array|string
5654 * @throws BadRequestException
5655 * @throws ForbiddenException
5656 * @throws ImagickException
5657 * @throws InternalServerErrorException
5658 * @throws UnauthorizedException
5659 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5661 function api_lists_destroy($type)
5665 if (api_user() === false) {
5666 throw new ForbiddenException();
5670 $user_info = api_get_user($a);
5671 $gid = $_REQUEST['list_id'] ?? 0;
5672 $uid = $user_info['uid'];
5674 // error if no gid specified
5676 throw new BadRequestException('gid not specified');
5679 // get data of the specified group id
5680 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5681 // error message if specified gid is not in database
5683 throw new BadRequestException('gid not available');
5686 if (Group::remove($gid)) {
5688 'name' => $group['name'],
5689 'id' => intval($gid),
5690 'id_str' => (string) $gid,
5691 'user' => $user_info
5694 return api_format_data("lists", $type, ['lists' => $list]);
5697 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5700 * Add a new group to the database.
5702 * @param string $name Group name
5703 * @param int $uid User ID
5704 * @param array $users List of users to add to the group
5707 * @throws BadRequestException
5709 function group_create($name, $uid, $users = [])
5711 // error if no name specified
5713 throw new BadRequestException('group name not specified');
5716 // get data of the specified group name
5718 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5722 // error message if specified group name already exists
5723 if (DBA::isResult($rname)) {
5724 throw new BadRequestException('group name already exists');
5727 // check if specified group name is a deleted group
5729 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5733 // error message if specified group name already exists
5734 if (DBA::isResult($rname)) {
5735 $reactivate_group = true;
5739 $ret = Group::create($uid, $name);
5741 $gid = Group::getIdByName($uid, $name);
5743 throw new BadRequestException('other API error');
5747 $erroraddinguser = false;
5749 foreach ($users as $user) {
5750 $cid = $user['cid'];
5751 // check if user really exists as contact
5753 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5757 if (count($contact)) {
5758 Group::addMember($gid, $cid);
5760 $erroraddinguser = true;
5761 $errorusers[] = $cid;
5765 // return success message incl. missing users in array
5766 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5768 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5772 * Create the specified group with the posted array of contacts.
5774 * @param string $type Return type (atom, rss, xml, json)
5776 * @return array|string
5777 * @throws BadRequestException
5778 * @throws ForbiddenException
5779 * @throws ImagickException
5780 * @throws InternalServerErrorException
5781 * @throws UnauthorizedException
5783 function api_friendica_group_create($type)
5787 if (api_user() === false) {
5788 throw new ForbiddenException();
5792 $user_info = api_get_user($a);
5793 $name = $_REQUEST['name'] ?? '';
5794 $uid = $user_info['uid'];
5795 $json = json_decode($_POST['json'], true);
5796 $users = $json['user'];
5798 $success = group_create($name, $uid, $users);
5800 return api_format_data("group_create", $type, ['result' => $success]);
5802 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5805 * Create a new group.
5807 * @param string $type Return type (atom, rss, xml, json)
5809 * @return array|string
5810 * @throws BadRequestException
5811 * @throws ForbiddenException
5812 * @throws ImagickException
5813 * @throws InternalServerErrorException
5814 * @throws UnauthorizedException
5815 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5817 function api_lists_create($type)
5821 if (api_user() === false) {
5822 throw new ForbiddenException();
5826 $user_info = api_get_user($a);
5827 $name = $_REQUEST['name'] ?? '';
5828 $uid = $user_info['uid'];
5830 $success = group_create($name, $uid);
5831 if ($success['success']) {
5833 'name' => $success['name'],
5834 'id' => intval($success['gid']),
5835 'id_str' => (string) $success['gid'],
5836 'user' => $user_info
5839 return api_format_data("lists", $type, ['lists'=>$grp]);
5842 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5845 * Update the specified group with the posted array of contacts.
5847 * @param string $type Return type (atom, rss, xml, json)
5849 * @return array|string
5850 * @throws BadRequestException
5851 * @throws ForbiddenException
5852 * @throws ImagickException
5853 * @throws InternalServerErrorException
5854 * @throws UnauthorizedException
5856 function api_friendica_group_update($type)
5860 if (api_user() === false) {
5861 throw new ForbiddenException();
5865 $user_info = api_get_user($a);
5866 $uid = $user_info['uid'];
5867 $gid = $_REQUEST['gid'] ?? 0;
5868 $name = $_REQUEST['name'] ?? '';
5869 $json = json_decode($_POST['json'], true);
5870 $users = $json['user'];
5872 // error if no name specified
5874 throw new BadRequestException('group name not specified');
5877 // error if no gid specified
5879 throw new BadRequestException('gid not specified');
5883 $members = Contact::getByGroupId($gid);
5884 foreach ($members as $member) {
5885 $cid = $member['id'];
5886 foreach ($users as $user) {
5887 $found = ($user['cid'] == $cid ? true : false);
5889 if (!isset($found) || !$found) {
5890 Group::removeMemberByName($uid, $name, $cid);
5895 $erroraddinguser = false;
5897 foreach ($users as $user) {
5898 $cid = $user['cid'];
5899 // check if user really exists as contact
5901 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5906 if (count($contact)) {
5907 Group::addMember($gid, $cid);
5909 $erroraddinguser = true;
5910 $errorusers[] = $cid;
5914 // return success message incl. missing users in array
5915 $status = ($erroraddinguser ? "missing user" : "ok");
5916 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5917 return api_format_data("group_update", $type, ['result' => $success]);
5920 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5923 * Update information about a group.
5925 * @param string $type Return type (atom, rss, xml, json)
5927 * @return array|string
5928 * @throws BadRequestException
5929 * @throws ForbiddenException
5930 * @throws ImagickException
5931 * @throws InternalServerErrorException
5932 * @throws UnauthorizedException
5933 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5935 function api_lists_update($type)
5939 if (api_user() === false) {
5940 throw new ForbiddenException();
5944 $user_info = api_get_user($a);
5945 $gid = $_REQUEST['list_id'] ?? 0;
5946 $name = $_REQUEST['name'] ?? '';
5947 $uid = $user_info['uid'];
5949 // error if no gid specified
5951 throw new BadRequestException('gid not specified');
5954 // get data of the specified group id
5955 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5956 // error message if specified gid is not in database
5958 throw new BadRequestException('gid not available');
5961 if (Group::update($gid, $name)) {
5964 'id' => intval($gid),
5965 'id_str' => (string) $gid,
5966 'user' => $user_info
5969 return api_format_data("lists", $type, ['lists' => $list]);
5973 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5977 * @param string $type Return type (atom, rss, xml, json)
5979 * @return array|string
5980 * @throws BadRequestException
5981 * @throws ForbiddenException
5982 * @throws ImagickException
5983 * @throws InternalServerErrorException
5985 function api_friendica_activity($type)
5989 if (api_user() === false) {
5990 throw new ForbiddenException();
5992 $verb = strtolower($a->argv[3]);
5993 $verb = preg_replace("|\..*$|", "", $verb);
5995 $id = $_REQUEST['id'] ?? 0;
5997 $res = Item::performLike($id, $verb);
6000 if ($type == "xml") {
6005 return api_format_data('ok', $type, ['ok' => $ok]);
6007 throw new BadRequestException('Error adding activity');
6011 /// @TODO move to top of file or somewhere better
6012 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
6013 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
6014 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
6015 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
6016 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6017 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
6018 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
6019 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
6020 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
6021 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6024 * @brief Returns notifications
6026 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6027 * @return string|array
6028 * @throws BadRequestException
6029 * @throws ForbiddenException
6030 * @throws InternalServerErrorException
6032 function api_friendica_notification($type)
6036 if (api_user() === false) {
6037 throw new ForbiddenException();
6040 throw new BadRequestException("Invalid argument count");
6042 $nm = new NotificationsManager();
6044 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6046 if ($type == "xml") {
6048 if (!empty($notes)) {
6049 foreach ($notes as $note) {
6050 $xmlnotes[] = ["@attributes" => $note];
6056 return api_format_data("notes", $type, ['note' => $notes]);
6060 * POST request with 'id' param as notification id
6062 * @brief Set notification as seen and returns associated item (if possible)
6064 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6065 * @return string|array
6066 * @throws BadRequestException
6067 * @throws ForbiddenException
6068 * @throws ImagickException
6069 * @throws InternalServerErrorException
6070 * @throws UnauthorizedException
6072 function api_friendica_notification_seen($type)
6075 $user_info = api_get_user($a);
6077 if (api_user() === false || $user_info === false) {
6078 throw new ForbiddenException();
6081 throw new BadRequestException("Invalid argument count");
6084 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6086 $nm = new NotificationsManager();
6087 $note = $nm->getByID($id);
6088 if (is_null($note)) {
6089 throw new BadRequestException("Invalid argument");
6092 $nm->setSeen($note);
6093 if ($note['otype']=='item') {
6094 // would be really better with an ItemsManager and $im->getByID() :-P
6095 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6096 if (DBA::isResult($item)) {
6097 // we found the item, return it to the user
6098 $ret = api_format_items([$item], $user_info, false, $type);
6099 $data = ['status' => $ret];
6100 return api_format_data("status", $type, $data);
6102 // the item can't be found, but we set the note as seen, so we count this as a success
6104 return api_format_data('result', $type, ['result' => "success"]);
6107 /// @TODO move to top of file or somewhere better
6108 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6109 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6112 * @brief update a direct_message to seen state
6114 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6115 * @return string|array (success result=ok, error result=error with error message)
6116 * @throws BadRequestException
6117 * @throws ForbiddenException
6118 * @throws ImagickException
6119 * @throws InternalServerErrorException
6120 * @throws UnauthorizedException
6122 function api_friendica_direct_messages_setseen($type)
6125 if (api_user() === false) {
6126 throw new ForbiddenException();
6130 $user_info = api_get_user($a);
6131 $uid = $user_info['uid'];
6132 $id = $_REQUEST['id'] ?? 0;
6134 // return error if id is zero
6136 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6137 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6140 // error message if specified id is not in database
6141 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6142 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6143 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6146 // update seen indicator
6147 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6151 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6152 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6154 $answer = ['result' => 'error', 'message' => 'unknown error'];
6155 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6159 /// @TODO move to top of file or somewhere better
6160 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6163 * @brief search for direct_messages containing a searchstring through api
6165 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6166 * @param string $box
6167 * @return string|array (success: success=true if found and search_result contains found messages,
6168 * success=false if nothing was found, search_result='nothing found',
6169 * error: result=error with error message)
6170 * @throws BadRequestException
6171 * @throws ForbiddenException
6172 * @throws ImagickException
6173 * @throws InternalServerErrorException
6174 * @throws UnauthorizedException
6176 function api_friendica_direct_messages_search($type, $box = "")
6180 if (api_user() === false) {
6181 throw new ForbiddenException();
6185 $user_info = api_get_user($a);
6186 $searchstring = $_REQUEST['searchstring'] ?? '';
6187 $uid = $user_info['uid'];
6189 // error if no searchstring specified
6190 if ($searchstring == "") {
6191 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6192 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6195 // get data for the specified searchstring
6197 "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",
6199 DBA::escape('%'.$searchstring.'%')
6202 $profile_url = $user_info["url"];
6204 // message if nothing was found
6205 if (!DBA::isResult($r)) {
6206 $success = ['success' => false, 'search_results' => 'problem with query'];
6207 } elseif (count($r) == 0) {
6208 $success = ['success' => false, 'search_results' => 'nothing found'];
6211 foreach ($r as $item) {
6212 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6213 $recipient = $user_info;
6214 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6215 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6216 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6217 $sender = $user_info;
6220 if (isset($recipient) && isset($sender)) {
6221 $ret[] = api_format_messages($item, $recipient, $sender);
6224 $success = ['success' => true, 'search_results' => $ret];
6227 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6230 /// @TODO move to top of file or somewhere better
6231 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6234 * @brief return data of all the profiles a user has to the client
6236 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6237 * @return string|array
6238 * @throws BadRequestException
6239 * @throws ForbiddenException
6240 * @throws ImagickException
6241 * @throws InternalServerErrorException
6242 * @throws UnauthorizedException
6244 function api_friendica_profile_show($type)
6248 if (api_user() === false) {
6249 throw new ForbiddenException();
6253 $profile_id = $_REQUEST['profile_id'] ?? 0;
6255 // retrieve general information about profiles for user
6256 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6257 $directory = Config::get('system', 'directory');
6259 // get data of the specified profile id or all profiles of the user if not specified
6260 if ($profile_id != 0) {
6261 $r = Profile::getById(api_user(), $profile_id);
6262 // error message if specified gid is not in database
6263 if (!DBA::isResult($r)) {
6264 throw new BadRequestException("profile_id not available");
6267 $r = Profile::getListByUser(api_user());
6269 // loop through all returned profiles and retrieve data and users
6272 if (DBA::isResult($r)) {
6273 foreach ($r as $rr) {
6274 $profile = api_format_items_profiles($rr);
6276 // select all users from contact table, loop and prepare standard return for user data
6278 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6279 foreach ($nurls as $nurl) {
6280 $user = api_get_user($a, $nurl['nurl']);
6281 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6283 $profile['users'] = $users;
6285 // add prepared profile data to array for final return
6286 if ($type == "xml") {
6287 $profiles[$k++ . ":profile"] = $profile;
6289 $profiles[] = $profile;
6294 // return settings, authenticated user and profiles data
6295 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6297 $result = ['multi_profiles' => $multi_profiles ? true : false,
6298 'global_dir' => $directory,
6299 'friendica_owner' => api_get_user($a, $self['nurl']),
6300 'profiles' => $profiles];
6301 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6303 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6306 * Returns a list of saved searches.
6308 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6310 * @param string $type Return format: json or xml
6312 * @return string|array
6315 function api_saved_searches_list($type)
6317 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6320 while ($term = DBA::fetch($terms)) {
6322 'created_at' => api_date(time()),
6323 'id' => intval($term['id']),
6324 'id_str' => $term['id'],
6325 'name' => $term['term'],
6327 'query' => $term['term']
6333 return api_format_data("terms", $type, ['terms' => $result]);
6336 /// @TODO move to top of file or somewhere better
6337 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6340 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6342 * @brief Number of comments
6344 * @param object $data [Status, Status]
6348 function bindComments(&$data)
6350 if (count($data) == 0) {
6356 foreach ($data as $item) {
6357 $ids[] = $item['id'];
6360 $idStr = DBA::escape(implode(', ', $ids));
6361 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6362 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6363 $itemsData = DBA::toArray($items);
6365 foreach ($itemsData as $item) {
6366 $comments[$item['parent']] = $item['comments'];
6369 foreach ($data as $idx => $item) {
6371 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6376 @TODO Maybe open to implement?
6378 [pagename] => api/1.1/statuses/lookup.json
6379 [id] => 605138389168451584
6380 [include_cards] => true
6381 [cards_platform] => Android-12
6382 [include_entities] => true
6383 [include_my_retweet] => 1
6385 [include_reply_count] => true
6386 [include_descendent_reply_count] => true
6390 Not implemented by now:
6391 statuses/retweets_of_me
6396 account/update_location
6397 account/update_profile_background_image
6400 friendica/profile/update
6401 friendica/profile/create
6402 friendica/profile/delete
6404 Not implemented in status.net:
6405 statuses/retweeted_to_me
6406 statuses/retweeted_by_me
6407 direct_messages/destroy
6409 account/update_delivery_device
6410 notifications/follow