3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\BaseObject;
11 use Friendica\Content\ContactSelector;
12 use Friendica\Content\Feature;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Notify;
30 use Friendica\Model\Photo;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\FKOAuth1;
34 use Friendica\Network\HTTPException;
35 use Friendica\Network\HTTPException\BadRequestException;
36 use Friendica\Network\HTTPException\ExpectationFailedException;
37 use Friendica\Network\HTTPException\ForbiddenException;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Network\HTTPException\MethodNotAllowedException;
40 use Friendica\Network\HTTPException\NotFoundException;
41 use Friendica\Network\HTTPException\NotImplementedException;
42 use Friendica\Network\HTTPException\TooManyRequestsException;
43 use Friendica\Network\HTTPException\UnauthorizedException;
44 use Friendica\Object\Image;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Diaspora;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy as ProxyUtils;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
53 require_once __DIR__ . '/../mod/share.php';
54 require_once __DIR__ . '/../mod/item.php';
55 require_once __DIR__ . '/../mod/wall_upload.php';
57 define('API_METHOD_ANY', '*');
58 define('API_METHOD_GET', 'GET');
59 define('API_METHOD_POST', 'POST,PUT');
60 define('API_METHOD_DELETE', 'POST,DELETE');
62 define('API_LOG_PREFIX', 'API {action} - ');
68 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
69 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
70 * into a page, and visitors will post something without noticing it).
72 * @brief Auth API user
76 if (!empty($_SESSION['allow_api'])) {
84 * Clients can send 'source' parameter to be show in post metadata
85 * as "sent via <source>".
86 * Some clients doesn't send a source param, we support ones we know
89 * @brief Get source name from API client
92 * Client source name, default to "api" if unset/unknown
97 if (requestdata('source')) {
98 return requestdata('source');
101 // Support for known clients that doesn't send a source name
102 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
103 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
107 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
109 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
116 * @brief Format date for API
118 * @param string $str Source date, as UTC
119 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
122 function api_date($str)
124 // Wed May 23 06:01:13 +0000 2007
125 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
129 * Register a function to be the endpoint for defined API path.
131 * @brief Register API endpoint
133 * @param string $path API URL path, relative to System::baseUrl()
134 * @param string $func Function name to call on path request
135 * @param bool $auth API need logged user
136 * @param string $method HTTP method reqiured to call this endpoint.
137 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
138 * Default to API_METHOD_ANY
140 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
150 // Workaround for hotot
151 $path = str_replace("api/", "api/1.1/", $path);
161 * Log in user via OAuth1 or Simple HTTP Auth.
162 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
164 * @brief Login API user
167 * @throws ForbiddenException
168 * @throws InternalServerErrorException
169 * @throws UnauthorizedException
170 * @hook 'authenticate'
172 * 'username' => username from login form
173 * 'password' => password from login form
174 * 'authenticated' => return status,
175 * 'user_record' => return authenticated user record
177 function api_login(App $a)
179 $oauth1 = new FKOAuth1();
182 $request = OAuthRequest::from_request();
183 list($consumer, $token) = $oauth1->verify_request($request);
184 if (!is_null($token)) {
185 $oauth1->loginUser($token->uid);
186 Session::set('allow_api', true);
189 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
190 var_dump($consumer, $token);
192 } catch (Exception $e) {
193 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
196 // workaround for HTTP-auth in CGI mode
197 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
198 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
199 if (strlen($userpass)) {
200 list($name, $password) = explode(':', $userpass);
201 $_SERVER['PHP_AUTH_USER'] = $name;
202 $_SERVER['PHP_AUTH_PW'] = $password;
206 if (empty($_SERVER['PHP_AUTH_USER'])) {
207 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
208 header('WWW-Authenticate: Basic realm="Friendica"');
209 throw new UnauthorizedException("This API requires login");
212 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
213 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
215 // allow "user@server" login (but ignore 'server' part)
216 $at = strstr($user, "@", true);
221 // next code from mod/auth.php. needs better solution
225 'username' => trim($user),
226 'password' => trim($password),
227 'authenticated' => 0,
228 'user_record' => null,
232 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
233 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
234 * and later addons should not interfere with an earlier one that succeeded.
236 Hook::callAll('authenticate', $addon_auth);
238 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
239 $record = $addon_auth['user_record'];
241 $user_id = User::authenticate(trim($user), trim($password), true);
242 if ($user_id !== false) {
243 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
247 if (!DBA::isResult($record)) {
248 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
249 header('WWW-Authenticate: Basic realm="Friendica"');
250 //header('HTTP/1.0 401 Unauthorized');
251 //die('This api requires login');
252 throw new UnauthorizedException("This API requires login");
255 Session::setAuthenticatedForUser($a, $record);
257 $_SESSION["allow_api"] = true;
259 Hook::callAll('logged_in', $a->user);
263 * API endpoints can define which HTTP method to accept when called.
264 * This function check the current HTTP method agains endpoint
267 * @brief Check HTTP method of called API
269 * @param string $method Required methods, uppercase, separated by comma
272 function api_check_method($method)
274 if ($method == "*") {
277 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
281 * Authenticate user, call registered API function, set HTTP headers
283 * @brief Main API entry point
286 * @return string|array API call result
289 function api_call(App $a)
291 global $API, $called_api;
294 if (strpos($a->query_string, ".xml") > 0) {
297 if (strpos($a->query_string, ".json") > 0) {
300 if (strpos($a->query_string, ".rss") > 0) {
303 if (strpos($a->query_string, ".atom") > 0) {
308 foreach ($API as $p => $info) {
309 if (strpos($a->query_string, $p) === 0) {
310 if (!api_check_method($info['method'])) {
311 throw new MethodNotAllowedException();
314 $called_api = explode("/", $p);
315 //unset($_SERVER['PHP_AUTH_USER']);
317 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
318 if (!empty($info['auth']) && api_user() === false) {
322 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
323 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
325 $stamp = microtime(true);
326 $return = call_user_func($info['func'], $type);
327 $duration = floatval(microtime(true) - $stamp);
329 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
331 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
333 if (false === $return) {
335 * api function returned false withour throw an
336 * exception. This should not happend, throw a 500
338 throw new InternalServerErrorException();
343 header("Content-Type: text/xml");
346 header("Content-Type: application/json");
347 if (!empty($return)) {
348 $json = json_encode(end($return));
349 if (!empty($_GET['callback'])) {
350 $json = $_GET['callback'] . "(" . $json . ")";
356 header("Content-Type: application/rss+xml");
357 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
360 header("Content-Type: application/atom+xml");
361 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
368 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
369 throw new NotImplementedException();
370 } catch (HTTPException $e) {
371 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
372 return api_error($type, $e);
377 * @brief Format API error string
379 * @param string $type Return type (xml, json, rss, as)
380 * @param object $e HTTPException Error object
381 * @return string|array error message formatted as $type
383 function api_error($type, $e)
387 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
388 /// @TODO: https://dev.twitter.com/overview/api/response-codes
390 $error = ["error" => $error,
391 "code" => $e->getCode() . " " . $e->httpdesc,
392 "request" => $a->query_string];
394 $return = api_format_data('status', $type, ['status' => $error]);
398 header("Content-Type: text/xml");
401 header("Content-Type: application/json");
402 $return = json_encode($return);
405 header("Content-Type: application/rss+xml");
408 header("Content-Type: application/atom+xml");
416 * @brief Set values for RSS template
419 * @param array $arr Array to be passed to template
420 * @param array $user_info User info
422 * @throws BadRequestException
423 * @throws ImagickException
424 * @throws InternalServerErrorException
425 * @throws UnauthorizedException
426 * @todo find proper type-hints
428 function api_rss_extra(App $a, $arr, $user_info)
430 if (is_null($user_info)) {
431 $user_info = api_get_user($a);
434 $arr['$user'] = $user_info;
436 'alternate' => $user_info['url'],
437 'self' => System::baseUrl() . "/" . $a->query_string,
438 'base' => System::baseUrl(),
439 'updated' => api_date(null),
440 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
441 'language' => $user_info['lang'],
442 'logo' => System::baseUrl() . "/images/friendica-32.png",
450 * @brief Unique contact to contact url.
452 * @param int $id Contact id
453 * @return bool|string
454 * Contact url or False if contact id is unknown
457 function api_unique_id_to_nurl($id)
459 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
461 if (DBA::isResult($r)) {
469 * @brief Get user info array.
472 * @param int|string $contact_id Contact ID or URL
474 * @throws BadRequestException
475 * @throws ImagickException
476 * @throws InternalServerErrorException
477 * @throws UnauthorizedException
479 function api_get_user(App $a, $contact_id = null)
487 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
489 // Searching for contact URL
490 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
491 $user = DBA::escape(Strings::normaliseLink($contact_id));
493 $extra_query = "AND `contact`.`nurl` = '%s' ";
494 if (api_user() !== false) {
495 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
499 // Searching for contact id with uid = 0
500 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
501 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
504 throw new BadRequestException("User ID ".$contact_id." not found.");
508 $extra_query = "AND `contact`.`nurl` = '%s' ";
509 if (api_user() !== false) {
510 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
514 if (is_null($user) && !empty($_GET['user_id'])) {
515 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
518 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
527 if (is_null($user) && !empty($_GET['screen_name'])) {
528 $user = DBA::escape($_GET['screen_name']);
529 $extra_query = "AND `contact`.`nick` = '%s' ";
530 if (api_user() !== false) {
531 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
535 if (is_null($user) && !empty($_GET['profileurl'])) {
536 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
537 $extra_query = "AND `contact`.`nurl` = '%s' ";
538 if (api_user() !== false) {
539 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
543 // $called_api is the API path exploded on / and is expected to have at least 2 elements
544 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
545 $argid = count($called_api);
546 if (!empty($a->argv[$argid])) {
547 $data = explode(".", $a->argv[$argid]);
548 if (count($data) > 1) {
549 list($user, $null) = $data;
552 if (is_numeric($user)) {
553 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
557 $extra_query = "AND `contact`.`nurl` = '%s' ";
558 if (api_user() !== false) {
559 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
563 $user = DBA::escape($user);
564 $extra_query = "AND `contact`.`nick` = '%s' ";
565 if (api_user() !== false) {
566 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
571 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
574 if (api_user() === false) {
578 $user = $_SESSION['uid'];
579 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
583 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
587 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
593 // Selecting the id by priority, friendica first
594 if (is_array($uinfo)) {
595 api_best_nickname($uinfo);
598 // if the contact wasn't found, fetch it from the contacts with uid = 0
599 if (!DBA::isResult($uinfo)) {
601 throw new BadRequestException("User not found.");
604 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
606 if (DBA::isResult($contact)) {
607 // If no nick where given, extract it from the address
608 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
609 $contact['nick'] = api_get_nick($contact["url"]);
613 'id' => $contact["id"],
614 'id_str' => (string) $contact["id"],
615 'name' => $contact["name"],
616 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
617 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
618 'description' => BBCode::toPlaintext($contact["about"]),
619 'profile_image_url' => $contact["micro"],
620 'profile_image_url_https' => $contact["micro"],
621 'profile_image_url_profile_size' => $contact["thumb"],
622 'profile_image_url_large' => $contact["photo"],
623 'url' => $contact["url"],
624 'protected' => false,
625 'followers_count' => 0,
626 'friends_count' => 0,
628 'created_at' => api_date($contact["created"]),
629 'favourites_count' => 0,
631 'time_zone' => 'UTC',
632 'geo_enabled' => false,
634 'statuses_count' => 0,
636 'contributors_enabled' => false,
637 'is_translator' => false,
638 'is_translation_enabled' => false,
639 'following' => false,
640 'follow_request_sent' => false,
641 'statusnet_blocking' => false,
642 'notifications' => false,
643 'statusnet_profile_url' => $contact["url"],
645 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
646 'pid' => Contact::getIdForURL($contact["url"], 0, true),
648 'network' => $contact["network"],
653 throw new BadRequestException("User ".$url." not found.");
657 if ($uinfo[0]['self']) {
658 if ($uinfo[0]['network'] == "") {
659 $uinfo[0]['network'] = Protocol::DFRN;
662 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
663 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
670 // Add a nick if it isn't present there
671 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
672 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
675 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
677 if (!empty($profile['about'])) {
678 $description = $profile['about'];
680 $description = $uinfo[0]["about"];
683 if (!empty($usr['default-location'])) {
684 $location = $usr['default-location'];
685 } elseif (!empty($uinfo[0]["location"])) {
686 $location = $uinfo[0]["location"];
688 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
692 'id' => intval($pcontact_id),
693 'id_str' => (string) intval($pcontact_id),
694 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
695 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
696 'location' => $location,
697 'description' => BBCode::toPlaintext($description),
698 'profile_image_url' => $uinfo[0]['micro'],
699 'profile_image_url_https' => $uinfo[0]['micro'],
700 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
701 'profile_image_url_large' => $uinfo[0]["photo"],
702 'url' => $uinfo[0]['url'],
703 'protected' => false,
704 'followers_count' => intval($countfollowers),
705 'friends_count' => intval($countfriends),
707 'created_at' => api_date($uinfo[0]['created']),
708 'favourites_count' => intval($starred),
710 'time_zone' => 'UTC',
711 'geo_enabled' => false,
713 'statuses_count' => intval($countitems),
715 'contributors_enabled' => false,
716 'is_translator' => false,
717 'is_translation_enabled' => false,
718 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
719 'follow_request_sent' => false,
720 'statusnet_blocking' => false,
721 'notifications' => false,
723 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
724 'statusnet_profile_url' => $uinfo[0]['url'],
725 'uid' => intval($uinfo[0]['uid']),
726 'cid' => intval($uinfo[0]['cid']),
727 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
728 'self' => $uinfo[0]['self'],
729 'network' => $uinfo[0]['network'],
732 // If this is a local user and it uses Frio, we can get its color preferences.
734 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
735 if ($theme_info['theme'] === 'frio') {
736 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
738 if ($schema && ($schema != '---')) {
739 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
740 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
741 require_once $schemefile;
744 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
745 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
746 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
748 if (empty($nav_bg)) {
751 if (empty($link_color)) {
752 $link_color = "#6fdbe8";
754 if (empty($bgcolor)) {
755 $bgcolor = "#ededed";
758 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
759 $ret['profile_link_color'] = str_replace('#', '', $link_color);
760 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
768 * @brief return api-formatted array for item's author and owner
771 * @param array $item item from db
772 * @return array(array:author, array:owner)
773 * @throws BadRequestException
774 * @throws ImagickException
775 * @throws InternalServerErrorException
776 * @throws UnauthorizedException
778 function api_item_get_user(App $a, $item)
780 $status_user = api_get_user($a, $item['author-id'] ?? null);
782 $author_user = $status_user;
784 $status_user["protected"] = $item['private'] ?? 0;
786 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
787 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
789 $owner_user = $author_user;
792 return ([$status_user, $author_user, $owner_user]);
796 * @brief walks recursively through an array with the possibility to change value and key
798 * @param array $array The array to walk through
799 * @param callable $callback The callback function
801 * @return array the transformed array
803 function api_walk_recursive(array &$array, callable $callback)
807 foreach ($array as $k => $v) {
809 if ($callback($v, $k)) {
810 $new_array[$k] = api_walk_recursive($v, $callback);
813 if ($callback($v, $k)) {
824 * @brief Callback function to transform the array in an array that can be transformed in a XML file
826 * @param mixed $item Array item value
827 * @param string $key Array key
829 * @return boolean Should the array item be deleted?
831 function api_reformat_xml(&$item, &$key)
833 if (is_bool($item)) {
834 $item = ($item ? "true" : "false");
837 if (substr($key, 0, 10) == "statusnet_") {
838 $key = "statusnet:".substr($key, 10);
839 } elseif (substr($key, 0, 10) == "friendica_") {
840 $key = "friendica:".substr($key, 10);
842 /// @TODO old-lost code?
844 // $key = "default:".$key;
850 * @brief Creates the XML from a JSON style array
852 * @param array $data JSON style array
853 * @param string $root_element Name of the root element
855 * @return string The XML data
857 function api_create_xml(array $data, $root_element)
859 $childname = key($data);
860 $data2 = array_pop($data);
862 $namespaces = ["" => "http://api.twitter.com",
863 "statusnet" => "http://status.net/schema/api/1/",
864 "friendica" => "http://friendi.ca/schema/api/1/",
865 "georss" => "http://www.georss.org/georss"];
867 /// @todo Auto detection of needed namespaces
868 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
872 if (is_array($data2)) {
874 api_walk_recursive($data2, "api_reformat_xml");
880 foreach ($data2 as $item) {
881 $data4[$i++ . ":" . $childname] = $item;
888 $data3 = [$root_element => $data2];
890 $ret = XML::fromArray($data3, $xml, false, $namespaces);
895 * @brief Formats the data according to the data type
897 * @param string $root_element Name of the root element
898 * @param string $type Return type (atom, rss, xml, json)
899 * @param array $data JSON style array
901 * @return array|string (string|array) XML data or JSON data
903 function api_format_data($root_element, $type, $data)
909 $ret = api_create_xml($data, $root_element);
924 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
925 * returns a 401 status code and an error message if not.
927 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
929 * @param string $type Return type (atom, rss, xml, json)
930 * @return array|string
931 * @throws BadRequestException
932 * @throws ForbiddenException
933 * @throws ImagickException
934 * @throws InternalServerErrorException
935 * @throws UnauthorizedException
937 function api_account_verify_credentials($type)
941 if (api_user() === false) {
942 throw new ForbiddenException();
945 unset($_REQUEST["user_id"]);
946 unset($_GET["user_id"]);
948 unset($_REQUEST["screen_name"]);
949 unset($_GET["screen_name"]);
951 $skip_status = $_REQUEST['skip_status'] ?? false;
953 $user_info = api_get_user($a);
955 // "verified" isn't used here in the standard
956 unset($user_info["verified"]);
958 // - Adding last status
960 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
962 $user_info['status'] = api_format_item($item, $type);
966 // "uid" and "self" are only needed for some internal stuff, so remove it from here
967 unset($user_info["uid"]);
968 unset($user_info["self"]);
970 return api_format_data("user", $type, ['user' => $user_info]);
973 /// @TODO move to top of file or somewhere better
974 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
977 * Get data from $_POST or $_GET
982 function requestdata($k)
984 if (!empty($_POST[$k])) {
987 if (!empty($_GET[$k])) {
994 * Deprecated function to upload media.
996 * @param string $type Return type (atom, rss, xml, json)
998 * @return array|string
999 * @throws BadRequestException
1000 * @throws ForbiddenException
1001 * @throws ImagickException
1002 * @throws InternalServerErrorException
1003 * @throws UnauthorizedException
1005 function api_statuses_mediap($type)
1009 if (api_user() === false) {
1010 Logger::log('api_statuses_update: no user');
1011 throw new ForbiddenException();
1013 $user_info = api_get_user($a);
1015 $_REQUEST['profile_uid'] = api_user();
1016 $_REQUEST['api_source'] = true;
1017 $txt = requestdata('status');
1018 /// @TODO old-lost code?
1019 //$txt = urldecode(requestdata('status'));
1021 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1022 $txt = HTML::toBBCodeVideo($txt);
1023 $config = HTMLPurifier_Config::createDefault();
1024 $config->set('Cache.DefinitionImpl', null);
1025 $purifier = new HTMLPurifier($config);
1026 $txt = $purifier->purify($txt);
1028 $txt = HTML::toBBCode($txt);
1030 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1032 $picture = wall_upload_post($a, false);
1034 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1035 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1036 $item_id = item_post($a);
1038 // output the post that we just posted.
1039 return api_status_show($type, $item_id);
1042 /// @TODO move this to top of file or somewhere better!
1043 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1046 * Updates the user’s current status.
1048 * @param string $type Return type (atom, rss, xml, json)
1050 * @return array|string
1051 * @throws BadRequestException
1052 * @throws ForbiddenException
1053 * @throws ImagickException
1054 * @throws InternalServerErrorException
1055 * @throws TooManyRequestsException
1056 * @throws UnauthorizedException
1057 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1059 function api_statuses_update($type)
1063 if (api_user() === false) {
1064 Logger::log('api_statuses_update: no user');
1065 throw new ForbiddenException();
1070 // convert $_POST array items to the form we use for web posts.
1071 if (requestdata('htmlstatus')) {
1072 $txt = requestdata('htmlstatus');
1073 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1074 $txt = HTML::toBBCodeVideo($txt);
1076 $config = HTMLPurifier_Config::createDefault();
1077 $config->set('Cache.DefinitionImpl', null);
1079 $purifier = new HTMLPurifier($config);
1080 $txt = $purifier->purify($txt);
1082 $_REQUEST['body'] = HTML::toBBCode($txt);
1085 $_REQUEST['body'] = requestdata('status');
1088 $_REQUEST['title'] = requestdata('title');
1090 $parent = requestdata('in_reply_to_status_id');
1092 // Twidere sends "-1" if it is no reply ...
1093 if ($parent == -1) {
1097 if (ctype_digit($parent)) {
1098 $_REQUEST['parent'] = $parent;
1100 $_REQUEST['parent_uri'] = $parent;
1103 if (requestdata('lat') && requestdata('long')) {
1104 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1106 $_REQUEST['profile_uid'] = api_user();
1109 // Check for throttling (maximum posts per day, week and month)
1110 $throttle_day = Config::get('system', 'throttle_limit_day');
1111 if ($throttle_day > 0) {
1112 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1114 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1115 $posts_day = DBA::count('thread', $condition);
1117 if ($posts_day > $throttle_day) {
1118 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1119 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1120 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));
1124 $throttle_week = Config::get('system', 'throttle_limit_week');
1125 if ($throttle_week > 0) {
1126 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1128 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1129 $posts_week = DBA::count('thread', $condition);
1131 if ($posts_week > $throttle_week) {
1132 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1133 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1134 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));
1138 $throttle_month = Config::get('system', 'throttle_limit_month');
1139 if ($throttle_month > 0) {
1140 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1142 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1143 $posts_month = DBA::count('thread', $condition);
1145 if ($posts_month > $throttle_month) {
1146 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1147 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1148 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));
1153 if (!empty($_FILES['media'])) {
1154 // upload the image if we have one
1155 $picture = wall_upload_post($a, false);
1156 if (is_array($picture)) {
1157 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1161 if (requestdata('media_ids')) {
1162 $ids = explode(',', requestdata('media_ids'));
1163 foreach ($ids as $id) {
1165 "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",
1169 if (DBA::isResult($r)) {
1170 $phototypes = Image::supportedTypes();
1171 $ext = $phototypes[$r[0]['type']];
1172 $description = $r[0]['desc'] ?? '';
1173 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1174 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1179 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1181 $_REQUEST['api_source'] = true;
1183 if (empty($_REQUEST['source'])) {
1184 $_REQUEST["source"] = api_source();
1187 // call out normal post function
1188 $item_id = item_post($a);
1190 // output the post that we just posted.
1191 return api_status_show($type, $item_id);
1194 /// @TODO move to top of file or somewhere better
1195 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1196 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1199 * Uploads an image to Friendica.
1202 * @throws BadRequestException
1203 * @throws ForbiddenException
1204 * @throws ImagickException
1205 * @throws InternalServerErrorException
1206 * @throws UnauthorizedException
1207 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1209 function api_media_upload()
1213 if (api_user() === false) {
1214 Logger::log('no user');
1215 throw new ForbiddenException();
1220 if (empty($_FILES['media'])) {
1222 throw new BadRequestException("No media.");
1225 $media = wall_upload_post($a, false);
1228 throw new InternalServerErrorException();
1232 $returndata["media_id"] = $media["id"];
1233 $returndata["media_id_string"] = (string)$media["id"];
1234 $returndata["size"] = $media["size"];
1235 $returndata["image"] = ["w" => $media["width"],
1236 "h" => $media["height"],
1237 "image_type" => $media["type"],
1238 "friendica_preview_url" => $media["preview"]];
1240 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1242 return ["media" => $returndata];
1245 /// @TODO move to top of file or somewhere better
1246 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1249 * Updates media meta data (picture descriptions)
1251 * @param string $type Return type (atom, rss, xml, json)
1253 * @return array|string
1254 * @throws BadRequestException
1255 * @throws ForbiddenException
1256 * @throws ImagickException
1257 * @throws InternalServerErrorException
1258 * @throws TooManyRequestsException
1259 * @throws UnauthorizedException
1260 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1262 * @todo Compare the corresponding Twitter function for correct return values
1264 function api_media_metadata_create($type)
1268 if (api_user() === false) {
1269 Logger::info('no user');
1270 throw new ForbiddenException();
1275 $postdata = Network::postdata();
1277 if (empty($postdata)) {
1278 throw new BadRequestException("No post data");
1281 $data = json_decode($postdata, true);
1283 throw new BadRequestException("Invalid post data");
1286 if (empty($data['media_id']) || empty($data['alt_text'])) {
1287 throw new BadRequestException("Missing post data values");
1290 if (empty($data['alt_text']['text'])) {
1291 throw new BadRequestException("No alt text.");
1294 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1296 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1297 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1298 if (!DBA::isResult($photo)) {
1299 throw new BadRequestException("Metadata not found.");
1302 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1305 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1308 * @param string $type Return format (atom, rss, xml, json)
1309 * @param int $item_id
1313 function api_status_show($type, $item_id)
1315 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1319 $item = api_get_item(['id' => $item_id]);
1321 $status_info = api_format_item($item, $type);
1324 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1326 return api_format_data('statuses', $type, ['status' => $status_info]);
1330 * Retrieves the last public status of the provided user info
1332 * @param int $ownerId Public contact Id
1333 * @param int $uid User Id
1337 function api_get_last_status($ownerId, $uid)
1340 'author-id'=> $ownerId,
1342 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1346 $item = api_get_item($condition);
1352 * Retrieves a single item record based on the provided condition and converts it for API use.
1354 * @param array $condition Item table condition array
1358 function api_get_item(array $condition)
1360 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1366 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1367 * The author's most recent status will be returned inline.
1369 * @param string $type Return type (atom, rss, xml, json)
1370 * @return array|string
1371 * @throws BadRequestException
1372 * @throws ImagickException
1373 * @throws InternalServerErrorException
1374 * @throws UnauthorizedException
1375 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1377 function api_users_show($type)
1379 $a = BaseObject::getApp();
1381 $user_info = api_get_user($a);
1383 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1385 $user_info['status'] = api_format_item($item, $type);
1388 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1389 unset($user_info['uid']);
1390 unset($user_info['self']);
1392 return api_format_data('user', $type, ['user' => $user_info]);
1395 /// @TODO move to top of file or somewhere better
1396 api_register_func('api/users/show', 'api_users_show');
1397 api_register_func('api/externalprofile/show', 'api_users_show');
1400 * Search a public user account.
1402 * @param string $type Return type (atom, rss, xml, json)
1404 * @return array|string
1405 * @throws BadRequestException
1406 * @throws ImagickException
1407 * @throws InternalServerErrorException
1408 * @throws UnauthorizedException
1409 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1411 function api_users_search($type)
1417 if (!empty($_GET['q'])) {
1418 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1420 if (!DBA::isResult($r)) {
1421 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1424 if (DBA::isResult($r)) {
1426 foreach ($r as $user) {
1427 $user_info = api_get_user($a, $user["id"]);
1429 if ($type == "xml") {
1430 $userlist[$k++.":user"] = $user_info;
1432 $userlist[] = $user_info;
1435 $userlist = ["users" => $userlist];
1437 throw new BadRequestException("User ".$_GET["q"]." not found.");
1440 throw new BadRequestException("No user specified.");
1443 return api_format_data("users", $type, $userlist);
1446 /// @TODO move to top of file or somewhere better
1447 api_register_func('api/users/search', 'api_users_search');
1450 * Return user objects
1452 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1454 * @param string $type Return format: json or xml
1456 * @return array|string
1457 * @throws BadRequestException
1458 * @throws ImagickException
1459 * @throws InternalServerErrorException
1460 * @throws NotFoundException if the results are empty.
1461 * @throws UnauthorizedException
1463 function api_users_lookup($type)
1467 if (!empty($_REQUEST['user_id'])) {
1468 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1470 $users[] = api_get_user(get_app(), $id);
1475 if (empty($users)) {
1476 throw new NotFoundException;
1479 return api_format_data("users", $type, ['users' => $users]);
1482 /// @TODO move to top of file or somewhere better
1483 api_register_func('api/users/lookup', 'api_users_lookup', true);
1486 * Returns statuses that match a specified query.
1488 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1490 * @param string $type Return format: json, xml, atom, rss
1492 * @return array|string
1493 * @throws BadRequestException if the "q" parameter is missing.
1494 * @throws ForbiddenException
1495 * @throws ImagickException
1496 * @throws InternalServerErrorException
1497 * @throws UnauthorizedException
1499 function api_search($type)
1502 $user_info = api_get_user($a);
1504 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1506 if (empty($_REQUEST['q'])) {
1507 throw new BadRequestException('q parameter is required.');
1510 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1513 $data['status'] = [];
1515 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1516 if (!empty($_REQUEST['rpp'])) {
1517 $count = $_REQUEST['rpp'];
1518 } elseif (!empty($_REQUEST['count'])) {
1519 $count = $_REQUEST['count'];
1522 $since_id = $_REQUEST['since_id'] ?? 0;
1523 $max_id = $_REQUEST['max_id'] ?? 0;
1524 $page = $_REQUEST['page'] ?? 1;
1526 $start = max(0, ($page - 1) * $count);
1528 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1529 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1530 $searchTerm = $matches[1];
1531 $condition = ["`oid` > ?
1532 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1533 AND `otype` = ? AND `type` = ? AND `term` = ?",
1534 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1536 $condition[0] .= ' AND `oid` <= ?';
1537 $condition[] = $max_id;
1539 $terms = DBA::select('term', ['oid'], $condition, []);
1541 while ($term = DBA::fetch($terms)) {
1542 $itemIds[] = $term['oid'];
1546 if (empty($itemIds)) {
1547 return api_format_data('statuses', $type, $data);
1550 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1551 if ($exclude_replies) {
1552 $preCondition[] = '`id` = `parent`';
1555 $condition = [implode(' AND ', $preCondition)];
1557 $condition = ["`id` > ?
1558 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1559 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1560 AND `body` LIKE CONCAT('%',?,'%')",
1561 $since_id, api_user(), $_REQUEST['q']];
1563 $condition[0] .= ' AND `id` <= ?';
1564 $condition[] = $max_id;
1568 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1570 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1572 bindComments($data['status']);
1574 return api_format_data('statuses', $type, $data);
1577 /// @TODO move to top of file or somewhere better
1578 api_register_func('api/search/tweets', 'api_search', true);
1579 api_register_func('api/search', 'api_search', true);
1582 * Returns the most recent statuses posted by the user and the users they follow.
1584 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1586 * @param string $type Return type (atom, rss, xml, json)
1588 * @return array|string
1589 * @throws BadRequestException
1590 * @throws ForbiddenException
1591 * @throws ImagickException
1592 * @throws InternalServerErrorException
1593 * @throws UnauthorizedException
1594 * @todo Optional parameters
1595 * @todo Add reply info
1597 function api_statuses_home_timeline($type)
1600 $user_info = api_get_user($a);
1602 if (api_user() === false || $user_info === false) {
1603 throw new ForbiddenException();
1606 unset($_REQUEST["user_id"]);
1607 unset($_GET["user_id"]);
1609 unset($_REQUEST["screen_name"]);
1610 unset($_GET["screen_name"]);
1612 // get last network messages
1615 $count = $_REQUEST['count'] ?? 20;
1616 $page = $_REQUEST['page']?? 0;
1617 $since_id = $_REQUEST['since_id'] ?? 0;
1618 $max_id = $_REQUEST['max_id'] ?? 0;
1619 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1620 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1622 $start = max(0, ($page - 1) * $count);
1624 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1625 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1628 $condition[0] .= " AND `item`.`id` <= ?";
1629 $condition[] = $max_id;
1631 if ($exclude_replies) {
1632 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1634 if ($conversation_id > 0) {
1635 $condition[0] .= " AND `item`.`parent` = ?";
1636 $condition[] = $conversation_id;
1639 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1640 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1642 $items = Item::inArray($statuses);
1644 $ret = api_format_items($items, $user_info, false, $type);
1646 // Set all posts from the query above to seen
1648 foreach ($items as $item) {
1649 $idarray[] = intval($item["id"]);
1652 if (!empty($idarray)) {
1653 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1655 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1661 $data = ['status' => $ret];
1666 $data = api_rss_extra($a, $data, $user_info);
1670 return api_format_data("statuses", $type, $data);
1674 /// @TODO move to top of file or somewhere better
1675 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1676 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1679 * Returns the most recent statuses from public users.
1681 * @param string $type Return type (atom, rss, xml, json)
1683 * @return array|string
1684 * @throws BadRequestException
1685 * @throws ForbiddenException
1686 * @throws ImagickException
1687 * @throws InternalServerErrorException
1688 * @throws UnauthorizedException
1690 function api_statuses_public_timeline($type)
1693 $user_info = api_get_user($a);
1695 if (api_user() === false || $user_info === false) {
1696 throw new ForbiddenException();
1699 // get last network messages
1702 $count = $_REQUEST['count'] ?? 20;
1703 $page = $_REQUEST['page'] ?? 1;
1704 $since_id = $_REQUEST['since_id'] ?? 0;
1705 $max_id = $_REQUEST['max_id'] ?? 0;
1706 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1707 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1709 $start = max(0, ($page - 1) * $count);
1711 if ($exclude_replies && !$conversation_id) {
1712 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1713 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1716 $condition[0] .= " AND `thread`.`iid` <= ?";
1717 $condition[] = $max_id;
1720 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1721 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1723 $r = Item::inArray($statuses);
1725 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1726 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1729 $condition[0] .= " AND `item`.`id` <= ?";
1730 $condition[] = $max_id;
1732 if ($conversation_id > 0) {
1733 $condition[0] .= " AND `item`.`parent` = ?";
1734 $condition[] = $conversation_id;
1737 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1738 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1740 $r = Item::inArray($statuses);
1743 $ret = api_format_items($r, $user_info, false, $type);
1747 $data = ['status' => $ret];
1752 $data = api_rss_extra($a, $data, $user_info);
1756 return api_format_data("statuses", $type, $data);
1759 /// @TODO move to top of file or somewhere better
1760 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1763 * Returns the most recent statuses posted by users this node knows about.
1765 * @brief Returns the list of public federated posts this node knows about
1767 * @param string $type Return format: json, xml, atom, rss
1768 * @return array|string
1769 * @throws BadRequestException
1770 * @throws ForbiddenException
1771 * @throws ImagickException
1772 * @throws InternalServerErrorException
1773 * @throws UnauthorizedException
1775 function api_statuses_networkpublic_timeline($type)
1778 $user_info = api_get_user($a);
1780 if (api_user() === false || $user_info === false) {
1781 throw new ForbiddenException();
1784 $since_id = $_REQUEST['since_id'] ?? 0;
1785 $max_id = $_REQUEST['max_id'] ?? 0;
1788 $count = $_REQUEST['count'] ?? 20;
1789 $page = $_REQUEST['page'] ?? 1;
1791 $start = max(0, ($page - 1) * $count);
1793 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1794 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1797 $condition[0] .= " AND `thread`.`iid` <= ?";
1798 $condition[] = $max_id;
1801 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1802 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1804 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1808 $data = ['status' => $ret];
1813 $data = api_rss_extra($a, $data, $user_info);
1817 return api_format_data("statuses", $type, $data);
1820 /// @TODO move to top of file or somewhere better
1821 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1824 * Returns a single status.
1826 * @param string $type Return type (atom, rss, xml, json)
1828 * @return array|string
1829 * @throws BadRequestException
1830 * @throws ForbiddenException
1831 * @throws ImagickException
1832 * @throws InternalServerErrorException
1833 * @throws UnauthorizedException
1834 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1836 function api_statuses_show($type)
1839 $user_info = api_get_user($a);
1841 if (api_user() === false || $user_info === false) {
1842 throw new ForbiddenException();
1846 $id = intval($a->argv[3] ?? 0);
1849 $id = intval($_REQUEST['id'] ?? 0);
1854 $id = intval($a->argv[4] ?? 0);
1857 Logger::log('API: api_statuses_show: ' . $id);
1859 $conversation = !empty($_REQUEST['conversation']);
1861 // try to fetch the item for the local user - or the public item, if there is no local one
1862 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1863 if (!DBA::isResult($uri_item)) {
1864 throw new BadRequestException("There is no status with this id.");
1867 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1868 if (!DBA::isResult($item)) {
1869 throw new BadRequestException("There is no status with this id.");
1874 if ($conversation) {
1875 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1876 $params = ['order' => ['id' => true]];
1878 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1882 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1884 /// @TODO How about copying this to above methods which don't check $r ?
1885 if (!DBA::isResult($statuses)) {
1886 throw new BadRequestException("There is no status with this id.");
1889 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1891 if ($conversation) {
1892 $data = ['status' => $ret];
1893 return api_format_data("statuses", $type, $data);
1895 $data = ['status' => $ret[0]];
1896 return api_format_data("status", $type, $data);
1900 /// @TODO move to top of file or somewhere better
1901 api_register_func('api/statuses/show', 'api_statuses_show', true);
1905 * @param string $type Return type (atom, rss, xml, json)
1907 * @return array|string
1908 * @throws BadRequestException
1909 * @throws ForbiddenException
1910 * @throws ImagickException
1911 * @throws InternalServerErrorException
1912 * @throws UnauthorizedException
1913 * @todo nothing to say?
1915 function api_conversation_show($type)
1918 $user_info = api_get_user($a);
1920 if (api_user() === false || $user_info === false) {
1921 throw new ForbiddenException();
1925 $id = intval($a->argv[3] ?? 0);
1926 $since_id = intval($_REQUEST['since_id'] ?? 0);
1927 $max_id = intval($_REQUEST['max_id'] ?? 0);
1928 $count = intval($_REQUEST['count'] ?? 20);
1929 $page = intval($_REQUEST['page'] ?? 1);
1931 $start = max(0, ($page - 1) * $count);
1934 $id = intval($_REQUEST['id'] ?? 0);
1939 $id = intval($a->argv[4] ?? 0);
1942 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1944 // try to fetch the item for the local user - or the public item, if there is no local one
1945 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1946 if (!DBA::isResult($item)) {
1947 throw new BadRequestException("There is no status with this id.");
1950 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1951 if (!DBA::isResult($parent)) {
1952 throw new BadRequestException("There is no status with this id.");
1955 $id = $parent['id'];
1957 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1958 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1961 $condition[0] .= " AND `item`.`id` <= ?";
1962 $condition[] = $max_id;
1965 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1966 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1968 if (!DBA::isResult($statuses)) {
1969 throw new BadRequestException("There is no status with id $id.");
1972 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1974 $data = ['status' => $ret];
1975 return api_format_data("statuses", $type, $data);
1978 /// @TODO move to top of file or somewhere better
1979 api_register_func('api/conversation/show', 'api_conversation_show', true);
1980 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1985 * @param string $type Return type (atom, rss, xml, json)
1987 * @return array|string
1988 * @throws BadRequestException
1989 * @throws ForbiddenException
1990 * @throws ImagickException
1991 * @throws InternalServerErrorException
1992 * @throws UnauthorizedException
1993 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1995 function api_statuses_repeat($type)
2001 if (api_user() === false) {
2002 throw new ForbiddenException();
2008 $id = intval($a->argv[3] ?? 0);
2011 $id = intval($_REQUEST['id'] ?? 0);
2016 $id = intval($a->argv[4] ?? 0);
2019 Logger::log('API: api_statuses_repeat: '.$id);
2021 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2022 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2024 if (DBA::isResult($item) && $item['body'] != "") {
2025 if (strpos($item['body'], "[/share]") !== false) {
2026 $pos = strpos($item['body'], "[share");
2027 $post = substr($item['body'], $pos);
2029 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2031 $post .= $item['body'];
2032 $post .= "[/share]";
2034 $_REQUEST['body'] = $post;
2035 $_REQUEST['profile_uid'] = api_user();
2036 $_REQUEST['api_source'] = true;
2038 if (empty($_REQUEST['source'])) {
2039 $_REQUEST["source"] = api_source();
2042 $item_id = item_post($a);
2044 throw new ForbiddenException();
2047 // output the post that we just posted.
2049 return api_status_show($type, $item_id);
2052 /// @TODO move to top of file or somewhere better
2053 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2056 * Destroys a specific status.
2058 * @param string $type Return type (atom, rss, xml, json)
2060 * @return array|string
2061 * @throws BadRequestException
2062 * @throws ForbiddenException
2063 * @throws ImagickException
2064 * @throws InternalServerErrorException
2065 * @throws UnauthorizedException
2066 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2068 function api_statuses_destroy($type)
2072 if (api_user() === false) {
2073 throw new ForbiddenException();
2079 $id = intval($a->argv[3] ?? 0);
2082 $id = intval($_REQUEST['id'] ?? 0);
2087 $id = intval($a->argv[4] ?? 0);
2090 Logger::log('API: api_statuses_destroy: '.$id);
2092 $ret = api_statuses_show($type);
2094 Item::deleteForUser(['id' => $id], api_user());
2099 /// @TODO move to top of file or somewhere better
2100 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2103 * Returns the most recent mentions.
2105 * @param string $type Return type (atom, rss, xml, json)
2107 * @return array|string
2108 * @throws BadRequestException
2109 * @throws ForbiddenException
2110 * @throws ImagickException
2111 * @throws InternalServerErrorException
2112 * @throws UnauthorizedException
2113 * @see http://developer.twitter.com/doc/get/statuses/mentions
2115 function api_statuses_mentions($type)
2118 $user_info = api_get_user($a);
2120 if (api_user() === false || $user_info === false) {
2121 throw new ForbiddenException();
2124 unset($_REQUEST["user_id"]);
2125 unset($_GET["user_id"]);
2127 unset($_REQUEST["screen_name"]);
2128 unset($_GET["screen_name"]);
2130 // get last network messages
2133 $since_id = $_REQUEST['since_id'] ?? 0;
2134 $max_id = $_REQUEST['max_id'] ?? 0;
2135 $count = $_REQUEST['count'] ?? 20;
2136 $page = $_REQUEST['page'] ?? 1;
2138 $start = max(0, ($page - 1) * $count);
2140 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2141 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2142 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2145 $condition[0] .= " AND `item`.`id` <= ?";
2146 $condition[] = $max_id;
2149 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2150 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2152 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2154 $data = ['status' => $ret];
2159 $data = api_rss_extra($a, $data, $user_info);
2163 return api_format_data("statuses", $type, $data);
2166 /// @TODO move to top of file or somewhere better
2167 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2168 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2171 * Returns the most recent statuses posted by the user.
2173 * @brief Returns a user's public timeline
2175 * @param string $type Either "json" or "xml"
2176 * @return string|array
2177 * @throws BadRequestException
2178 * @throws ForbiddenException
2179 * @throws ImagickException
2180 * @throws InternalServerErrorException
2181 * @throws UnauthorizedException
2182 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2184 function api_statuses_user_timeline($type)
2187 $user_info = api_get_user($a);
2189 if (api_user() === false || $user_info === false) {
2190 throw new ForbiddenException();
2194 "api_statuses_user_timeline: api_user: ". api_user() .
2195 "\nuser_info: ".print_r($user_info, true) .
2196 "\n_REQUEST: ".print_r($_REQUEST, true),
2200 $since_id = $_REQUEST['since_id'] ?? 0;
2201 $max_id = $_REQUEST['max_id'] ?? 0;
2202 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2203 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2206 $count = $_REQUEST['count'] ?? 20;
2207 $page = $_REQUEST['page'] ?? 1;
2209 $start = max(0, ($page - 1) * $count);
2211 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2212 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2214 if ($user_info['self'] == 1) {
2215 $condition[0] .= ' AND `item`.`wall` ';
2218 if ($exclude_replies) {
2219 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2222 if ($conversation_id > 0) {
2223 $condition[0] .= " AND `item`.`parent` = ?";
2224 $condition[] = $conversation_id;
2228 $condition[0] .= " AND `item`.`id` <= ?";
2229 $condition[] = $max_id;
2232 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2233 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2235 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2239 $data = ['status' => $ret];
2244 $data = api_rss_extra($a, $data, $user_info);
2248 return api_format_data("statuses", $type, $data);
2251 /// @TODO move to top of file or somewhere better
2252 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2255 * Star/unstar an item.
2256 * param: id : id of the item
2258 * @param string $type Return type (atom, rss, xml, json)
2260 * @return array|string
2261 * @throws BadRequestException
2262 * @throws ForbiddenException
2263 * @throws ImagickException
2264 * @throws InternalServerErrorException
2265 * @throws UnauthorizedException
2266 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2268 function api_favorites_create_destroy($type)
2272 if (api_user() === false) {
2273 throw new ForbiddenException();
2276 // for versioned api.
2277 /// @TODO We need a better global soluton
2278 $action_argv_id = 2;
2279 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2280 $action_argv_id = 3;
2283 if ($a->argc <= $action_argv_id) {
2284 throw new BadRequestException("Invalid request.");
2286 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2287 if ($a->argc == $action_argv_id + 2) {
2288 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2290 $itemid = intval($_REQUEST['id'] ?? 0);
2293 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2295 if (!DBA::isResult($item)) {
2296 throw new BadRequestException("Invalid item.");
2301 $item['starred'] = 1;
2304 $item['starred'] = 0;
2307 throw new BadRequestException("Invalid action ".$action);
2310 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2313 throw new InternalServerErrorException("DB error");
2317 $user_info = api_get_user($a);
2318 $rets = api_format_items([$item], $user_info, false, $type);
2321 $data = ['status' => $ret];
2326 $data = api_rss_extra($a, $data, $user_info);
2330 return api_format_data("status", $type, $data);
2333 /// @TODO move to top of file or somewhere better
2334 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2335 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2338 * Returns the most recent favorite statuses.
2340 * @param string $type Return type (atom, rss, xml, json)
2342 * @return string|array
2343 * @throws BadRequestException
2344 * @throws ForbiddenException
2345 * @throws ImagickException
2346 * @throws InternalServerErrorException
2347 * @throws UnauthorizedException
2349 function api_favorites($type)
2354 $user_info = api_get_user($a);
2356 if (api_user() === false || $user_info === false) {
2357 throw new ForbiddenException();
2362 // in friendica starred item are private
2363 // return favorites only for self
2364 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2366 if ($user_info['self'] == 0) {
2370 $since_id = $_REQUEST['since_id'] ?? 0;
2371 $max_id = $_REQUEST['max_id'] ?? 0;
2372 $count = $_GET['count'] ?? 20;
2373 $page = $_REQUEST['page'] ?? 1;
2375 $start = max(0, ($page - 1) * $count);
2377 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2378 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2380 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2383 $condition[0] .= " AND `item`.`id` <= ?";
2384 $condition[] = $max_id;
2387 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2389 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2394 $data = ['status' => $ret];
2399 $data = api_rss_extra($a, $data, $user_info);
2403 return api_format_data("statuses", $type, $data);
2406 /// @TODO move to top of file or somewhere better
2407 api_register_func('api/favorites', 'api_favorites', true);
2411 * @param array $item
2412 * @param array $recipient
2413 * @param array $sender
2416 * @throws InternalServerErrorException
2418 function api_format_messages($item, $recipient, $sender)
2420 // standard meta information
2422 'id' => $item['id'],
2423 'sender_id' => $sender['id'],
2425 'recipient_id' => $recipient['id'],
2426 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2427 'sender_screen_name' => $sender['screen_name'],
2428 'recipient_screen_name' => $recipient['screen_name'],
2429 'sender' => $sender,
2430 'recipient' => $recipient,
2432 'friendica_seen' => $item['seen'] ?? 0,
2433 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2436 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2437 if (isset($ret['sender']['uid'])) {
2438 unset($ret['sender']['uid']);
2440 if (isset($ret['sender']['self'])) {
2441 unset($ret['sender']['self']);
2443 if (isset($ret['recipient']['uid'])) {
2444 unset($ret['recipient']['uid']);
2446 if (isset($ret['recipient']['self'])) {
2447 unset($ret['recipient']['self']);
2450 //don't send title to regular StatusNET requests to avoid confusing these apps
2451 if (!empty($_GET['getText'])) {
2452 $ret['title'] = $item['title'];
2453 if ($_GET['getText'] == 'html') {
2454 $ret['text'] = BBCode::convert($item['body'], false);
2455 } elseif ($_GET['getText'] == 'plain') {
2456 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2459 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2461 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2462 unset($ret['sender']);
2463 unset($ret['recipient']);
2471 * @param array $item
2474 * @throws InternalServerErrorException
2476 function api_convert_item($item)
2478 $body = $item['body'];
2479 $attachments = api_get_attachments($body);
2481 // Workaround for ostatus messages where the title is identically to the body
2482 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2483 $statusbody = trim(HTML::toPlaintext($html, 0));
2485 // handle data: images
2486 $statusbody = api_format_items_embeded_images($item, $statusbody);
2488 $statustitle = trim($item['title']);
2490 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2491 $statustext = trim($statusbody);
2493 $statustext = trim($statustitle."\n\n".$statusbody);
2496 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2497 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2500 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2502 // Workaround for clients with limited HTML parser functionality
2503 $search = ["<br>", "<blockquote>", "</blockquote>",
2504 "<h1>", "</h1>", "<h2>", "</h2>",
2505 "<h3>", "</h3>", "<h4>", "</h4>",
2506 "<h5>", "</h5>", "<h6>", "</h6>"];
2507 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2508 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2509 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2510 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2511 $statushtml = str_replace($search, $replace, $statushtml);
2513 if ($item['title'] != "") {
2514 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2518 $oldtext = $statushtml;
2519 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2520 } while ($oldtext != $statushtml);
2522 if (substr($statushtml, 0, 4) == '<br>') {
2523 $statushtml = substr($statushtml, 4);
2526 if (substr($statushtml, 0, -4) == '<br>') {
2527 $statushtml = substr($statushtml, -4);
2530 // feeds without body should contain the link
2531 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2532 $statushtml .= BBCode::convert($item['plink']);
2535 $entities = api_get_entitities($statustext, $body);
2538 "text" => $statustext,
2539 "html" => $statushtml,
2540 "attachments" => $attachments,
2541 "entities" => $entities
2547 * @param string $body
2550 * @throws InternalServerErrorException
2552 function api_get_attachments(&$body)
2555 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2557 $URLSearchString = "^\[\]";
2558 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2566 foreach ($images[1] as $image) {
2567 $imagedata = Image::getInfoFromURL($image);
2570 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2574 if (strstr($_SERVER['HTTP_USER_AGENT'] ?? '', 'AndStatus')) {
2575 foreach ($images[0] as $orig) {
2576 $body = str_replace($orig, "", $body);
2580 return $attachments;
2585 * @param string $text
2586 * @param string $bbcode
2589 * @throws InternalServerErrorException
2590 * @todo Links at the first character of the post
2592 function api_get_entitities(&$text, $bbcode)
2594 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2596 if ($include_entities != "true") {
2597 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2599 foreach ($images[1] as $image) {
2600 $replace = ProxyUtils::proxifyUrl($image);
2601 $text = str_replace($image, $replace, $text);
2606 $bbcode = BBCode::cleanPictureLinks($bbcode);
2608 // Change pure links in text to bbcode uris
2609 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2612 $entities["hashtags"] = [];
2613 $entities["symbols"] = [];
2614 $entities["urls"] = [];
2615 $entities["user_mentions"] = [];
2617 $URLSearchString = "^\[\]";
2619 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2621 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2622 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2623 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2625 $bbcode = preg_replace(
2626 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2627 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2630 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2632 $bbcode = preg_replace(
2633 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2634 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2637 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2639 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2641 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2642 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2645 foreach ($urls[1] as $id => $url) {
2646 //$start = strpos($text, $url, $offset);
2647 $start = iconv_strpos($text, $url, 0, "UTF-8");
2648 if (!($start === false)) {
2649 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2653 ksort($ordered_urls);
2656 //foreach ($urls[1] AS $id=>$url) {
2657 foreach ($ordered_urls as $url) {
2658 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2659 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2661 $display_url = $url["title"];
2663 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2664 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2666 if (strlen($display_url) > 26) {
2667 $display_url = substr($display_url, 0, 25)."…";
2671 //$start = strpos($text, $url, $offset);
2672 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2673 if (!($start === false)) {
2674 $entities["urls"][] = ["url" => $url["url"],
2675 "expanded_url" => $url["url"],
2676 "display_url" => $display_url,
2677 "indices" => [$start, $start+strlen($url["url"])]];
2678 $offset = $start + 1;
2682 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2683 $ordered_images = [];
2684 foreach ($images as $image) {
2685 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2686 if (!($start === false)) {
2687 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2691 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2692 foreach ($images[1] as $image) {
2693 $start = iconv_strpos($text, $image, 0, "UTF-8");
2694 if (!($start === false)) {
2695 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2698 //$entities["media"] = array();
2701 foreach ($ordered_images as $image) {
2702 $url = $image['url'];
2703 $ext_alt_text = $image['alt'];
2705 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2706 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2708 if (strlen($display_url) > 26) {
2709 $display_url = substr($display_url, 0, 25)."…";
2712 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2713 if (!($start === false)) {
2714 $image = Image::getInfoFromURL($url);
2716 // If image cache is activated, then use the following sizes:
2717 // thumb (150), small (340), medium (600) and large (1024)
2718 if (!Config::get("system", "proxy_disabled")) {
2719 $media_url = ProxyUtils::proxifyUrl($url);
2722 $scale = Image::getScalingDimensions($image[0], $image[1], 150);
2723 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2725 if (($image[0] > 150) || ($image[1] > 150)) {
2726 $scale = Image::getScalingDimensions($image[0], $image[1], 340);
2727 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2730 $scale = Image::getScalingDimensions($image[0], $image[1], 600);
2731 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2733 if (($image[0] > 600) || ($image[1] > 600)) {
2734 $scale = Image::getScalingDimensions($image[0], $image[1], 1024);
2735 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2739 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2742 $entities["media"][] = [
2744 "id_str" => (string) ($start + 1),
2745 "indices" => [$start, $start+strlen($url)],
2746 "media_url" => Strings::normaliseLink($media_url),
2747 "media_url_https" => $media_url,
2749 "display_url" => $display_url,
2750 "expanded_url" => $url,
2751 "ext_alt_text" => $ext_alt_text,
2755 $offset = $start + 1;
2764 * @param array $item
2765 * @param string $text
2769 function api_format_items_embeded_images($item, $text)
2771 $text = preg_replace_callback(
2772 '|data:image/([^;]+)[^=]+=*|m',
2773 function () use ($item) {
2774 return System::baseUrl() . '/display/' . $item['guid'];
2782 * @brief return <a href='url'>name</a> as array
2784 * @param string $txt text
2789 function api_contactlink_to_array($txt)
2792 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2793 if ($r && count($match)==3) {
2795 'name' => $match[2],
2809 * @brief return likes, dislikes and attend status for item
2811 * @param array $item array
2812 * @param string $type Return type (atom, rss, xml, json)
2815 * likes => int count,
2816 * dislikes => int count
2817 * @throws BadRequestException
2818 * @throws ImagickException
2819 * @throws InternalServerErrorException
2820 * @throws UnauthorizedException
2822 function api_format_items_activities($item, $type = "json")
2831 'attendmaybe' => [],
2834 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2835 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2837 while ($parent_item = Item::fetch($ret)) {
2838 // not used as result should be structured like other user data
2839 //builtin_activity_puller($i, $activities);
2841 // get user data and add it to the array of the activity
2842 $user = api_get_user($a, $parent_item['author-id']);
2843 switch ($parent_item['verb']) {
2844 case Activity::LIKE:
2845 $activities['like'][] = $user;
2847 case Activity::DISLIKE:
2848 $activities['dislike'][] = $user;
2850 case Activity::ATTEND:
2851 $activities['attendyes'][] = $user;
2853 case Activity::ATTENDNO:
2854 $activities['attendno'][] = $user;
2856 case Activity::ATTENDMAYBE:
2857 $activities['attendmaybe'][] = $user;
2866 if ($type == "xml") {
2867 $xml_activities = [];
2868 foreach ($activities as $k => $v) {
2869 // change xml element from "like" to "friendica:like"
2870 $xml_activities["friendica:".$k] = $v;
2871 // add user data into xml output
2873 foreach ($v as $user) {
2874 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2877 $activities = $xml_activities;
2885 * @brief return data from profiles
2887 * @param array $profile_row array containing data from db table 'profile'
2889 * @throws InternalServerErrorException
2891 function api_format_items_profiles($profile_row)
2894 'profile_id' => $profile_row['id'],
2895 'profile_name' => $profile_row['profile-name'],
2896 'is_default' => $profile_row['is-default'] ? true : false,
2897 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2898 'profile_photo' => $profile_row['photo'],
2899 'profile_thumb' => $profile_row['thumb'],
2900 'publish' => $profile_row['publish'] ? true : false,
2901 'net_publish' => $profile_row['net-publish'] ? true : false,
2902 'description' => $profile_row['pdesc'],
2903 'date_of_birth' => $profile_row['dob'],
2904 'address' => $profile_row['address'],
2905 'city' => $profile_row['locality'],
2906 'region' => $profile_row['region'],
2907 'postal_code' => $profile_row['postal-code'],
2908 'country' => $profile_row['country-name'],
2909 'hometown' => $profile_row['hometown'],
2910 'gender' => $profile_row['gender'],
2911 'marital' => $profile_row['marital'],
2912 'marital_with' => $profile_row['with'],
2913 'marital_since' => $profile_row['howlong'],
2914 'sexual' => $profile_row['sexual'],
2915 'politic' => $profile_row['politic'],
2916 'religion' => $profile_row['religion'],
2917 'public_keywords' => $profile_row['pub_keywords'],
2918 'private_keywords' => $profile_row['prv_keywords'],
2919 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2920 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2921 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2922 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2923 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2924 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2925 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2926 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2927 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2928 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2929 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2930 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2931 'homepage' => $profile_row['homepage'],
2938 * @brief format items to be returned by api
2940 * @param array $items array of items
2941 * @param array $user_info
2942 * @param bool $filter_user filter items by $user_info
2943 * @param string $type Return type (atom, rss, xml, json)
2945 * @throws BadRequestException
2946 * @throws ImagickException
2947 * @throws InternalServerErrorException
2948 * @throws UnauthorizedException
2950 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2952 $a = BaseObject::getApp();
2956 foreach ((array)$items as $item) {
2957 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2959 // Look if the posts are matching if they should be filtered by user id
2960 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2964 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2973 * @param array $item Item record
2974 * @param string $type Return format (atom, rss, xml, json)
2975 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2976 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2977 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2978 * @return array API-formatted status
2979 * @throws BadRequestException
2980 * @throws ImagickException
2981 * @throws InternalServerErrorException
2982 * @throws UnauthorizedException
2984 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2986 $a = BaseObject::getApp();
2988 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2989 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2992 localize_item($item);
2994 $in_reply_to = api_in_reply_to($item);
2996 $converted = api_convert_item($item);
2998 if ($type == "xml") {
2999 $geo = "georss:point";
3005 'text' => $converted["text"],
3006 'truncated' => false,
3007 'created_at'=> api_date($item['created']),
3008 'in_reply_to_status_id' => $in_reply_to['status_id'],
3009 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3010 'source' => (($item['app']) ? $item['app'] : 'web'),
3011 'id' => intval($item['id']),
3012 'id_str' => (string) intval($item['id']),
3013 'in_reply_to_user_id' => $in_reply_to['user_id'],
3014 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3015 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3017 'favorited' => $item['starred'] ? true : false,
3018 'user' => $status_user,
3019 'friendica_author' => $author_user,
3020 'friendica_owner' => $owner_user,
3021 'friendica_private' => $item['private'] == 1,
3022 //'entities' => NULL,
3023 'statusnet_html' => $converted["html"],
3024 'statusnet_conversation_id' => $item['parent'],
3025 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3026 'friendica_activities' => api_format_items_activities($item, $type),
3027 'friendica_title' => $item['title'],
3028 'friendica_html' => BBCode::convert($item['body'], false)
3031 if (count($converted["attachments"]) > 0) {
3032 $status["attachments"] = $converted["attachments"];
3035 if (count($converted["entities"]) > 0) {
3036 $status["entities"] = $converted["entities"];
3039 if ($status["source"] == 'web') {
3040 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3041 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3042 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3045 $retweeted_item = [];
3048 if ($item["id"] == $item["parent"]) {
3049 $body = $item['body'];
3050 $retweeted_item = api_share_as_retweet($item);
3051 if ($body != $item['body']) {
3052 $quoted_item = $retweeted_item;
3053 $retweeted_item = [];
3057 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3058 $announce = api_get_announce($item);
3059 if (!empty($announce)) {
3060 $retweeted_item = $item;
3062 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3066 if (!empty($quoted_item)) {
3067 $conv_quoted = api_convert_item($quoted_item);
3068 $quoted_status = $status;
3069 unset($quoted_status['friendica_author']);
3070 unset($quoted_status['friendica_owner']);
3071 unset($quoted_status['friendica_activities']);
3072 unset($quoted_status['friendica_private']);
3073 unset($quoted_status['statusnet_conversation_id']);
3074 $quoted_status['text'] = $conv_quoted['text'];
3075 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3077 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3078 } catch (BadRequestException $e) {
3079 // user not found. should be found?
3080 /// @todo check if the user should be always found
3081 $quoted_status["user"] = [];
3085 if (!empty($retweeted_item)) {
3086 $retweeted_status = $status;
3087 unset($retweeted_status['friendica_author']);
3088 unset($retweeted_status['friendica_owner']);
3089 unset($retweeted_status['friendica_activities']);
3090 unset($retweeted_status['friendica_private']);
3091 unset($retweeted_status['statusnet_conversation_id']);
3092 $status['user'] = $status['friendica_owner'];
3094 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3095 } catch (BadRequestException $e) {
3096 // user not found. should be found?
3097 /// @todo check if the user should be always found
3098 $retweeted_status["user"] = [];
3101 $rt_converted = api_convert_item($retweeted_item);
3103 $retweeted_status['text'] = $rt_converted["text"];
3104 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3105 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3107 if (!empty($quoted_status)) {
3108 $retweeted_status['quoted_status'] = $quoted_status;
3111 $status['friendica_author'] = $retweeted_status['user'];
3112 $status['retweeted_status'] = $retweeted_status;
3113 } elseif (!empty($quoted_status)) {
3114 $root_status = api_convert_item($item);
3116 $status['text'] = $root_status["text"];
3117 $status['statusnet_html'] = $root_status["html"];
3118 $status['quoted_status'] = $quoted_status;
3121 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3122 unset($status["user"]["uid"]);
3123 unset($status["user"]["self"]);
3125 if ($item["coord"] != "") {
3126 $coords = explode(' ', $item["coord"]);
3127 if (count($coords) == 2) {
3128 if ($type == "json") {
3129 $status["geo"] = ['type' => 'Point',
3130 'coordinates' => [(float) $coords[0],
3131 (float) $coords[1]]];
3132 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3133 $status["georss:point"] = $item["coord"];
3142 * Returns the remaining number of API requests available to the user before the API limit is reached.
3144 * @param string $type Return type (atom, rss, xml, json)
3146 * @return array|string
3149 function api_account_rate_limit_status($type)
3151 if ($type == "xml") {
3153 'remaining-hits' => '150',
3154 '@attributes' => ["type" => "integer"],
3155 'hourly-limit' => '150',
3156 '@attributes2' => ["type" => "integer"],
3157 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3158 '@attributes3' => ["type" => "datetime"],
3159 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3160 '@attributes4' => ["type" => "integer"],
3164 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3165 'remaining_hits' => '150',
3166 'hourly_limit' => '150',
3167 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3171 return api_format_data('hash', $type, ['hash' => $hash]);
3174 /// @TODO move to top of file or somewhere better
3175 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3178 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3180 * @param string $type Return type (atom, rss, xml, json)
3182 * @return array|string
3184 function api_help_test($type)
3186 if ($type == 'xml') {
3192 return api_format_data('ok', $type, ["ok" => $ok]);
3195 /// @TODO move to top of file or somewhere better
3196 api_register_func('api/help/test', 'api_help_test', false);
3199 * Returns all lists the user subscribes to.
3201 * @param string $type Return type (atom, rss, xml, json)
3203 * @return array|string
3204 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3206 function api_lists_list($type)
3209 /// @TODO $ret is not filled here?
3210 return api_format_data('lists', $type, ["lists_list" => $ret]);
3213 /// @TODO move to top of file or somewhere better
3214 api_register_func('api/lists/list', 'api_lists_list', true);
3215 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3218 * Returns all groups the user owns.
3220 * @param string $type Return type (atom, rss, xml, json)
3222 * @return array|string
3223 * @throws BadRequestException
3224 * @throws ForbiddenException
3225 * @throws ImagickException
3226 * @throws InternalServerErrorException
3227 * @throws UnauthorizedException
3228 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3230 function api_lists_ownerships($type)
3234 if (api_user() === false) {
3235 throw new ForbiddenException();
3239 $user_info = api_get_user($a);
3240 $uid = $user_info['uid'];
3242 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3244 // loop through all groups
3246 foreach ($groups as $group) {
3247 if ($group['visible']) {
3253 'name' => $group['name'],
3254 'id' => intval($group['id']),
3255 'id_str' => (string) $group['id'],
3256 'user' => $user_info,
3260 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3263 /// @TODO move to top of file or somewhere better
3264 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3267 * Returns recent statuses from users in the specified group.
3269 * @param string $type Return type (atom, rss, xml, json)
3271 * @return array|string
3272 * @throws BadRequestException
3273 * @throws ForbiddenException
3274 * @throws ImagickException
3275 * @throws InternalServerErrorException
3276 * @throws UnauthorizedException
3277 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3279 function api_lists_statuses($type)
3283 $user_info = api_get_user($a);
3284 if (api_user() === false || $user_info === false) {
3285 throw new ForbiddenException();
3288 unset($_REQUEST["user_id"]);
3289 unset($_GET["user_id"]);
3291 unset($_REQUEST["screen_name"]);
3292 unset($_GET["screen_name"]);
3294 if (empty($_REQUEST['list_id'])) {
3295 throw new BadRequestException('list_id not specified');
3299 $count = $_REQUEST['count'] ?? 20;
3300 $page = $_REQUEST['page'] ?? 1;
3301 $since_id = $_REQUEST['since_id'] ?? 0;
3302 $max_id = $_REQUEST['max_id'] ?? 0;
3303 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3304 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3306 $start = max(0, ($page - 1) * $count);
3308 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3309 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3312 $condition[0] .= " AND `item`.`id` <= ?";
3313 $condition[] = $max_id;
3315 if ($exclude_replies > 0) {
3316 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3318 if ($conversation_id > 0) {
3319 $condition[0] .= " AND `item`.`parent` = ?";
3320 $condition[] = $conversation_id;
3323 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3324 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3326 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3328 $data = ['status' => $items];
3333 $data = api_rss_extra($a, $data, $user_info);
3337 return api_format_data("statuses", $type, $data);
3340 /// @TODO move to top of file or somewhere better
3341 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3344 * Considers friends and followers lists to be private and won't return
3345 * anything if any user_id parameter is passed.
3347 * @brief Returns either the friends of the follower list
3349 * @param string $qtype Either "friends" or "followers"
3350 * @return boolean|array
3351 * @throws BadRequestException
3352 * @throws ForbiddenException
3353 * @throws ImagickException
3354 * @throws InternalServerErrorException
3355 * @throws UnauthorizedException
3357 function api_statuses_f($qtype)
3361 if (api_user() === false) {
3362 throw new ForbiddenException();
3366 $count = $_GET['count'] ?? 20;
3367 $page = $_GET['page'] ?? 1;
3369 $start = max(0, ($page - 1) * $count);
3371 $user_info = api_get_user($a);
3373 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3374 /* this is to stop Hotot to load friends multiple times
3375 * I'm not sure if I'm missing return something or
3376 * is a bug in hotot. Workaround, meantime
3380 return array('$users' => $ret);*/
3385 if ($qtype == 'friends') {
3386 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3387 } elseif ($qtype == 'followers') {
3388 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3391 // friends and followers only for self
3392 if ($user_info['self'] == 0) {
3393 $sql_extra = " AND false ";
3396 if ($qtype == 'blocks') {
3397 $sql_filter = 'AND `blocked` AND NOT `pending`';
3398 } elseif ($qtype == 'incoming') {
3399 $sql_filter = 'AND `pending`';
3401 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3419 foreach ($r as $cid) {
3420 $user = api_get_user($a, $cid['nurl']);
3421 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3422 unset($user["uid"]);
3423 unset($user["self"]);
3430 return ['user' => $ret];
3435 * Returns the user's friends.
3437 * @brief Returns the list of friends of the provided user
3439 * @deprecated By Twitter API in favor of friends/list
3441 * @param string $type Either "json" or "xml"
3442 * @return boolean|string|array
3443 * @throws BadRequestException
3444 * @throws ForbiddenException
3446 function api_statuses_friends($type)
3448 $data = api_statuses_f("friends");
3449 if ($data === false) {
3452 return api_format_data("users", $type, $data);
3456 * Returns the user's followers.
3458 * @brief Returns the list of followers of the provided user
3460 * @deprecated By Twitter API in favor of friends/list
3462 * @param string $type Either "json" or "xml"
3463 * @return boolean|string|array
3464 * @throws BadRequestException
3465 * @throws ForbiddenException
3467 function api_statuses_followers($type)
3469 $data = api_statuses_f("followers");
3470 if ($data === false) {
3473 return api_format_data("users", $type, $data);
3476 /// @TODO move to top of file or somewhere better
3477 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3478 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3481 * Returns the list of blocked users
3483 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3485 * @param string $type Either "json" or "xml"
3487 * @return boolean|string|array
3488 * @throws BadRequestException
3489 * @throws ForbiddenException
3491 function api_blocks_list($type)
3493 $data = api_statuses_f('blocks');
3494 if ($data === false) {
3497 return api_format_data("users", $type, $data);
3500 /// @TODO move to top of file or somewhere better
3501 api_register_func('api/blocks/list', 'api_blocks_list', true);
3504 * Returns the list of pending users IDs
3506 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3508 * @param string $type Either "json" or "xml"
3510 * @return boolean|string|array
3511 * @throws BadRequestException
3512 * @throws ForbiddenException
3514 function api_friendships_incoming($type)
3516 $data = api_statuses_f('incoming');
3517 if ($data === false) {
3522 foreach ($data['user'] as $user) {
3523 $ids[] = $user['id'];
3526 return api_format_data("ids", $type, ['id' => $ids]);
3529 /// @TODO move to top of file or somewhere better
3530 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3533 * Returns the instance's configuration information.
3535 * @param string $type Return type (atom, rss, xml, json)
3537 * @return array|string
3538 * @throws InternalServerErrorException
3540 function api_statusnet_config($type)
3544 $name = Config::get('config', 'sitename');
3545 $server = $a->getHostName();
3546 $logo = System::baseUrl() . '/images/friendica-64.png';
3547 $email = Config::get('config', 'admin_email');
3548 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3549 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3550 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3551 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3552 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3555 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3556 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3557 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3558 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3559 'shorturllength' => '30',
3561 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3562 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3563 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3564 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3569 return api_format_data('config', $type, ['config' => $config]);
3572 /// @TODO move to top of file or somewhere better
3573 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3574 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3578 * @param string $type Return type (atom, rss, xml, json)
3580 * @return array|string
3582 function api_statusnet_version($type)
3585 $fake_statusnet_version = "0.9.7";
3587 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3590 /// @TODO move to top of file or somewhere better
3591 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3592 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3596 * @param string $type Return type (atom, rss, xml, json)
3598 * @return array|string|void
3599 * @throws BadRequestException
3600 * @throws ForbiddenException
3601 * @throws ImagickException
3602 * @throws InternalServerErrorException
3603 * @throws UnauthorizedException
3604 * @todo use api_format_data() to return data
3606 function api_ff_ids($type)
3609 throw new ForbiddenException();
3616 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3619 "SELECT `pcontact`.`id` FROM `contact`
3620 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3621 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3624 if (!DBA::isResult($r)) {
3629 foreach ($r as $rr) {
3630 if ($stringify_ids) {
3633 $ids[] = intval($rr['id']);
3637 return api_format_data("ids", $type, ['id' => $ids]);
3641 * Returns the ID of every user the user is following.
3643 * @param string $type Return type (atom, rss, xml, json)
3645 * @return array|string
3646 * @throws BadRequestException
3647 * @throws ForbiddenException
3648 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3650 function api_friends_ids($type)
3652 return api_ff_ids($type);
3656 * Returns the ID of every user following the user.
3658 * @param string $type Return type (atom, rss, xml, json)
3660 * @return array|string
3661 * @throws BadRequestException
3662 * @throws ForbiddenException
3663 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3665 function api_followers_ids($type)
3667 return api_ff_ids($type);
3670 /// @TODO move to top of file or somewhere better
3671 api_register_func('api/friends/ids', 'api_friends_ids', true);
3672 api_register_func('api/followers/ids', 'api_followers_ids', true);
3675 * Sends a new direct message.
3677 * @param string $type Return type (atom, rss, xml, json)
3679 * @return array|string
3680 * @throws BadRequestException
3681 * @throws ForbiddenException
3682 * @throws ImagickException
3683 * @throws InternalServerErrorException
3684 * @throws NotFoundException
3685 * @throws UnauthorizedException
3686 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3688 function api_direct_messages_new($type)
3692 if (api_user() === false) {
3693 throw new ForbiddenException();
3696 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3700 $sender = api_get_user($a);
3703 if (!empty($_POST['screen_name'])) {
3705 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3707 DBA::escape($_POST['screen_name'])
3710 if (DBA::isResult($r)) {
3711 // Selecting the id by priority, friendica first
3712 api_best_nickname($r);
3714 $recipient = api_get_user($a, $r[0]['nurl']);
3717 $recipient = api_get_user($a, $_POST['user_id']);
3720 if (empty($recipient)) {
3721 throw new NotFoundException('Recipient not found');
3725 if (!empty($_REQUEST['replyto'])) {
3727 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3729 intval($_REQUEST['replyto'])
3731 $replyto = $r[0]['parent-uri'];
3732 $sub = $r[0]['title'];
3734 if (!empty($_REQUEST['title'])) {
3735 $sub = $_REQUEST['title'];
3737 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3741 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3744 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3745 $ret = api_format_messages($r[0], $recipient, $sender);
3747 $ret = ["error"=>$id];
3750 $data = ['direct_message'=>$ret];
3756 $data = api_rss_extra($a, $data, $sender);
3760 return api_format_data("direct-messages", $type, $data);
3763 /// @TODO move to top of file or somewhere better
3764 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3767 * Destroys a direct message.
3769 * @brief delete a direct_message from mail table through api
3771 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3772 * @return string|array
3773 * @throws BadRequestException
3774 * @throws ForbiddenException
3775 * @throws ImagickException
3776 * @throws InternalServerErrorException
3777 * @throws UnauthorizedException
3778 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3780 function api_direct_messages_destroy($type)
3784 if (api_user() === false) {
3785 throw new ForbiddenException();
3789 $user_info = api_get_user($a);
3791 $id = $_REQUEST['id'] ?? 0;
3793 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3794 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3795 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3797 $uid = $user_info['uid'];
3798 // error if no id or parenturi specified (for clients posting parent-uri as well)
3799 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3800 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3801 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3804 // BadRequestException if no id specified (for clients using Twitter API)
3806 throw new BadRequestException('Message id not specified');
3809 // add parent-uri to sql command if specified by calling app
3810 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3812 // get data of the specified message id
3814 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3819 // error message if specified id is not in database
3820 if (!DBA::isResult($r)) {
3821 if ($verbose == "true") {
3822 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3823 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3825 /// @todo BadRequestException ok for Twitter API clients?
3826 throw new BadRequestException('message id not in database');
3831 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3836 if ($verbose == "true") {
3839 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3840 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3842 $answer = ['result' => 'error', 'message' => 'unknown error'];
3843 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3846 /// @todo return JSON data like Twitter API not yet implemented
3849 /// @TODO move to top of file or somewhere better
3850 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3855 * @brief unfollow contact
3857 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3858 * @return string|array
3859 * @throws BadRequestException
3860 * @throws ForbiddenException
3861 * @throws ImagickException
3862 * @throws InternalServerErrorException
3863 * @throws NotFoundException
3864 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3866 function api_friendships_destroy($type)
3870 if ($uid === false) {
3871 throw new ForbiddenException();
3874 $contact_id = $_REQUEST['user_id'] ?? 0;
3876 if (empty($contact_id)) {
3877 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3878 throw new BadRequestException("no user_id specified");
3881 // Get Contact by given id
3882 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3884 if(!DBA::isResult($contact)) {
3885 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3886 throw new NotFoundException("no contact found to given ID");
3889 $url = $contact["url"];
3891 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3892 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3893 Strings::normaliseLink($url), $url];
3894 $contact = DBA::selectFirst('contact', [], $condition);
3896 if (!DBA::isResult($contact)) {
3897 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3898 throw new NotFoundException("Not following Contact");
3901 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3902 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3903 throw new ExpectationFailedException("Not supported");
3906 $dissolve = ($contact['rel'] == Contact::SHARING);
3908 $owner = User::getOwnerDataById($uid);
3910 Contact::terminateFriendship($owner, $contact, $dissolve);
3913 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3914 throw new NotFoundException("Error Processing Request");
3917 // Sharing-only contacts get deleted as there no relationship any more
3919 Contact::remove($contact['id']);
3921 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3924 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3925 unset($contact["uid"]);
3926 unset($contact["self"]);
3928 // Set screen_name since Twidere requests it
3929 $contact["screen_name"] = $contact["nick"];
3931 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3933 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3937 * @param string $type Return type (atom, rss, xml, json)
3938 * @param string $box
3939 * @param string $verbose
3941 * @return array|string
3942 * @throws BadRequestException
3943 * @throws ForbiddenException
3944 * @throws ImagickException
3945 * @throws InternalServerErrorException
3946 * @throws UnauthorizedException
3948 function api_direct_messages_box($type, $box, $verbose)
3951 if (api_user() === false) {
3952 throw new ForbiddenException();
3955 $count = $_GET['count'] ?? 20;
3956 $page = $_REQUEST['page'] ?? 1;
3958 $since_id = $_REQUEST['since_id'] ?? 0;
3959 $max_id = $_REQUEST['max_id'] ?? 0;
3961 $user_id = $_REQUEST['user_id'] ?? '';
3962 $screen_name = $_REQUEST['screen_name'] ?? '';
3965 unset($_REQUEST["user_id"]);
3966 unset($_GET["user_id"]);
3968 unset($_REQUEST["screen_name"]);
3969 unset($_GET["screen_name"]);
3971 $user_info = api_get_user($a);
3972 if ($user_info === false) {
3973 throw new ForbiddenException();
3975 $profile_url = $user_info["url"];
3978 $start = max(0, ($page - 1) * $count);
3983 if ($box=="sentbox") {
3984 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3985 } elseif ($box == "conversation") {
3986 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3987 } elseif ($box == "all") {
3988 $sql_extra = "true";
3989 } elseif ($box == "inbox") {
3990 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3994 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3997 if ($user_id != "") {
3998 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3999 } elseif ($screen_name !="") {
4000 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4004 "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",
4010 if ($verbose == "true" && !DBA::isResult($r)) {
4011 $answer = ['result' => 'error', 'message' => 'no mails available'];
4012 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4016 foreach ($r as $item) {
4017 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4018 $recipient = $user_info;
4019 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4020 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4021 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4022 $sender = $user_info;
4025 if (isset($recipient) && isset($sender)) {
4026 $ret[] = api_format_messages($item, $recipient, $sender);
4031 $data = ['direct_message' => $ret];
4036 $data = api_rss_extra($a, $data, $user_info);
4040 return api_format_data("direct-messages", $type, $data);
4044 * Returns the most recent direct messages sent by the user.
4046 * @param string $type Return type (atom, rss, xml, json)
4048 * @return array|string
4049 * @throws BadRequestException
4050 * @throws ForbiddenException
4051 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4053 function api_direct_messages_sentbox($type)
4055 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4056 return api_direct_messages_box($type, "sentbox", $verbose);
4060 * Returns the most recent direct messages sent to the user.
4062 * @param string $type Return type (atom, rss, xml, json)
4064 * @return array|string
4065 * @throws BadRequestException
4066 * @throws ForbiddenException
4067 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4069 function api_direct_messages_inbox($type)
4071 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4072 return api_direct_messages_box($type, "inbox", $verbose);
4077 * @param string $type Return type (atom, rss, xml, json)
4079 * @return array|string
4080 * @throws BadRequestException
4081 * @throws ForbiddenException
4083 function api_direct_messages_all($type)
4085 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4086 return api_direct_messages_box($type, "all", $verbose);
4091 * @param string $type Return type (atom, rss, xml, json)
4093 * @return array|string
4094 * @throws BadRequestException
4095 * @throws ForbiddenException
4097 function api_direct_messages_conversation($type)
4099 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4100 return api_direct_messages_box($type, "conversation", $verbose);
4103 /// @TODO move to top of file or somewhere better
4104 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4105 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4106 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4107 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4110 * Returns an OAuth Request Token.
4112 * @see https://oauth.net/core/1.0/#auth_step1
4114 function api_oauth_request_token()
4116 $oauth1 = new FKOAuth1();
4118 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4119 } catch (Exception $e) {
4120 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4128 * Returns an OAuth Access Token.
4130 * @return array|string
4131 * @see https://oauth.net/core/1.0/#auth_step3
4133 function api_oauth_access_token()
4135 $oauth1 = new FKOAuth1();
4137 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4138 } catch (Exception $e) {
4139 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4146 /// @TODO move to top of file or somewhere better
4147 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4148 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4152 * @brief delete a complete photoalbum with all containing photos from database through api
4154 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4155 * @return string|array
4156 * @throws BadRequestException
4157 * @throws ForbiddenException
4158 * @throws InternalServerErrorException
4160 function api_fr_photoalbum_delete($type)
4162 if (api_user() === false) {
4163 throw new ForbiddenException();
4166 $album = $_REQUEST['album'] ?? '';
4168 // we do not allow calls without album string
4170 throw new BadRequestException("no albumname specified");
4172 // check if album is existing
4174 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4178 if (!DBA::isResult($r)) {
4179 throw new BadRequestException("album not available");
4182 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4183 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4184 foreach ($r as $rr) {
4185 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4186 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4188 if (!DBA::isResult($photo_item)) {
4189 throw new InternalServerErrorException("problem with deleting items occured");
4191 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4194 // now let's delete all photos from the album
4195 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4197 // return success of deletion or error message
4199 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4200 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4202 throw new InternalServerErrorException("unknown error - deleting from database failed");
4207 * @brief update the name of the album for all photos of an album
4209 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4210 * @return string|array
4211 * @throws BadRequestException
4212 * @throws ForbiddenException
4213 * @throws InternalServerErrorException
4215 function api_fr_photoalbum_update($type)
4217 if (api_user() === false) {
4218 throw new ForbiddenException();
4221 $album = $_REQUEST['album'] ?? '';
4222 $album_new = $_REQUEST['album_new'] ?? '';
4224 // we do not allow calls without album string
4226 throw new BadRequestException("no albumname specified");
4228 if ($album_new == "") {
4229 throw new BadRequestException("no new albumname specified");
4231 // check if album is existing
4232 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4233 throw new BadRequestException("album not available");
4235 // now let's update all photos to the albumname
4236 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4238 // return success of updating or error message
4240 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4241 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4243 throw new InternalServerErrorException("unknown error - updating in database failed");
4249 * @brief list all photos of the authenticated user
4251 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4252 * @return string|array
4253 * @throws ForbiddenException
4254 * @throws InternalServerErrorException
4256 function api_fr_photos_list($type)
4258 if (api_user() === false) {
4259 throw new ForbiddenException();
4262 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4263 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4264 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4265 intval(local_user())
4268 'image/jpeg' => 'jpg',
4269 'image/png' => 'png',
4270 'image/gif' => 'gif'
4272 $data = ['photo'=>[]];
4273 if (DBA::isResult($r)) {
4274 foreach ($r as $rr) {
4276 $photo['id'] = $rr['resource-id'];
4277 $photo['album'] = $rr['album'];
4278 $photo['filename'] = $rr['filename'];
4279 $photo['type'] = $rr['type'];
4280 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4281 $photo['created'] = $rr['created'];
4282 $photo['edited'] = $rr['edited'];
4283 $photo['desc'] = $rr['desc'];
4285 if ($type == "xml") {
4286 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4288 $photo['thumb'] = $thumb;
4289 $data['photo'][] = $photo;
4293 return api_format_data("photos", $type, $data);
4297 * @brief upload a new photo or change an existing photo
4299 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4300 * @return string|array
4301 * @throws BadRequestException
4302 * @throws ForbiddenException
4303 * @throws ImagickException
4304 * @throws InternalServerErrorException
4305 * @throws NotFoundException
4307 function api_fr_photo_create_update($type)
4309 if (api_user() === false) {
4310 throw new ForbiddenException();
4313 $photo_id = $_REQUEST['photo_id'] ?? null;
4314 $desc = $_REQUEST['desc'] ?? null;
4315 $album = $_REQUEST['album'] ?? null;
4316 $album_new = $_REQUEST['album_new'] ?? null;
4317 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4318 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4319 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4320 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4321 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4323 // do several checks on input parameters
4324 // we do not allow calls without album string
4325 if ($album == null) {
4326 throw new BadRequestException("no albumname specified");
4328 // if photo_id == null --> we are uploading a new photo
4329 if ($photo_id == null) {
4332 // error if no media posted in create-mode
4333 if (empty($_FILES['media'])) {
4335 throw new BadRequestException("no media data submitted");
4338 // album_new will be ignored in create-mode
4343 // check if photo is existing in databasei
4344 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4345 throw new BadRequestException("photo not available");
4349 // checks on acl strings provided by clients
4350 $acl_input_error = false;
4351 $acl_input_error |= check_acl_input($allow_cid);
4352 $acl_input_error |= check_acl_input($deny_cid);
4353 $acl_input_error |= check_acl_input($allow_gid);
4354 $acl_input_error |= check_acl_input($deny_gid);
4355 if ($acl_input_error) {
4356 throw new BadRequestException("acl data invalid");
4358 // now let's upload the new media in create-mode
4359 if ($mode == "create") {
4360 $media = $_FILES['media'];
4361 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4363 // return success of updating or error message
4364 if (!is_null($data)) {
4365 return api_format_data("photo_create", $type, $data);
4367 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4371 // now let's do the changes in update-mode
4372 if ($mode == "update") {
4373 $updated_fields = [];
4375 if (!is_null($desc)) {
4376 $updated_fields['desc'] = $desc;
4379 if (!is_null($album_new)) {
4380 $updated_fields['album'] = $album_new;
4383 if (!is_null($allow_cid)) {
4384 $allow_cid = trim($allow_cid);
4385 $updated_fields['allow_cid'] = $allow_cid;
4388 if (!is_null($deny_cid)) {
4389 $deny_cid = trim($deny_cid);
4390 $updated_fields['deny_cid'] = $deny_cid;
4393 if (!is_null($allow_gid)) {
4394 $allow_gid = trim($allow_gid);
4395 $updated_fields['allow_gid'] = $allow_gid;
4398 if (!is_null($deny_gid)) {
4399 $deny_gid = trim($deny_gid);
4400 $updated_fields['deny_gid'] = $deny_gid;
4404 if (count($updated_fields) > 0) {
4405 $nothingtodo = false;
4406 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4408 $nothingtodo = true;
4411 if (!empty($_FILES['media'])) {
4412 $nothingtodo = false;
4413 $media = $_FILES['media'];
4414 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4415 if (!is_null($data)) {
4416 return api_format_data("photo_update", $type, $data);
4420 // return success of updating or error message
4422 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4423 return api_format_data("photo_update", $type, ['$result' => $answer]);
4426 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4427 return api_format_data("photo_update", $type, ['$result' => $answer]);
4429 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4432 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4436 * @brief delete a single photo from the database through api
4438 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4439 * @return string|array
4440 * @throws BadRequestException
4441 * @throws ForbiddenException
4442 * @throws InternalServerErrorException
4444 function api_fr_photo_delete($type)
4446 if (api_user() === false) {
4447 throw new ForbiddenException();
4451 $photo_id = $_REQUEST['photo_id'] ?? null;
4453 // do several checks on input parameters
4454 // we do not allow calls without photo id
4455 if ($photo_id == null) {
4456 throw new BadRequestException("no photo_id specified");
4459 // check if photo is existing in database
4460 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4461 throw new BadRequestException("photo not available");
4464 // now we can perform on the deletion of the photo
4465 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4467 // return success of deletion or error message
4469 // retrieve the id of the parent element (the photo element)
4470 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4471 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4473 if (!DBA::isResult($photo_item)) {
4474 throw new InternalServerErrorException("problem with deleting items occured");
4476 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4477 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4478 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4480 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4481 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4483 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4489 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4491 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4492 * @return string|array
4493 * @throws BadRequestException
4494 * @throws ForbiddenException
4495 * @throws InternalServerErrorException
4496 * @throws NotFoundException
4498 function api_fr_photo_detail($type)
4500 if (api_user() === false) {
4501 throw new ForbiddenException();
4503 if (empty($_REQUEST['photo_id'])) {
4504 throw new BadRequestException("No photo id.");
4507 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4508 $photo_id = $_REQUEST['photo_id'];
4510 // prepare json/xml output with data from database for the requested photo
4511 $data = prepare_photo_data($type, $scale, $photo_id);
4513 return api_format_data("photo_detail", $type, $data);
4518 * Updates the user’s profile image.
4520 * @brief updates the profile image for the user (either a specified profile or the default profile)
4522 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4524 * @return string|array
4525 * @throws BadRequestException
4526 * @throws ForbiddenException
4527 * @throws ImagickException
4528 * @throws InternalServerErrorException
4529 * @throws NotFoundException
4530 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4532 function api_account_update_profile_image($type)
4534 if (api_user() === false) {
4535 throw new ForbiddenException();
4538 $profile_id = $_REQUEST['profile_id'] ?? 0;
4540 // error if image data is missing
4541 if (empty($_FILES['image'])) {
4542 throw new BadRequestException("no media data submitted");
4545 // check if specified profile id is valid
4546 if ($profile_id != 0) {
4547 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4548 // error message if specified profile id is not in database
4549 if (!DBA::isResult($profile)) {
4550 throw new BadRequestException("profile_id not available");
4552 $is_default_profile = $profile['is-default'];
4554 $is_default_profile = 1;
4557 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4559 if (!empty($_FILES['image'])) {
4560 $media = $_FILES['image'];
4561 } elseif (!empty($_FILES['media'])) {
4562 $media = $_FILES['media'];
4564 // save new profile image
4565 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4568 if (is_array($media['type'])) {
4569 $filetype = $media['type'][0];
4571 $filetype = $media['type'];
4573 if ($filetype == "image/jpeg") {
4575 } elseif ($filetype == "image/png") {
4578 throw new InternalServerErrorException('Unsupported filetype');
4581 // change specified profile or all profiles to the new resource-id
4582 if ($is_default_profile) {
4583 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4584 Photo::update(['profile' => false], $condition);
4586 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4587 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4588 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4591 Contact::updateSelfFromUserID(api_user(), true);
4593 // Update global directory in background
4594 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4595 if ($url && strlen(Config::get('system', 'directory'))) {
4596 Worker::add(PRIORITY_LOW, "Directory", $url);
4599 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4601 // output for client
4603 return api_account_verify_credentials($type);
4605 // SaveMediaToDatabase failed for some reason
4606 throw new InternalServerErrorException("image upload failed");
4610 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4611 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4612 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4613 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4614 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4615 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4616 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4617 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4618 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4621 * Update user profile
4623 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4625 * @return array|string
4626 * @throws BadRequestException
4627 * @throws ForbiddenException
4628 * @throws ImagickException
4629 * @throws InternalServerErrorException
4630 * @throws UnauthorizedException
4632 function api_account_update_profile($type)
4634 $local_user = api_user();
4635 $api_user = api_get_user(get_app());
4637 if (!empty($_POST['name'])) {
4638 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4639 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4640 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4641 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4644 if (isset($_POST['description'])) {
4645 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4646 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4647 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4650 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4651 // Update global directory in background
4652 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4653 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4656 return api_account_verify_credentials($type);
4659 /// @TODO move to top of file or somewhere better
4660 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4664 * @param string $acl_string
4668 function check_acl_input($acl_string)
4670 if (empty($acl_string)) {
4674 $contact_not_found = false;
4676 // split <x><y><z> into array of cid's
4677 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4679 // check for each cid if it is available on server
4680 $cid_array = $array[0];
4681 foreach ($cid_array as $cid) {
4682 $cid = str_replace("<", "", $cid);
4683 $cid = str_replace(">", "", $cid);
4684 $condition = ['id' => $cid, 'uid' => api_user()];
4685 $contact_not_found |= !DBA::exists('contact', $condition);
4687 return $contact_not_found;
4691 * @param string $mediatype
4692 * @param array $media
4693 * @param string $type
4694 * @param string $album
4695 * @param string $allow_cid
4696 * @param string $deny_cid
4697 * @param string $allow_gid
4698 * @param string $deny_gid
4699 * @param string $desc
4700 * @param integer $profile
4701 * @param boolean $visibility
4702 * @param string $photo_id
4704 * @throws BadRequestException
4705 * @throws ForbiddenException
4706 * @throws ImagickException
4707 * @throws InternalServerErrorException
4708 * @throws NotFoundException
4709 * @throws UnauthorizedException
4711 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)
4719 if (is_array($media)) {
4720 if (is_array($media['tmp_name'])) {
4721 $src = $media['tmp_name'][0];
4723 $src = $media['tmp_name'];
4725 if (is_array($media['name'])) {
4726 $filename = basename($media['name'][0]);
4728 $filename = basename($media['name']);
4730 if (is_array($media['size'])) {
4731 $filesize = intval($media['size'][0]);
4733 $filesize = intval($media['size']);
4735 if (is_array($media['type'])) {
4736 $filetype = $media['type'][0];
4738 $filetype = $media['type'];
4742 if ($filetype == "") {
4743 $filetype=Image::guessType($filename);
4745 $imagedata = @getimagesize($src);
4747 $filetype = $imagedata['mime'];
4750 "File upload src: " . $src . " - filename: " . $filename .
4751 " - size: " . $filesize . " - type: " . $filetype,
4755 // check if there was a php upload error
4756 if ($filesize == 0 && $media['error'] == 1) {
4757 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4759 // check against max upload size within Friendica instance
4760 $maximagesize = Config::get('system', 'maximagesize');
4761 if ($maximagesize && ($filesize > $maximagesize)) {
4762 $formattedBytes = Strings::formatBytes($maximagesize);
4763 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4766 // create Photo instance with the data of the image
4767 $imagedata = @file_get_contents($src);
4768 $Image = new Image($imagedata, $filetype);
4769 if (!$Image->isValid()) {
4770 throw new InternalServerErrorException("unable to process image data");
4773 // check orientation of image
4774 $Image->orient($src);
4777 // check max length of images on server
4778 $max_length = Config::get('system', 'max_image_length');
4780 $max_length = MAX_IMAGE_LENGTH;
4782 if ($max_length > 0) {
4783 $Image->scaleDown($max_length);
4784 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4786 $width = $Image->getWidth();
4787 $height = $Image->getHeight();
4789 // create a new resource-id if not already provided
4790 $hash = ($photo_id == null) ? Photo::newResource() : $photo_id;
4792 if ($mediatype == "photo") {
4793 // upload normal image (scales 0, 1, 2)
4794 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4796 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4798 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4800 if ($width > 640 || $height > 640) {
4801 $Image->scaleDown(640);
4802 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4804 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4808 if ($width > 320 || $height > 320) {
4809 $Image->scaleDown(320);
4810 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4812 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4815 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4816 } elseif ($mediatype == "profileimage") {
4817 // upload profile image (scales 4, 5, 6)
4818 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4820 if ($width > 300 || $height > 300) {
4821 $Image->scaleDown(300);
4822 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4824 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4828 if ($width > 80 || $height > 80) {
4829 $Image->scaleDown(80);
4830 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4832 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4836 if ($width > 48 || $height > 48) {
4837 $Image->scaleDown(48);
4838 $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4840 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4843 $Image->__destruct();
4844 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4847 if (isset($r) && $r) {
4848 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4849 if ($photo_id == null && $mediatype == "photo") {
4850 post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4852 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4853 return prepare_photo_data($type, false, $hash);
4855 throw new InternalServerErrorException("image upload failed");
4861 * @param string $hash
4862 * @param string $allow_cid
4863 * @param string $deny_cid
4864 * @param string $allow_gid
4865 * @param string $deny_gid
4866 * @param string $filetype
4867 * @param boolean $visibility
4868 * @throws InternalServerErrorException
4870 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4872 // get data about the api authenticated user
4873 $uri = Item::newURI(intval(api_user()));
4874 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4877 $arr['guid'] = System::createUUID();
4878 $arr['uid'] = intval(api_user());
4880 $arr['parent-uri'] = $uri;
4881 $arr['type'] = 'photo';
4883 $arr['resource-id'] = $hash;
4884 $arr['contact-id'] = $owner_record['id'];
4885 $arr['owner-name'] = $owner_record['name'];
4886 $arr['owner-link'] = $owner_record['url'];
4887 $arr['owner-avatar'] = $owner_record['thumb'];
4888 $arr['author-name'] = $owner_record['name'];
4889 $arr['author-link'] = $owner_record['url'];
4890 $arr['author-avatar'] = $owner_record['thumb'];
4892 $arr['allow_cid'] = $allow_cid;
4893 $arr['allow_gid'] = $allow_gid;
4894 $arr['deny_cid'] = $deny_cid;
4895 $arr['deny_gid'] = $deny_gid;
4896 $arr['visible'] = $visibility;
4900 'image/jpeg' => 'jpg',
4901 'image/png' => 'png',
4902 'image/gif' => 'gif'
4905 // adds link to the thumbnail scale photo
4906 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4907 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4910 // do the magic for storing the item in the database and trigger the federation to other contacts
4916 * @param string $type
4918 * @param string $photo_id
4921 * @throws BadRequestException
4922 * @throws ForbiddenException
4923 * @throws ImagickException
4924 * @throws InternalServerErrorException
4925 * @throws NotFoundException
4926 * @throws UnauthorizedException
4928 function prepare_photo_data($type, $scale, $photo_id)
4931 $user_info = api_get_user($a);
4933 if ($user_info === false) {
4934 throw new ForbiddenException();
4937 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4938 $data_sql = ($scale === false ? "" : "data, ");
4940 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4941 // clients needs to convert this in their way for further processing
4943 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4944 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4945 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4946 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4947 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4948 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4950 intval(local_user()),
4951 DBA::escape($photo_id),
4956 'image/jpeg' => 'jpg',
4957 'image/png' => 'png',
4958 'image/gif' => 'gif'
4961 // prepare output data for photo
4962 if (DBA::isResult($r)) {
4963 $data = ['photo' => $r[0]];
4964 $data['photo']['id'] = $data['photo']['resource-id'];
4965 if ($scale !== false) {
4966 $data['photo']['data'] = base64_encode($data['photo']['data']);
4968 unset($data['photo']['datasize']); //needed only with scale param
4970 if ($type == "xml") {
4971 $data['photo']['links'] = [];
4972 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4973 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4975 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4978 $data['photo']['link'] = [];
4979 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4981 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4982 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4986 unset($data['photo']['resource-id']);
4987 unset($data['photo']['minscale']);
4988 unset($data['photo']['maxscale']);
4990 throw new NotFoundException();
4993 // retrieve item element for getting activities (like, dislike etc.) related to photo
4994 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4995 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4997 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4999 // retrieve comments on photo
5000 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5001 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5003 $statuses = Item::selectForUser(api_user(), [], $condition);
5005 // prepare output of comments
5006 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5008 if ($type == "xml") {
5010 foreach ($commentData as $comment) {
5011 $comments[$k++ . ":comment"] = $comment;
5014 foreach ($commentData as $comment) {
5015 $comments[] = $comment;
5018 $data['photo']['friendica_comments'] = $comments;
5020 // include info if rights on photo and rights on item are mismatching
5021 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5022 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5023 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5024 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5025 $data['photo']['rights_mismatch'] = $rights_mismatch;
5032 * Similar as /mod/redir.php
5033 * redirect to 'url' after dfrn auth
5035 * Why this when there is mod/redir.php already?
5036 * This use api_user() and api_login()
5039 * c_url: url of remote contact to auth to
5040 * url: string, url to redirect after auth
5042 function api_friendica_remoteauth()
5044 $url = $_GET['url'] ?? '';
5045 $c_url = $_GET['c_url'] ?? '';
5047 if ($url === '' || $c_url === '') {
5048 throw new BadRequestException("Wrong parameters.");
5051 $c_url = Strings::normaliseLink($c_url);
5055 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5057 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5058 throw new BadRequestException("Unknown contact");
5061 $cid = $contact['id'];
5063 $dfrn_id = $contact['issued-id'] ?? $contact['dfrn-id'];
5065 if ($contact['duplex'] && $contact['issued-id']) {
5066 $orig_id = $contact['issued-id'];
5067 $dfrn_id = '1:' . $orig_id;
5069 if ($contact['duplex'] && $contact['dfrn-id']) {
5070 $orig_id = $contact['dfrn-id'];
5071 $dfrn_id = '0:' . $orig_id;
5074 $sec = Strings::getRandomHex();
5076 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5077 'sec' => $sec, 'expire' => time() + 45];
5078 DBA::insert('profile_check', $fields);
5080 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5081 $dest = ($url ? '&destination_url=' . $url : '');
5083 System::externalRedirect(
5084 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5085 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5086 . '&type=profile&sec=' . $sec . $dest
5089 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5092 * Return an item with announcer data if it had been announced
5094 * @param array $item Item array
5095 * @return array Item array with announce data
5097 function api_get_announce($item)
5099 // Quit if the item already has got a different owner and author
5100 if ($item['owner-id'] != $item['author-id']) {
5104 // Don't change original or Diaspora posts
5105 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5109 // Quit if we do now the original author and it had been a post from a native network
5110 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5114 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5115 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5116 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5117 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5118 if (!DBA::isResult($announce)) {
5122 return array_merge($item, $announce);
5126 * @brief Return the item shared, if the item contains only the [share] tag
5128 * @param array $item Sharer item
5129 * @return array|false Shared item or false if not a reshare
5130 * @throws ImagickException
5131 * @throws InternalServerErrorException
5133 function api_share_as_retweet(&$item)
5135 $body = trim($item["body"]);
5137 if (Diaspora::isReshare($body, false) === false) {
5138 if ($item['author-id'] == $item['owner-id']) {
5141 // Reshares from OStatus, ActivityPub and Twitter
5142 $reshared_item = $item;
5143 $reshared_item['owner-id'] = $reshared_item['author-id'];
5144 $reshared_item['owner-link'] = $reshared_item['author-link'];
5145 $reshared_item['owner-name'] = $reshared_item['author-name'];
5146 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5147 return $reshared_item;
5151 /// @TODO "$1" should maybe mean '$1' ?
5152 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5154 * Skip if there is no shared message in there
5155 * we already checked this in diaspora::isReshare()
5156 * but better one more than one less...
5158 if (($body == $attributes) || empty($attributes)) {
5162 // build the fake reshared item
5163 $reshared_item = $item;
5166 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5167 if (!empty($matches[1])) {
5168 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5171 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5172 if (!empty($matches[1])) {
5173 $author = $matches[1];
5177 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5178 if (!empty($matches[1])) {
5179 $profile = $matches[1];
5182 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5183 if (!empty($matches[1])) {
5184 $profile = $matches[1];
5188 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5189 if (!empty($matches[1])) {
5190 $avatar = $matches[1];
5193 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5194 if (!empty($matches[1])) {
5195 $avatar = $matches[1];
5199 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5200 if (!empty($matches[1])) {
5201 $link = $matches[1];
5204 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5205 if (!empty($matches[1])) {
5206 $link = $matches[1];
5210 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5211 if (!empty($matches[1])) {
5212 $posted = $matches[1];
5215 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5216 if (!empty($matches[1])) {
5217 $posted = $matches[1];
5220 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5224 $pre_body = trim($matches[1]);
5225 if ($pre_body != '') {
5226 $item['body'] = $pre_body;
5229 $shared_body = trim($matches[2]);
5231 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5235 $reshared_item["share-pre-body"] = $pre_body;
5236 $reshared_item["body"] = $shared_body;
5237 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5238 $reshared_item["author-name"] = $author;
5239 $reshared_item["author-link"] = $profile;
5240 $reshared_item["author-avatar"] = $avatar;
5241 $reshared_item["plink"] = $link;
5242 $reshared_item["created"] = $posted;
5243 $reshared_item["edited"] = $posted;
5245 return $reshared_item;
5250 * @param string $profile
5252 * @return string|false
5253 * @throws InternalServerErrorException
5254 * @todo remove trailing junk from profile url
5255 * @todo pump.io check has to check the website
5257 function api_get_nick($profile)
5262 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5263 DBA::escape(Strings::normaliseLink($profile))
5266 if (DBA::isResult($r)) {
5267 $nick = $r[0]["nick"];
5272 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5273 DBA::escape(Strings::normaliseLink($profile))
5276 if (DBA::isResult($r)) {
5277 $nick = $r[0]["nick"];
5282 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5283 if ($friendica != $profile) {
5289 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5290 if ($diaspora != $profile) {
5296 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5297 if ($twitter != $profile) {
5304 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5305 if ($StatusnetHost != $profile) {
5306 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5307 if ($StatusnetUser != $profile) {
5308 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5309 $user = json_decode($UserData);
5311 $nick = $user->screen_name;
5317 // To-Do: look at the page if its really a pumpio site
5318 //if (!$nick == "") {
5319 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5320 // if ($pumpio != $profile)
5322 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5335 * @param array $item
5340 function api_in_reply_to($item)
5344 $in_reply_to['status_id'] = null;
5345 $in_reply_to['user_id'] = null;
5346 $in_reply_to['status_id_str'] = null;
5347 $in_reply_to['user_id_str'] = null;
5348 $in_reply_to['screen_name'] = null;
5350 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5351 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5352 if (DBA::isResult($parent)) {
5353 $in_reply_to['status_id'] = intval($parent['id']);
5355 $in_reply_to['status_id'] = intval($item['parent']);
5358 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5360 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5361 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5363 if (DBA::isResult($parent)) {
5364 if ($parent['author-nick'] == "") {
5365 $parent['author-nick'] = api_get_nick($parent['author-link']);
5368 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5369 $in_reply_to['user_id'] = intval($parent['author-id']);
5370 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5373 // There seems to be situation, where both fields are identical:
5374 // https://github.com/friendica/friendica/issues/1010
5375 // This is a bugfix for that.
5376 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5377 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']]);
5378 $in_reply_to['status_id'] = null;
5379 $in_reply_to['user_id'] = null;
5380 $in_reply_to['status_id_str'] = null;
5381 $in_reply_to['user_id_str'] = null;
5382 $in_reply_to['screen_name'] = null;
5386 return $in_reply_to;
5391 * @param string $text
5394 * @throws InternalServerErrorException
5396 function api_clean_plain_items($text)
5398 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5400 $text = BBCode::cleanPictureLinks($text);
5401 $URLSearchString = "^\[\]";
5403 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5405 if ($include_entities == "true") {
5406 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5409 // Simplify "attachment" element
5410 $text = api_clean_attachments($text);
5416 * @brief Removes most sharing information for API text export
5418 * @param string $body The original body
5420 * @return string Cleaned body
5421 * @throws InternalServerErrorException
5423 function api_clean_attachments($body)
5425 $data = BBCode::getAttachmentData($body);
5432 if (isset($data["text"])) {
5433 $body = $data["text"];
5435 if (($body == "") && isset($data["title"])) {
5436 $body = $data["title"];
5438 if (isset($data["url"])) {
5439 $body .= "\n".$data["url"];
5441 $body .= $data["after"];
5448 * @param array $contacts
5452 function api_best_nickname(&$contacts)
5456 if (count($contacts) == 0) {
5460 foreach ($contacts as $contact) {
5461 if ($contact["network"] == "") {
5462 $contact["network"] = "dfrn";
5463 $best_contact = [$contact];
5467 if (sizeof($best_contact) == 0) {
5468 foreach ($contacts as $contact) {
5469 if ($contact["network"] == "dfrn") {
5470 $best_contact = [$contact];
5475 if (sizeof($best_contact) == 0) {
5476 foreach ($contacts as $contact) {
5477 if ($contact["network"] == "dspr") {
5478 $best_contact = [$contact];
5483 if (sizeof($best_contact) == 0) {
5484 foreach ($contacts as $contact) {
5485 if ($contact["network"] == "stat") {
5486 $best_contact = [$contact];
5491 if (sizeof($best_contact) == 0) {
5492 foreach ($contacts as $contact) {
5493 if ($contact["network"] == "pump") {
5494 $best_contact = [$contact];
5499 if (sizeof($best_contact) == 0) {
5500 foreach ($contacts as $contact) {
5501 if ($contact["network"] == "twit") {
5502 $best_contact = [$contact];
5507 if (sizeof($best_contact) == 1) {
5508 $contacts = $best_contact;
5510 $contacts = [$contacts[0]];
5515 * Return all or a specified group of the user with the containing contacts.
5517 * @param string $type Return type (atom, rss, xml, json)
5519 * @return array|string
5520 * @throws BadRequestException
5521 * @throws ForbiddenException
5522 * @throws ImagickException
5523 * @throws InternalServerErrorException
5524 * @throws UnauthorizedException
5526 function api_friendica_group_show($type)
5530 if (api_user() === false) {
5531 throw new ForbiddenException();
5535 $user_info = api_get_user($a);
5536 $gid = $_REQUEST['gid'] ?? 0;
5537 $uid = $user_info['uid'];
5539 // get data of the specified group id or all groups if not specified
5542 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5546 // error message if specified gid is not in database
5547 if (!DBA::isResult($r)) {
5548 throw new BadRequestException("gid not available");
5552 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5557 // loop through all groups and retrieve all members for adding data in the user array
5559 foreach ($r as $rr) {
5560 $members = Contact::getByGroupId($rr['id']);
5563 if ($type == "xml") {
5564 $user_element = "users";
5566 foreach ($members as $member) {
5567 $user = api_get_user($a, $member['nurl']);
5568 $users[$k++.":user"] = $user;
5571 $user_element = "user";
5572 foreach ($members as $member) {
5573 $user = api_get_user($a, $member['nurl']);
5577 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5579 return api_format_data("groups", $type, ['group' => $grps]);
5581 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5585 * Delete the specified group of the user.
5587 * @param string $type Return type (atom, rss, xml, json)
5589 * @return array|string
5590 * @throws BadRequestException
5591 * @throws ForbiddenException
5592 * @throws ImagickException
5593 * @throws InternalServerErrorException
5594 * @throws UnauthorizedException
5596 function api_friendica_group_delete($type)
5600 if (api_user() === false) {
5601 throw new ForbiddenException();
5605 $user_info = api_get_user($a);
5606 $gid = $_REQUEST['gid'] ?? 0;
5607 $name = $_REQUEST['name'] ?? '';
5608 $uid = $user_info['uid'];
5610 // error if no gid specified
5611 if ($gid == 0 || $name == "") {
5612 throw new BadRequestException('gid or name not specified');
5615 // get data of the specified group id
5617 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5621 // error message if specified gid is not in database
5622 if (!DBA::isResult($r)) {
5623 throw new BadRequestException('gid not available');
5626 // get data of the specified group id and group name
5628 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5633 // error message if specified gid is not in database
5634 if (!DBA::isResult($rname)) {
5635 throw new BadRequestException('wrong group name');
5639 $ret = Group::removeByName($uid, $name);
5642 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5643 return api_format_data("group_delete", $type, ['result' => $success]);
5645 throw new BadRequestException('other API error');
5648 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5653 * @param string $type Return type (atom, rss, xml, json)
5655 * @return array|string
5656 * @throws BadRequestException
5657 * @throws ForbiddenException
5658 * @throws ImagickException
5659 * @throws InternalServerErrorException
5660 * @throws UnauthorizedException
5661 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5663 function api_lists_destroy($type)
5667 if (api_user() === false) {
5668 throw new ForbiddenException();
5672 $user_info = api_get_user($a);
5673 $gid = $_REQUEST['list_id'] ?? 0;
5674 $uid = $user_info['uid'];
5676 // error if no gid specified
5678 throw new BadRequestException('gid not specified');
5681 // get data of the specified group id
5682 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5683 // error message if specified gid is not in database
5685 throw new BadRequestException('gid not available');
5688 if (Group::remove($gid)) {
5690 'name' => $group['name'],
5691 'id' => intval($gid),
5692 'id_str' => (string) $gid,
5693 'user' => $user_info
5696 return api_format_data("lists", $type, ['lists' => $list]);
5699 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5702 * Add a new group to the database.
5704 * @param string $name Group name
5705 * @param int $uid User ID
5706 * @param array $users List of users to add to the group
5709 * @throws BadRequestException
5711 function group_create($name, $uid, $users = [])
5713 // error if no name specified
5715 throw new BadRequestException('group name not specified');
5718 // get data of the specified group name
5720 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5724 // error message if specified group name already exists
5725 if (DBA::isResult($rname)) {
5726 throw new BadRequestException('group name already exists');
5729 // check if specified group name is a deleted group
5731 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5735 // error message if specified group name already exists
5736 if (DBA::isResult($rname)) {
5737 $reactivate_group = true;
5741 $ret = Group::create($uid, $name);
5743 $gid = Group::getIdByName($uid, $name);
5745 throw new BadRequestException('other API error');
5749 $erroraddinguser = false;
5751 foreach ($users as $user) {
5752 $cid = $user['cid'];
5753 // check if user really exists as contact
5755 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5759 if (count($contact)) {
5760 Group::addMember($gid, $cid);
5762 $erroraddinguser = true;
5763 $errorusers[] = $cid;
5767 // return success message incl. missing users in array
5768 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5770 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5774 * Create the specified group with the posted array of contacts.
5776 * @param string $type Return type (atom, rss, xml, json)
5778 * @return array|string
5779 * @throws BadRequestException
5780 * @throws ForbiddenException
5781 * @throws ImagickException
5782 * @throws InternalServerErrorException
5783 * @throws UnauthorizedException
5785 function api_friendica_group_create($type)
5789 if (api_user() === false) {
5790 throw new ForbiddenException();
5794 $user_info = api_get_user($a);
5795 $name = $_REQUEST['name'] ?? '';
5796 $uid = $user_info['uid'];
5797 $json = json_decode($_POST['json'], true);
5798 $users = $json['user'];
5800 $success = group_create($name, $uid, $users);
5802 return api_format_data("group_create", $type, ['result' => $success]);
5804 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5807 * Create a new group.
5809 * @param string $type Return type (atom, rss, xml, json)
5811 * @return array|string
5812 * @throws BadRequestException
5813 * @throws ForbiddenException
5814 * @throws ImagickException
5815 * @throws InternalServerErrorException
5816 * @throws UnauthorizedException
5817 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5819 function api_lists_create($type)
5823 if (api_user() === false) {
5824 throw new ForbiddenException();
5828 $user_info = api_get_user($a);
5829 $name = $_REQUEST['name'] ?? '';
5830 $uid = $user_info['uid'];
5832 $success = group_create($name, $uid);
5833 if ($success['success']) {
5835 'name' => $success['name'],
5836 'id' => intval($success['gid']),
5837 'id_str' => (string) $success['gid'],
5838 'user' => $user_info
5841 return api_format_data("lists", $type, ['lists'=>$grp]);
5844 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5847 * Update the specified group with the posted array of contacts.
5849 * @param string $type Return type (atom, rss, xml, json)
5851 * @return array|string
5852 * @throws BadRequestException
5853 * @throws ForbiddenException
5854 * @throws ImagickException
5855 * @throws InternalServerErrorException
5856 * @throws UnauthorizedException
5858 function api_friendica_group_update($type)
5862 if (api_user() === false) {
5863 throw new ForbiddenException();
5867 $user_info = api_get_user($a);
5868 $uid = $user_info['uid'];
5869 $gid = $_REQUEST['gid'] ?? 0;
5870 $name = $_REQUEST['name'] ?? '';
5871 $json = json_decode($_POST['json'], true);
5872 $users = $json['user'];
5874 // error if no name specified
5876 throw new BadRequestException('group name not specified');
5879 // error if no gid specified
5881 throw new BadRequestException('gid not specified');
5885 $members = Contact::getByGroupId($gid);
5886 foreach ($members as $member) {
5887 $cid = $member['id'];
5888 foreach ($users as $user) {
5889 $found = ($user['cid'] == $cid ? true : false);
5891 if (!isset($found) || !$found) {
5892 Group::removeMemberByName($uid, $name, $cid);
5897 $erroraddinguser = false;
5899 foreach ($users as $user) {
5900 $cid = $user['cid'];
5901 // check if user really exists as contact
5903 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5908 if (count($contact)) {
5909 Group::addMember($gid, $cid);
5911 $erroraddinguser = true;
5912 $errorusers[] = $cid;
5916 // return success message incl. missing users in array
5917 $status = ($erroraddinguser ? "missing user" : "ok");
5918 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5919 return api_format_data("group_update", $type, ['result' => $success]);
5922 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5925 * Update information about a group.
5927 * @param string $type Return type (atom, rss, xml, json)
5929 * @return array|string
5930 * @throws BadRequestException
5931 * @throws ForbiddenException
5932 * @throws ImagickException
5933 * @throws InternalServerErrorException
5934 * @throws UnauthorizedException
5935 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5937 function api_lists_update($type)
5941 if (api_user() === false) {
5942 throw new ForbiddenException();
5946 $user_info = api_get_user($a);
5947 $gid = $_REQUEST['list_id'] ?? 0;
5948 $name = $_REQUEST['name'] ?? '';
5949 $uid = $user_info['uid'];
5951 // error if no gid specified
5953 throw new BadRequestException('gid not specified');
5956 // get data of the specified group id
5957 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5958 // error message if specified gid is not in database
5960 throw new BadRequestException('gid not available');
5963 if (Group::update($gid, $name)) {
5966 'id' => intval($gid),
5967 'id_str' => (string) $gid,
5968 'user' => $user_info
5971 return api_format_data("lists", $type, ['lists' => $list]);
5975 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5979 * @param string $type Return type (atom, rss, xml, json)
5981 * @return array|string
5982 * @throws BadRequestException
5983 * @throws ForbiddenException
5984 * @throws ImagickException
5985 * @throws InternalServerErrorException
5987 function api_friendica_activity($type)
5991 if (api_user() === false) {
5992 throw new ForbiddenException();
5994 $verb = strtolower($a->argv[3]);
5995 $verb = preg_replace("|\..*$|", "", $verb);
5997 $id = $_REQUEST['id'] ?? 0;
5999 $res = Item::performLike($id, $verb);
6002 if ($type == "xml") {
6007 return api_format_data('ok', $type, ['ok' => $ok]);
6009 throw new BadRequestException('Error adding activity');
6013 /// @TODO move to top of file or somewhere better
6014 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
6015 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
6016 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
6017 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
6018 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6019 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
6020 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
6021 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
6022 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
6023 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6026 * @brief Returns notifications
6028 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6029 * @return string|array
6030 * @throws BadRequestException
6031 * @throws ForbiddenException
6032 * @throws InternalServerErrorException
6034 function api_friendica_notification($type)
6038 if (api_user() === false) {
6039 throw new ForbiddenException();
6042 throw new BadRequestException("Invalid argument count");
6044 /** @var Notify $nm */
6045 $nm = BaseObject::getClass(Notify::class);
6047 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6049 if ($type == "xml") {
6051 if (!empty($notes)) {
6052 foreach ($notes as $note) {
6053 $xmlnotes[] = ["@attributes" => $note];
6059 return api_format_data("notes", $type, ['note' => $notes]);
6063 * POST request with 'id' param as notification id
6065 * @brief Set notification as seen and returns associated item (if possible)
6067 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6068 * @return string|array
6069 * @throws BadRequestException
6070 * @throws ForbiddenException
6071 * @throws ImagickException
6072 * @throws InternalServerErrorException
6073 * @throws UnauthorizedException
6075 function api_friendica_notification_seen($type)
6078 $user_info = api_get_user($a);
6080 if (api_user() === false || $user_info === false) {
6081 throw new ForbiddenException();
6084 throw new BadRequestException("Invalid argument count");
6087 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6089 /** @var Notify $nm */
6090 $nm = BaseObject::getClass(Notify::class);
6091 $note = $nm->getByID($id);
6092 if (is_null($note)) {
6093 throw new BadRequestException("Invalid argument");
6096 $nm->setSeen($note);
6097 if ($note['otype']=='item') {
6098 // would be really better with an ItemsManager and $im->getByID() :-P
6099 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6100 if (DBA::isResult($item)) {
6101 // we found the item, return it to the user
6102 $ret = api_format_items([$item], $user_info, false, $type);
6103 $data = ['status' => $ret];
6104 return api_format_data("status", $type, $data);
6106 // the item can't be found, but we set the note as seen, so we count this as a success
6108 return api_format_data('result', $type, ['result' => "success"]);
6111 /// @TODO move to top of file or somewhere better
6112 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6113 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6116 * @brief update a direct_message to seen state
6118 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6119 * @return string|array (success result=ok, error result=error with error message)
6120 * @throws BadRequestException
6121 * @throws ForbiddenException
6122 * @throws ImagickException
6123 * @throws InternalServerErrorException
6124 * @throws UnauthorizedException
6126 function api_friendica_direct_messages_setseen($type)
6129 if (api_user() === false) {
6130 throw new ForbiddenException();
6134 $user_info = api_get_user($a);
6135 $uid = $user_info['uid'];
6136 $id = $_REQUEST['id'] ?? 0;
6138 // return error if id is zero
6140 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6141 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6144 // error message if specified id is not in database
6145 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6146 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6147 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6150 // update seen indicator
6151 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6155 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6156 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6158 $answer = ['result' => 'error', 'message' => 'unknown error'];
6159 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6163 /// @TODO move to top of file or somewhere better
6164 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6167 * @brief search for direct_messages containing a searchstring through api
6169 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6170 * @param string $box
6171 * @return string|array (success: success=true if found and search_result contains found messages,
6172 * success=false if nothing was found, search_result='nothing found',
6173 * error: result=error with error message)
6174 * @throws BadRequestException
6175 * @throws ForbiddenException
6176 * @throws ImagickException
6177 * @throws InternalServerErrorException
6178 * @throws UnauthorizedException
6180 function api_friendica_direct_messages_search($type, $box = "")
6184 if (api_user() === false) {
6185 throw new ForbiddenException();
6189 $user_info = api_get_user($a);
6190 $searchstring = $_REQUEST['searchstring'] ?? '';
6191 $uid = $user_info['uid'];
6193 // error if no searchstring specified
6194 if ($searchstring == "") {
6195 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6196 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6199 // get data for the specified searchstring
6201 "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",
6203 DBA::escape('%'.$searchstring.'%')
6206 $profile_url = $user_info["url"];
6208 // message if nothing was found
6209 if (!DBA::isResult($r)) {
6210 $success = ['success' => false, 'search_results' => 'problem with query'];
6211 } elseif (count($r) == 0) {
6212 $success = ['success' => false, 'search_results' => 'nothing found'];
6215 foreach ($r as $item) {
6216 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6217 $recipient = $user_info;
6218 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6219 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6220 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6221 $sender = $user_info;
6224 if (isset($recipient) && isset($sender)) {
6225 $ret[] = api_format_messages($item, $recipient, $sender);
6228 $success = ['success' => true, 'search_results' => $ret];
6231 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6234 /// @TODO move to top of file or somewhere better
6235 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6238 * @brief return data of all the profiles a user has to the client
6240 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6241 * @return string|array
6242 * @throws BadRequestException
6243 * @throws ForbiddenException
6244 * @throws ImagickException
6245 * @throws InternalServerErrorException
6246 * @throws UnauthorizedException
6248 function api_friendica_profile_show($type)
6252 if (api_user() === false) {
6253 throw new ForbiddenException();
6257 $profile_id = $_REQUEST['profile_id'] ?? 0;
6259 // retrieve general information about profiles for user
6260 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6261 $directory = Config::get('system', 'directory');
6263 // get data of the specified profile id or all profiles of the user if not specified
6264 if ($profile_id != 0) {
6265 $r = Profile::getById(api_user(), $profile_id);
6266 // error message if specified gid is not in database
6267 if (!DBA::isResult($r)) {
6268 throw new BadRequestException("profile_id not available");
6271 $r = Profile::getListByUser(api_user());
6273 // loop through all returned profiles and retrieve data and users
6276 if (DBA::isResult($r)) {
6277 foreach ($r as $rr) {
6278 $profile = api_format_items_profiles($rr);
6280 // select all users from contact table, loop and prepare standard return for user data
6282 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6283 foreach ($nurls as $nurl) {
6284 $user = api_get_user($a, $nurl['nurl']);
6285 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6287 $profile['users'] = $users;
6289 // add prepared profile data to array for final return
6290 if ($type == "xml") {
6291 $profiles[$k++ . ":profile"] = $profile;
6293 $profiles[] = $profile;
6298 // return settings, authenticated user and profiles data
6299 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6301 $result = ['multi_profiles' => $multi_profiles ? true : false,
6302 'global_dir' => $directory,
6303 'friendica_owner' => api_get_user($a, $self['nurl']),
6304 'profiles' => $profiles];
6305 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6307 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6310 * Returns a list of saved searches.
6312 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6314 * @param string $type Return format: json or xml
6316 * @return string|array
6319 function api_saved_searches_list($type)
6321 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6324 while ($term = DBA::fetch($terms)) {
6326 'created_at' => api_date(time()),
6327 'id' => intval($term['id']),
6328 'id_str' => $term['id'],
6329 'name' => $term['term'],
6331 'query' => $term['term']
6337 return api_format_data("terms", $type, ['terms' => $result]);
6340 /// @TODO move to top of file or somewhere better
6341 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6344 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6346 * @brief Number of comments
6348 * @param object $data [Status, Status]
6352 function bindComments(&$data)
6354 if (count($data) == 0) {
6360 foreach ($data as $item) {
6361 $ids[] = $item['id'];
6364 $idStr = DBA::escape(implode(', ', $ids));
6365 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6366 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6367 $itemsData = DBA::toArray($items);
6369 foreach ($itemsData as $item) {
6370 $comments[$item['parent']] = $item['comments'];
6373 foreach ($data as $idx => $item) {
6375 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6380 @TODO Maybe open to implement?
6382 [pagename] => api/1.1/statuses/lookup.json
6383 [id] => 605138389168451584
6384 [include_cards] => true
6385 [cards_platform] => Android-12
6386 [include_entities] => true
6387 [include_my_retweet] => 1
6389 [include_reply_count] => true
6390 [include_descendent_reply_count] => true
6394 Not implemented by now:
6395 statuses/retweets_of_me
6400 account/update_location
6401 account/update_profile_background_image
6404 friendica/profile/update
6405 friendica/profile/create
6406 friendica/profile/delete
6408 Not implemented in status.net:
6409 statuses/retweeted_to_me
6410 statuses/retweeted_by_me
6411 direct_messages/destroy
6413 account/update_delivery_device
6414 notifications/follow