3 * Friendica implementation of statusnet/twitter API
5 * @file include/api.php
6 * @todo Automatically detect if incoming data is HTML or BBCode
10 use Friendica\BaseObject;
11 use Friendica\Content\ContactSelector;
12 use Friendica\Content\Feature;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Core\Config;
16 use Friendica\Core\Hook;
17 use Friendica\Core\L10n;
18 use Friendica\Core\Logger;
19 use Friendica\Core\PConfig;
20 use Friendica\Core\Protocol;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Model\Contact;
26 use Friendica\Model\Group;
27 use Friendica\Model\Item;
28 use Friendica\Model\Mail;
29 use Friendica\Model\Notify;
30 use Friendica\Model\Photo;
31 use Friendica\Model\Profile;
32 use Friendica\Model\User;
33 use Friendica\Network\FKOAuth1;
34 use Friendica\Network\HTTPException;
35 use Friendica\Network\HTTPException\BadRequestException;
36 use Friendica\Network\HTTPException\ExpectationFailedException;
37 use Friendica\Network\HTTPException\ForbiddenException;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Network\HTTPException\MethodNotAllowedException;
40 use Friendica\Network\HTTPException\NotFoundException;
41 use Friendica\Network\HTTPException\NotImplementedException;
42 use Friendica\Network\HTTPException\TooManyRequestsException;
43 use Friendica\Network\HTTPException\UnauthorizedException;
44 use Friendica\Object\Image;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\Diaspora;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\Images;
49 use Friendica\Util\Network;
50 use Friendica\Util\Proxy as ProxyUtils;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
54 require_once __DIR__ . '/../mod/share.php';
55 require_once __DIR__ . '/../mod/item.php';
56 require_once __DIR__ . '/../mod/wall_upload.php';
58 define('API_METHOD_ANY', '*');
59 define('API_METHOD_GET', 'GET');
60 define('API_METHOD_POST', 'POST,PUT');
61 define('API_METHOD_DELETE', 'POST,DELETE');
63 define('API_LOG_PREFIX', 'API {action} - ');
69 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
70 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
71 * into a page, and visitors will post something without noticing it).
73 * @brief Auth API user
77 if (!empty($_SESSION['allow_api'])) {
85 * Clients can send 'source' parameter to be show in post metadata
86 * as "sent via <source>".
87 * Some clients doesn't send a source param, we support ones we know
90 * @brief Get source name from API client
93 * Client source name, default to "api" if unset/unknown
98 if (requestdata('source')) {
99 return requestdata('source');
102 // Support for known clients that doesn't send a source name
103 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
104 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
108 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
110 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
117 * @brief Format date for API
119 * @param string $str Source date, as UTC
120 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
123 function api_date($str)
125 // Wed May 23 06:01:13 +0000 2007
126 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
130 * Register a function to be the endpoint for defined API path.
132 * @brief Register API endpoint
134 * @param string $path API URL path, relative to System::baseUrl()
135 * @param string $func Function name to call on path request
136 * @param bool $auth API need logged user
137 * @param string $method HTTP method reqiured to call this endpoint.
138 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
139 * Default to API_METHOD_ANY
141 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
151 // Workaround for hotot
152 $path = str_replace("api/", "api/1.1/", $path);
162 * Log in user via OAuth1 or Simple HTTP Auth.
163 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
165 * @brief Login API user
168 * @throws ForbiddenException
169 * @throws InternalServerErrorException
170 * @throws UnauthorizedException
171 * @hook 'authenticate'
173 * 'username' => username from login form
174 * 'password' => password from login form
175 * 'authenticated' => return status,
176 * 'user_record' => return authenticated user record
178 function api_login(App $a)
180 $oauth1 = new FKOAuth1();
183 $request = OAuthRequest::from_request();
184 list($consumer, $token) = $oauth1->verify_request($request);
185 if (!is_null($token)) {
186 $oauth1->loginUser($token->uid);
187 Session::set('allow_api', true);
190 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
191 var_dump($consumer, $token);
193 } catch (Exception $e) {
194 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
197 // workaround for HTTP-auth in CGI mode
198 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
199 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
200 if (strlen($userpass)) {
201 list($name, $password) = explode(':', $userpass);
202 $_SERVER['PHP_AUTH_USER'] = $name;
203 $_SERVER['PHP_AUTH_PW'] = $password;
207 if (empty($_SERVER['PHP_AUTH_USER'])) {
208 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
209 header('WWW-Authenticate: Basic realm="Friendica"');
210 throw new UnauthorizedException("This API requires login");
213 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
214 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
216 // allow "user@server" login (but ignore 'server' part)
217 $at = strstr($user, "@", true);
222 // next code from mod/auth.php. needs better solution
226 'username' => trim($user),
227 'password' => trim($password),
228 'authenticated' => 0,
229 'user_record' => null,
233 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
234 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
235 * and later addons should not interfere with an earlier one that succeeded.
237 Hook::callAll('authenticate', $addon_auth);
239 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
240 $record = $addon_auth['user_record'];
242 $user_id = User::authenticate(trim($user), trim($password), true);
243 if ($user_id !== false) {
244 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
248 if (!DBA::isResult($record)) {
249 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
250 header('WWW-Authenticate: Basic realm="Friendica"');
251 //header('HTTP/1.0 401 Unauthorized');
252 //die('This api requires login');
253 throw new UnauthorizedException("This API requires login");
256 Session::setAuthenticatedForUser($a, $record);
258 $_SESSION["allow_api"] = true;
260 Hook::callAll('logged_in', $a->user);
264 * API endpoints can define which HTTP method to accept when called.
265 * This function check the current HTTP method agains endpoint
268 * @brief Check HTTP method of called API
270 * @param string $method Required methods, uppercase, separated by comma
273 function api_check_method($method)
275 if ($method == "*") {
278 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
282 * Authenticate user, call registered API function, set HTTP headers
284 * @brief Main API entry point
287 * @return string|array API call result
290 function api_call(App $a)
292 global $API, $called_api;
295 if (strpos($a->query_string, ".xml") > 0) {
298 if (strpos($a->query_string, ".json") > 0) {
301 if (strpos($a->query_string, ".rss") > 0) {
304 if (strpos($a->query_string, ".atom") > 0) {
309 foreach ($API as $p => $info) {
310 if (strpos($a->query_string, $p) === 0) {
311 if (!api_check_method($info['method'])) {
312 throw new MethodNotAllowedException();
315 $called_api = explode("/", $p);
316 //unset($_SERVER['PHP_AUTH_USER']);
318 /// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
319 if (!empty($info['auth']) && api_user() === false) {
323 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
324 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
326 $stamp = microtime(true);
327 $return = call_user_func($info['func'], $type);
328 $duration = floatval(microtime(true) - $stamp);
330 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
332 $a->getProfiler()->saveLog($a->getLogger(), API_LOG_PREFIX . 'performance');
334 if (false === $return) {
336 * api function returned false withour throw an
337 * exception. This should not happend, throw a 500
339 throw new InternalServerErrorException();
344 header("Content-Type: text/xml");
347 header("Content-Type: application/json");
348 if (!empty($return)) {
349 $json = json_encode(end($return));
350 if (!empty($_GET['callback'])) {
351 $json = $_GET['callback'] . "(" . $json . ")";
357 header("Content-Type: application/rss+xml");
358 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
361 header("Content-Type: application/atom+xml");
362 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
369 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => $a->query_string]);
370 throw new NotImplementedException();
371 } catch (HTTPException $e) {
372 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
373 return api_error($type, $e);
378 * @brief Format API error string
380 * @param string $type Return type (xml, json, rss, as)
381 * @param object $e HTTPException Error object
382 * @return string|array error message formatted as $type
384 function api_error($type, $e)
388 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
389 /// @TODO: https://dev.twitter.com/overview/api/response-codes
391 $error = ["error" => $error,
392 "code" => $e->getCode() . " " . $e->httpdesc,
393 "request" => $a->query_string];
395 $return = api_format_data('status', $type, ['status' => $error]);
399 header("Content-Type: text/xml");
402 header("Content-Type: application/json");
403 $return = json_encode($return);
406 header("Content-Type: application/rss+xml");
409 header("Content-Type: application/atom+xml");
417 * @brief Set values for RSS template
420 * @param array $arr Array to be passed to template
421 * @param array $user_info User info
423 * @throws BadRequestException
424 * @throws ImagickException
425 * @throws InternalServerErrorException
426 * @throws UnauthorizedException
427 * @todo find proper type-hints
429 function api_rss_extra(App $a, $arr, $user_info)
431 if (is_null($user_info)) {
432 $user_info = api_get_user($a);
435 $arr['$user'] = $user_info;
437 'alternate' => $user_info['url'],
438 'self' => System::baseUrl() . "/" . $a->query_string,
439 'base' => System::baseUrl(),
440 'updated' => api_date(null),
441 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
442 'language' => $user_info['lang'],
443 'logo' => System::baseUrl() . "/images/friendica-32.png",
451 * @brief Unique contact to contact url.
453 * @param int $id Contact id
454 * @return bool|string
455 * Contact url or False if contact id is unknown
458 function api_unique_id_to_nurl($id)
460 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
462 if (DBA::isResult($r)) {
470 * @brief Get user info array.
473 * @param int|string $contact_id Contact ID or URL
475 * @throws BadRequestException
476 * @throws ImagickException
477 * @throws InternalServerErrorException
478 * @throws UnauthorizedException
480 function api_get_user(App $a, $contact_id = null)
488 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
490 // Searching for contact URL
491 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
492 $user = DBA::escape(Strings::normaliseLink($contact_id));
494 $extra_query = "AND `contact`.`nurl` = '%s' ";
495 if (api_user() !== false) {
496 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
500 // Searching for contact id with uid = 0
501 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
502 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
505 throw new BadRequestException("User ID ".$contact_id." not found.");
509 $extra_query = "AND `contact`.`nurl` = '%s' ";
510 if (api_user() !== false) {
511 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
515 if (is_null($user) && !empty($_GET['user_id'])) {
516 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
519 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
523 $extra_query = "AND `contact`.`nurl` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && !empty($_GET['screen_name'])) {
529 $user = DBA::escape($_GET['screen_name']);
530 $extra_query = "AND `contact`.`nick` = '%s' ";
531 if (api_user() !== false) {
532 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
536 if (is_null($user) && !empty($_GET['profileurl'])) {
537 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
538 $extra_query = "AND `contact`.`nurl` = '%s' ";
539 if (api_user() !== false) {
540 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
544 // $called_api is the API path exploded on / and is expected to have at least 2 elements
545 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
546 $argid = count($called_api);
547 if (!empty($a->argv[$argid])) {
548 $data = explode(".", $a->argv[$argid]);
549 if (count($data) > 1) {
550 list($user, $null) = $data;
553 if (is_numeric($user)) {
554 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
558 $extra_query = "AND `contact`.`nurl` = '%s' ";
559 if (api_user() !== false) {
560 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
564 $user = DBA::escape($user);
565 $extra_query = "AND `contact`.`nick` = '%s' ";
566 if (api_user() !== false) {
567 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
572 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
575 if (api_user() === false) {
579 $user = $_SESSION['uid'];
580 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
584 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
588 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
594 // Selecting the id by priority, friendica first
595 if (is_array($uinfo)) {
596 api_best_nickname($uinfo);
599 // if the contact wasn't found, fetch it from the contacts with uid = 0
600 if (!DBA::isResult($uinfo)) {
602 throw new BadRequestException("User not found.");
605 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
607 if (DBA::isResult($contact)) {
608 // If no nick where given, extract it from the address
609 if (($contact['nick'] == "") || ($contact['name'] == $contact['nick'])) {
610 $contact['nick'] = api_get_nick($contact["url"]);
614 'id' => $contact["id"],
615 'id_str' => (string) $contact["id"],
616 'name' => $contact["name"],
617 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
618 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url']),
619 'description' => BBCode::toPlaintext($contact["about"]),
620 'profile_image_url' => $contact["micro"],
621 'profile_image_url_https' => $contact["micro"],
622 'profile_image_url_profile_size' => $contact["thumb"],
623 'profile_image_url_large' => $contact["photo"],
624 'url' => $contact["url"],
625 'protected' => false,
626 'followers_count' => 0,
627 'friends_count' => 0,
629 'created_at' => api_date($contact["created"]),
630 'favourites_count' => 0,
632 'time_zone' => 'UTC',
633 'geo_enabled' => false,
635 'statuses_count' => 0,
637 'contributors_enabled' => false,
638 'is_translator' => false,
639 'is_translation_enabled' => false,
640 'following' => false,
641 'follow_request_sent' => false,
642 'statusnet_blocking' => false,
643 'notifications' => false,
644 'statusnet_profile_url' => $contact["url"],
646 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
647 'pid' => Contact::getIdForURL($contact["url"], 0, true),
649 'network' => $contact["network"],
654 throw new BadRequestException("User ".$url." not found.");
658 if ($uinfo[0]['self']) {
659 if ($uinfo[0]['network'] == "") {
660 $uinfo[0]['network'] = Protocol::DFRN;
663 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
664 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
671 // Add a nick if it isn't present there
672 if (($uinfo[0]['nick'] == "") || ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
673 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
676 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
678 if (!empty($profile['about'])) {
679 $description = $profile['about'];
681 $description = $uinfo[0]["about"];
684 if (!empty($usr['default-location'])) {
685 $location = $usr['default-location'];
686 } elseif (!empty($uinfo[0]["location"])) {
687 $location = $uinfo[0]["location"];
689 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url']);
693 'id' => intval($pcontact_id),
694 'id_str' => (string) intval($pcontact_id),
695 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
696 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
697 'location' => $location,
698 'description' => BBCode::toPlaintext($description),
699 'profile_image_url' => $uinfo[0]['micro'],
700 'profile_image_url_https' => $uinfo[0]['micro'],
701 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
702 'profile_image_url_large' => $uinfo[0]["photo"],
703 'url' => $uinfo[0]['url'],
704 'protected' => false,
705 'followers_count' => intval($countfollowers),
706 'friends_count' => intval($countfriends),
708 'created_at' => api_date($uinfo[0]['created']),
709 'favourites_count' => intval($starred),
711 'time_zone' => 'UTC',
712 'geo_enabled' => false,
714 'statuses_count' => intval($countitems),
716 'contributors_enabled' => false,
717 'is_translator' => false,
718 'is_translation_enabled' => false,
719 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
720 'follow_request_sent' => false,
721 'statusnet_blocking' => false,
722 'notifications' => false,
724 //'statusnet_profile_url' => System::baseUrl()."/contact/".$uinfo[0]['cid'],
725 'statusnet_profile_url' => $uinfo[0]['url'],
726 'uid' => intval($uinfo[0]['uid']),
727 'cid' => intval($uinfo[0]['cid']),
728 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
729 'self' => $uinfo[0]['self'],
730 'network' => $uinfo[0]['network'],
733 // If this is a local user and it uses Frio, we can get its color preferences.
735 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
736 if ($theme_info['theme'] === 'frio') {
737 $schema = PConfig::get($ret['uid'], 'frio', 'schema');
739 if ($schema && ($schema != '---')) {
740 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
741 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
742 require_once $schemefile;
745 $nav_bg = PConfig::get($ret['uid'], 'frio', 'nav_bg');
746 $link_color = PConfig::get($ret['uid'], 'frio', 'link_color');
747 $bgcolor = PConfig::get($ret['uid'], 'frio', 'background_color');
749 if (empty($nav_bg)) {
752 if (empty($link_color)) {
753 $link_color = "#6fdbe8";
755 if (empty($bgcolor)) {
756 $bgcolor = "#ededed";
759 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
760 $ret['profile_link_color'] = str_replace('#', '', $link_color);
761 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
769 * @brief return api-formatted array for item's author and owner
772 * @param array $item item from db
773 * @return array(array:author, array:owner)
774 * @throws BadRequestException
775 * @throws ImagickException
776 * @throws InternalServerErrorException
777 * @throws UnauthorizedException
779 function api_item_get_user(App $a, $item)
781 $status_user = api_get_user($a, $item['author-id'] ?? null);
783 $author_user = $status_user;
785 $status_user["protected"] = $item['private'] ?? 0;
787 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
788 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
790 $owner_user = $author_user;
793 return ([$status_user, $author_user, $owner_user]);
797 * @brief walks recursively through an array with the possibility to change value and key
799 * @param array $array The array to walk through
800 * @param callable $callback The callback function
802 * @return array the transformed array
804 function api_walk_recursive(array &$array, callable $callback)
808 foreach ($array as $k => $v) {
810 if ($callback($v, $k)) {
811 $new_array[$k] = api_walk_recursive($v, $callback);
814 if ($callback($v, $k)) {
825 * @brief Callback function to transform the array in an array that can be transformed in a XML file
827 * @param mixed $item Array item value
828 * @param string $key Array key
830 * @return boolean Should the array item be deleted?
832 function api_reformat_xml(&$item, &$key)
834 if (is_bool($item)) {
835 $item = ($item ? "true" : "false");
838 if (substr($key, 0, 10) == "statusnet_") {
839 $key = "statusnet:".substr($key, 10);
840 } elseif (substr($key, 0, 10) == "friendica_") {
841 $key = "friendica:".substr($key, 10);
843 /// @TODO old-lost code?
845 // $key = "default:".$key;
851 * @brief Creates the XML from a JSON style array
853 * @param array $data JSON style array
854 * @param string $root_element Name of the root element
856 * @return string The XML data
858 function api_create_xml(array $data, $root_element)
860 $childname = key($data);
861 $data2 = array_pop($data);
863 $namespaces = ["" => "http://api.twitter.com",
864 "statusnet" => "http://status.net/schema/api/1/",
865 "friendica" => "http://friendi.ca/schema/api/1/",
866 "georss" => "http://www.georss.org/georss"];
868 /// @todo Auto detection of needed namespaces
869 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
873 if (is_array($data2)) {
875 api_walk_recursive($data2, "api_reformat_xml");
881 foreach ($data2 as $item) {
882 $data4[$i++ . ":" . $childname] = $item;
889 $data3 = [$root_element => $data2];
891 $ret = XML::fromArray($data3, $xml, false, $namespaces);
896 * @brief Formats the data according to the data type
898 * @param string $root_element Name of the root element
899 * @param string $type Return type (atom, rss, xml, json)
900 * @param array $data JSON style array
902 * @return array|string (string|array) XML data or JSON data
904 function api_format_data($root_element, $type, $data)
910 $ret = api_create_xml($data, $root_element);
925 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
926 * returns a 401 status code and an error message if not.
928 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
930 * @param string $type Return type (atom, rss, xml, json)
931 * @return array|string
932 * @throws BadRequestException
933 * @throws ForbiddenException
934 * @throws ImagickException
935 * @throws InternalServerErrorException
936 * @throws UnauthorizedException
938 function api_account_verify_credentials($type)
942 if (api_user() === false) {
943 throw new ForbiddenException();
946 unset($_REQUEST["user_id"]);
947 unset($_GET["user_id"]);
949 unset($_REQUEST["screen_name"]);
950 unset($_GET["screen_name"]);
952 $skip_status = $_REQUEST['skip_status'] ?? false;
954 $user_info = api_get_user($a);
956 // "verified" isn't used here in the standard
957 unset($user_info["verified"]);
959 // - Adding last status
961 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
963 $user_info['status'] = api_format_item($item, $type);
967 // "uid" and "self" are only needed for some internal stuff, so remove it from here
968 unset($user_info["uid"]);
969 unset($user_info["self"]);
971 return api_format_data("user", $type, ['user' => $user_info]);
974 /// @TODO move to top of file or somewhere better
975 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
978 * Get data from $_POST or $_GET
983 function requestdata($k)
985 if (!empty($_POST[$k])) {
988 if (!empty($_GET[$k])) {
995 * Deprecated function to upload media.
997 * @param string $type Return type (atom, rss, xml, json)
999 * @return array|string
1000 * @throws BadRequestException
1001 * @throws ForbiddenException
1002 * @throws ImagickException
1003 * @throws InternalServerErrorException
1004 * @throws UnauthorizedException
1006 function api_statuses_mediap($type)
1010 if (api_user() === false) {
1011 Logger::log('api_statuses_update: no user');
1012 throw new ForbiddenException();
1014 $user_info = api_get_user($a);
1016 $_REQUEST['profile_uid'] = api_user();
1017 $_REQUEST['api_source'] = true;
1018 $txt = requestdata('status');
1019 /// @TODO old-lost code?
1020 //$txt = urldecode(requestdata('status'));
1022 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1023 $txt = HTML::toBBCodeVideo($txt);
1024 $config = HTMLPurifier_Config::createDefault();
1025 $config->set('Cache.DefinitionImpl', null);
1026 $purifier = new HTMLPurifier($config);
1027 $txt = $purifier->purify($txt);
1029 $txt = HTML::toBBCode($txt);
1031 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1033 $picture = wall_upload_post($a, false);
1035 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1036 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1037 $item_id = item_post($a);
1039 // output the post that we just posted.
1040 return api_status_show($type, $item_id);
1043 /// @TODO move this to top of file or somewhere better!
1044 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1047 * Updates the user’s current status.
1049 * @param string $type Return type (atom, rss, xml, json)
1051 * @return array|string
1052 * @throws BadRequestException
1053 * @throws ForbiddenException
1054 * @throws ImagickException
1055 * @throws InternalServerErrorException
1056 * @throws TooManyRequestsException
1057 * @throws UnauthorizedException
1058 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1060 function api_statuses_update($type)
1064 if (api_user() === false) {
1065 Logger::log('api_statuses_update: no user');
1066 throw new ForbiddenException();
1071 // convert $_POST array items to the form we use for web posts.
1072 if (requestdata('htmlstatus')) {
1073 $txt = requestdata('htmlstatus');
1074 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1075 $txt = HTML::toBBCodeVideo($txt);
1077 $config = HTMLPurifier_Config::createDefault();
1078 $config->set('Cache.DefinitionImpl', null);
1080 $purifier = new HTMLPurifier($config);
1081 $txt = $purifier->purify($txt);
1083 $_REQUEST['body'] = HTML::toBBCode($txt);
1086 $_REQUEST['body'] = requestdata('status');
1089 $_REQUEST['title'] = requestdata('title');
1091 $parent = requestdata('in_reply_to_status_id');
1093 // Twidere sends "-1" if it is no reply ...
1094 if ($parent == -1) {
1098 if (ctype_digit($parent)) {
1099 $_REQUEST['parent'] = $parent;
1101 $_REQUEST['parent_uri'] = $parent;
1104 if (requestdata('lat') && requestdata('long')) {
1105 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1107 $_REQUEST['profile_uid'] = api_user();
1110 // Check for throttling (maximum posts per day, week and month)
1111 $throttle_day = Config::get('system', 'throttle_limit_day');
1112 if ($throttle_day > 0) {
1113 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1115 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1116 $posts_day = DBA::count('thread', $condition);
1118 if ($posts_day > $throttle_day) {
1119 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1120 // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1121 throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1125 $throttle_week = Config::get('system', 'throttle_limit_week');
1126 if ($throttle_week > 0) {
1127 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1129 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1130 $posts_week = DBA::count('thread', $condition);
1132 if ($posts_week > $throttle_week) {
1133 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1134 // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1135 throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
1139 $throttle_month = Config::get('system', 'throttle_limit_month');
1140 if ($throttle_month > 0) {
1141 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1143 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1144 $posts_month = DBA::count('thread', $condition);
1146 if ($posts_month > $throttle_month) {
1147 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1148 // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1149 throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1154 if (!empty($_FILES['media'])) {
1155 // upload the image if we have one
1156 $picture = wall_upload_post($a, false);
1157 if (is_array($picture)) {
1158 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1162 if (requestdata('media_ids')) {
1163 $ids = explode(',', requestdata('media_ids'));
1164 foreach ($ids as $id) {
1166 "SELECT `resource-id`, `scale`, `nickname`, `type`, `desc` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1170 if (DBA::isResult($r)) {
1171 $phototypes = Images::supportedTypes();
1172 $ext = $phototypes[$r[0]['type']];
1173 $description = $r[0]['desc'] ?? '';
1174 $_REQUEST['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1175 $_REQUEST['body'] .= '[img=' . System::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1180 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1182 $_REQUEST['api_source'] = true;
1184 if (empty($_REQUEST['source'])) {
1185 $_REQUEST["source"] = api_source();
1188 // call out normal post function
1189 $item_id = item_post($a);
1191 // output the post that we just posted.
1192 return api_status_show($type, $item_id);
1195 /// @TODO move to top of file or somewhere better
1196 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1197 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1200 * Uploads an image to Friendica.
1203 * @throws BadRequestException
1204 * @throws ForbiddenException
1205 * @throws ImagickException
1206 * @throws InternalServerErrorException
1207 * @throws UnauthorizedException
1208 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1210 function api_media_upload()
1214 if (api_user() === false) {
1215 Logger::log('no user');
1216 throw new ForbiddenException();
1221 if (empty($_FILES['media'])) {
1223 throw new BadRequestException("No media.");
1226 $media = wall_upload_post($a, false);
1229 throw new InternalServerErrorException();
1233 $returndata["media_id"] = $media["id"];
1234 $returndata["media_id_string"] = (string)$media["id"];
1235 $returndata["size"] = $media["size"];
1236 $returndata["image"] = ["w" => $media["width"],
1237 "h" => $media["height"],
1238 "image_type" => $media["type"],
1239 "friendica_preview_url" => $media["preview"]];
1241 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1243 return ["media" => $returndata];
1246 /// @TODO move to top of file or somewhere better
1247 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1250 * Updates media meta data (picture descriptions)
1252 * @param string $type Return type (atom, rss, xml, json)
1254 * @return array|string
1255 * @throws BadRequestException
1256 * @throws ForbiddenException
1257 * @throws ImagickException
1258 * @throws InternalServerErrorException
1259 * @throws TooManyRequestsException
1260 * @throws UnauthorizedException
1261 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1263 * @todo Compare the corresponding Twitter function for correct return values
1265 function api_media_metadata_create($type)
1269 if (api_user() === false) {
1270 Logger::info('no user');
1271 throw new ForbiddenException();
1276 $postdata = Network::postdata();
1278 if (empty($postdata)) {
1279 throw new BadRequestException("No post data");
1282 $data = json_decode($postdata, true);
1284 throw new BadRequestException("Invalid post data");
1287 if (empty($data['media_id']) || empty($data['alt_text'])) {
1288 throw new BadRequestException("Missing post data values");
1291 if (empty($data['alt_text']['text'])) {
1292 throw new BadRequestException("No alt text.");
1295 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1297 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1298 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1299 if (!DBA::isResult($photo)) {
1300 throw new BadRequestException("Metadata not found.");
1303 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1306 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1309 * @param string $type Return format (atom, rss, xml, json)
1310 * @param int $item_id
1314 function api_status_show($type, $item_id)
1316 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1320 $item = api_get_item(['id' => $item_id]);
1322 $status_info = api_format_item($item, $type);
1325 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1327 return api_format_data('statuses', $type, ['status' => $status_info]);
1331 * Retrieves the last public status of the provided user info
1333 * @param int $ownerId Public contact Id
1334 * @param int $uid User Id
1338 function api_get_last_status($ownerId, $uid)
1341 'author-id'=> $ownerId,
1343 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1347 $item = api_get_item($condition);
1353 * Retrieves a single item record based on the provided condition and converts it for API use.
1355 * @param array $condition Item table condition array
1359 function api_get_item(array $condition)
1361 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1367 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1368 * The author's most recent status will be returned inline.
1370 * @param string $type Return type (atom, rss, xml, json)
1371 * @return array|string
1372 * @throws BadRequestException
1373 * @throws ImagickException
1374 * @throws InternalServerErrorException
1375 * @throws UnauthorizedException
1376 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1378 function api_users_show($type)
1380 $a = BaseObject::getApp();
1382 $user_info = api_get_user($a);
1384 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1386 $user_info['status'] = api_format_item($item, $type);
1389 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1390 unset($user_info['uid']);
1391 unset($user_info['self']);
1393 return api_format_data('user', $type, ['user' => $user_info]);
1396 /// @TODO move to top of file or somewhere better
1397 api_register_func('api/users/show', 'api_users_show');
1398 api_register_func('api/externalprofile/show', 'api_users_show');
1401 * Search a public user account.
1403 * @param string $type Return type (atom, rss, xml, json)
1405 * @return array|string
1406 * @throws BadRequestException
1407 * @throws ImagickException
1408 * @throws InternalServerErrorException
1409 * @throws UnauthorizedException
1410 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1412 function api_users_search($type)
1418 if (!empty($_GET['q'])) {
1419 $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", DBA::escape($_GET["q"]));
1421 if (!DBA::isResult($r)) {
1422 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", DBA::escape($_GET["q"]));
1425 if (DBA::isResult($r)) {
1427 foreach ($r as $user) {
1428 $user_info = api_get_user($a, $user["id"]);
1430 if ($type == "xml") {
1431 $userlist[$k++.":user"] = $user_info;
1433 $userlist[] = $user_info;
1436 $userlist = ["users" => $userlist];
1438 throw new BadRequestException("User ".$_GET["q"]." not found.");
1441 throw new BadRequestException("No user specified.");
1444 return api_format_data("users", $type, $userlist);
1447 /// @TODO move to top of file or somewhere better
1448 api_register_func('api/users/search', 'api_users_search');
1451 * Return user objects
1453 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1455 * @param string $type Return format: json or xml
1457 * @return array|string
1458 * @throws BadRequestException
1459 * @throws ImagickException
1460 * @throws InternalServerErrorException
1461 * @throws NotFoundException if the results are empty.
1462 * @throws UnauthorizedException
1464 function api_users_lookup($type)
1468 if (!empty($_REQUEST['user_id'])) {
1469 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1471 $users[] = api_get_user(get_app(), $id);
1476 if (empty($users)) {
1477 throw new NotFoundException;
1480 return api_format_data("users", $type, ['users' => $users]);
1483 /// @TODO move to top of file or somewhere better
1484 api_register_func('api/users/lookup', 'api_users_lookup', true);
1487 * Returns statuses that match a specified query.
1489 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1491 * @param string $type Return format: json, xml, atom, rss
1493 * @return array|string
1494 * @throws BadRequestException if the "q" parameter is missing.
1495 * @throws ForbiddenException
1496 * @throws ImagickException
1497 * @throws InternalServerErrorException
1498 * @throws UnauthorizedException
1500 function api_search($type)
1503 $user_info = api_get_user($a);
1505 if (api_user() === false || $user_info === false) { throw new ForbiddenException(); }
1507 if (empty($_REQUEST['q'])) {
1508 throw new BadRequestException('q parameter is required.');
1511 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1514 $data['status'] = [];
1516 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1517 if (!empty($_REQUEST['rpp'])) {
1518 $count = $_REQUEST['rpp'];
1519 } elseif (!empty($_REQUEST['count'])) {
1520 $count = $_REQUEST['count'];
1523 $since_id = $_REQUEST['since_id'] ?? 0;
1524 $max_id = $_REQUEST['max_id'] ?? 0;
1525 $page = $_REQUEST['page'] ?? 1;
1527 $start = max(0, ($page - 1) * $count);
1529 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1530 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1531 $searchTerm = $matches[1];
1532 $condition = ["`oid` > ?
1533 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1534 AND `otype` = ? AND `type` = ? AND `term` = ?",
1535 $since_id, local_user(), TERM_OBJ_POST, TERM_HASHTAG, $searchTerm];
1537 $condition[0] .= ' AND `oid` <= ?';
1538 $condition[] = $max_id;
1540 $terms = DBA::select('term', ['oid'], $condition, []);
1542 while ($term = DBA::fetch($terms)) {
1543 $itemIds[] = $term['oid'];
1547 if (empty($itemIds)) {
1548 return api_format_data('statuses', $type, $data);
1551 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1552 if ($exclude_replies) {
1553 $preCondition[] = '`id` = `parent`';
1556 $condition = [implode(' AND ', $preCondition)];
1558 $condition = ["`id` > ?
1559 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1560 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1561 AND `body` LIKE CONCAT('%',?,'%')",
1562 $since_id, api_user(), $_REQUEST['q']];
1564 $condition[0] .= ' AND `id` <= ?';
1565 $condition[] = $max_id;
1569 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1571 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1573 bindComments($data['status']);
1575 return api_format_data('statuses', $type, $data);
1578 /// @TODO move to top of file or somewhere better
1579 api_register_func('api/search/tweets', 'api_search', true);
1580 api_register_func('api/search', 'api_search', true);
1583 * Returns the most recent statuses posted by the user and the users they follow.
1585 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1587 * @param string $type Return type (atom, rss, xml, json)
1589 * @return array|string
1590 * @throws BadRequestException
1591 * @throws ForbiddenException
1592 * @throws ImagickException
1593 * @throws InternalServerErrorException
1594 * @throws UnauthorizedException
1595 * @todo Optional parameters
1596 * @todo Add reply info
1598 function api_statuses_home_timeline($type)
1601 $user_info = api_get_user($a);
1603 if (api_user() === false || $user_info === false) {
1604 throw new ForbiddenException();
1607 unset($_REQUEST["user_id"]);
1608 unset($_GET["user_id"]);
1610 unset($_REQUEST["screen_name"]);
1611 unset($_GET["screen_name"]);
1613 // get last network messages
1616 $count = $_REQUEST['count'] ?? 20;
1617 $page = $_REQUEST['page']?? 0;
1618 $since_id = $_REQUEST['since_id'] ?? 0;
1619 $max_id = $_REQUEST['max_id'] ?? 0;
1620 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1621 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1623 $start = max(0, ($page - 1) * $count);
1625 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1626 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1629 $condition[0] .= " AND `item`.`id` <= ?";
1630 $condition[] = $max_id;
1632 if ($exclude_replies) {
1633 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1635 if ($conversation_id > 0) {
1636 $condition[0] .= " AND `item`.`parent` = ?";
1637 $condition[] = $conversation_id;
1640 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1641 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1643 $items = Item::inArray($statuses);
1645 $ret = api_format_items($items, $user_info, false, $type);
1647 // Set all posts from the query above to seen
1649 foreach ($items as $item) {
1650 $idarray[] = intval($item["id"]);
1653 if (!empty($idarray)) {
1654 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1656 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1662 $data = ['status' => $ret];
1667 $data = api_rss_extra($a, $data, $user_info);
1671 return api_format_data("statuses", $type, $data);
1675 /// @TODO move to top of file or somewhere better
1676 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1677 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1680 * Returns the most recent statuses from public users.
1682 * @param string $type Return type (atom, rss, xml, json)
1684 * @return array|string
1685 * @throws BadRequestException
1686 * @throws ForbiddenException
1687 * @throws ImagickException
1688 * @throws InternalServerErrorException
1689 * @throws UnauthorizedException
1691 function api_statuses_public_timeline($type)
1694 $user_info = api_get_user($a);
1696 if (api_user() === false || $user_info === false) {
1697 throw new ForbiddenException();
1700 // get last network messages
1703 $count = $_REQUEST['count'] ?? 20;
1704 $page = $_REQUEST['page'] ?? 1;
1705 $since_id = $_REQUEST['since_id'] ?? 0;
1706 $max_id = $_REQUEST['max_id'] ?? 0;
1707 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1708 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1710 $start = max(0, ($page - 1) * $count);
1712 if ($exclude_replies && !$conversation_id) {
1713 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1714 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1717 $condition[0] .= " AND `thread`.`iid` <= ?";
1718 $condition[] = $max_id;
1721 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1722 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1724 $r = Item::inArray($statuses);
1726 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1727 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1730 $condition[0] .= " AND `item`.`id` <= ?";
1731 $condition[] = $max_id;
1733 if ($conversation_id > 0) {
1734 $condition[0] .= " AND `item`.`parent` = ?";
1735 $condition[] = $conversation_id;
1738 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1739 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1741 $r = Item::inArray($statuses);
1744 $ret = api_format_items($r, $user_info, false, $type);
1748 $data = ['status' => $ret];
1753 $data = api_rss_extra($a, $data, $user_info);
1757 return api_format_data("statuses", $type, $data);
1760 /// @TODO move to top of file or somewhere better
1761 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1764 * Returns the most recent statuses posted by users this node knows about.
1766 * @brief Returns the list of public federated posts this node knows about
1768 * @param string $type Return format: json, xml, atom, rss
1769 * @return array|string
1770 * @throws BadRequestException
1771 * @throws ForbiddenException
1772 * @throws ImagickException
1773 * @throws InternalServerErrorException
1774 * @throws UnauthorizedException
1776 function api_statuses_networkpublic_timeline($type)
1779 $user_info = api_get_user($a);
1781 if (api_user() === false || $user_info === false) {
1782 throw new ForbiddenException();
1785 $since_id = $_REQUEST['since_id'] ?? 0;
1786 $max_id = $_REQUEST['max_id'] ?? 0;
1789 $count = $_REQUEST['count'] ?? 20;
1790 $page = $_REQUEST['page'] ?? 1;
1792 $start = max(0, ($page - 1) * $count);
1794 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`",
1795 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1798 $condition[0] .= " AND `thread`.`iid` <= ?";
1799 $condition[] = $max_id;
1802 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1803 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1805 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1809 $data = ['status' => $ret];
1814 $data = api_rss_extra($a, $data, $user_info);
1818 return api_format_data("statuses", $type, $data);
1821 /// @TODO move to top of file or somewhere better
1822 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1825 * Returns a single status.
1827 * @param string $type Return type (atom, rss, xml, json)
1829 * @return array|string
1830 * @throws BadRequestException
1831 * @throws ForbiddenException
1832 * @throws ImagickException
1833 * @throws InternalServerErrorException
1834 * @throws UnauthorizedException
1835 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1837 function api_statuses_show($type)
1840 $user_info = api_get_user($a);
1842 if (api_user() === false || $user_info === false) {
1843 throw new ForbiddenException();
1847 $id = intval($a->argv[3] ?? 0);
1850 $id = intval($_REQUEST['id'] ?? 0);
1855 $id = intval($a->argv[4] ?? 0);
1858 Logger::log('API: api_statuses_show: ' . $id);
1860 $conversation = !empty($_REQUEST['conversation']);
1862 // try to fetch the item for the local user - or the public item, if there is no local one
1863 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1864 if (!DBA::isResult($uri_item)) {
1865 throw new BadRequestException("There is no status with this id.");
1868 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1869 if (!DBA::isResult($item)) {
1870 throw new BadRequestException("There is no status with this id.");
1875 if ($conversation) {
1876 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1877 $params = ['order' => ['id' => true]];
1879 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1883 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1885 /// @TODO How about copying this to above methods which don't check $r ?
1886 if (!DBA::isResult($statuses)) {
1887 throw new BadRequestException("There is no status with this id.");
1890 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1892 if ($conversation) {
1893 $data = ['status' => $ret];
1894 return api_format_data("statuses", $type, $data);
1896 $data = ['status' => $ret[0]];
1897 return api_format_data("status", $type, $data);
1901 /// @TODO move to top of file or somewhere better
1902 api_register_func('api/statuses/show', 'api_statuses_show', true);
1906 * @param string $type Return type (atom, rss, xml, json)
1908 * @return array|string
1909 * @throws BadRequestException
1910 * @throws ForbiddenException
1911 * @throws ImagickException
1912 * @throws InternalServerErrorException
1913 * @throws UnauthorizedException
1914 * @todo nothing to say?
1916 function api_conversation_show($type)
1919 $user_info = api_get_user($a);
1921 if (api_user() === false || $user_info === false) {
1922 throw new ForbiddenException();
1926 $id = intval($a->argv[3] ?? 0);
1927 $since_id = intval($_REQUEST['since_id'] ?? 0);
1928 $max_id = intval($_REQUEST['max_id'] ?? 0);
1929 $count = intval($_REQUEST['count'] ?? 20);
1930 $page = intval($_REQUEST['page'] ?? 1);
1932 $start = max(0, ($page - 1) * $count);
1935 $id = intval($_REQUEST['id'] ?? 0);
1940 $id = intval($a->argv[4] ?? 0);
1943 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1945 // try to fetch the item for the local user - or the public item, if there is no local one
1946 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1947 if (!DBA::isResult($item)) {
1948 throw new BadRequestException("There is no status with this id.");
1951 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1952 if (!DBA::isResult($parent)) {
1953 throw new BadRequestException("There is no status with this id.");
1956 $id = $parent['id'];
1958 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1959 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1962 $condition[0] .= " AND `item`.`id` <= ?";
1963 $condition[] = $max_id;
1966 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1967 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1969 if (!DBA::isResult($statuses)) {
1970 throw new BadRequestException("There is no status with id $id.");
1973 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1975 $data = ['status' => $ret];
1976 return api_format_data("statuses", $type, $data);
1979 /// @TODO move to top of file or somewhere better
1980 api_register_func('api/conversation/show', 'api_conversation_show', true);
1981 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1986 * @param string $type Return type (atom, rss, xml, json)
1988 * @return array|string
1989 * @throws BadRequestException
1990 * @throws ForbiddenException
1991 * @throws ImagickException
1992 * @throws InternalServerErrorException
1993 * @throws UnauthorizedException
1994 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1996 function api_statuses_repeat($type)
2002 if (api_user() === false) {
2003 throw new ForbiddenException();
2009 $id = intval($a->argv[3] ?? 0);
2012 $id = intval($_REQUEST['id'] ?? 0);
2017 $id = intval($a->argv[4] ?? 0);
2020 Logger::log('API: api_statuses_repeat: '.$id);
2022 $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2023 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
2025 if (DBA::isResult($item) && $item['body'] != "") {
2026 if (strpos($item['body'], "[/share]") !== false) {
2027 $pos = strpos($item['body'], "[share");
2028 $post = substr($item['body'], $pos);
2030 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2032 $post .= $item['body'];
2033 $post .= "[/share]";
2035 $_REQUEST['body'] = $post;
2036 $_REQUEST['profile_uid'] = api_user();
2037 $_REQUEST['api_source'] = true;
2039 if (empty($_REQUEST['source'])) {
2040 $_REQUEST["source"] = api_source();
2043 $item_id = item_post($a);
2045 throw new ForbiddenException();
2048 // output the post that we just posted.
2050 return api_status_show($type, $item_id);
2053 /// @TODO move to top of file or somewhere better
2054 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2057 * Destroys a specific status.
2059 * @param string $type Return type (atom, rss, xml, json)
2061 * @return array|string
2062 * @throws BadRequestException
2063 * @throws ForbiddenException
2064 * @throws ImagickException
2065 * @throws InternalServerErrorException
2066 * @throws UnauthorizedException
2067 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2069 function api_statuses_destroy($type)
2073 if (api_user() === false) {
2074 throw new ForbiddenException();
2080 $id = intval($a->argv[3] ?? 0);
2083 $id = intval($_REQUEST['id'] ?? 0);
2088 $id = intval($a->argv[4] ?? 0);
2091 Logger::log('API: api_statuses_destroy: '.$id);
2093 $ret = api_statuses_show($type);
2095 Item::deleteForUser(['id' => $id], api_user());
2100 /// @TODO move to top of file or somewhere better
2101 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2104 * Returns the most recent mentions.
2106 * @param string $type Return type (atom, rss, xml, json)
2108 * @return array|string
2109 * @throws BadRequestException
2110 * @throws ForbiddenException
2111 * @throws ImagickException
2112 * @throws InternalServerErrorException
2113 * @throws UnauthorizedException
2114 * @see http://developer.twitter.com/doc/get/statuses/mentions
2116 function api_statuses_mentions($type)
2119 $user_info = api_get_user($a);
2121 if (api_user() === false || $user_info === false) {
2122 throw new ForbiddenException();
2125 unset($_REQUEST["user_id"]);
2126 unset($_GET["user_id"]);
2128 unset($_REQUEST["screen_name"]);
2129 unset($_GET["screen_name"]);
2131 // get last network messages
2134 $since_id = $_REQUEST['since_id'] ?? 0;
2135 $max_id = $_REQUEST['max_id'] ?? 0;
2136 $count = $_REQUEST['count'] ?? 20;
2137 $page = $_REQUEST['page'] ?? 1;
2139 $start = max(0, ($page - 1) * $count);
2141 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `author-id` != ?
2142 AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `thread`.`uid` = ? AND `thread`.`mention` AND NOT `thread`.`ignored`)",
2143 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['pid'], api_user()];
2146 $condition[0] .= " AND `item`.`id` <= ?";
2147 $condition[] = $max_id;
2150 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2151 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2153 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2155 $data = ['status' => $ret];
2160 $data = api_rss_extra($a, $data, $user_info);
2164 return api_format_data("statuses", $type, $data);
2167 /// @TODO move to top of file or somewhere better
2168 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2169 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2172 * Returns the most recent statuses posted by the user.
2174 * @brief Returns a user's public timeline
2176 * @param string $type Either "json" or "xml"
2177 * @return string|array
2178 * @throws BadRequestException
2179 * @throws ForbiddenException
2180 * @throws ImagickException
2181 * @throws InternalServerErrorException
2182 * @throws UnauthorizedException
2183 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2185 function api_statuses_user_timeline($type)
2188 $user_info = api_get_user($a);
2190 if (api_user() === false || $user_info === false) {
2191 throw new ForbiddenException();
2195 "api_statuses_user_timeline: api_user: ". api_user() .
2196 "\nuser_info: ".print_r($user_info, true) .
2197 "\n_REQUEST: ".print_r($_REQUEST, true),
2201 $since_id = $_REQUEST['since_id'] ?? 0;
2202 $max_id = $_REQUEST['max_id'] ?? 0;
2203 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2204 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2207 $count = $_REQUEST['count'] ?? 20;
2208 $page = $_REQUEST['page'] ?? 1;
2210 $start = max(0, ($page - 1) * $count);
2212 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2213 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2215 if ($user_info['self'] == 1) {
2216 $condition[0] .= ' AND `item`.`wall` ';
2219 if ($exclude_replies) {
2220 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2223 if ($conversation_id > 0) {
2224 $condition[0] .= " AND `item`.`parent` = ?";
2225 $condition[] = $conversation_id;
2229 $condition[0] .= " AND `item`.`id` <= ?";
2230 $condition[] = $max_id;
2233 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2234 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2236 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2240 $data = ['status' => $ret];
2245 $data = api_rss_extra($a, $data, $user_info);
2249 return api_format_data("statuses", $type, $data);
2252 /// @TODO move to top of file or somewhere better
2253 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2256 * Star/unstar an item.
2257 * param: id : id of the item
2259 * @param string $type Return type (atom, rss, xml, json)
2261 * @return array|string
2262 * @throws BadRequestException
2263 * @throws ForbiddenException
2264 * @throws ImagickException
2265 * @throws InternalServerErrorException
2266 * @throws UnauthorizedException
2267 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2269 function api_favorites_create_destroy($type)
2273 if (api_user() === false) {
2274 throw new ForbiddenException();
2277 // for versioned api.
2278 /// @TODO We need a better global soluton
2279 $action_argv_id = 2;
2280 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2281 $action_argv_id = 3;
2284 if ($a->argc <= $action_argv_id) {
2285 throw new BadRequestException("Invalid request.");
2287 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2288 if ($a->argc == $action_argv_id + 2) {
2289 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2291 $itemid = intval($_REQUEST['id'] ?? 0);
2294 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2296 if (!DBA::isResult($item)) {
2297 throw new BadRequestException("Invalid item.");
2302 $item['starred'] = 1;
2305 $item['starred'] = 0;
2308 throw new BadRequestException("Invalid action ".$action);
2311 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2314 throw new InternalServerErrorException("DB error");
2318 $user_info = api_get_user($a);
2319 $rets = api_format_items([$item], $user_info, false, $type);
2322 $data = ['status' => $ret];
2327 $data = api_rss_extra($a, $data, $user_info);
2331 return api_format_data("status", $type, $data);
2334 /// @TODO move to top of file or somewhere better
2335 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2336 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2339 * Returns the most recent favorite statuses.
2341 * @param string $type Return type (atom, rss, xml, json)
2343 * @return string|array
2344 * @throws BadRequestException
2345 * @throws ForbiddenException
2346 * @throws ImagickException
2347 * @throws InternalServerErrorException
2348 * @throws UnauthorizedException
2350 function api_favorites($type)
2355 $user_info = api_get_user($a);
2357 if (api_user() === false || $user_info === false) {
2358 throw new ForbiddenException();
2363 // in friendica starred item are private
2364 // return favorites only for self
2365 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2367 if ($user_info['self'] == 0) {
2371 $since_id = $_REQUEST['since_id'] ?? 0;
2372 $max_id = $_REQUEST['max_id'] ?? 0;
2373 $count = $_GET['count'] ?? 20;
2374 $page = $_REQUEST['page'] ?? 1;
2376 $start = max(0, ($page - 1) * $count);
2378 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2379 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2381 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2384 $condition[0] .= " AND `item`.`id` <= ?";
2385 $condition[] = $max_id;
2388 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2390 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2395 $data = ['status' => $ret];
2400 $data = api_rss_extra($a, $data, $user_info);
2404 return api_format_data("statuses", $type, $data);
2407 /// @TODO move to top of file or somewhere better
2408 api_register_func('api/favorites', 'api_favorites', true);
2412 * @param array $item
2413 * @param array $recipient
2414 * @param array $sender
2417 * @throws InternalServerErrorException
2419 function api_format_messages($item, $recipient, $sender)
2421 // standard meta information
2423 'id' => $item['id'],
2424 'sender_id' => $sender['id'],
2426 'recipient_id' => $recipient['id'],
2427 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2428 'sender_screen_name' => $sender['screen_name'],
2429 'recipient_screen_name' => $recipient['screen_name'],
2430 'sender' => $sender,
2431 'recipient' => $recipient,
2433 'friendica_seen' => $item['seen'] ?? 0,
2434 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2437 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2438 if (isset($ret['sender']['uid'])) {
2439 unset($ret['sender']['uid']);
2441 if (isset($ret['sender']['self'])) {
2442 unset($ret['sender']['self']);
2444 if (isset($ret['recipient']['uid'])) {
2445 unset($ret['recipient']['uid']);
2447 if (isset($ret['recipient']['self'])) {
2448 unset($ret['recipient']['self']);
2451 //don't send title to regular StatusNET requests to avoid confusing these apps
2452 if (!empty($_GET['getText'])) {
2453 $ret['title'] = $item['title'];
2454 if ($_GET['getText'] == 'html') {
2455 $ret['text'] = BBCode::convert($item['body'], false);
2456 } elseif ($_GET['getText'] == 'plain') {
2457 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2460 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2462 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2463 unset($ret['sender']);
2464 unset($ret['recipient']);
2472 * @param array $item
2475 * @throws InternalServerErrorException
2477 function api_convert_item($item)
2479 $body = $item['body'];
2480 $attachments = api_get_attachments($body);
2482 // Workaround for ostatus messages where the title is identically to the body
2483 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2484 $statusbody = trim(HTML::toPlaintext($html, 0));
2486 // handle data: images
2487 $statusbody = api_format_items_embeded_images($item, $statusbody);
2489 $statustitle = trim($item['title']);
2491 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2492 $statustext = trim($statusbody);
2494 $statustext = trim($statustitle."\n\n".$statusbody);
2497 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2498 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2501 $statushtml = BBCode::convert(api_clean_attachments($body), false);
2503 // Workaround for clients with limited HTML parser functionality
2504 $search = ["<br>", "<blockquote>", "</blockquote>",
2505 "<h1>", "</h1>", "<h2>", "</h2>",
2506 "<h3>", "</h3>", "<h4>", "</h4>",
2507 "<h5>", "</h5>", "<h6>", "</h6>"];
2508 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2509 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2510 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2511 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2512 $statushtml = str_replace($search, $replace, $statushtml);
2514 if ($item['title'] != "") {
2515 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2519 $oldtext = $statushtml;
2520 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2521 } while ($oldtext != $statushtml);
2523 if (substr($statushtml, 0, 4) == '<br>') {
2524 $statushtml = substr($statushtml, 4);
2527 if (substr($statushtml, 0, -4) == '<br>') {
2528 $statushtml = substr($statushtml, -4);
2531 // feeds without body should contain the link
2532 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2533 $statushtml .= BBCode::convert($item['plink']);
2536 $entities = api_get_entitities($statustext, $body);
2539 "text" => $statustext,
2540 "html" => $statushtml,
2541 "attachments" => $attachments,
2542 "entities" => $entities
2548 * @param string $body
2551 * @throws InternalServerErrorException
2553 function api_get_attachments(&$body)
2556 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2557 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $text);
2559 $URLSearchString = "^\[\]";
2560 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2568 foreach ($images[1] as $image) {
2569 $imagedata = Images::getInfoFromURLCached($image);
2572 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2576 if (strstr($_SERVER['HTTP_USER_AGENT'] ?? '', 'AndStatus')) {
2577 foreach ($images[0] as $orig) {
2578 $body = str_replace($orig, "", $body);
2582 return $attachments;
2587 * @param string $text
2588 * @param string $bbcode
2591 * @throws InternalServerErrorException
2592 * @todo Links at the first character of the post
2594 function api_get_entitities(&$text, $bbcode)
2596 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2598 if ($include_entities != "true") {
2599 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2601 foreach ($images[1] as $image) {
2602 $replace = ProxyUtils::proxifyUrl($image);
2603 $text = str_replace($image, $replace, $text);
2608 $bbcode = BBCode::cleanPictureLinks($bbcode);
2610 // Change pure links in text to bbcode uris
2611 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2614 $entities["hashtags"] = [];
2615 $entities["symbols"] = [];
2616 $entities["urls"] = [];
2617 $entities["user_mentions"] = [];
2619 $URLSearchString = "^\[\]";
2621 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2623 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2624 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2625 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2627 $bbcode = preg_replace(
2628 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2629 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2632 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2634 $bbcode = preg_replace(
2635 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2636 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2639 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2641 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2643 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2644 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2647 foreach ($urls[1] as $id => $url) {
2648 //$start = strpos($text, $url, $offset);
2649 $start = iconv_strpos($text, $url, 0, "UTF-8");
2650 if (!($start === false)) {
2651 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2655 ksort($ordered_urls);
2658 //foreach ($urls[1] AS $id=>$url) {
2659 foreach ($ordered_urls as $url) {
2660 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2661 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2663 $display_url = $url["title"];
2665 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2666 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2668 if (strlen($display_url) > 26) {
2669 $display_url = substr($display_url, 0, 25)."…";
2673 //$start = strpos($text, $url, $offset);
2674 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2675 if (!($start === false)) {
2676 $entities["urls"][] = ["url" => $url["url"],
2677 "expanded_url" => $url["url"],
2678 "display_url" => $display_url,
2679 "indices" => [$start, $start+strlen($url["url"])]];
2680 $offset = $start + 1;
2684 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2685 $ordered_images = [];
2686 foreach ($images as $image) {
2687 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2688 if (!($start === false)) {
2689 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2693 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2694 foreach ($images[1] as $image) {
2695 $start = iconv_strpos($text, $image, 0, "UTF-8");
2696 if (!($start === false)) {
2697 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2700 //$entities["media"] = array();
2703 foreach ($ordered_images as $image) {
2704 $url = $image['url'];
2705 $ext_alt_text = $image['alt'];
2707 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2708 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2710 if (strlen($display_url) > 26) {
2711 $display_url = substr($display_url, 0, 25)."…";
2714 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2715 if (!($start === false)) {
2716 $image = Images::getInfoFromURLCached($url);
2718 // If image cache is activated, then use the following sizes:
2719 // thumb (150), small (340), medium (600) and large (1024)
2720 if (!Config::get("system", "proxy_disabled")) {
2721 $media_url = ProxyUtils::proxifyUrl($url);
2724 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2725 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2727 if (($image[0] > 150) || ($image[1] > 150)) {
2728 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2729 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2732 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2733 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2735 if (($image[0] > 600) || ($image[1] > 600)) {
2736 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2737 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2741 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2744 $entities["media"][] = [
2746 "id_str" => (string) ($start + 1),
2747 "indices" => [$start, $start+strlen($url)],
2748 "media_url" => Strings::normaliseLink($media_url),
2749 "media_url_https" => $media_url,
2751 "display_url" => $display_url,
2752 "expanded_url" => $url,
2753 "ext_alt_text" => $ext_alt_text,
2757 $offset = $start + 1;
2766 * @param array $item
2767 * @param string $text
2771 function api_format_items_embeded_images($item, $text)
2773 $text = preg_replace_callback(
2774 '|data:image/([^;]+)[^=]+=*|m',
2775 function () use ($item) {
2776 return System::baseUrl() . '/display/' . $item['guid'];
2784 * @brief return <a href='url'>name</a> as array
2786 * @param string $txt text
2791 function api_contactlink_to_array($txt)
2794 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2795 if ($r && count($match)==3) {
2797 'name' => $match[2],
2811 * @brief return likes, dislikes and attend status for item
2813 * @param array $item array
2814 * @param string $type Return type (atom, rss, xml, json)
2817 * likes => int count,
2818 * dislikes => int count
2819 * @throws BadRequestException
2820 * @throws ImagickException
2821 * @throws InternalServerErrorException
2822 * @throws UnauthorizedException
2824 function api_format_items_activities($item, $type = "json")
2833 'attendmaybe' => [],
2836 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri']];
2837 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2839 while ($parent_item = Item::fetch($ret)) {
2840 // not used as result should be structured like other user data
2841 //builtin_activity_puller($i, $activities);
2843 // get user data and add it to the array of the activity
2844 $user = api_get_user($a, $parent_item['author-id']);
2845 switch ($parent_item['verb']) {
2846 case Activity::LIKE:
2847 $activities['like'][] = $user;
2849 case Activity::DISLIKE:
2850 $activities['dislike'][] = $user;
2852 case Activity::ATTEND:
2853 $activities['attendyes'][] = $user;
2855 case Activity::ATTENDNO:
2856 $activities['attendno'][] = $user;
2858 case Activity::ATTENDMAYBE:
2859 $activities['attendmaybe'][] = $user;
2868 if ($type == "xml") {
2869 $xml_activities = [];
2870 foreach ($activities as $k => $v) {
2871 // change xml element from "like" to "friendica:like"
2872 $xml_activities["friendica:".$k] = $v;
2873 // add user data into xml output
2875 foreach ($v as $user) {
2876 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2879 $activities = $xml_activities;
2887 * @brief return data from profiles
2889 * @param array $profile_row array containing data from db table 'profile'
2891 * @throws InternalServerErrorException
2893 function api_format_items_profiles($profile_row)
2896 'profile_id' => $profile_row['id'],
2897 'profile_name' => $profile_row['profile-name'],
2898 'is_default' => $profile_row['is-default'] ? true : false,
2899 'hide_friends' => $profile_row['hide-friends'] ? true : false,
2900 'profile_photo' => $profile_row['photo'],
2901 'profile_thumb' => $profile_row['thumb'],
2902 'publish' => $profile_row['publish'] ? true : false,
2903 'net_publish' => $profile_row['net-publish'] ? true : false,
2904 'description' => $profile_row['pdesc'],
2905 'date_of_birth' => $profile_row['dob'],
2906 'address' => $profile_row['address'],
2907 'city' => $profile_row['locality'],
2908 'region' => $profile_row['region'],
2909 'postal_code' => $profile_row['postal-code'],
2910 'country' => $profile_row['country-name'],
2911 'hometown' => $profile_row['hometown'],
2912 'gender' => $profile_row['gender'],
2913 'marital' => $profile_row['marital'],
2914 'marital_with' => $profile_row['with'],
2915 'marital_since' => $profile_row['howlong'],
2916 'sexual' => $profile_row['sexual'],
2917 'politic' => $profile_row['politic'],
2918 'religion' => $profile_row['religion'],
2919 'public_keywords' => $profile_row['pub_keywords'],
2920 'private_keywords' => $profile_row['prv_keywords'],
2921 'likes' => BBCode::convert(api_clean_plain_items($profile_row['likes']) , false, 2),
2922 'dislikes' => BBCode::convert(api_clean_plain_items($profile_row['dislikes']) , false, 2),
2923 'about' => BBCode::convert(api_clean_plain_items($profile_row['about']) , false, 2),
2924 'music' => BBCode::convert(api_clean_plain_items($profile_row['music']) , false, 2),
2925 'book' => BBCode::convert(api_clean_plain_items($profile_row['book']) , false, 2),
2926 'tv' => BBCode::convert(api_clean_plain_items($profile_row['tv']) , false, 2),
2927 'film' => BBCode::convert(api_clean_plain_items($profile_row['film']) , false, 2),
2928 'interest' => BBCode::convert(api_clean_plain_items($profile_row['interest']) , false, 2),
2929 'romance' => BBCode::convert(api_clean_plain_items($profile_row['romance']) , false, 2),
2930 'work' => BBCode::convert(api_clean_plain_items($profile_row['work']) , false, 2),
2931 'education' => BBCode::convert(api_clean_plain_items($profile_row['education']), false, 2),
2932 'social_networks' => BBCode::convert(api_clean_plain_items($profile_row['contact']) , false, 2),
2933 'homepage' => $profile_row['homepage'],
2940 * @brief format items to be returned by api
2942 * @param array $items array of items
2943 * @param array $user_info
2944 * @param bool $filter_user filter items by $user_info
2945 * @param string $type Return type (atom, rss, xml, json)
2947 * @throws BadRequestException
2948 * @throws ImagickException
2949 * @throws InternalServerErrorException
2950 * @throws UnauthorizedException
2952 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2954 $a = BaseObject::getApp();
2958 foreach ((array)$items as $item) {
2959 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2961 // Look if the posts are matching if they should be filtered by user id
2962 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2966 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2975 * @param array $item Item record
2976 * @param string $type Return format (atom, rss, xml, json)
2977 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2978 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2979 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2980 * @return array API-formatted status
2981 * @throws BadRequestException
2982 * @throws ImagickException
2983 * @throws InternalServerErrorException
2984 * @throws UnauthorizedException
2986 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2988 $a = BaseObject::getApp();
2990 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2991 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2994 localize_item($item);
2996 $in_reply_to = api_in_reply_to($item);
2998 $converted = api_convert_item($item);
3000 if ($type == "xml") {
3001 $geo = "georss:point";
3007 'text' => $converted["text"],
3008 'truncated' => false,
3009 'created_at'=> api_date($item['created']),
3010 'in_reply_to_status_id' => $in_reply_to['status_id'],
3011 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3012 'source' => (($item['app']) ? $item['app'] : 'web'),
3013 'id' => intval($item['id']),
3014 'id_str' => (string) intval($item['id']),
3015 'in_reply_to_user_id' => $in_reply_to['user_id'],
3016 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3017 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3019 'favorited' => $item['starred'] ? true : false,
3020 'user' => $status_user,
3021 'friendica_author' => $author_user,
3022 'friendica_owner' => $owner_user,
3023 'friendica_private' => $item['private'] == 1,
3024 //'entities' => NULL,
3025 'statusnet_html' => $converted["html"],
3026 'statusnet_conversation_id' => $item['parent'],
3027 'external_url' => System::baseUrl() . "/display/" . $item['guid'],
3028 'friendica_activities' => api_format_items_activities($item, $type),
3029 'friendica_title' => $item['title'],
3030 'friendica_html' => BBCode::convert($item['body'], false)
3033 if (count($converted["attachments"]) > 0) {
3034 $status["attachments"] = $converted["attachments"];
3037 if (count($converted["entities"]) > 0) {
3038 $status["entities"] = $converted["entities"];
3041 if ($status["source"] == 'web') {
3042 $status["source"] = ContactSelector::networkToName($item['network'], $item['author-link']);
3043 } elseif (ContactSelector::networkToName($item['network'], $item['author-link']) != $status["source"]) {
3044 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['network'], $item['author-link']).')');
3047 $retweeted_item = [];
3050 if ($item["id"] == $item["parent"]) {
3051 $body = $item['body'];
3052 $retweeted_item = api_share_as_retweet($item);
3053 if ($body != $item['body']) {
3054 $quoted_item = $retweeted_item;
3055 $retweeted_item = [];
3059 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3060 $announce = api_get_announce($item);
3061 if (!empty($announce)) {
3062 $retweeted_item = $item;
3064 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3068 if (!empty($quoted_item)) {
3069 $conv_quoted = api_convert_item($quoted_item);
3070 $quoted_status = $status;
3071 unset($quoted_status['friendica_author']);
3072 unset($quoted_status['friendica_owner']);
3073 unset($quoted_status['friendica_activities']);
3074 unset($quoted_status['friendica_private']);
3075 unset($quoted_status['statusnet_conversation_id']);
3076 $quoted_status['text'] = $conv_quoted['text'];
3077 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3079 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3080 } catch (BadRequestException $e) {
3081 // user not found. should be found?
3082 /// @todo check if the user should be always found
3083 $quoted_status["user"] = [];
3087 if (!empty($retweeted_item)) {
3088 $retweeted_status = $status;
3089 unset($retweeted_status['friendica_author']);
3090 unset($retweeted_status['friendica_owner']);
3091 unset($retweeted_status['friendica_activities']);
3092 unset($retweeted_status['friendica_private']);
3093 unset($retweeted_status['statusnet_conversation_id']);
3094 $status['user'] = $status['friendica_owner'];
3096 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3097 } catch (BadRequestException $e) {
3098 // user not found. should be found?
3099 /// @todo check if the user should be always found
3100 $retweeted_status["user"] = [];
3103 $rt_converted = api_convert_item($retweeted_item);
3105 $retweeted_status['text'] = $rt_converted["text"];
3106 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3107 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3109 if (!empty($quoted_status)) {
3110 $retweeted_status['quoted_status'] = $quoted_status;
3113 $status['friendica_author'] = $retweeted_status['user'];
3114 $status['retweeted_status'] = $retweeted_status;
3115 } elseif (!empty($quoted_status)) {
3116 $root_status = api_convert_item($item);
3118 $status['text'] = $root_status["text"];
3119 $status['statusnet_html'] = $root_status["html"];
3120 $status['quoted_status'] = $quoted_status;
3123 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3124 unset($status["user"]["uid"]);
3125 unset($status["user"]["self"]);
3127 if ($item["coord"] != "") {
3128 $coords = explode(' ', $item["coord"]);
3129 if (count($coords) == 2) {
3130 if ($type == "json") {
3131 $status["geo"] = ['type' => 'Point',
3132 'coordinates' => [(float) $coords[0],
3133 (float) $coords[1]]];
3134 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3135 $status["georss:point"] = $item["coord"];
3144 * Returns the remaining number of API requests available to the user before the API limit is reached.
3146 * @param string $type Return type (atom, rss, xml, json)
3148 * @return array|string
3151 function api_account_rate_limit_status($type)
3153 if ($type == "xml") {
3155 'remaining-hits' => '150',
3156 '@attributes' => ["type" => "integer"],
3157 'hourly-limit' => '150',
3158 '@attributes2' => ["type" => "integer"],
3159 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3160 '@attributes3' => ["type" => "datetime"],
3161 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3162 '@attributes4' => ["type" => "integer"],
3166 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3167 'remaining_hits' => '150',
3168 'hourly_limit' => '150',
3169 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3173 return api_format_data('hash', $type, ['hash' => $hash]);
3176 /// @TODO move to top of file or somewhere better
3177 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3180 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3182 * @param string $type Return type (atom, rss, xml, json)
3184 * @return array|string
3186 function api_help_test($type)
3188 if ($type == 'xml') {
3194 return api_format_data('ok', $type, ["ok" => $ok]);
3197 /// @TODO move to top of file or somewhere better
3198 api_register_func('api/help/test', 'api_help_test', false);
3201 * Returns all lists the user subscribes to.
3203 * @param string $type Return type (atom, rss, xml, json)
3205 * @return array|string
3206 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3208 function api_lists_list($type)
3211 /// @TODO $ret is not filled here?
3212 return api_format_data('lists', $type, ["lists_list" => $ret]);
3215 /// @TODO move to top of file or somewhere better
3216 api_register_func('api/lists/list', 'api_lists_list', true);
3217 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3220 * Returns all groups the user owns.
3222 * @param string $type Return type (atom, rss, xml, json)
3224 * @return array|string
3225 * @throws BadRequestException
3226 * @throws ForbiddenException
3227 * @throws ImagickException
3228 * @throws InternalServerErrorException
3229 * @throws UnauthorizedException
3230 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3232 function api_lists_ownerships($type)
3236 if (api_user() === false) {
3237 throw new ForbiddenException();
3241 $user_info = api_get_user($a);
3242 $uid = $user_info['uid'];
3244 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3246 // loop through all groups
3248 foreach ($groups as $group) {
3249 if ($group['visible']) {
3255 'name' => $group['name'],
3256 'id' => intval($group['id']),
3257 'id_str' => (string) $group['id'],
3258 'user' => $user_info,
3262 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3265 /// @TODO move to top of file or somewhere better
3266 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3269 * Returns recent statuses from users in the specified group.
3271 * @param string $type Return type (atom, rss, xml, json)
3273 * @return array|string
3274 * @throws BadRequestException
3275 * @throws ForbiddenException
3276 * @throws ImagickException
3277 * @throws InternalServerErrorException
3278 * @throws UnauthorizedException
3279 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3281 function api_lists_statuses($type)
3285 $user_info = api_get_user($a);
3286 if (api_user() === false || $user_info === false) {
3287 throw new ForbiddenException();
3290 unset($_REQUEST["user_id"]);
3291 unset($_GET["user_id"]);
3293 unset($_REQUEST["screen_name"]);
3294 unset($_GET["screen_name"]);
3296 if (empty($_REQUEST['list_id'])) {
3297 throw new BadRequestException('list_id not specified');
3301 $count = $_REQUEST['count'] ?? 20;
3302 $page = $_REQUEST['page'] ?? 1;
3303 $since_id = $_REQUEST['since_id'] ?? 0;
3304 $max_id = $_REQUEST['max_id'] ?? 0;
3305 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3306 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3308 $start = max(0, ($page - 1) * $count);
3310 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3311 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3314 $condition[0] .= " AND `item`.`id` <= ?";
3315 $condition[] = $max_id;
3317 if ($exclude_replies > 0) {
3318 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3320 if ($conversation_id > 0) {
3321 $condition[0] .= " AND `item`.`parent` = ?";
3322 $condition[] = $conversation_id;
3325 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3326 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3328 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3330 $data = ['status' => $items];
3335 $data = api_rss_extra($a, $data, $user_info);
3339 return api_format_data("statuses", $type, $data);
3342 /// @TODO move to top of file or somewhere better
3343 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3346 * Considers friends and followers lists to be private and won't return
3347 * anything if any user_id parameter is passed.
3349 * @brief Returns either the friends of the follower list
3351 * @param string $qtype Either "friends" or "followers"
3352 * @return boolean|array
3353 * @throws BadRequestException
3354 * @throws ForbiddenException
3355 * @throws ImagickException
3356 * @throws InternalServerErrorException
3357 * @throws UnauthorizedException
3359 function api_statuses_f($qtype)
3363 if (api_user() === false) {
3364 throw new ForbiddenException();
3368 $count = $_GET['count'] ?? 20;
3369 $page = $_GET['page'] ?? 1;
3371 $start = max(0, ($page - 1) * $count);
3373 $user_info = api_get_user($a);
3375 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3376 /* this is to stop Hotot to load friends multiple times
3377 * I'm not sure if I'm missing return something or
3378 * is a bug in hotot. Workaround, meantime
3382 return array('$users' => $ret);*/
3387 if ($qtype == 'friends') {
3388 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3389 } elseif ($qtype == 'followers') {
3390 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3393 // friends and followers only for self
3394 if ($user_info['self'] == 0) {
3395 $sql_extra = " AND false ";
3398 if ($qtype == 'blocks') {
3399 $sql_filter = 'AND `blocked` AND NOT `pending`';
3400 } elseif ($qtype == 'incoming') {
3401 $sql_filter = 'AND `pending`';
3403 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3421 foreach ($r as $cid) {
3422 $user = api_get_user($a, $cid['nurl']);
3423 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3424 unset($user["uid"]);
3425 unset($user["self"]);
3432 return ['user' => $ret];
3437 * Returns the user's friends.
3439 * @brief Returns the list of friends of the provided user
3441 * @deprecated By Twitter API in favor of friends/list
3443 * @param string $type Either "json" or "xml"
3444 * @return boolean|string|array
3445 * @throws BadRequestException
3446 * @throws ForbiddenException
3448 function api_statuses_friends($type)
3450 $data = api_statuses_f("friends");
3451 if ($data === false) {
3454 return api_format_data("users", $type, $data);
3458 * Returns the user's followers.
3460 * @brief Returns the list of followers of the provided user
3462 * @deprecated By Twitter API in favor of friends/list
3464 * @param string $type Either "json" or "xml"
3465 * @return boolean|string|array
3466 * @throws BadRequestException
3467 * @throws ForbiddenException
3469 function api_statuses_followers($type)
3471 $data = api_statuses_f("followers");
3472 if ($data === false) {
3475 return api_format_data("users", $type, $data);
3478 /// @TODO move to top of file or somewhere better
3479 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3480 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3483 * Returns the list of blocked users
3485 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3487 * @param string $type Either "json" or "xml"
3489 * @return boolean|string|array
3490 * @throws BadRequestException
3491 * @throws ForbiddenException
3493 function api_blocks_list($type)
3495 $data = api_statuses_f('blocks');
3496 if ($data === false) {
3499 return api_format_data("users", $type, $data);
3502 /// @TODO move to top of file or somewhere better
3503 api_register_func('api/blocks/list', 'api_blocks_list', true);
3506 * Returns the list of pending users IDs
3508 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3510 * @param string $type Either "json" or "xml"
3512 * @return boolean|string|array
3513 * @throws BadRequestException
3514 * @throws ForbiddenException
3516 function api_friendships_incoming($type)
3518 $data = api_statuses_f('incoming');
3519 if ($data === false) {
3524 foreach ($data['user'] as $user) {
3525 $ids[] = $user['id'];
3528 return api_format_data("ids", $type, ['id' => $ids]);
3531 /// @TODO move to top of file or somewhere better
3532 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3535 * Returns the instance's configuration information.
3537 * @param string $type Return type (atom, rss, xml, json)
3539 * @return array|string
3540 * @throws InternalServerErrorException
3542 function api_statusnet_config($type)
3546 $name = Config::get('config', 'sitename');
3547 $server = $a->getHostName();
3548 $logo = System::baseUrl() . '/images/friendica-64.png';
3549 $email = Config::get('config', 'admin_email');
3550 $closed = intval(Config::get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3551 $private = Config::get('system', 'block_public') ? 'true' : 'false';
3552 $textlimit = (string) Config::get('config', 'api_import_size', Config::get('config', 'max_import_size', 200000));
3553 $ssl = Config::get('system', 'have_ssl') ? 'true' : 'false';
3554 $sslserver = Config::get('system', 'have_ssl') ? str_replace('http:', 'https:', System::baseUrl()) : '';
3557 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3558 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3559 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3560 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3561 'shorturllength' => '30',
3563 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3564 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3565 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3566 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3571 return api_format_data('config', $type, ['config' => $config]);
3574 /// @TODO move to top of file or somewhere better
3575 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3576 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3580 * @param string $type Return type (atom, rss, xml, json)
3582 * @return array|string
3584 function api_statusnet_version($type)
3587 $fake_statusnet_version = "0.9.7";
3589 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3592 /// @TODO move to top of file or somewhere better
3593 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3594 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3598 * @param string $type Return type (atom, rss, xml, json)
3600 * @return array|string|void
3601 * @throws BadRequestException
3602 * @throws ForbiddenException
3603 * @throws ImagickException
3604 * @throws InternalServerErrorException
3605 * @throws UnauthorizedException
3606 * @todo use api_format_data() to return data
3608 function api_ff_ids($type)
3611 throw new ForbiddenException();
3618 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3621 "SELECT `pcontact`.`id` FROM `contact`
3622 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
3623 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
3626 if (!DBA::isResult($r)) {
3631 foreach ($r as $rr) {
3632 if ($stringify_ids) {
3635 $ids[] = intval($rr['id']);
3639 return api_format_data("ids", $type, ['id' => $ids]);
3643 * Returns the ID of every user the user is following.
3645 * @param string $type Return type (atom, rss, xml, json)
3647 * @return array|string
3648 * @throws BadRequestException
3649 * @throws ForbiddenException
3650 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3652 function api_friends_ids($type)
3654 return api_ff_ids($type);
3658 * Returns the ID of every user following the user.
3660 * @param string $type Return type (atom, rss, xml, json)
3662 * @return array|string
3663 * @throws BadRequestException
3664 * @throws ForbiddenException
3665 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3667 function api_followers_ids($type)
3669 return api_ff_ids($type);
3672 /// @TODO move to top of file or somewhere better
3673 api_register_func('api/friends/ids', 'api_friends_ids', true);
3674 api_register_func('api/followers/ids', 'api_followers_ids', true);
3677 * Sends a new direct message.
3679 * @param string $type Return type (atom, rss, xml, json)
3681 * @return array|string
3682 * @throws BadRequestException
3683 * @throws ForbiddenException
3684 * @throws ImagickException
3685 * @throws InternalServerErrorException
3686 * @throws NotFoundException
3687 * @throws UnauthorizedException
3688 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3690 function api_direct_messages_new($type)
3694 if (api_user() === false) {
3695 throw new ForbiddenException();
3698 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3702 $sender = api_get_user($a);
3705 if (!empty($_POST['screen_name'])) {
3707 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3709 DBA::escape($_POST['screen_name'])
3712 if (DBA::isResult($r)) {
3713 // Selecting the id by priority, friendica first
3714 api_best_nickname($r);
3716 $recipient = api_get_user($a, $r[0]['nurl']);
3719 $recipient = api_get_user($a, $_POST['user_id']);
3722 if (empty($recipient)) {
3723 throw new NotFoundException('Recipient not found');
3727 if (!empty($_REQUEST['replyto'])) {
3729 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3731 intval($_REQUEST['replyto'])
3733 $replyto = $r[0]['parent-uri'];
3734 $sub = $r[0]['title'];
3736 if (!empty($_REQUEST['title'])) {
3737 $sub = $_REQUEST['title'];
3739 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3743 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3746 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3747 $ret = api_format_messages($r[0], $recipient, $sender);
3749 $ret = ["error"=>$id];
3752 $data = ['direct_message'=>$ret];
3758 $data = api_rss_extra($a, $data, $sender);
3762 return api_format_data("direct-messages", $type, $data);
3765 /// @TODO move to top of file or somewhere better
3766 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3769 * Destroys a direct message.
3771 * @brief delete a direct_message from mail table through api
3773 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3774 * @return string|array
3775 * @throws BadRequestException
3776 * @throws ForbiddenException
3777 * @throws ImagickException
3778 * @throws InternalServerErrorException
3779 * @throws UnauthorizedException
3780 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3782 function api_direct_messages_destroy($type)
3786 if (api_user() === false) {
3787 throw new ForbiddenException();
3791 $user_info = api_get_user($a);
3793 $id = $_REQUEST['id'] ?? 0;
3795 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3796 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3797 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3799 $uid = $user_info['uid'];
3800 // error if no id or parenturi specified (for clients posting parent-uri as well)
3801 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3802 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3803 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3806 // BadRequestException if no id specified (for clients using Twitter API)
3808 throw new BadRequestException('Message id not specified');
3811 // add parent-uri to sql command if specified by calling app
3812 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3814 // get data of the specified message id
3816 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3821 // error message if specified id is not in database
3822 if (!DBA::isResult($r)) {
3823 if ($verbose == "true") {
3824 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3825 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3827 /// @todo BadRequestException ok for Twitter API clients?
3828 throw new BadRequestException('message id not in database');
3833 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3838 if ($verbose == "true") {
3841 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3842 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3844 $answer = ['result' => 'error', 'message' => 'unknown error'];
3845 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3848 /// @todo return JSON data like Twitter API not yet implemented
3851 /// @TODO move to top of file or somewhere better
3852 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3857 * @brief unfollow contact
3859 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3860 * @return string|array
3861 * @throws BadRequestException
3862 * @throws ForbiddenException
3863 * @throws ImagickException
3864 * @throws InternalServerErrorException
3865 * @throws NotFoundException
3866 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3868 function api_friendships_destroy($type)
3872 if ($uid === false) {
3873 throw new ForbiddenException();
3876 $contact_id = $_REQUEST['user_id'] ?? 0;
3878 if (empty($contact_id)) {
3879 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3880 throw new BadRequestException("no user_id specified");
3883 // Get Contact by given id
3884 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3886 if(!DBA::isResult($contact)) {
3887 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3888 throw new NotFoundException("no contact found to given ID");
3891 $url = $contact["url"];
3893 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3894 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3895 Strings::normaliseLink($url), $url];
3896 $contact = DBA::selectFirst('contact', [], $condition);
3898 if (!DBA::isResult($contact)) {
3899 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3900 throw new NotFoundException("Not following Contact");
3903 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3904 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3905 throw new ExpectationFailedException("Not supported");
3908 $dissolve = ($contact['rel'] == Contact::SHARING);
3910 $owner = User::getOwnerDataById($uid);
3912 Contact::terminateFriendship($owner, $contact, $dissolve);
3915 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3916 throw new NotFoundException("Error Processing Request");
3919 // Sharing-only contacts get deleted as there no relationship any more
3921 Contact::remove($contact['id']);
3923 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3926 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3927 unset($contact["uid"]);
3928 unset($contact["self"]);
3930 // Set screen_name since Twidere requests it
3931 $contact["screen_name"] = $contact["nick"];
3933 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3935 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3939 * @param string $type Return type (atom, rss, xml, json)
3940 * @param string $box
3941 * @param string $verbose
3943 * @return array|string
3944 * @throws BadRequestException
3945 * @throws ForbiddenException
3946 * @throws ImagickException
3947 * @throws InternalServerErrorException
3948 * @throws UnauthorizedException
3950 function api_direct_messages_box($type, $box, $verbose)
3953 if (api_user() === false) {
3954 throw new ForbiddenException();
3957 $count = $_GET['count'] ?? 20;
3958 $page = $_REQUEST['page'] ?? 1;
3960 $since_id = $_REQUEST['since_id'] ?? 0;
3961 $max_id = $_REQUEST['max_id'] ?? 0;
3963 $user_id = $_REQUEST['user_id'] ?? '';
3964 $screen_name = $_REQUEST['screen_name'] ?? '';
3967 unset($_REQUEST["user_id"]);
3968 unset($_GET["user_id"]);
3970 unset($_REQUEST["screen_name"]);
3971 unset($_GET["screen_name"]);
3973 $user_info = api_get_user($a);
3974 if ($user_info === false) {
3975 throw new ForbiddenException();
3977 $profile_url = $user_info["url"];
3980 $start = max(0, ($page - 1) * $count);
3985 if ($box=="sentbox") {
3986 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3987 } elseif ($box == "conversation") {
3988 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3989 } elseif ($box == "all") {
3990 $sql_extra = "true";
3991 } elseif ($box == "inbox") {
3992 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3996 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3999 if ($user_id != "") {
4000 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4001 } elseif ($screen_name !="") {
4002 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4006 "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",
4012 if ($verbose == "true" && !DBA::isResult($r)) {
4013 $answer = ['result' => 'error', 'message' => 'no mails available'];
4014 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4018 foreach ($r as $item) {
4019 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4020 $recipient = $user_info;
4021 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4022 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4023 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4024 $sender = $user_info;
4027 if (isset($recipient) && isset($sender)) {
4028 $ret[] = api_format_messages($item, $recipient, $sender);
4033 $data = ['direct_message' => $ret];
4038 $data = api_rss_extra($a, $data, $user_info);
4042 return api_format_data("direct-messages", $type, $data);
4046 * Returns the most recent direct messages sent by the user.
4048 * @param string $type Return type (atom, rss, xml, json)
4050 * @return array|string
4051 * @throws BadRequestException
4052 * @throws ForbiddenException
4053 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4055 function api_direct_messages_sentbox($type)
4057 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4058 return api_direct_messages_box($type, "sentbox", $verbose);
4062 * Returns the most recent direct messages sent to the user.
4064 * @param string $type Return type (atom, rss, xml, json)
4066 * @return array|string
4067 * @throws BadRequestException
4068 * @throws ForbiddenException
4069 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4071 function api_direct_messages_inbox($type)
4073 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4074 return api_direct_messages_box($type, "inbox", $verbose);
4079 * @param string $type Return type (atom, rss, xml, json)
4081 * @return array|string
4082 * @throws BadRequestException
4083 * @throws ForbiddenException
4085 function api_direct_messages_all($type)
4087 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4088 return api_direct_messages_box($type, "all", $verbose);
4093 * @param string $type Return type (atom, rss, xml, json)
4095 * @return array|string
4096 * @throws BadRequestException
4097 * @throws ForbiddenException
4099 function api_direct_messages_conversation($type)
4101 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4102 return api_direct_messages_box($type, "conversation", $verbose);
4105 /// @TODO move to top of file or somewhere better
4106 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4107 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4108 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4109 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4112 * Returns an OAuth Request Token.
4114 * @see https://oauth.net/core/1.0/#auth_step1
4116 function api_oauth_request_token()
4118 $oauth1 = new FKOAuth1();
4120 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4121 } catch (Exception $e) {
4122 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4130 * Returns an OAuth Access Token.
4132 * @return array|string
4133 * @see https://oauth.net/core/1.0/#auth_step3
4135 function api_oauth_access_token()
4137 $oauth1 = new FKOAuth1();
4139 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4140 } catch (Exception $e) {
4141 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4148 /// @TODO move to top of file or somewhere better
4149 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4150 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4154 * @brief delete a complete photoalbum with all containing photos from database through api
4156 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4157 * @return string|array
4158 * @throws BadRequestException
4159 * @throws ForbiddenException
4160 * @throws InternalServerErrorException
4162 function api_fr_photoalbum_delete($type)
4164 if (api_user() === false) {
4165 throw new ForbiddenException();
4168 $album = $_REQUEST['album'] ?? '';
4170 // we do not allow calls without album string
4172 throw new BadRequestException("no albumname specified");
4174 // check if album is existing
4176 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4180 if (!DBA::isResult($r)) {
4181 throw new BadRequestException("album not available");
4184 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4185 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4186 foreach ($r as $rr) {
4187 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4188 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4190 if (!DBA::isResult($photo_item)) {
4191 throw new InternalServerErrorException("problem with deleting items occured");
4193 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4196 // now let's delete all photos from the album
4197 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4199 // return success of deletion or error message
4201 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4202 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4204 throw new InternalServerErrorException("unknown error - deleting from database failed");
4209 * @brief update the name of the album for all photos of an album
4211 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4212 * @return string|array
4213 * @throws BadRequestException
4214 * @throws ForbiddenException
4215 * @throws InternalServerErrorException
4217 function api_fr_photoalbum_update($type)
4219 if (api_user() === false) {
4220 throw new ForbiddenException();
4223 $album = $_REQUEST['album'] ?? '';
4224 $album_new = $_REQUEST['album_new'] ?? '';
4226 // we do not allow calls without album string
4228 throw new BadRequestException("no albumname specified");
4230 if ($album_new == "") {
4231 throw new BadRequestException("no new albumname specified");
4233 // check if album is existing
4234 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4235 throw new BadRequestException("album not available");
4237 // now let's update all photos to the albumname
4238 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4240 // return success of updating or error message
4242 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4243 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4245 throw new InternalServerErrorException("unknown error - updating in database failed");
4251 * @brief list all photos of the authenticated user
4253 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4254 * @return string|array
4255 * @throws ForbiddenException
4256 * @throws InternalServerErrorException
4258 function api_fr_photos_list($type)
4260 if (api_user() === false) {
4261 throw new ForbiddenException();
4264 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4265 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4266 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4267 intval(local_user())
4270 'image/jpeg' => 'jpg',
4271 'image/png' => 'png',
4272 'image/gif' => 'gif'
4274 $data = ['photo'=>[]];
4275 if (DBA::isResult($r)) {
4276 foreach ($r as $rr) {
4278 $photo['id'] = $rr['resource-id'];
4279 $photo['album'] = $rr['album'];
4280 $photo['filename'] = $rr['filename'];
4281 $photo['type'] = $rr['type'];
4282 $thumb = System::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4283 $photo['created'] = $rr['created'];
4284 $photo['edited'] = $rr['edited'];
4285 $photo['desc'] = $rr['desc'];
4287 if ($type == "xml") {
4288 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4290 $photo['thumb'] = $thumb;
4291 $data['photo'][] = $photo;
4295 return api_format_data("photos", $type, $data);
4299 * @brief upload a new photo or change an existing photo
4301 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4302 * @return string|array
4303 * @throws BadRequestException
4304 * @throws ForbiddenException
4305 * @throws ImagickException
4306 * @throws InternalServerErrorException
4307 * @throws NotFoundException
4309 function api_fr_photo_create_update($type)
4311 if (api_user() === false) {
4312 throw new ForbiddenException();
4315 $photo_id = $_REQUEST['photo_id'] ?? null;
4316 $desc = $_REQUEST['desc'] ?? null;
4317 $album = $_REQUEST['album'] ?? null;
4318 $album_new = $_REQUEST['album_new'] ?? null;
4319 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4320 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4321 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4322 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4323 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4325 // do several checks on input parameters
4326 // we do not allow calls without album string
4327 if ($album == null) {
4328 throw new BadRequestException("no albumname specified");
4330 // if photo_id == null --> we are uploading a new photo
4331 if ($photo_id == null) {
4334 // error if no media posted in create-mode
4335 if (empty($_FILES['media'])) {
4337 throw new BadRequestException("no media data submitted");
4340 // album_new will be ignored in create-mode
4345 // check if photo is existing in databasei
4346 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4347 throw new BadRequestException("photo not available");
4351 // checks on acl strings provided by clients
4352 $acl_input_error = false;
4353 $acl_input_error |= check_acl_input($allow_cid);
4354 $acl_input_error |= check_acl_input($deny_cid);
4355 $acl_input_error |= check_acl_input($allow_gid);
4356 $acl_input_error |= check_acl_input($deny_gid);
4357 if ($acl_input_error) {
4358 throw new BadRequestException("acl data invalid");
4360 // now let's upload the new media in create-mode
4361 if ($mode == "create") {
4362 $media = $_FILES['media'];
4363 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4365 // return success of updating or error message
4366 if (!is_null($data)) {
4367 return api_format_data("photo_create", $type, $data);
4369 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4373 // now let's do the changes in update-mode
4374 if ($mode == "update") {
4375 $updated_fields = [];
4377 if (!is_null($desc)) {
4378 $updated_fields['desc'] = $desc;
4381 if (!is_null($album_new)) {
4382 $updated_fields['album'] = $album_new;
4385 if (!is_null($allow_cid)) {
4386 $allow_cid = trim($allow_cid);
4387 $updated_fields['allow_cid'] = $allow_cid;
4390 if (!is_null($deny_cid)) {
4391 $deny_cid = trim($deny_cid);
4392 $updated_fields['deny_cid'] = $deny_cid;
4395 if (!is_null($allow_gid)) {
4396 $allow_gid = trim($allow_gid);
4397 $updated_fields['allow_gid'] = $allow_gid;
4400 if (!is_null($deny_gid)) {
4401 $deny_gid = trim($deny_gid);
4402 $updated_fields['deny_gid'] = $deny_gid;
4406 if (count($updated_fields) > 0) {
4407 $nothingtodo = false;
4408 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4410 $nothingtodo = true;
4413 if (!empty($_FILES['media'])) {
4414 $nothingtodo = false;
4415 $media = $_FILES['media'];
4416 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4417 if (!is_null($data)) {
4418 return api_format_data("photo_update", $type, $data);
4422 // return success of updating or error message
4424 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4425 return api_format_data("photo_update", $type, ['$result' => $answer]);
4428 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4429 return api_format_data("photo_update", $type, ['$result' => $answer]);
4431 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4434 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4438 * @brief delete a single photo from the database through api
4440 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4441 * @return string|array
4442 * @throws BadRequestException
4443 * @throws ForbiddenException
4444 * @throws InternalServerErrorException
4446 function api_fr_photo_delete($type)
4448 if (api_user() === false) {
4449 throw new ForbiddenException();
4453 $photo_id = $_REQUEST['photo_id'] ?? null;
4455 // do several checks on input parameters
4456 // we do not allow calls without photo id
4457 if ($photo_id == null) {
4458 throw new BadRequestException("no photo_id specified");
4461 // check if photo is existing in database
4462 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4463 throw new BadRequestException("photo not available");
4466 // now we can perform on the deletion of the photo
4467 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4469 // return success of deletion or error message
4471 // retrieve the id of the parent element (the photo element)
4472 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4473 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4475 if (!DBA::isResult($photo_item)) {
4476 throw new InternalServerErrorException("problem with deleting items occured");
4478 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4479 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4480 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4482 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4483 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4485 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4491 * @brief returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4493 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4494 * @return string|array
4495 * @throws BadRequestException
4496 * @throws ForbiddenException
4497 * @throws InternalServerErrorException
4498 * @throws NotFoundException
4500 function api_fr_photo_detail($type)
4502 if (api_user() === false) {
4503 throw new ForbiddenException();
4505 if (empty($_REQUEST['photo_id'])) {
4506 throw new BadRequestException("No photo id.");
4509 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4510 $photo_id = $_REQUEST['photo_id'];
4512 // prepare json/xml output with data from database for the requested photo
4513 $data = prepare_photo_data($type, $scale, $photo_id);
4515 return api_format_data("photo_detail", $type, $data);
4520 * Updates the user’s profile image.
4522 * @brief updates the profile image for the user (either a specified profile or the default profile)
4524 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4526 * @return string|array
4527 * @throws BadRequestException
4528 * @throws ForbiddenException
4529 * @throws ImagickException
4530 * @throws InternalServerErrorException
4531 * @throws NotFoundException
4532 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4534 function api_account_update_profile_image($type)
4536 if (api_user() === false) {
4537 throw new ForbiddenException();
4540 $profile_id = $_REQUEST['profile_id'] ?? 0;
4542 // error if image data is missing
4543 if (empty($_FILES['image'])) {
4544 throw new BadRequestException("no media data submitted");
4547 // check if specified profile id is valid
4548 if ($profile_id != 0) {
4549 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4550 // error message if specified profile id is not in database
4551 if (!DBA::isResult($profile)) {
4552 throw new BadRequestException("profile_id not available");
4554 $is_default_profile = $profile['is-default'];
4556 $is_default_profile = 1;
4559 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4561 if (!empty($_FILES['image'])) {
4562 $media = $_FILES['image'];
4563 } elseif (!empty($_FILES['media'])) {
4564 $media = $_FILES['media'];
4566 // save new profile image
4567 $data = save_media_to_database("profileimage", $media, $type, L10n::t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4570 if (is_array($media['type'])) {
4571 $filetype = $media['type'][0];
4573 $filetype = $media['type'];
4575 if ($filetype == "image/jpeg") {
4577 } elseif ($filetype == "image/png") {
4580 throw new InternalServerErrorException('Unsupported filetype');
4583 // change specified profile or all profiles to the new resource-id
4584 if ($is_default_profile) {
4585 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4586 Photo::update(['profile' => false], $condition);
4588 $fields = ['photo' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4589 'thumb' => System::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4590 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4593 Contact::updateSelfFromUserID(api_user(), true);
4595 // Update global directory in background
4596 $url = System::baseUrl() . '/profile/' . \get_app()->user['nickname'];
4597 if ($url && strlen(Config::get('system', 'directory'))) {
4598 Worker::add(PRIORITY_LOW, "Directory", $url);
4601 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4603 // output for client
4605 return api_account_verify_credentials($type);
4607 // SaveMediaToDatabase failed for some reason
4608 throw new InternalServerErrorException("image upload failed");
4612 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4613 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4614 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4615 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4616 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4617 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4618 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4619 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4620 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4623 * Update user profile
4625 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4627 * @return array|string
4628 * @throws BadRequestException
4629 * @throws ForbiddenException
4630 * @throws ImagickException
4631 * @throws InternalServerErrorException
4632 * @throws UnauthorizedException
4634 function api_account_update_profile($type)
4636 $local_user = api_user();
4637 $api_user = api_get_user(get_app());
4639 if (!empty($_POST['name'])) {
4640 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4641 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4642 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4643 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4646 if (isset($_POST['description'])) {
4647 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4648 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4649 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4652 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4653 // Update global directory in background
4654 if ($api_user['url'] && strlen(Config::get('system', 'directory'))) {
4655 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4658 return api_account_verify_credentials($type);
4661 /// @TODO move to top of file or somewhere better
4662 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4666 * @param string $acl_string
4670 function check_acl_input($acl_string)
4672 if (empty($acl_string)) {
4676 $contact_not_found = false;
4678 // split <x><y><z> into array of cid's
4679 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4681 // check for each cid if it is available on server
4682 $cid_array = $array[0];
4683 foreach ($cid_array as $cid) {
4684 $cid = str_replace("<", "", $cid);
4685 $cid = str_replace(">", "", $cid);
4686 $condition = ['id' => $cid, 'uid' => api_user()];
4687 $contact_not_found |= !DBA::exists('contact', $condition);
4689 return $contact_not_found;
4693 * @param string $mediatype
4694 * @param array $media
4695 * @param string $type
4696 * @param string $album
4697 * @param string $allow_cid
4698 * @param string $deny_cid
4699 * @param string $allow_gid
4700 * @param string $deny_gid
4701 * @param string $desc
4702 * @param integer $profile
4703 * @param boolean $visibility
4704 * @param string $photo_id
4706 * @throws BadRequestException
4707 * @throws ForbiddenException
4708 * @throws ImagickException
4709 * @throws InternalServerErrorException
4710 * @throws NotFoundException
4711 * @throws UnauthorizedException
4713 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)
4721 if (is_array($media)) {
4722 if (is_array($media['tmp_name'])) {
4723 $src = $media['tmp_name'][0];
4725 $src = $media['tmp_name'];
4727 if (is_array($media['name'])) {
4728 $filename = basename($media['name'][0]);
4730 $filename = basename($media['name']);
4732 if (is_array($media['size'])) {
4733 $filesize = intval($media['size'][0]);
4735 $filesize = intval($media['size']);
4737 if (is_array($media['type'])) {
4738 $filetype = $media['type'][0];
4740 $filetype = $media['type'];
4744 if ($filetype == "") {
4745 $filetype = Images::guessType($filename);
4747 $imagedata = @getimagesize($src);
4749 $filetype = $imagedata['mime'];
4752 "File upload src: " . $src . " - filename: " . $filename .
4753 " - size: " . $filesize . " - type: " . $filetype,
4757 // check if there was a php upload error
4758 if ($filesize == 0 && $media['error'] == 1) {
4759 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4761 // check against max upload size within Friendica instance
4762 $maximagesize = Config::get('system', 'maximagesize');
4763 if ($maximagesize && ($filesize > $maximagesize)) {
4764 $formattedBytes = Strings::formatBytes($maximagesize);
4765 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4768 // create Photo instance with the data of the image
4769 $imagedata = @file_get_contents($src);
4770 $Image = new Image($imagedata, $filetype);
4771 if (!$Image->isValid()) {
4772 throw new InternalServerErrorException("unable to process image data");
4775 // check orientation of image
4776 $Image->orient($src);
4779 // check max length of images on server
4780 $max_length = Config::get('system', 'max_image_length');
4782 $max_length = MAX_IMAGE_LENGTH;
4784 if ($max_length > 0) {
4785 $Image->scaleDown($max_length);
4786 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4788 $width = $Image->getWidth();
4789 $height = $Image->getHeight();
4791 // create a new resource-id if not already provided
4792 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4794 if ($mediatype == "photo") {
4795 // upload normal image (scales 0, 1, 2)
4796 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4798 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4800 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4802 if ($width > 640 || $height > 640) {
4803 $Image->scaleDown(640);
4804 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4806 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4810 if ($width > 320 || $height > 320) {
4811 $Image->scaleDown(320);
4812 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4814 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4817 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4818 } elseif ($mediatype == "profileimage") {
4819 // upload profile image (scales 4, 5, 6)
4820 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4822 if ($width > 300 || $height > 300) {
4823 $Image->scaleDown(300);
4824 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4826 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4830 if ($width > 80 || $height > 80) {
4831 $Image->scaleDown(80);
4832 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4834 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4838 if ($width > 48 || $height > 48) {
4839 $Image->scaleDown(48);
4840 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4842 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4845 $Image->__destruct();
4846 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4849 if (isset($r) && $r) {
4850 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4851 if ($photo_id == null && $mediatype == "photo") {
4852 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4854 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4855 return prepare_photo_data($type, false, $resource_id);
4857 throw new InternalServerErrorException("image upload failed");
4863 * @param string $hash
4864 * @param string $allow_cid
4865 * @param string $deny_cid
4866 * @param string $allow_gid
4867 * @param string $deny_gid
4868 * @param string $filetype
4869 * @param boolean $visibility
4870 * @throws InternalServerErrorException
4872 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4874 // get data about the api authenticated user
4875 $uri = Item::newURI(intval(api_user()));
4876 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4879 $arr['guid'] = System::createUUID();
4880 $arr['uid'] = intval(api_user());
4882 $arr['parent-uri'] = $uri;
4883 $arr['type'] = 'photo';
4885 $arr['resource-id'] = $hash;
4886 $arr['contact-id'] = $owner_record['id'];
4887 $arr['owner-name'] = $owner_record['name'];
4888 $arr['owner-link'] = $owner_record['url'];
4889 $arr['owner-avatar'] = $owner_record['thumb'];
4890 $arr['author-name'] = $owner_record['name'];
4891 $arr['author-link'] = $owner_record['url'];
4892 $arr['author-avatar'] = $owner_record['thumb'];
4894 $arr['allow_cid'] = $allow_cid;
4895 $arr['allow_gid'] = $allow_gid;
4896 $arr['deny_cid'] = $deny_cid;
4897 $arr['deny_gid'] = $deny_gid;
4898 $arr['visible'] = $visibility;
4902 'image/jpeg' => 'jpg',
4903 'image/png' => 'png',
4904 'image/gif' => 'gif'
4907 // adds link to the thumbnail scale photo
4908 $arr['body'] = '[url=' . System::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4909 . '[img]' . System::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4912 // do the magic for storing the item in the database and trigger the federation to other contacts
4918 * @param string $type
4920 * @param string $photo_id
4923 * @throws BadRequestException
4924 * @throws ForbiddenException
4925 * @throws ImagickException
4926 * @throws InternalServerErrorException
4927 * @throws NotFoundException
4928 * @throws UnauthorizedException
4930 function prepare_photo_data($type, $scale, $photo_id)
4933 $user_info = api_get_user($a);
4935 if ($user_info === false) {
4936 throw new ForbiddenException();
4939 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4940 $data_sql = ($scale === false ? "" : "data, ");
4942 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4943 // clients needs to convert this in their way for further processing
4945 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4946 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4947 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4948 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4949 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4950 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4952 intval(local_user()),
4953 DBA::escape($photo_id),
4958 'image/jpeg' => 'jpg',
4959 'image/png' => 'png',
4960 'image/gif' => 'gif'
4963 // prepare output data for photo
4964 if (DBA::isResult($r)) {
4965 $data = ['photo' => $r[0]];
4966 $data['photo']['id'] = $data['photo']['resource-id'];
4967 if ($scale !== false) {
4968 $data['photo']['data'] = base64_encode($data['photo']['data']);
4970 unset($data['photo']['datasize']); //needed only with scale param
4972 if ($type == "xml") {
4973 $data['photo']['links'] = [];
4974 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4975 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4977 "href" => System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4980 $data['photo']['link'] = [];
4981 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4983 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4984 $data['photo']['link'][$i] = System::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4988 unset($data['photo']['resource-id']);
4989 unset($data['photo']['minscale']);
4990 unset($data['photo']['maxscale']);
4992 throw new NotFoundException();
4995 // retrieve item element for getting activities (like, dislike etc.) related to photo
4996 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4997 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4999 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
5001 // retrieve comments on photo
5002 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5003 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5005 $statuses = Item::selectForUser(api_user(), [], $condition);
5007 // prepare output of comments
5008 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5010 if ($type == "xml") {
5012 foreach ($commentData as $comment) {
5013 $comments[$k++ . ":comment"] = $comment;
5016 foreach ($commentData as $comment) {
5017 $comments[] = $comment;
5020 $data['photo']['friendica_comments'] = $comments;
5022 // include info if rights on photo and rights on item are mismatching
5023 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5024 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5025 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5026 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5027 $data['photo']['rights_mismatch'] = $rights_mismatch;
5034 * Similar as /mod/redir.php
5035 * redirect to 'url' after dfrn auth
5037 * Why this when there is mod/redir.php already?
5038 * This use api_user() and api_login()
5041 * c_url: url of remote contact to auth to
5042 * url: string, url to redirect after auth
5044 function api_friendica_remoteauth()
5046 $url = $_GET['url'] ?? '';
5047 $c_url = $_GET['c_url'] ?? '';
5049 if ($url === '' || $c_url === '') {
5050 throw new BadRequestException("Wrong parameters.");
5053 $c_url = Strings::normaliseLink($c_url);
5057 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5059 if (!DBA::isResult($contact) || ($contact['network'] !== Protocol::DFRN)) {
5060 throw new BadRequestException("Unknown contact");
5063 $cid = $contact['id'];
5065 $dfrn_id = $contact['issued-id'] ?? $contact['dfrn-id'];
5067 if ($contact['duplex'] && $contact['issued-id']) {
5068 $orig_id = $contact['issued-id'];
5069 $dfrn_id = '1:' . $orig_id;
5071 if ($contact['duplex'] && $contact['dfrn-id']) {
5072 $orig_id = $contact['dfrn-id'];
5073 $dfrn_id = '0:' . $orig_id;
5076 $sec = Strings::getRandomHex();
5078 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5079 'sec' => $sec, 'expire' => time() + 45];
5080 DBA::insert('profile_check', $fields);
5082 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5083 $dest = ($url ? '&destination_url=' . $url : '');
5085 System::externalRedirect(
5086 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5087 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5088 . '&type=profile&sec=' . $sec . $dest
5091 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5094 * Return an item with announcer data if it had been announced
5096 * @param array $item Item array
5097 * @return array Item array with announce data
5099 function api_get_announce($item)
5101 // Quit if the item already has got a different owner and author
5102 if ($item['owner-id'] != $item['author-id']) {
5106 // Don't change original or Diaspora posts
5107 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5111 // Quit if we do now the original author and it had been a post from a native network
5112 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5116 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5117 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5118 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5119 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5120 if (!DBA::isResult($announce)) {
5124 return array_merge($item, $announce);
5128 * @brief Return the item shared, if the item contains only the [share] tag
5130 * @param array $item Sharer item
5131 * @return array|false Shared item or false if not a reshare
5132 * @throws ImagickException
5133 * @throws InternalServerErrorException
5135 function api_share_as_retweet(&$item)
5137 $body = trim($item["body"]);
5139 if (Diaspora::isReshare($body, false) === false) {
5140 if ($item['author-id'] == $item['owner-id']) {
5143 // Reshares from OStatus, ActivityPub and Twitter
5144 $reshared_item = $item;
5145 $reshared_item['owner-id'] = $reshared_item['author-id'];
5146 $reshared_item['owner-link'] = $reshared_item['author-link'];
5147 $reshared_item['owner-name'] = $reshared_item['author-name'];
5148 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5149 return $reshared_item;
5153 /// @TODO "$1" should maybe mean '$1' ?
5154 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
5156 * Skip if there is no shared message in there
5157 * we already checked this in diaspora::isReshare()
5158 * but better one more than one less...
5160 if (($body == $attributes) || empty($attributes)) {
5164 // build the fake reshared item
5165 $reshared_item = $item;
5168 preg_match("/author='(.*?)'/ism", $attributes, $matches);
5169 if (!empty($matches[1])) {
5170 $author = html_entity_decode($matches[1], ENT_QUOTES, 'UTF-8');
5173 preg_match('/author="(.*?)"/ism', $attributes, $matches);
5174 if (!empty($matches[1])) {
5175 $author = $matches[1];
5179 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
5180 if (!empty($matches[1])) {
5181 $profile = $matches[1];
5184 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
5185 if (!empty($matches[1])) {
5186 $profile = $matches[1];
5190 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
5191 if (!empty($matches[1])) {
5192 $avatar = $matches[1];
5195 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
5196 if (!empty($matches[1])) {
5197 $avatar = $matches[1];
5201 preg_match("/link='(.*?)'/ism", $attributes, $matches);
5202 if (!empty($matches[1])) {
5203 $link = $matches[1];
5206 preg_match('/link="(.*?)"/ism', $attributes, $matches);
5207 if (!empty($matches[1])) {
5208 $link = $matches[1];
5212 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
5213 if (!empty($matches[1])) {
5214 $posted = $matches[1];
5217 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
5218 if (!empty($matches[1])) {
5219 $posted = $matches[1];
5222 if (!preg_match("/(.*?)\[share.*?\]\s?(.*?)\s?\[\/share\]\s?(.*?)/ism", $body, $matches)) {
5226 $pre_body = trim($matches[1]);
5227 if ($pre_body != '') {
5228 $item['body'] = $pre_body;
5231 $shared_body = trim($matches[2]);
5233 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == "")) {
5237 $reshared_item["share-pre-body"] = $pre_body;
5238 $reshared_item["body"] = $shared_body;
5239 $reshared_item["author-id"] = Contact::getIdForURL($profile, 0, true);
5240 $reshared_item["author-name"] = $author;
5241 $reshared_item["author-link"] = $profile;
5242 $reshared_item["author-avatar"] = $avatar;
5243 $reshared_item["plink"] = $link;
5244 $reshared_item["created"] = $posted;
5245 $reshared_item["edited"] = $posted;
5247 return $reshared_item;
5252 * @param string $profile
5254 * @return string|false
5255 * @throws InternalServerErrorException
5256 * @todo remove trailing junk from profile url
5257 * @todo pump.io check has to check the website
5259 function api_get_nick($profile)
5264 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5265 DBA::escape(Strings::normaliseLink($profile))
5268 if (DBA::isResult($r)) {
5269 $nick = $r[0]["nick"];
5274 "SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
5275 DBA::escape(Strings::normaliseLink($profile))
5278 if (DBA::isResult($r)) {
5279 $nick = $r[0]["nick"];
5284 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
5285 if ($friendica != $profile) {
5291 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
5292 if ($diaspora != $profile) {
5298 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
5299 if ($twitter != $profile) {
5306 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
5307 if ($StatusnetHost != $profile) {
5308 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
5309 if ($StatusnetUser != $profile) {
5310 $UserData = Network::fetchUrl("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
5311 $user = json_decode($UserData);
5313 $nick = $user->screen_name;
5319 // To-Do: look at the page if its really a pumpio site
5320 //if (!$nick == "") {
5321 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
5322 // if ($pumpio != $profile)
5324 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
5337 * @param array $item
5342 function api_in_reply_to($item)
5346 $in_reply_to['status_id'] = null;
5347 $in_reply_to['user_id'] = null;
5348 $in_reply_to['status_id_str'] = null;
5349 $in_reply_to['user_id_str'] = null;
5350 $in_reply_to['screen_name'] = null;
5352 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5353 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5354 if (DBA::isResult($parent)) {
5355 $in_reply_to['status_id'] = intval($parent['id']);
5357 $in_reply_to['status_id'] = intval($item['parent']);
5360 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5362 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5363 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5365 if (DBA::isResult($parent)) {
5366 if ($parent['author-nick'] == "") {
5367 $parent['author-nick'] = api_get_nick($parent['author-link']);
5370 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5371 $in_reply_to['user_id'] = intval($parent['author-id']);
5372 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5375 // There seems to be situation, where both fields are identical:
5376 // https://github.com/friendica/friendica/issues/1010
5377 // This is a bugfix for that.
5378 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5379 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']]);
5380 $in_reply_to['status_id'] = null;
5381 $in_reply_to['user_id'] = null;
5382 $in_reply_to['status_id_str'] = null;
5383 $in_reply_to['user_id_str'] = null;
5384 $in_reply_to['screen_name'] = null;
5388 return $in_reply_to;
5393 * @param string $text
5396 * @throws InternalServerErrorException
5398 function api_clean_plain_items($text)
5400 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5402 $text = BBCode::cleanPictureLinks($text);
5403 $URLSearchString = "^\[\]";
5405 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5407 if ($include_entities == "true") {
5408 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5411 // Simplify "attachment" element
5412 $text = api_clean_attachments($text);
5418 * @brief Removes most sharing information for API text export
5420 * @param string $body The original body
5422 * @return string Cleaned body
5423 * @throws InternalServerErrorException
5425 function api_clean_attachments($body)
5427 $data = BBCode::getAttachmentData($body);
5434 if (isset($data["text"])) {
5435 $body = $data["text"];
5437 if (($body == "") && isset($data["title"])) {
5438 $body = $data["title"];
5440 if (isset($data["url"])) {
5441 $body .= "\n".$data["url"];
5443 $body .= $data["after"];
5450 * @param array $contacts
5454 function api_best_nickname(&$contacts)
5458 if (count($contacts) == 0) {
5462 foreach ($contacts as $contact) {
5463 if ($contact["network"] == "") {
5464 $contact["network"] = "dfrn";
5465 $best_contact = [$contact];
5469 if (sizeof($best_contact) == 0) {
5470 foreach ($contacts as $contact) {
5471 if ($contact["network"] == "dfrn") {
5472 $best_contact = [$contact];
5477 if (sizeof($best_contact) == 0) {
5478 foreach ($contacts as $contact) {
5479 if ($contact["network"] == "dspr") {
5480 $best_contact = [$contact];
5485 if (sizeof($best_contact) == 0) {
5486 foreach ($contacts as $contact) {
5487 if ($contact["network"] == "stat") {
5488 $best_contact = [$contact];
5493 if (sizeof($best_contact) == 0) {
5494 foreach ($contacts as $contact) {
5495 if ($contact["network"] == "pump") {
5496 $best_contact = [$contact];
5501 if (sizeof($best_contact) == 0) {
5502 foreach ($contacts as $contact) {
5503 if ($contact["network"] == "twit") {
5504 $best_contact = [$contact];
5509 if (sizeof($best_contact) == 1) {
5510 $contacts = $best_contact;
5512 $contacts = [$contacts[0]];
5517 * Return all or a specified group of the user with the containing contacts.
5519 * @param string $type Return type (atom, rss, xml, json)
5521 * @return array|string
5522 * @throws BadRequestException
5523 * @throws ForbiddenException
5524 * @throws ImagickException
5525 * @throws InternalServerErrorException
5526 * @throws UnauthorizedException
5528 function api_friendica_group_show($type)
5532 if (api_user() === false) {
5533 throw new ForbiddenException();
5537 $user_info = api_get_user($a);
5538 $gid = $_REQUEST['gid'] ?? 0;
5539 $uid = $user_info['uid'];
5541 // get data of the specified group id or all groups if not specified
5544 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5548 // error message if specified gid is not in database
5549 if (!DBA::isResult($r)) {
5550 throw new BadRequestException("gid not available");
5554 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5559 // loop through all groups and retrieve all members for adding data in the user array
5561 foreach ($r as $rr) {
5562 $members = Contact::getByGroupId($rr['id']);
5565 if ($type == "xml") {
5566 $user_element = "users";
5568 foreach ($members as $member) {
5569 $user = api_get_user($a, $member['nurl']);
5570 $users[$k++.":user"] = $user;
5573 $user_element = "user";
5574 foreach ($members as $member) {
5575 $user = api_get_user($a, $member['nurl']);
5579 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5581 return api_format_data("groups", $type, ['group' => $grps]);
5583 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5587 * Delete the specified group of the user.
5589 * @param string $type Return type (atom, rss, xml, json)
5591 * @return array|string
5592 * @throws BadRequestException
5593 * @throws ForbiddenException
5594 * @throws ImagickException
5595 * @throws InternalServerErrorException
5596 * @throws UnauthorizedException
5598 function api_friendica_group_delete($type)
5602 if (api_user() === false) {
5603 throw new ForbiddenException();
5607 $user_info = api_get_user($a);
5608 $gid = $_REQUEST['gid'] ?? 0;
5609 $name = $_REQUEST['name'] ?? '';
5610 $uid = $user_info['uid'];
5612 // error if no gid specified
5613 if ($gid == 0 || $name == "") {
5614 throw new BadRequestException('gid or name not specified');
5617 // get data of the specified group id
5619 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5623 // error message if specified gid is not in database
5624 if (!DBA::isResult($r)) {
5625 throw new BadRequestException('gid not available');
5628 // get data of the specified group id and group name
5630 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5635 // error message if specified gid is not in database
5636 if (!DBA::isResult($rname)) {
5637 throw new BadRequestException('wrong group name');
5641 $ret = Group::removeByName($uid, $name);
5644 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5645 return api_format_data("group_delete", $type, ['result' => $success]);
5647 throw new BadRequestException('other API error');
5650 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5655 * @param string $type Return type (atom, rss, xml, json)
5657 * @return array|string
5658 * @throws BadRequestException
5659 * @throws ForbiddenException
5660 * @throws ImagickException
5661 * @throws InternalServerErrorException
5662 * @throws UnauthorizedException
5663 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5665 function api_lists_destroy($type)
5669 if (api_user() === false) {
5670 throw new ForbiddenException();
5674 $user_info = api_get_user($a);
5675 $gid = $_REQUEST['list_id'] ?? 0;
5676 $uid = $user_info['uid'];
5678 // error if no gid specified
5680 throw new BadRequestException('gid not specified');
5683 // get data of the specified group id
5684 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5685 // error message if specified gid is not in database
5687 throw new BadRequestException('gid not available');
5690 if (Group::remove($gid)) {
5692 'name' => $group['name'],
5693 'id' => intval($gid),
5694 'id_str' => (string) $gid,
5695 'user' => $user_info
5698 return api_format_data("lists", $type, ['lists' => $list]);
5701 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5704 * Add a new group to the database.
5706 * @param string $name Group name
5707 * @param int $uid User ID
5708 * @param array $users List of users to add to the group
5711 * @throws BadRequestException
5713 function group_create($name, $uid, $users = [])
5715 // error if no name specified
5717 throw new BadRequestException('group name not specified');
5720 // get data of the specified group name
5722 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5726 // error message if specified group name already exists
5727 if (DBA::isResult($rname)) {
5728 throw new BadRequestException('group name already exists');
5731 // check if specified group name is a deleted group
5733 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5737 // error message if specified group name already exists
5738 if (DBA::isResult($rname)) {
5739 $reactivate_group = true;
5743 $ret = Group::create($uid, $name);
5745 $gid = Group::getIdByName($uid, $name);
5747 throw new BadRequestException('other API error');
5751 $erroraddinguser = false;
5753 foreach ($users as $user) {
5754 $cid = $user['cid'];
5755 // check if user really exists as contact
5757 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5761 if (count($contact)) {
5762 Group::addMember($gid, $cid);
5764 $erroraddinguser = true;
5765 $errorusers[] = $cid;
5769 // return success message incl. missing users in array
5770 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5772 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5776 * Create the specified group with the posted array of contacts.
5778 * @param string $type Return type (atom, rss, xml, json)
5780 * @return array|string
5781 * @throws BadRequestException
5782 * @throws ForbiddenException
5783 * @throws ImagickException
5784 * @throws InternalServerErrorException
5785 * @throws UnauthorizedException
5787 function api_friendica_group_create($type)
5791 if (api_user() === false) {
5792 throw new ForbiddenException();
5796 $user_info = api_get_user($a);
5797 $name = $_REQUEST['name'] ?? '';
5798 $uid = $user_info['uid'];
5799 $json = json_decode($_POST['json'], true);
5800 $users = $json['user'];
5802 $success = group_create($name, $uid, $users);
5804 return api_format_data("group_create", $type, ['result' => $success]);
5806 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5809 * Create a new group.
5811 * @param string $type Return type (atom, rss, xml, json)
5813 * @return array|string
5814 * @throws BadRequestException
5815 * @throws ForbiddenException
5816 * @throws ImagickException
5817 * @throws InternalServerErrorException
5818 * @throws UnauthorizedException
5819 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5821 function api_lists_create($type)
5825 if (api_user() === false) {
5826 throw new ForbiddenException();
5830 $user_info = api_get_user($a);
5831 $name = $_REQUEST['name'] ?? '';
5832 $uid = $user_info['uid'];
5834 $success = group_create($name, $uid);
5835 if ($success['success']) {
5837 'name' => $success['name'],
5838 'id' => intval($success['gid']),
5839 'id_str' => (string) $success['gid'],
5840 'user' => $user_info
5843 return api_format_data("lists", $type, ['lists'=>$grp]);
5846 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5849 * Update the specified group with the posted array of contacts.
5851 * @param string $type Return type (atom, rss, xml, json)
5853 * @return array|string
5854 * @throws BadRequestException
5855 * @throws ForbiddenException
5856 * @throws ImagickException
5857 * @throws InternalServerErrorException
5858 * @throws UnauthorizedException
5860 function api_friendica_group_update($type)
5864 if (api_user() === false) {
5865 throw new ForbiddenException();
5869 $user_info = api_get_user($a);
5870 $uid = $user_info['uid'];
5871 $gid = $_REQUEST['gid'] ?? 0;
5872 $name = $_REQUEST['name'] ?? '';
5873 $json = json_decode($_POST['json'], true);
5874 $users = $json['user'];
5876 // error if no name specified
5878 throw new BadRequestException('group name not specified');
5881 // error if no gid specified
5883 throw new BadRequestException('gid not specified');
5887 $members = Contact::getByGroupId($gid);
5888 foreach ($members as $member) {
5889 $cid = $member['id'];
5890 foreach ($users as $user) {
5891 $found = ($user['cid'] == $cid ? true : false);
5893 if (!isset($found) || !$found) {
5894 Group::removeMemberByName($uid, $name, $cid);
5899 $erroraddinguser = false;
5901 foreach ($users as $user) {
5902 $cid = $user['cid'];
5903 // check if user really exists as contact
5905 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5910 if (count($contact)) {
5911 Group::addMember($gid, $cid);
5913 $erroraddinguser = true;
5914 $errorusers[] = $cid;
5918 // return success message incl. missing users in array
5919 $status = ($erroraddinguser ? "missing user" : "ok");
5920 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5921 return api_format_data("group_update", $type, ['result' => $success]);
5924 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5927 * Update information about a group.
5929 * @param string $type Return type (atom, rss, xml, json)
5931 * @return array|string
5932 * @throws BadRequestException
5933 * @throws ForbiddenException
5934 * @throws ImagickException
5935 * @throws InternalServerErrorException
5936 * @throws UnauthorizedException
5937 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5939 function api_lists_update($type)
5943 if (api_user() === false) {
5944 throw new ForbiddenException();
5948 $user_info = api_get_user($a);
5949 $gid = $_REQUEST['list_id'] ?? 0;
5950 $name = $_REQUEST['name'] ?? '';
5951 $uid = $user_info['uid'];
5953 // error if no gid specified
5955 throw new BadRequestException('gid not specified');
5958 // get data of the specified group id
5959 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5960 // error message if specified gid is not in database
5962 throw new BadRequestException('gid not available');
5965 if (Group::update($gid, $name)) {
5968 'id' => intval($gid),
5969 'id_str' => (string) $gid,
5970 'user' => $user_info
5973 return api_format_data("lists", $type, ['lists' => $list]);
5977 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5981 * @param string $type Return type (atom, rss, xml, json)
5983 * @return array|string
5984 * @throws BadRequestException
5985 * @throws ForbiddenException
5986 * @throws ImagickException
5987 * @throws InternalServerErrorException
5989 function api_friendica_activity($type)
5993 if (api_user() === false) {
5994 throw new ForbiddenException();
5996 $verb = strtolower($a->argv[3]);
5997 $verb = preg_replace("|\..*$|", "", $verb);
5999 $id = $_REQUEST['id'] ?? 0;
6001 $res = Item::performLike($id, $verb);
6004 if ($type == "xml") {
6009 return api_format_data('ok', $type, ['ok' => $ok]);
6011 throw new BadRequestException('Error adding activity');
6015 /// @TODO move to top of file or somewhere better
6016 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
6017 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
6018 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
6019 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
6020 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6021 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
6022 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
6023 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
6024 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
6025 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
6028 * @brief Returns notifications
6030 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6031 * @return string|array
6032 * @throws BadRequestException
6033 * @throws ForbiddenException
6034 * @throws InternalServerErrorException
6036 function api_friendica_notification($type)
6040 if (api_user() === false) {
6041 throw new ForbiddenException();
6044 throw new BadRequestException("Invalid argument count");
6046 /** @var Notify $nm */
6047 $nm = BaseObject::getClass(Notify::class);
6049 $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
6051 if ($type == "xml") {
6053 if (!empty($notes)) {
6054 foreach ($notes as $note) {
6055 $xmlnotes[] = ["@attributes" => $note];
6061 return api_format_data("notes", $type, ['note' => $notes]);
6065 * POST request with 'id' param as notification id
6067 * @brief Set notification as seen and returns associated item (if possible)
6069 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6070 * @return string|array
6071 * @throws BadRequestException
6072 * @throws ForbiddenException
6073 * @throws ImagickException
6074 * @throws InternalServerErrorException
6075 * @throws UnauthorizedException
6077 function api_friendica_notification_seen($type)
6080 $user_info = api_get_user($a);
6082 if (api_user() === false || $user_info === false) {
6083 throw new ForbiddenException();
6086 throw new BadRequestException("Invalid argument count");
6089 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
6091 /** @var Notify $nm */
6092 $nm = BaseObject::getClass(Notify::class);
6093 $note = $nm->getByID($id);
6094 if (is_null($note)) {
6095 throw new BadRequestException("Invalid argument");
6098 $nm->setSeen($note);
6099 if ($note['otype']=='item') {
6100 // would be really better with an ItemsManager and $im->getByID() :-P
6101 $item = Item::selectFirstForUser(api_user(), [], ['id' => $note['iid'], 'uid' => api_user()]);
6102 if (DBA::isResult($item)) {
6103 // we found the item, return it to the user
6104 $ret = api_format_items([$item], $user_info, false, $type);
6105 $data = ['status' => $ret];
6106 return api_format_data("status", $type, $data);
6108 // the item can't be found, but we set the note as seen, so we count this as a success
6110 return api_format_data('result', $type, ['result' => "success"]);
6113 /// @TODO move to top of file or somewhere better
6114 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
6115 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
6118 * @brief update a direct_message to seen state
6120 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6121 * @return string|array (success result=ok, error result=error with error message)
6122 * @throws BadRequestException
6123 * @throws ForbiddenException
6124 * @throws ImagickException
6125 * @throws InternalServerErrorException
6126 * @throws UnauthorizedException
6128 function api_friendica_direct_messages_setseen($type)
6131 if (api_user() === false) {
6132 throw new ForbiddenException();
6136 $user_info = api_get_user($a);
6137 $uid = $user_info['uid'];
6138 $id = $_REQUEST['id'] ?? 0;
6140 // return error if id is zero
6142 $answer = ['result' => 'error', 'message' => 'message id not specified'];
6143 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6146 // error message if specified id is not in database
6147 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
6148 $answer = ['result' => 'error', 'message' => 'message id not in database'];
6149 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6152 // update seen indicator
6153 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
6157 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
6158 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
6160 $answer = ['result' => 'error', 'message' => 'unknown error'];
6161 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
6165 /// @TODO move to top of file or somewhere better
6166 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6169 * @brief search for direct_messages containing a searchstring through api
6171 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6172 * @param string $box
6173 * @return string|array (success: success=true if found and search_result contains found messages,
6174 * success=false if nothing was found, search_result='nothing found',
6175 * error: result=error with error message)
6176 * @throws BadRequestException
6177 * @throws ForbiddenException
6178 * @throws ImagickException
6179 * @throws InternalServerErrorException
6180 * @throws UnauthorizedException
6182 function api_friendica_direct_messages_search($type, $box = "")
6186 if (api_user() === false) {
6187 throw new ForbiddenException();
6191 $user_info = api_get_user($a);
6192 $searchstring = $_REQUEST['searchstring'] ?? '';
6193 $uid = $user_info['uid'];
6195 // error if no searchstring specified
6196 if ($searchstring == "") {
6197 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6198 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6201 // get data for the specified searchstring
6203 "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",
6205 DBA::escape('%'.$searchstring.'%')
6208 $profile_url = $user_info["url"];
6210 // message if nothing was found
6211 if (!DBA::isResult($r)) {
6212 $success = ['success' => false, 'search_results' => 'problem with query'];
6213 } elseif (count($r) == 0) {
6214 $success = ['success' => false, 'search_results' => 'nothing found'];
6217 foreach ($r as $item) {
6218 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6219 $recipient = $user_info;
6220 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6221 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6222 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6223 $sender = $user_info;
6226 if (isset($recipient) && isset($sender)) {
6227 $ret[] = api_format_messages($item, $recipient, $sender);
6230 $success = ['success' => true, 'search_results' => $ret];
6233 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6236 /// @TODO move to top of file or somewhere better
6237 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6240 * @brief return data of all the profiles a user has to the client
6242 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6243 * @return string|array
6244 * @throws BadRequestException
6245 * @throws ForbiddenException
6246 * @throws ImagickException
6247 * @throws InternalServerErrorException
6248 * @throws UnauthorizedException
6250 function api_friendica_profile_show($type)
6254 if (api_user() === false) {
6255 throw new ForbiddenException();
6259 $profile_id = $_REQUEST['profile_id'] ?? 0;
6261 // retrieve general information about profiles for user
6262 $multi_profiles = Feature::isEnabled(api_user(), 'multi_profiles');
6263 $directory = Config::get('system', 'directory');
6265 // get data of the specified profile id or all profiles of the user if not specified
6266 if ($profile_id != 0) {
6267 $r = Profile::getById(api_user(), $profile_id);
6268 // error message if specified gid is not in database
6269 if (!DBA::isResult($r)) {
6270 throw new BadRequestException("profile_id not available");
6273 $r = Profile::getListByUser(api_user());
6275 // loop through all returned profiles and retrieve data and users
6278 if (DBA::isResult($r)) {
6279 foreach ($r as $rr) {
6280 $profile = api_format_items_profiles($rr);
6282 // select all users from contact table, loop and prepare standard return for user data
6284 $nurls = Contact::selectToArray(['id', 'nurl'], ['uid' => api_user(), 'profile-id' => $rr['id']]);
6285 foreach ($nurls as $nurl) {
6286 $user = api_get_user($a, $nurl['nurl']);
6287 ($type == "xml") ? $users[$k++ . ":user"] = $user : $users[] = $user;
6289 $profile['users'] = $users;
6291 // add prepared profile data to array for final return
6292 if ($type == "xml") {
6293 $profiles[$k++ . ":profile"] = $profile;
6295 $profiles[] = $profile;
6300 // return settings, authenticated user and profiles data
6301 $self = DBA::selectFirst('contact', ['nurl'], ['uid' => api_user(), 'self' => true]);
6303 $result = ['multi_profiles' => $multi_profiles ? true : false,
6304 'global_dir' => $directory,
6305 'friendica_owner' => api_get_user($a, $self['nurl']),
6306 'profiles' => $profiles];
6307 return api_format_data("friendica_profiles", $type, ['$result' => $result]);
6309 api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
6312 * Returns a list of saved searches.
6314 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6316 * @param string $type Return format: json or xml
6318 * @return string|array
6321 function api_saved_searches_list($type)
6323 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6326 while ($term = DBA::fetch($terms)) {
6328 'created_at' => api_date(time()),
6329 'id' => intval($term['id']),
6330 'id_str' => $term['id'],
6331 'name' => $term['term'],
6333 'query' => $term['term']
6339 return api_format_data("terms", $type, ['terms' => $result]);
6342 /// @TODO move to top of file or somewhere better
6343 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6346 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6348 * @brief Number of comments
6350 * @param object $data [Status, Status]
6354 function bindComments(&$data)
6356 if (count($data) == 0) {
6362 foreach ($data as $item) {
6363 $ids[] = $item['id'];
6366 $idStr = DBA::escape(implode(', ', $ids));
6367 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6368 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6369 $itemsData = DBA::toArray($items);
6371 foreach ($itemsData as $item) {
6372 $comments[$item['parent']] = $item['comments'];
6375 foreach ($data as $idx => $item) {
6377 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6382 @TODO Maybe open to implement?
6384 [pagename] => api/1.1/statuses/lookup.json
6385 [id] => 605138389168451584
6386 [include_cards] => true
6387 [cards_platform] => Android-12
6388 [include_entities] => true
6389 [include_my_retweet] => 1
6391 [include_reply_count] => true
6392 [include_descendent_reply_count] => true
6396 Not implemented by now:
6397 statuses/retweets_of_me
6402 account/update_location
6403 account/update_profile_background_image
6406 friendica/profile/update
6407 friendica/profile/create
6408 friendica/profile/delete
6410 Not implemented in status.net:
6411 statuses/retweeted_to_me
6412 statuses/retweeted_by_me
6413 direct_messages/destroy
6415 account/update_delivery_device
6416 notifications/follow