3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notify;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Term;
45 use Friendica\Model\User;
46 use Friendica\Model\UserItem;
47 use Friendica\Network\FKOAuth1;
48 use Friendica\Network\HTTPException;
49 use Friendica\Network\HTTPException\BadRequestException;
50 use Friendica\Network\HTTPException\ExpectationFailedException;
51 use Friendica\Network\HTTPException\ForbiddenException;
52 use Friendica\Network\HTTPException\InternalServerErrorException;
53 use Friendica\Network\HTTPException\MethodNotAllowedException;
54 use Friendica\Network\HTTPException\NotFoundException;
55 use Friendica\Network\HTTPException\NotImplementedException;
56 use Friendica\Network\HTTPException\TooManyRequestsException;
57 use Friendica\Network\HTTPException\UnauthorizedException;
58 use Friendica\Object\Image;
59 use Friendica\Protocol\Activity;
60 use Friendica\Protocol\Diaspora;
61 use Friendica\Util\DateTimeFormat;
62 use Friendica\Util\Images;
63 use Friendica\Util\Network;
64 use Friendica\Util\Proxy as ProxyUtils;
65 use Friendica\Util\Strings;
66 use Friendica\Util\XML;
68 require_once __DIR__ . '/../mod/share.php';
69 require_once __DIR__ . '/../mod/item.php';
70 require_once __DIR__ . '/../mod/wall_upload.php';
72 define('API_METHOD_ANY', '*');
73 define('API_METHOD_GET', 'GET');
74 define('API_METHOD_POST', 'POST,PUT');
75 define('API_METHOD_DELETE', 'POST,DELETE');
77 define('API_LOG_PREFIX', 'API {action} - ');
85 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
86 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
87 * into a page, and visitors will post something without noticing it).
91 if (!empty($_SESSION['allow_api'])) {
99 * Get source name from API client
101 * Clients can send 'source' parameter to be show in post metadata
102 * as "sent via <source>".
103 * Some clients doesn't send a source param, we support ones we know
104 * (only Twidere, atm)
107 * Client source name, default to "api" if unset/unknown
110 function api_source()
112 if (requestdata('source')) {
113 return requestdata('source');
116 // Support for known clients that doesn't send a source name
117 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
118 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
122 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
124 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
131 * Format date for API
133 * @param string $str Source date, as UTC
134 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
137 function api_date($str)
139 // Wed May 23 06:01:13 +0000 2007
140 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
144 * Register a function to be the endpoint for defined API path.
146 * @param string $path API URL path, relative to DI::baseUrl()
147 * @param string $func Function name to call on path request
148 * @param bool $auth API need logged user
149 * @param string $method HTTP method reqiured to call this endpoint.
150 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
151 * Default to API_METHOD_ANY
153 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
163 // Workaround for hotot
164 $path = str_replace("api/", "api/1.1/", $path);
174 * Log in user via OAuth1 or Simple HTTP Auth.
175 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
178 * @throws ForbiddenException
179 * @throws InternalServerErrorException
180 * @throws UnauthorizedException
181 * @hook 'authenticate'
183 * 'username' => username from login form
184 * 'password' => password from login form
185 * 'authenticated' => return status,
186 * 'user_record' => return authenticated user record
188 function api_login(App $a)
190 // workaround for HTTP-auth in CGI mode
191 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
192 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
193 if (strlen($userpass)) {
194 list($name, $password) = explode(':', $userpass);
195 $_SERVER['PHP_AUTH_USER'] = $name;
196 $_SERVER['PHP_AUTH_PW'] = $password;
200 if (empty($_SERVER['PHP_AUTH_USER'])) {
201 // Try OAuth when no user is provided
202 $oauth1 = new FKOAuth1();
205 $request = OAuthRequest::from_request();
206 list($consumer, $token) = $oauth1->verify_request($request);
207 if (!is_null($token)) {
208 $oauth1->loginUser($token->uid);
209 Session::set('allow_api', true);
212 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
213 var_dump($consumer, $token);
215 } catch (Exception $e) {
216 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
219 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
220 header('WWW-Authenticate: Basic realm="Friendica"');
221 throw new UnauthorizedException("This API requires login");
224 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
225 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
227 // allow "user@server" login (but ignore 'server' part)
228 $at = strstr($user, "@", true);
233 // next code from mod/auth.php. needs better solution
237 'username' => trim($user),
238 'password' => trim($password),
239 'authenticated' => 0,
240 'user_record' => null,
244 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
245 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
246 * and later addons should not interfere with an earlier one that succeeded.
248 Hook::callAll('authenticate', $addon_auth);
250 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
251 $record = $addon_auth['user_record'];
253 $user_id = User::authenticate(trim($user), trim($password), true);
254 if ($user_id !== false) {
255 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
259 if (!DBA::isResult($record)) {
260 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
261 header('WWW-Authenticate: Basic realm="Friendica"');
262 //header('HTTP/1.0 401 Unauthorized');
263 //die('This api requires login');
264 throw new UnauthorizedException("This API requires login");
267 DI::auth()->setForUser($a, $record);
269 $_SESSION["allow_api"] = true;
271 Hook::callAll('logged_in', $a->user);
275 * Check HTTP method of called API
277 * API endpoints can define which HTTP method to accept when called.
278 * This function check the current HTTP method agains endpoint
281 * @param string $method Required methods, uppercase, separated by comma
284 function api_check_method($method)
286 if ($method == "*") {
289 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
293 * Main API entry point
295 * Authenticate user, call registered API function, set HTTP headers
298 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
299 * @return string|array API call result
302 function api_call(App $a, App\Arguments $args = null)
304 global $API, $called_api;
311 if (strpos($args->getQueryString(), ".xml") > 0) {
314 if (strpos($args->getQueryString(), ".json") > 0) {
317 if (strpos($args->getQueryString(), ".rss") > 0) {
320 if (strpos($args->getQueryString(), ".atom") > 0) {
325 foreach ($API as $p => $info) {
326 if (strpos($args->getQueryString(), $p) === 0) {
327 if (!api_check_method($info['method'])) {
328 throw new MethodNotAllowedException();
331 $called_api = explode("/", $p);
333 if (!empty($info['auth']) && api_user() === false) {
337 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
338 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
340 $stamp = microtime(true);
341 $return = call_user_func($info['func'], $type);
342 $duration = floatval(microtime(true) - $stamp);
344 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
346 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
348 if (false === $return) {
350 * api function returned false withour throw an
351 * exception. This should not happend, throw a 500
353 throw new InternalServerErrorException();
358 header("Content-Type: text/xml");
361 header("Content-Type: application/json");
362 if (!empty($return)) {
363 $json = json_encode(end($return));
364 if (!empty($_GET['callback'])) {
365 $json = $_GET['callback'] . "(" . $json . ")";
371 header("Content-Type: application/rss+xml");
372 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
375 header("Content-Type: application/atom+xml");
376 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
383 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
384 throw new NotImplementedException();
385 } catch (HTTPException $e) {
386 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
387 return api_error($type, $e, $args);
392 * Format API error string
394 * @param string $type Return type (xml, json, rss, as)
395 * @param object $e HTTPException Error object
396 * @param App\Arguments $args The App arguments
397 * @return string|array error message formatted as $type
399 function api_error($type, $e, App\Arguments $args)
401 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
402 /// @TODO: https://dev.twitter.com/overview/api/response-codes
404 $error = ["error" => $error,
405 "code" => $e->getCode() . " " . $e->httpdesc,
406 "request" => $args->getQueryString()];
408 $return = api_format_data('status', $type, ['status' => $error]);
412 header("Content-Type: text/xml");
415 header("Content-Type: application/json");
416 $return = json_encode($return);
419 header("Content-Type: application/rss+xml");
422 header("Content-Type: application/atom+xml");
430 * Set values for RSS template
433 * @param array $arr Array to be passed to template
434 * @param array $user_info User info
436 * @throws BadRequestException
437 * @throws ImagickException
438 * @throws InternalServerErrorException
439 * @throws UnauthorizedException
440 * @todo find proper type-hints
442 function api_rss_extra(App $a, $arr, $user_info)
444 if (is_null($user_info)) {
445 $user_info = api_get_user($a);
448 $arr['$user'] = $user_info;
450 'alternate' => $user_info['url'],
451 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
452 'base' => DI::baseUrl(),
453 'updated' => api_date(null),
454 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
455 'language' => $user_info['lang'],
456 'logo' => DI::baseUrl() . "/images/friendica-32.png",
464 * Unique contact to contact url.
466 * @param int $id Contact id
467 * @return bool|string
468 * Contact url or False if contact id is unknown
471 function api_unique_id_to_nurl($id)
473 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
475 if (DBA::isResult($r)) {
483 * Get user info array.
486 * @param int|string $contact_id Contact ID or URL
488 * @throws BadRequestException
489 * @throws ImagickException
490 * @throws InternalServerErrorException
491 * @throws UnauthorizedException
493 function api_get_user(App $a, $contact_id = null)
501 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
503 // Searching for contact URL
504 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
505 $user = DBA::escape(Strings::normaliseLink($contact_id));
507 $extra_query = "AND `contact`.`nurl` = '%s' ";
508 if (api_user() !== false) {
509 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
513 // Searching for contact id with uid = 0
514 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
515 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
518 throw new BadRequestException("User ID ".$contact_id." not found.");
522 $extra_query = "AND `contact`.`nurl` = '%s' ";
523 if (api_user() !== false) {
524 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
528 if (is_null($user) && !empty($_GET['user_id'])) {
529 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
532 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
536 $extra_query = "AND `contact`.`nurl` = '%s' ";
537 if (api_user() !== false) {
538 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
541 if (is_null($user) && !empty($_GET['screen_name'])) {
542 $user = DBA::escape($_GET['screen_name']);
543 $extra_query = "AND `contact`.`nick` = '%s' ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 if (is_null($user) && !empty($_GET['profileurl'])) {
550 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
551 $extra_query = "AND `contact`.`nurl` = '%s' ";
552 if (api_user() !== false) {
553 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
557 // $called_api is the API path exploded on / and is expected to have at least 2 elements
558 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
559 $argid = count($called_api);
560 if (!empty($a->argv[$argid])) {
561 $data = explode(".", $a->argv[$argid]);
562 if (count($data) > 1) {
563 list($user, $null) = $data;
566 if (is_numeric($user)) {
567 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
571 $extra_query = "AND `contact`.`nurl` = '%s' ";
572 if (api_user() !== false) {
573 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
577 $user = DBA::escape($user);
578 $extra_query = "AND `contact`.`nick` = '%s' ";
579 if (api_user() !== false) {
580 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
585 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
588 if (api_user() === false) {
592 $user = $_SESSION['uid'];
593 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
597 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
601 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
607 // Selecting the id by priority, friendica first
608 if (is_array($uinfo)) {
609 api_best_nickname($uinfo);
612 // if the contact wasn't found, fetch it from the contacts with uid = 0
613 if (!DBA::isResult($uinfo)) {
615 throw new BadRequestException("User not found.");
618 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
620 if (DBA::isResult($contact)) {
622 'id' => $contact["id"],
623 'id_str' => (string) $contact["id"],
624 'name' => $contact["name"],
625 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
626 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
627 'description' => BBCode::toPlaintext($contact["about"]),
628 'profile_image_url' => $contact["micro"],
629 'profile_image_url_https' => $contact["micro"],
630 'profile_image_url_profile_size' => $contact["thumb"],
631 'profile_image_url_large' => $contact["photo"],
632 'url' => $contact["url"],
633 'protected' => false,
634 'followers_count' => 0,
635 'friends_count' => 0,
637 'created_at' => api_date($contact["created"]),
638 'favourites_count' => 0,
640 'time_zone' => 'UTC',
641 'geo_enabled' => false,
643 'statuses_count' => 0,
645 'contributors_enabled' => false,
646 'is_translator' => false,
647 'is_translation_enabled' => false,
648 'following' => false,
649 'follow_request_sent' => false,
650 'statusnet_blocking' => false,
651 'notifications' => false,
652 'statusnet_profile_url' => $contact["url"],
654 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
655 'pid' => Contact::getIdForURL($contact["url"], 0, true),
657 'network' => $contact["network"],
662 throw new BadRequestException("User ".$url." not found.");
666 if ($uinfo[0]['self']) {
667 if ($uinfo[0]['network'] == "") {
668 $uinfo[0]['network'] = Protocol::DFRN;
671 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
672 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
679 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
681 if (!empty($profile['about'])) {
682 $description = $profile['about'];
684 $description = $uinfo[0]["about"];
687 if (!empty($usr['default-location'])) {
688 $location = $usr['default-location'];
689 } elseif (!empty($uinfo[0]["location"])) {
690 $location = $uinfo[0]["location"];
692 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
696 'id' => intval($pcontact_id),
697 'id_str' => (string) intval($pcontact_id),
698 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
699 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
700 'location' => $location,
701 'description' => BBCode::toPlaintext($description),
702 'profile_image_url' => $uinfo[0]['micro'],
703 'profile_image_url_https' => $uinfo[0]['micro'],
704 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
705 'profile_image_url_large' => $uinfo[0]["photo"],
706 'url' => $uinfo[0]['url'],
707 'protected' => false,
708 'followers_count' => intval($countfollowers),
709 'friends_count' => intval($countfriends),
711 'created_at' => api_date($uinfo[0]['created']),
712 'favourites_count' => intval($starred),
714 'time_zone' => 'UTC',
715 'geo_enabled' => false,
717 'statuses_count' => intval($countitems),
719 'contributors_enabled' => false,
720 'is_translator' => false,
721 'is_translation_enabled' => false,
722 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
723 'follow_request_sent' => false,
724 'statusnet_blocking' => false,
725 'notifications' => false,
727 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
728 'statusnet_profile_url' => $uinfo[0]['url'],
729 'uid' => intval($uinfo[0]['uid']),
730 'cid' => intval($uinfo[0]['cid']),
731 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
732 'self' => $uinfo[0]['self'],
733 'network' => $uinfo[0]['network'],
736 // If this is a local user and it uses Frio, we can get its color preferences.
738 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
739 if ($theme_info['theme'] === 'frio') {
740 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
742 if ($schema && ($schema != '---')) {
743 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
744 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
745 require_once $schemefile;
748 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
749 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
750 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
752 if (empty($nav_bg)) {
755 if (empty($link_color)) {
756 $link_color = "#6fdbe8";
758 if (empty($bgcolor)) {
759 $bgcolor = "#ededed";
762 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
763 $ret['profile_link_color'] = str_replace('#', '', $link_color);
764 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
772 * return api-formatted array for item's author and owner
775 * @param array $item item from db
776 * @return array(array:author, array:owner)
777 * @throws BadRequestException
778 * @throws ImagickException
779 * @throws InternalServerErrorException
780 * @throws UnauthorizedException
782 function api_item_get_user(App $a, $item)
784 $status_user = api_get_user($a, $item['author-id'] ?? null);
786 $author_user = $status_user;
788 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
790 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
791 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
793 $owner_user = $author_user;
796 return ([$status_user, $author_user, $owner_user]);
800 * walks recursively through an array with the possibility to change value and key
802 * @param array $array The array to walk through
803 * @param callable $callback The callback function
805 * @return array the transformed array
807 function api_walk_recursive(array &$array, callable $callback)
811 foreach ($array as $k => $v) {
813 if ($callback($v, $k)) {
814 $new_array[$k] = api_walk_recursive($v, $callback);
817 if ($callback($v, $k)) {
828 * Callback function to transform the array in an array that can be transformed in a XML file
830 * @param mixed $item Array item value
831 * @param string $key Array key
833 * @return boolean Should the array item be deleted?
835 function api_reformat_xml(&$item, &$key)
837 if (is_bool($item)) {
838 $item = ($item ? "true" : "false");
841 if (substr($key, 0, 10) == "statusnet_") {
842 $key = "statusnet:".substr($key, 10);
843 } elseif (substr($key, 0, 10) == "friendica_") {
844 $key = "friendica:".substr($key, 10);
846 /// @TODO old-lost code?
848 // $key = "default:".$key;
854 * Creates the XML from a JSON style array
856 * @param array $data JSON style array
857 * @param string $root_element Name of the root element
859 * @return string The XML data
861 function api_create_xml(array $data, $root_element)
863 $childname = key($data);
864 $data2 = array_pop($data);
866 $namespaces = ["" => "http://api.twitter.com",
867 "statusnet" => "http://status.net/schema/api/1/",
868 "friendica" => "http://friendi.ca/schema/api/1/",
869 "georss" => "http://www.georss.org/georss"];
871 /// @todo Auto detection of needed namespaces
872 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
876 if (is_array($data2)) {
878 api_walk_recursive($data2, "api_reformat_xml");
884 foreach ($data2 as $item) {
885 $data4[$i++ . ":" . $childname] = $item;
892 $data3 = [$root_element => $data2];
894 $ret = XML::fromArray($data3, $xml, false, $namespaces);
899 * Formats the data according to the data type
901 * @param string $root_element Name of the root element
902 * @param string $type Return type (atom, rss, xml, json)
903 * @param array $data JSON style array
905 * @return array|string (string|array) XML data or JSON data
907 function api_format_data($root_element, $type, $data)
913 $ret = api_create_xml($data, $root_element);
928 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
929 * returns a 401 status code and an error message if not.
931 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
933 * @param string $type Return type (atom, rss, xml, json)
934 * @return array|string
935 * @throws BadRequestException
936 * @throws ForbiddenException
937 * @throws ImagickException
938 * @throws InternalServerErrorException
939 * @throws UnauthorizedException
941 function api_account_verify_credentials($type)
945 if (api_user() === false) {
946 throw new ForbiddenException();
949 unset($_REQUEST["user_id"]);
950 unset($_GET["user_id"]);
952 unset($_REQUEST["screen_name"]);
953 unset($_GET["screen_name"]);
955 $skip_status = $_REQUEST['skip_status'] ?? false;
957 $user_info = api_get_user($a);
959 // "verified" isn't used here in the standard
960 unset($user_info["verified"]);
962 // - Adding last status
964 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
966 $user_info['status'] = api_format_item($item, $type);
970 // "uid" and "self" are only needed for some internal stuff, so remove it from here
971 unset($user_info["uid"]);
972 unset($user_info["self"]);
974 return api_format_data("user", $type, ['user' => $user_info]);
977 /// @TODO move to top of file or somewhere better
978 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
981 * Get data from $_POST or $_GET
986 function requestdata($k)
988 if (!empty($_POST[$k])) {
991 if (!empty($_GET[$k])) {
998 * Deprecated function to upload media.
1000 * @param string $type Return type (atom, rss, xml, json)
1002 * @return array|string
1003 * @throws BadRequestException
1004 * @throws ForbiddenException
1005 * @throws ImagickException
1006 * @throws InternalServerErrorException
1007 * @throws UnauthorizedException
1009 function api_statuses_mediap($type)
1013 if (api_user() === false) {
1014 Logger::log('api_statuses_update: no user');
1015 throw new ForbiddenException();
1017 $user_info = api_get_user($a);
1019 $_REQUEST['profile_uid'] = api_user();
1020 $_REQUEST['api_source'] = true;
1021 $txt = requestdata('status');
1022 /// @TODO old-lost code?
1023 //$txt = urldecode(requestdata('status'));
1025 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1026 $txt = HTML::toBBCodeVideo($txt);
1027 $config = HTMLPurifier_Config::createDefault();
1028 $config->set('Cache.DefinitionImpl', null);
1029 $purifier = new HTMLPurifier($config);
1030 $txt = $purifier->purify($txt);
1032 $txt = HTML::toBBCode($txt);
1034 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1036 $picture = wall_upload_post($a, false);
1038 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1039 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1040 $item_id = item_post($a);
1042 // output the post that we just posted.
1043 return api_status_show($type, $item_id);
1046 /// @TODO move this to top of file or somewhere better!
1047 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1050 * Updates the user’s current status.
1052 * @param string $type Return type (atom, rss, xml, json)
1054 * @return array|string
1055 * @throws BadRequestException
1056 * @throws ForbiddenException
1057 * @throws ImagickException
1058 * @throws InternalServerErrorException
1059 * @throws TooManyRequestsException
1060 * @throws UnauthorizedException
1061 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1063 function api_statuses_update($type)
1067 if (api_user() === false) {
1068 Logger::log('api_statuses_update: no user');
1069 throw new ForbiddenException();
1074 // convert $_POST array items to the form we use for web posts.
1075 if (requestdata('htmlstatus')) {
1076 $txt = requestdata('htmlstatus');
1077 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1078 $txt = HTML::toBBCodeVideo($txt);
1080 $config = HTMLPurifier_Config::createDefault();
1081 $config->set('Cache.DefinitionImpl', null);
1083 $purifier = new HTMLPurifier($config);
1084 $txt = $purifier->purify($txt);
1086 $_REQUEST['body'] = HTML::toBBCode($txt);
1089 $_REQUEST['body'] = requestdata('status');
1092 $_REQUEST['title'] = requestdata('title');
1094 $parent = requestdata('in_reply_to_status_id');
1096 // Twidere sends "-1" if it is no reply ...
1097 if ($parent == -1) {
1101 if (ctype_digit($parent)) {
1102 $_REQUEST['parent'] = $parent;
1104 $_REQUEST['parent_uri'] = $parent;
1107 if (requestdata('lat') && requestdata('long')) {
1108 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1110 $_REQUEST['profile_uid'] = api_user();
1113 // Check for throttling (maximum posts per day, week and month)
1114 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1115 if ($throttle_day > 0) {
1116 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1118 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1119 $posts_day = DBA::count('thread', $condition);
1121 if ($posts_day > $throttle_day) {
1122 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1123 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1124 throw new TooManyRequestsException(DI::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));
1128 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1129 if ($throttle_week > 0) {
1130 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1132 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1133 $posts_week = DBA::count('thread', $condition);
1135 if ($posts_week > $throttle_week) {
1136 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1137 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1138 throw new TooManyRequestsException(DI::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));
1142 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1143 if ($throttle_month > 0) {
1144 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1146 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1147 $posts_month = DBA::count('thread', $condition);
1149 if ($posts_month > $throttle_month) {
1150 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1151 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1152 throw new TooManyRequestsException(DI::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));
1157 if (!empty($_FILES['media'])) {
1158 // upload the image if we have one
1159 $picture = wall_upload_post($a, false);
1160 if (is_array($picture)) {
1161 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1165 if (requestdata('media_ids')) {
1166 $ids = explode(',', requestdata('media_ids'));
1167 foreach ($ids as $id) {
1169 "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",
1173 if (DBA::isResult($r)) {
1174 $phototypes = Images::supportedTypes();
1175 $ext = $phototypes[$r[0]['type']];
1176 $description = $r[0]['desc'] ?? '';
1177 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1178 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1183 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1185 $_REQUEST['api_source'] = true;
1187 if (empty($_REQUEST['source'])) {
1188 $_REQUEST["source"] = api_source();
1191 // call out normal post function
1192 $item_id = item_post($a);
1194 // output the post that we just posted.
1195 return api_status_show($type, $item_id);
1198 /// @TODO move to top of file or somewhere better
1199 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1200 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1203 * Uploads an image to Friendica.
1206 * @throws BadRequestException
1207 * @throws ForbiddenException
1208 * @throws ImagickException
1209 * @throws InternalServerErrorException
1210 * @throws UnauthorizedException
1211 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1213 function api_media_upload()
1217 if (api_user() === false) {
1218 Logger::log('no user');
1219 throw new ForbiddenException();
1224 if (empty($_FILES['media'])) {
1226 throw new BadRequestException("No media.");
1229 $media = wall_upload_post($a, false);
1232 throw new InternalServerErrorException();
1236 $returndata["media_id"] = $media["id"];
1237 $returndata["media_id_string"] = (string)$media["id"];
1238 $returndata["size"] = $media["size"];
1239 $returndata["image"] = ["w" => $media["width"],
1240 "h" => $media["height"],
1241 "image_type" => $media["type"],
1242 "friendica_preview_url" => $media["preview"]];
1244 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1246 return ["media" => $returndata];
1249 /// @TODO move to top of file or somewhere better
1250 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1253 * Updates media meta data (picture descriptions)
1255 * @param string $type Return type (atom, rss, xml, json)
1257 * @return array|string
1258 * @throws BadRequestException
1259 * @throws ForbiddenException
1260 * @throws ImagickException
1261 * @throws InternalServerErrorException
1262 * @throws TooManyRequestsException
1263 * @throws UnauthorizedException
1264 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1266 * @todo Compare the corresponding Twitter function for correct return values
1268 function api_media_metadata_create($type)
1272 if (api_user() === false) {
1273 Logger::info('no user');
1274 throw new ForbiddenException();
1279 $postdata = Network::postdata();
1281 if (empty($postdata)) {
1282 throw new BadRequestException("No post data");
1285 $data = json_decode($postdata, true);
1287 throw new BadRequestException("Invalid post data");
1290 if (empty($data['media_id']) || empty($data['alt_text'])) {
1291 throw new BadRequestException("Missing post data values");
1294 if (empty($data['alt_text']['text'])) {
1295 throw new BadRequestException("No alt text.");
1298 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1300 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1301 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1302 if (!DBA::isResult($photo)) {
1303 throw new BadRequestException("Metadata not found.");
1306 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1309 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1312 * @param string $type Return format (atom, rss, xml, json)
1313 * @param int $item_id
1317 function api_status_show($type, $item_id)
1319 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1323 $item = api_get_item(['id' => $item_id]);
1324 if (!empty($item)) {
1325 $status_info = api_format_item($item, $type);
1328 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1330 return api_format_data('statuses', $type, ['status' => $status_info]);
1334 * Retrieves the last public status of the provided user info
1336 * @param int $ownerId Public contact Id
1337 * @param int $uid User Id
1341 function api_get_last_status($ownerId, $uid)
1344 'author-id'=> $ownerId,
1346 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1347 'private' => [Item::PUBLIC, Item::UNLISTED]
1350 $item = api_get_item($condition);
1356 * Retrieves a single item record based on the provided condition and converts it for API use.
1358 * @param array $condition Item table condition array
1362 function api_get_item(array $condition)
1364 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1370 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1371 * The author's most recent status will be returned inline.
1373 * @param string $type Return type (atom, rss, xml, json)
1374 * @return array|string
1375 * @throws BadRequestException
1376 * @throws ImagickException
1377 * @throws InternalServerErrorException
1378 * @throws UnauthorizedException
1379 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1381 function api_users_show($type)
1383 $a = Friendica\DI::app();
1385 $user_info = api_get_user($a);
1387 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1388 if (!empty($item)) {
1389 $user_info['status'] = api_format_item($item, $type);
1392 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1393 unset($user_info['uid']);
1394 unset($user_info['self']);
1396 return api_format_data('user', $type, ['user' => $user_info]);
1399 /// @TODO move to top of file or somewhere better
1400 api_register_func('api/users/show', 'api_users_show');
1401 api_register_func('api/externalprofile/show', 'api_users_show');
1404 * Search a public user account.
1406 * @param string $type Return type (atom, rss, xml, json)
1408 * @return array|string
1409 * @throws BadRequestException
1410 * @throws ImagickException
1411 * @throws InternalServerErrorException
1412 * @throws UnauthorizedException
1413 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1415 function api_users_search($type)
1421 if (!empty($_GET['q'])) {
1422 $contacts = Contact::selectToArray(
1425 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1433 if (DBA::isResult($contacts)) {
1435 foreach ($contacts as $contact) {
1436 $user_info = api_get_user($a, $contact['id']);
1438 if ($type == 'xml') {
1439 $userlist[$k++ . ':user'] = $user_info;
1441 $userlist[] = $user_info;
1444 $userlist = ['users' => $userlist];
1446 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1449 throw new BadRequestException('No search term specified.');
1452 return api_format_data('users', $type, $userlist);
1455 /// @TODO move to top of file or somewhere better
1456 api_register_func('api/users/search', 'api_users_search');
1459 * Return user objects
1461 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1463 * @param string $type Return format: json or xml
1465 * @return array|string
1466 * @throws BadRequestException
1467 * @throws ImagickException
1468 * @throws InternalServerErrorException
1469 * @throws NotFoundException if the results are empty.
1470 * @throws UnauthorizedException
1472 function api_users_lookup($type)
1476 if (!empty($_REQUEST['user_id'])) {
1477 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1479 $users[] = api_get_user(DI::app(), $id);
1484 if (empty($users)) {
1485 throw new NotFoundException;
1488 return api_format_data("users", $type, ['users' => $users]);
1491 /// @TODO move to top of file or somewhere better
1492 api_register_func('api/users/lookup', 'api_users_lookup', true);
1495 * Returns statuses that match a specified query.
1497 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1499 * @param string $type Return format: json, xml, atom, rss
1501 * @return array|string
1502 * @throws BadRequestException if the "q" parameter is missing.
1503 * @throws ForbiddenException
1504 * @throws ImagickException
1505 * @throws InternalServerErrorException
1506 * @throws UnauthorizedException
1508 function api_search($type)
1511 $user_info = api_get_user($a);
1513 if (api_user() === false || $user_info === false) {
1514 throw new ForbiddenException();
1517 if (empty($_REQUEST['q'])) {
1518 throw new BadRequestException('q parameter is required.');
1521 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1524 $data['status'] = [];
1526 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1527 if (!empty($_REQUEST['rpp'])) {
1528 $count = $_REQUEST['rpp'];
1529 } elseif (!empty($_REQUEST['count'])) {
1530 $count = $_REQUEST['count'];
1533 $since_id = $_REQUEST['since_id'] ?? 0;
1534 $max_id = $_REQUEST['max_id'] ?? 0;
1535 $page = $_REQUEST['page'] ?? 1;
1537 $start = max(0, ($page - 1) * $count);
1539 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1540 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1541 $searchTerm = $matches[1];
1542 $condition = ["`oid` > ?
1543 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1544 AND `otype` = ? AND `type` = ? AND `term` = ?",
1545 $since_id, local_user(), Term::OBJECT_TYPE_POST, Term::HASHTAG, $searchTerm];
1547 $condition[0] .= ' AND `oid` <= ?';
1548 $condition[] = $max_id;
1550 $terms = DBA::select('term', ['oid'], $condition, []);
1552 while ($term = DBA::fetch($terms)) {
1553 $itemIds[] = $term['oid'];
1557 if (empty($itemIds)) {
1558 return api_format_data('statuses', $type, $data);
1561 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1562 if ($exclude_replies) {
1563 $preCondition[] = '`id` = `parent`';
1566 $condition = [implode(' AND ', $preCondition)];
1568 $condition = ["`id` > ?
1569 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1570 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1571 AND `body` LIKE CONCAT('%',?,'%')",
1572 $since_id, api_user(), $_REQUEST['q']];
1574 $condition[0] .= ' AND `id` <= ?';
1575 $condition[] = $max_id;
1581 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1582 $id = Item::fetchByLink($searchTerm, api_user());
1585 $id = Item::fetchByLink($searchTerm);
1589 $statuses = Item::select([], ['id' => $id]);
1593 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1595 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1597 bindComments($data['status']);
1599 return api_format_data('statuses', $type, $data);
1602 /// @TODO move to top of file or somewhere better
1603 api_register_func('api/search/tweets', 'api_search', true);
1604 api_register_func('api/search', 'api_search', true);
1607 * Returns the most recent statuses posted by the user and the users they follow.
1609 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1611 * @param string $type Return type (atom, rss, xml, json)
1613 * @return array|string
1614 * @throws BadRequestException
1615 * @throws ForbiddenException
1616 * @throws ImagickException
1617 * @throws InternalServerErrorException
1618 * @throws UnauthorizedException
1619 * @todo Optional parameters
1620 * @todo Add reply info
1622 function api_statuses_home_timeline($type)
1625 $user_info = api_get_user($a);
1627 if (api_user() === false || $user_info === false) {
1628 throw new ForbiddenException();
1631 unset($_REQUEST["user_id"]);
1632 unset($_GET["user_id"]);
1634 unset($_REQUEST["screen_name"]);
1635 unset($_GET["screen_name"]);
1637 // get last network messages
1640 $count = $_REQUEST['count'] ?? 20;
1641 $page = $_REQUEST['page']?? 0;
1642 $since_id = $_REQUEST['since_id'] ?? 0;
1643 $max_id = $_REQUEST['max_id'] ?? 0;
1644 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1645 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1647 $start = max(0, ($page - 1) * $count);
1649 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1650 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1653 $condition[0] .= " AND `item`.`id` <= ?";
1654 $condition[] = $max_id;
1656 if ($exclude_replies) {
1657 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1659 if ($conversation_id > 0) {
1660 $condition[0] .= " AND `item`.`parent` = ?";
1661 $condition[] = $conversation_id;
1664 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1665 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1667 $items = Item::inArray($statuses);
1669 $ret = api_format_items($items, $user_info, false, $type);
1671 // Set all posts from the query above to seen
1673 foreach ($items as $item) {
1674 $idarray[] = intval($item["id"]);
1677 if (!empty($idarray)) {
1678 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1680 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1686 $data = ['status' => $ret];
1691 $data = api_rss_extra($a, $data, $user_info);
1695 return api_format_data("statuses", $type, $data);
1699 /// @TODO move to top of file or somewhere better
1700 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1701 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1704 * Returns the most recent statuses from public users.
1706 * @param string $type Return type (atom, rss, xml, json)
1708 * @return array|string
1709 * @throws BadRequestException
1710 * @throws ForbiddenException
1711 * @throws ImagickException
1712 * @throws InternalServerErrorException
1713 * @throws UnauthorizedException
1715 function api_statuses_public_timeline($type)
1718 $user_info = api_get_user($a);
1720 if (api_user() === false || $user_info === false) {
1721 throw new ForbiddenException();
1724 // get last network messages
1727 $count = $_REQUEST['count'] ?? 20;
1728 $page = $_REQUEST['page'] ?? 1;
1729 $since_id = $_REQUEST['since_id'] ?? 0;
1730 $max_id = $_REQUEST['max_id'] ?? 0;
1731 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1732 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1734 $start = max(0, ($page - 1) * $count);
1736 if ($exclude_replies && !$conversation_id) {
1737 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
1738 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1741 $condition[0] .= " AND `thread`.`iid` <= ?";
1742 $condition[] = $max_id;
1745 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1746 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1748 $r = Item::inArray($statuses);
1750 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
1751 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1754 $condition[0] .= " AND `item`.`id` <= ?";
1755 $condition[] = $max_id;
1757 if ($conversation_id > 0) {
1758 $condition[0] .= " AND `item`.`parent` = ?";
1759 $condition[] = $conversation_id;
1762 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1763 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1765 $r = Item::inArray($statuses);
1768 $ret = api_format_items($r, $user_info, false, $type);
1772 $data = ['status' => $ret];
1777 $data = api_rss_extra($a, $data, $user_info);
1781 return api_format_data("statuses", $type, $data);
1784 /// @TODO move to top of file or somewhere better
1785 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1788 * Returns the most recent statuses posted by users this node knows about.
1790 * @param string $type Return format: json, xml, atom, rss
1791 * @return array|string
1792 * @throws BadRequestException
1793 * @throws ForbiddenException
1794 * @throws ImagickException
1795 * @throws InternalServerErrorException
1796 * @throws UnauthorizedException
1798 function api_statuses_networkpublic_timeline($type)
1801 $user_info = api_get_user($a);
1803 if (api_user() === false || $user_info === false) {
1804 throw new ForbiddenException();
1807 $since_id = $_REQUEST['since_id'] ?? 0;
1808 $max_id = $_REQUEST['max_id'] ?? 0;
1811 $count = $_REQUEST['count'] ?? 20;
1812 $page = $_REQUEST['page'] ?? 1;
1814 $start = max(0, ($page - 1) * $count);
1816 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
1817 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1820 $condition[0] .= " AND `thread`.`iid` <= ?";
1821 $condition[] = $max_id;
1824 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1825 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1827 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1831 $data = ['status' => $ret];
1836 $data = api_rss_extra($a, $data, $user_info);
1840 return api_format_data("statuses", $type, $data);
1843 /// @TODO move to top of file or somewhere better
1844 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1847 * Returns a single status.
1849 * @param string $type Return type (atom, rss, xml, json)
1851 * @return array|string
1852 * @throws BadRequestException
1853 * @throws ForbiddenException
1854 * @throws ImagickException
1855 * @throws InternalServerErrorException
1856 * @throws UnauthorizedException
1857 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1859 function api_statuses_show($type)
1862 $user_info = api_get_user($a);
1864 if (api_user() === false || $user_info === false) {
1865 throw new ForbiddenException();
1869 $id = intval($a->argv[3] ?? 0);
1872 $id = intval($_REQUEST['id'] ?? 0);
1877 $id = intval($a->argv[4] ?? 0);
1880 Logger::log('API: api_statuses_show: ' . $id);
1882 $conversation = !empty($_REQUEST['conversation']);
1884 // try to fetch the item for the local user - or the public item, if there is no local one
1885 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1886 if (!DBA::isResult($uri_item)) {
1887 throw new BadRequestException("There is no status with this id.");
1890 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1891 if (!DBA::isResult($item)) {
1892 throw new BadRequestException("There is no status with this id.");
1897 if ($conversation) {
1898 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1899 $params = ['order' => ['id' => true]];
1901 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1905 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1907 /// @TODO How about copying this to above methods which don't check $r ?
1908 if (!DBA::isResult($statuses)) {
1909 throw new BadRequestException("There is no status with this id.");
1912 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1914 if ($conversation) {
1915 $data = ['status' => $ret];
1916 return api_format_data("statuses", $type, $data);
1918 $data = ['status' => $ret[0]];
1919 return api_format_data("status", $type, $data);
1923 /// @TODO move to top of file or somewhere better
1924 api_register_func('api/statuses/show', 'api_statuses_show', true);
1928 * @param string $type Return type (atom, rss, xml, json)
1930 * @return array|string
1931 * @throws BadRequestException
1932 * @throws ForbiddenException
1933 * @throws ImagickException
1934 * @throws InternalServerErrorException
1935 * @throws UnauthorizedException
1936 * @todo nothing to say?
1938 function api_conversation_show($type)
1941 $user_info = api_get_user($a);
1943 if (api_user() === false || $user_info === false) {
1944 throw new ForbiddenException();
1948 $id = intval($a->argv[3] ?? 0);
1949 $since_id = intval($_REQUEST['since_id'] ?? 0);
1950 $max_id = intval($_REQUEST['max_id'] ?? 0);
1951 $count = intval($_REQUEST['count'] ?? 20);
1952 $page = intval($_REQUEST['page'] ?? 1);
1954 $start = max(0, ($page - 1) * $count);
1957 $id = intval($_REQUEST['id'] ?? 0);
1962 $id = intval($a->argv[4] ?? 0);
1965 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1967 // try to fetch the item for the local user - or the public item, if there is no local one
1968 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1969 if (!DBA::isResult($item)) {
1970 throw new BadRequestException("There is no status with this id.");
1973 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1974 if (!DBA::isResult($parent)) {
1975 throw new BadRequestException("There is no status with this id.");
1978 $id = $parent['id'];
1980 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1981 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1984 $condition[0] .= " AND `item`.`id` <= ?";
1985 $condition[] = $max_id;
1988 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1989 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1991 if (!DBA::isResult($statuses)) {
1992 throw new BadRequestException("There is no status with id $id.");
1995 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1997 $data = ['status' => $ret];
1998 return api_format_data("statuses", $type, $data);
2001 /// @TODO move to top of file or somewhere better
2002 api_register_func('api/conversation/show', 'api_conversation_show', true);
2003 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2008 * @param string $type Return type (atom, rss, xml, json)
2010 * @return array|string
2011 * @throws BadRequestException
2012 * @throws ForbiddenException
2013 * @throws ImagickException
2014 * @throws InternalServerErrorException
2015 * @throws UnauthorizedException
2016 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2018 function api_statuses_repeat($type)
2024 if (api_user() === false) {
2025 throw new ForbiddenException();
2031 $id = intval($a->argv[3] ?? 0);
2034 $id = intval($_REQUEST['id'] ?? 0);
2039 $id = intval($a->argv[4] ?? 0);
2042 Logger::log('API: api_statuses_repeat: '.$id);
2044 $fields = ['uri-id', 'body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2045 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2047 if (DBA::isResult($item) && $item['body'] != "") {
2048 if (strpos($item['body'], "[/share]") !== false) {
2049 $pos = strpos($item['body'], "[share");
2050 $post = substr($item['body'], $pos);
2052 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2054 if (!empty($item['title'])) {
2055 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2058 $post .= $item['body'];
2059 $post .= "[/share]";
2061 $_REQUEST['body'] = $post;
2062 $_REQUEST['tag'] = $item['tag'];
2063 $_REQUEST['attach'] = $item['attach'];
2064 $_REQUEST['profile_uid'] = api_user();
2065 $_REQUEST['api_source'] = true;
2067 if (empty($_REQUEST['source'])) {
2068 $_REQUEST["source"] = api_source();
2071 $item_id = item_post($a);
2073 /// @todo Copy tags from the original post to the new one
2075 throw new ForbiddenException();
2078 // output the post that we just posted.
2080 return api_status_show($type, $item_id);
2083 /// @TODO move to top of file or somewhere better
2084 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2087 * Destroys a specific status.
2089 * @param string $type Return type (atom, rss, xml, json)
2091 * @return array|string
2092 * @throws BadRequestException
2093 * @throws ForbiddenException
2094 * @throws ImagickException
2095 * @throws InternalServerErrorException
2096 * @throws UnauthorizedException
2097 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2099 function api_statuses_destroy($type)
2103 if (api_user() === false) {
2104 throw new ForbiddenException();
2110 $id = intval($a->argv[3] ?? 0);
2113 $id = intval($_REQUEST['id'] ?? 0);
2118 $id = intval($a->argv[4] ?? 0);
2121 Logger::log('API: api_statuses_destroy: '.$id);
2123 $ret = api_statuses_show($type);
2125 Item::deleteForUser(['id' => $id], api_user());
2130 /// @TODO move to top of file or somewhere better
2131 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2134 * Returns the most recent mentions.
2136 * @param string $type Return type (atom, rss, xml, json)
2138 * @return array|string
2139 * @throws BadRequestException
2140 * @throws ForbiddenException
2141 * @throws ImagickException
2142 * @throws InternalServerErrorException
2143 * @throws UnauthorizedException
2144 * @see http://developer.twitter.com/doc/get/statuses/mentions
2146 function api_statuses_mentions($type)
2149 $user_info = api_get_user($a);
2151 if (api_user() === false || $user_info === false) {
2152 throw new ForbiddenException();
2155 unset($_REQUEST["user_id"]);
2156 unset($_GET["user_id"]);
2158 unset($_REQUEST["screen_name"]);
2159 unset($_GET["screen_name"]);
2161 // get last network messages
2164 $since_id = $_REQUEST['since_id'] ?? 0;
2165 $max_id = $_REQUEST['max_id'] ?? 0;
2166 $count = $_REQUEST['count'] ?? 20;
2167 $page = $_REQUEST['page'] ?? 1;
2169 $start = max(0, ($page - 1) * $count);
2171 $query = "SELECT `item`.`id` FROM `user-item`
2172 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2173 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2174 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2175 AND `user-item`.`iid` > ?";
2176 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2177 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2178 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2179 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2183 $query .= " AND `item`.`id` <= ?";
2184 $condition[] = $max_id;
2187 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2188 $condition[] = $start;
2189 $condition[] = $count;
2191 $useritems = DBA::p($query, $condition);
2193 while ($useritem = DBA::fetch($useritems)) {
2194 $itemids[] = $useritem['id'];
2196 DBA::close($useritems);
2198 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2199 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2201 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2203 $data = ['status' => $ret];
2208 $data = api_rss_extra($a, $data, $user_info);
2212 return api_format_data("statuses", $type, $data);
2215 /// @TODO move to top of file or somewhere better
2216 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2217 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2220 * Returns the most recent statuses posted by the user.
2222 * @param string $type Either "json" or "xml"
2223 * @return string|array
2224 * @throws BadRequestException
2225 * @throws ForbiddenException
2226 * @throws ImagickException
2227 * @throws InternalServerErrorException
2228 * @throws UnauthorizedException
2229 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2231 function api_statuses_user_timeline($type)
2234 $user_info = api_get_user($a);
2236 if (api_user() === false || $user_info === false) {
2237 throw new ForbiddenException();
2241 "api_statuses_user_timeline: api_user: ". api_user() .
2242 "\nuser_info: ".print_r($user_info, true) .
2243 "\n_REQUEST: ".print_r($_REQUEST, true),
2247 $since_id = $_REQUEST['since_id'] ?? 0;
2248 $max_id = $_REQUEST['max_id'] ?? 0;
2249 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2250 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2253 $count = $_REQUEST['count'] ?? 20;
2254 $page = $_REQUEST['page'] ?? 1;
2256 $start = max(0, ($page - 1) * $count);
2258 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2259 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2261 if ($user_info['self'] == 1) {
2262 $condition[0] .= ' AND `item`.`wall` ';
2265 if ($exclude_replies) {
2266 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2269 if ($conversation_id > 0) {
2270 $condition[0] .= " AND `item`.`parent` = ?";
2271 $condition[] = $conversation_id;
2275 $condition[0] .= " AND `item`.`id` <= ?";
2276 $condition[] = $max_id;
2279 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2280 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2282 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2286 $data = ['status' => $ret];
2291 $data = api_rss_extra($a, $data, $user_info);
2295 return api_format_data("statuses", $type, $data);
2298 /// @TODO move to top of file or somewhere better
2299 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2302 * Star/unstar an item.
2303 * param: id : id of the item
2305 * @param string $type Return type (atom, rss, xml, json)
2307 * @return array|string
2308 * @throws BadRequestException
2309 * @throws ForbiddenException
2310 * @throws ImagickException
2311 * @throws InternalServerErrorException
2312 * @throws UnauthorizedException
2313 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2315 function api_favorites_create_destroy($type)
2319 if (api_user() === false) {
2320 throw new ForbiddenException();
2323 // for versioned api.
2324 /// @TODO We need a better global soluton
2325 $action_argv_id = 2;
2326 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2327 $action_argv_id = 3;
2330 if ($a->argc <= $action_argv_id) {
2331 throw new BadRequestException("Invalid request.");
2333 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2334 if ($a->argc == $action_argv_id + 2) {
2335 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2337 $itemid = intval($_REQUEST['id'] ?? 0);
2340 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2342 if (!DBA::isResult($item)) {
2343 throw new BadRequestException("Invalid item.");
2348 $item['starred'] = 1;
2351 $item['starred'] = 0;
2354 throw new BadRequestException("Invalid action ".$action);
2357 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2360 throw new InternalServerErrorException("DB error");
2364 $user_info = api_get_user($a);
2365 $rets = api_format_items([$item], $user_info, false, $type);
2368 $data = ['status' => $ret];
2373 $data = api_rss_extra($a, $data, $user_info);
2377 return api_format_data("status", $type, $data);
2380 /// @TODO move to top of file or somewhere better
2381 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2382 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2385 * Returns the most recent favorite statuses.
2387 * @param string $type Return type (atom, rss, xml, json)
2389 * @return string|array
2390 * @throws BadRequestException
2391 * @throws ForbiddenException
2392 * @throws ImagickException
2393 * @throws InternalServerErrorException
2394 * @throws UnauthorizedException
2396 function api_favorites($type)
2401 $user_info = api_get_user($a);
2403 if (api_user() === false || $user_info === false) {
2404 throw new ForbiddenException();
2409 // in friendica starred item are private
2410 // return favorites only for self
2411 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2413 if ($user_info['self'] == 0) {
2417 $since_id = $_REQUEST['since_id'] ?? 0;
2418 $max_id = $_REQUEST['max_id'] ?? 0;
2419 $count = $_GET['count'] ?? 20;
2420 $page = $_REQUEST['page'] ?? 1;
2422 $start = max(0, ($page - 1) * $count);
2424 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2425 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2427 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2430 $condition[0] .= " AND `item`.`id` <= ?";
2431 $condition[] = $max_id;
2434 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2436 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2441 $data = ['status' => $ret];
2446 $data = api_rss_extra($a, $data, $user_info);
2450 return api_format_data("statuses", $type, $data);
2453 /// @TODO move to top of file or somewhere better
2454 api_register_func('api/favorites', 'api_favorites', true);
2458 * @param array $item
2459 * @param array $recipient
2460 * @param array $sender
2463 * @throws InternalServerErrorException
2465 function api_format_messages($item, $recipient, $sender)
2467 // standard meta information
2469 'id' => $item['id'],
2470 'sender_id' => $sender['id'],
2472 'recipient_id' => $recipient['id'],
2473 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2474 'sender_screen_name' => $sender['screen_name'],
2475 'recipient_screen_name' => $recipient['screen_name'],
2476 'sender' => $sender,
2477 'recipient' => $recipient,
2479 'friendica_seen' => $item['seen'] ?? 0,
2480 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2483 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2484 if (isset($ret['sender']['uid'])) {
2485 unset($ret['sender']['uid']);
2487 if (isset($ret['sender']['self'])) {
2488 unset($ret['sender']['self']);
2490 if (isset($ret['recipient']['uid'])) {
2491 unset($ret['recipient']['uid']);
2493 if (isset($ret['recipient']['self'])) {
2494 unset($ret['recipient']['self']);
2497 //don't send title to regular StatusNET requests to avoid confusing these apps
2498 if (!empty($_GET['getText'])) {
2499 $ret['title'] = $item['title'];
2500 if ($_GET['getText'] == 'html') {
2501 $ret['text'] = BBCode::convert($item['body'], false);
2502 } elseif ($_GET['getText'] == 'plain') {
2503 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2506 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2508 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2509 unset($ret['sender']);
2510 unset($ret['recipient']);
2518 * @param array $item
2521 * @throws InternalServerErrorException
2523 function api_convert_item($item)
2525 $body = $item['body'];
2526 $entities = api_get_entitities($statustext, $body);
2528 // Add pictures to the attachment array and remove them from the body
2529 $attachments = api_get_attachments($body);
2531 // Workaround for ostatus messages where the title is identically to the body
2532 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2533 $statusbody = trim(HTML::toPlaintext($html, 0));
2535 // handle data: images
2536 $statusbody = api_format_items_embeded_images($item, $statusbody);
2538 $statustitle = trim($item['title']);
2540 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2541 $statustext = trim($statusbody);
2543 $statustext = trim($statustitle."\n\n".$statusbody);
2546 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2547 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2550 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2552 // Workaround for clients with limited HTML parser functionality
2553 $search = ["<br>", "<blockquote>", "</blockquote>",
2554 "<h1>", "</h1>", "<h2>", "</h2>",
2555 "<h3>", "</h3>", "<h4>", "</h4>",
2556 "<h5>", "</h5>", "<h6>", "</h6>"];
2557 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2558 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2559 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2560 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2561 $statushtml = str_replace($search, $replace, $statushtml);
2563 if ($item['title'] != "") {
2564 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2568 $oldtext = $statushtml;
2569 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2570 } while ($oldtext != $statushtml);
2572 if (substr($statushtml, 0, 4) == '<br>') {
2573 $statushtml = substr($statushtml, 4);
2576 if (substr($statushtml, 0, -4) == '<br>') {
2577 $statushtml = substr($statushtml, -4);
2580 // feeds without body should contain the link
2581 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2582 $statushtml .= BBCode::convert($item['plink']);
2586 "text" => $statustext,
2587 "html" => $statushtml,
2588 "attachments" => $attachments,
2589 "entities" => $entities
2595 * @param string $body
2598 * @throws InternalServerErrorException
2600 function api_get_attachments(&$body)
2602 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2603 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2605 $URLSearchString = "^\[\]";
2606 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2610 // Remove all embedded pictures, since they are added as attachments
2611 foreach ($images[0] as $orig) {
2612 $body = str_replace($orig, '', $body);
2617 foreach ($images[1] as $image) {
2618 $imagedata = Images::getInfoFromURLCached($image);
2621 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2625 return $attachments;
2630 * @param string $text
2631 * @param string $bbcode
2634 * @throws InternalServerErrorException
2635 * @todo Links at the first character of the post
2637 function api_get_entitities(&$text, $bbcode)
2639 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2641 if ($include_entities != "true") {
2642 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2644 foreach ($images[1] as $image) {
2645 $replace = ProxyUtils::proxifyUrl($image);
2646 $text = str_replace($image, $replace, $text);
2651 $bbcode = BBCode::cleanPictureLinks($bbcode);
2653 // Change pure links in text to bbcode uris
2654 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2657 $entities["hashtags"] = [];
2658 $entities["symbols"] = [];
2659 $entities["urls"] = [];
2660 $entities["user_mentions"] = [];
2662 $URLSearchString = "^\[\]";
2664 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2666 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2667 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2669 $bbcode = preg_replace(
2670 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2671 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2674 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2676 $bbcode = preg_replace(
2677 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2678 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2681 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2683 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2685 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2688 foreach ($urls[1] as $id => $url) {
2689 $start = iconv_strpos($text, $url, 0, "UTF-8");
2690 if (!($start === false)) {
2691 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2695 ksort($ordered_urls);
2699 foreach ($ordered_urls as $url) {
2700 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2701 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2703 $display_url = $url["title"];
2705 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2706 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2708 if (strlen($display_url) > 26) {
2709 $display_url = substr($display_url, 0, 25)."…";
2713 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2714 if (!($start === false)) {
2715 $entities["urls"][] = ["url" => $url["url"],
2716 "expanded_url" => $url["url"],
2717 "display_url" => $display_url,
2718 "indices" => [$start, $start+strlen($url["url"])]];
2719 $offset = $start + 1;
2723 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2724 $ordered_images = [];
2725 foreach ($images as $image) {
2726 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2727 if (!($start === false)) {
2728 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2732 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2733 foreach ($images[1] as $image) {
2734 $start = iconv_strpos($text, $image, 0, "UTF-8");
2735 if (!($start === false)) {
2736 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2742 foreach ($ordered_images as $image) {
2743 $url = $image['url'];
2744 $ext_alt_text = $image['alt'];
2746 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2747 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2749 if (strlen($display_url) > 26) {
2750 $display_url = substr($display_url, 0, 25)."…";
2753 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2754 if (!($start === false)) {
2755 $image = Images::getInfoFromURLCached($url);
2757 // If image cache is activated, then use the following sizes:
2758 // thumb (150), small (340), medium (600) and large (1024)
2759 if (!DI::config()->get("system", "proxy_disabled")) {
2760 $media_url = ProxyUtils::proxifyUrl($url);
2763 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2764 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2766 if (($image[0] > 150) || ($image[1] > 150)) {
2767 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2768 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2771 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2772 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2774 if (($image[0] > 600) || ($image[1] > 600)) {
2775 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2776 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2780 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2783 $entities["media"][] = [
2785 "id_str" => (string) ($start + 1),
2786 "indices" => [$start, $start+strlen($url)],
2787 "media_url" => Strings::normaliseLink($media_url),
2788 "media_url_https" => $media_url,
2790 "display_url" => $display_url,
2791 "expanded_url" => $url,
2792 "ext_alt_text" => $ext_alt_text,
2796 $offset = $start + 1;
2805 * @param array $item
2806 * @param string $text
2810 function api_format_items_embeded_images($item, $text)
2812 $text = preg_replace_callback(
2813 '|data:image/([^;]+)[^=]+=*|m',
2814 function () use ($item) {
2815 return DI::baseUrl() . '/display/' . $item['guid'];
2823 * return <a href='url'>name</a> as array
2825 * @param string $txt text
2830 function api_contactlink_to_array($txt)
2833 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2834 if ($r && count($match)==3) {
2836 'name' => $match[2],
2850 * return likes, dislikes and attend status for item
2852 * @param array $item array
2853 * @param string $type Return type (atom, rss, xml, json)
2856 * likes => int count,
2857 * dislikes => int count
2858 * @throws BadRequestException
2859 * @throws ImagickException
2860 * @throws InternalServerErrorException
2861 * @throws UnauthorizedException
2863 function api_format_items_activities($item, $type = "json")
2872 'attendmaybe' => [],
2876 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2877 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2879 while ($parent_item = Item::fetch($ret)) {
2880 // not used as result should be structured like other user data
2881 //builtin_activity_puller($i, $activities);
2883 // get user data and add it to the array of the activity
2884 $user = api_get_user($a, $parent_item['author-id']);
2885 switch ($parent_item['verb']) {
2886 case Activity::LIKE:
2887 $activities['like'][] = $user;
2889 case Activity::DISLIKE:
2890 $activities['dislike'][] = $user;
2892 case Activity::ATTEND:
2893 $activities['attendyes'][] = $user;
2895 case Activity::ATTENDNO:
2896 $activities['attendno'][] = $user;
2898 case Activity::ATTENDMAYBE:
2899 $activities['attendmaybe'][] = $user;
2901 case Activity::ANNOUNCE:
2902 $activities['announce'][] = $user;
2911 if ($type == "xml") {
2912 $xml_activities = [];
2913 foreach ($activities as $k => $v) {
2914 // change xml element from "like" to "friendica:like"
2915 $xml_activities["friendica:".$k] = $v;
2916 // add user data into xml output
2918 foreach ($v as $user) {
2919 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2922 $activities = $xml_activities;
2929 * format items to be returned by api
2931 * @param array $items array of items
2932 * @param array $user_info
2933 * @param bool $filter_user filter items by $user_info
2934 * @param string $type Return type (atom, rss, xml, json)
2936 * @throws BadRequestException
2937 * @throws ImagickException
2938 * @throws InternalServerErrorException
2939 * @throws UnauthorizedException
2941 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2943 $a = Friendica\DI::app();
2947 foreach ((array)$items as $item) {
2948 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2950 // Look if the posts are matching if they should be filtered by user id
2951 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2955 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2964 * @param array $item Item record
2965 * @param string $type Return format (atom, rss, xml, json)
2966 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2967 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2968 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2969 * @return array API-formatted status
2970 * @throws BadRequestException
2971 * @throws ImagickException
2972 * @throws InternalServerErrorException
2973 * @throws UnauthorizedException
2975 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2977 $a = Friendica\DI::app();
2979 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2980 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2983 localize_item($item);
2985 $in_reply_to = api_in_reply_to($item);
2987 $converted = api_convert_item($item);
2989 if ($type == "xml") {
2990 $geo = "georss:point";
2996 'text' => $converted["text"],
2997 'truncated' => false,
2998 'created_at'=> api_date($item['created']),
2999 'in_reply_to_status_id' => $in_reply_to['status_id'],
3000 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3001 'source' => (($item['app']) ? $item['app'] : 'web'),
3002 'id' => intval($item['id']),
3003 'id_str' => (string) intval($item['id']),
3004 'in_reply_to_user_id' => $in_reply_to['user_id'],
3005 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3006 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3008 'favorited' => $item['starred'] ? true : false,
3009 'user' => $status_user,
3010 'friendica_author' => $author_user,
3011 'friendica_owner' => $owner_user,
3012 'friendica_private' => $item['private'] == Item::PRIVATE,
3013 //'entities' => NULL,
3014 'statusnet_html' => $converted["html"],
3015 'statusnet_conversation_id' => $item['parent'],
3016 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3017 'friendica_activities' => api_format_items_activities($item, $type),
3018 'friendica_title' => $item['title'],
3019 'friendica_html' => BBCode::convert($item['body'], false)
3022 if (count($converted["attachments"]) > 0) {
3023 $status["attachments"] = $converted["attachments"];
3026 if (count($converted["entities"]) > 0) {
3027 $status["entities"] = $converted["entities"];
3030 if ($status["source"] == 'web') {
3031 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3032 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3033 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3036 $retweeted_item = [];
3039 if ($item["id"] == $item["parent"]) {
3040 $body = $item['body'];
3041 $retweeted_item = api_share_as_retweet($item);
3042 if ($body != $item['body']) {
3043 $quoted_item = $retweeted_item;
3044 $retweeted_item = [];
3048 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3049 $announce = api_get_announce($item);
3050 if (!empty($announce)) {
3051 $retweeted_item = $item;
3053 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3057 if (!empty($quoted_item)) {
3058 if ($quoted_item['id'] != $item['id']) {
3059 $quoted_status = api_format_item($quoted_item);
3060 /// @todo Only remove the attachments that are also contained in the quotes status
3061 unset($status['attachments']);
3062 unset($status['entities']);
3064 $conv_quoted = api_convert_item($quoted_item);
3065 $quoted_status = $status;
3066 unset($quoted_status['attachments']);
3067 unset($quoted_status['entities']);
3068 unset($quoted_status['statusnet_conversation_id']);
3069 $quoted_status['text'] = $conv_quoted['text'];
3070 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3072 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3073 } catch (BadRequestException $e) {
3074 // user not found. should be found?
3075 /// @todo check if the user should be always found
3076 $quoted_status["user"] = [];
3079 unset($quoted_status['friendica_author']);
3080 unset($quoted_status['friendica_owner']);
3081 unset($quoted_status['friendica_activities']);
3082 unset($quoted_status['friendica_private']);
3085 if (!empty($retweeted_item)) {
3086 $retweeted_status = $status;
3087 unset($retweeted_status['friendica_author']);
3088 unset($retweeted_status['friendica_owner']);
3089 unset($retweeted_status['friendica_activities']);
3090 unset($retweeted_status['friendica_private']);
3091 unset($retweeted_status['statusnet_conversation_id']);
3092 $status['user'] = $status['friendica_owner'];
3094 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3095 } catch (BadRequestException $e) {
3096 // user not found. should be found?
3097 /// @todo check if the user should be always found
3098 $retweeted_status["user"] = [];
3101 $rt_converted = api_convert_item($retweeted_item);
3103 $retweeted_status['text'] = $rt_converted["text"];
3104 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3105 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3107 if (!empty($quoted_status)) {
3108 $retweeted_status['quoted_status'] = $quoted_status;
3111 $status['friendica_author'] = $retweeted_status['user'];
3112 $status['retweeted_status'] = $retweeted_status;
3113 } elseif (!empty($quoted_status)) {
3114 $root_status = api_convert_item($item);
3116 $status['text'] = $root_status["text"];
3117 $status['statusnet_html'] = $root_status["html"];
3118 $status['quoted_status'] = $quoted_status;
3121 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3122 unset($status["user"]["uid"]);
3123 unset($status["user"]["self"]);
3125 if ($item["coord"] != "") {
3126 $coords = explode(' ', $item["coord"]);
3127 if (count($coords) == 2) {
3128 if ($type == "json") {
3129 $status["geo"] = ['type' => 'Point',
3130 'coordinates' => [(float) $coords[0],
3131 (float) $coords[1]]];
3132 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3133 $status["georss:point"] = $item["coord"];
3142 * Returns the remaining number of API requests available to the user before the API limit is reached.
3144 * @param string $type Return type (atom, rss, xml, json)
3146 * @return array|string
3149 function api_account_rate_limit_status($type)
3151 if ($type == "xml") {
3153 'remaining-hits' => '150',
3154 '@attributes' => ["type" => "integer"],
3155 'hourly-limit' => '150',
3156 '@attributes2' => ["type" => "integer"],
3157 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3158 '@attributes3' => ["type" => "datetime"],
3159 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3160 '@attributes4' => ["type" => "integer"],
3164 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3165 'remaining_hits' => '150',
3166 'hourly_limit' => '150',
3167 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3171 return api_format_data('hash', $type, ['hash' => $hash]);
3174 /// @TODO move to top of file or somewhere better
3175 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3178 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3180 * @param string $type Return type (atom, rss, xml, json)
3182 * @return array|string
3184 function api_help_test($type)
3186 if ($type == 'xml') {
3192 return api_format_data('ok', $type, ["ok" => $ok]);
3195 /// @TODO move to top of file or somewhere better
3196 api_register_func('api/help/test', 'api_help_test', false);
3199 * Returns all lists the user subscribes to.
3201 * @param string $type Return type (atom, rss, xml, json)
3203 * @return array|string
3204 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3206 function api_lists_list($type)
3209 /// @TODO $ret is not filled here?
3210 return api_format_data('lists', $type, ["lists_list" => $ret]);
3213 /// @TODO move to top of file or somewhere better
3214 api_register_func('api/lists/list', 'api_lists_list', true);
3215 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3218 * Returns all groups the user owns.
3220 * @param string $type Return type (atom, rss, xml, json)
3222 * @return array|string
3223 * @throws BadRequestException
3224 * @throws ForbiddenException
3225 * @throws ImagickException
3226 * @throws InternalServerErrorException
3227 * @throws UnauthorizedException
3228 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3230 function api_lists_ownerships($type)
3234 if (api_user() === false) {
3235 throw new ForbiddenException();
3239 $user_info = api_get_user($a);
3240 $uid = $user_info['uid'];
3242 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3244 // loop through all groups
3246 foreach ($groups as $group) {
3247 if ($group['visible']) {
3253 'name' => $group['name'],
3254 'id' => intval($group['id']),
3255 'id_str' => (string) $group['id'],
3256 'user' => $user_info,
3260 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3263 /// @TODO move to top of file or somewhere better
3264 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3267 * Returns recent statuses from users in the specified group.
3269 * @param string $type Return type (atom, rss, xml, json)
3271 * @return array|string
3272 * @throws BadRequestException
3273 * @throws ForbiddenException
3274 * @throws ImagickException
3275 * @throws InternalServerErrorException
3276 * @throws UnauthorizedException
3277 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3279 function api_lists_statuses($type)
3283 $user_info = api_get_user($a);
3284 if (api_user() === false || $user_info === false) {
3285 throw new ForbiddenException();
3288 unset($_REQUEST["user_id"]);
3289 unset($_GET["user_id"]);
3291 unset($_REQUEST["screen_name"]);
3292 unset($_GET["screen_name"]);
3294 if (empty($_REQUEST['list_id'])) {
3295 throw new BadRequestException('list_id not specified');
3299 $count = $_REQUEST['count'] ?? 20;
3300 $page = $_REQUEST['page'] ?? 1;
3301 $since_id = $_REQUEST['since_id'] ?? 0;
3302 $max_id = $_REQUEST['max_id'] ?? 0;
3303 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3304 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3306 $start = max(0, ($page - 1) * $count);
3308 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3309 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3312 $condition[0] .= " AND `item`.`id` <= ?";
3313 $condition[] = $max_id;
3315 if ($exclude_replies > 0) {
3316 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3318 if ($conversation_id > 0) {
3319 $condition[0] .= " AND `item`.`parent` = ?";
3320 $condition[] = $conversation_id;
3323 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3324 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3326 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3328 $data = ['status' => $items];
3333 $data = api_rss_extra($a, $data, $user_info);
3337 return api_format_data("statuses", $type, $data);
3340 /// @TODO move to top of file or somewhere better
3341 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3344 * Returns either the friends of the follower list
3346 * Considers friends and followers lists to be private and won't return
3347 * anything if any user_id parameter is passed.
3349 * @param string $qtype Either "friends" or "followers"
3350 * @return boolean|array
3351 * @throws BadRequestException
3352 * @throws ForbiddenException
3353 * @throws ImagickException
3354 * @throws InternalServerErrorException
3355 * @throws UnauthorizedException
3357 function api_statuses_f($qtype)
3361 if (api_user() === false) {
3362 throw new ForbiddenException();
3366 $count = $_GET['count'] ?? 20;
3367 $page = $_GET['page'] ?? 1;
3369 $start = max(0, ($page - 1) * $count);
3371 $user_info = api_get_user($a);
3373 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3374 /* this is to stop Hotot to load friends multiple times
3375 * I'm not sure if I'm missing return something or
3376 * is a bug in hotot. Workaround, meantime
3380 return array('$users' => $ret);*/
3385 if ($qtype == 'friends') {
3386 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3387 } elseif ($qtype == 'followers') {
3388 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3391 // friends and followers only for self
3392 if ($user_info['self'] == 0) {
3393 $sql_extra = " AND false ";
3396 if ($qtype == 'blocks') {
3397 $sql_filter = 'AND `blocked` AND NOT `pending`';
3398 } elseif ($qtype == 'incoming') {
3399 $sql_filter = 'AND `pending`';
3401 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3419 foreach ($r as $cid) {
3420 $user = api_get_user($a, $cid['nurl']);
3421 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3422 unset($user["uid"]);
3423 unset($user["self"]);
3430 return ['user' => $ret];
3435 * Returns the list of friends of the provided user
3437 * @deprecated By Twitter API in favor of friends/list
3439 * @param string $type Either "json" or "xml"
3440 * @return boolean|string|array
3441 * @throws BadRequestException
3442 * @throws ForbiddenException
3444 function api_statuses_friends($type)
3446 $data = api_statuses_f("friends");
3447 if ($data === false) {
3450 return api_format_data("users", $type, $data);
3454 * Returns the list of followers of the provided user
3456 * @deprecated By Twitter API in favor of friends/list
3458 * @param string $type Either "json" or "xml"
3459 * @return boolean|string|array
3460 * @throws BadRequestException
3461 * @throws ForbiddenException
3463 function api_statuses_followers($type)
3465 $data = api_statuses_f("followers");
3466 if ($data === false) {
3469 return api_format_data("users", $type, $data);
3472 /// @TODO move to top of file or somewhere better
3473 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3474 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3477 * Returns the list of blocked users
3479 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3481 * @param string $type Either "json" or "xml"
3483 * @return boolean|string|array
3484 * @throws BadRequestException
3485 * @throws ForbiddenException
3487 function api_blocks_list($type)
3489 $data = api_statuses_f('blocks');
3490 if ($data === false) {
3493 return api_format_data("users", $type, $data);
3496 /// @TODO move to top of file or somewhere better
3497 api_register_func('api/blocks/list', 'api_blocks_list', true);
3500 * Returns the list of pending users IDs
3502 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3504 * @param string $type Either "json" or "xml"
3506 * @return boolean|string|array
3507 * @throws BadRequestException
3508 * @throws ForbiddenException
3510 function api_friendships_incoming($type)
3512 $data = api_statuses_f('incoming');
3513 if ($data === false) {
3518 foreach ($data['user'] as $user) {
3519 $ids[] = $user['id'];
3522 return api_format_data("ids", $type, ['id' => $ids]);
3525 /// @TODO move to top of file or somewhere better
3526 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3529 * Returns the instance's configuration information.
3531 * @param string $type Return type (atom, rss, xml, json)
3533 * @return array|string
3534 * @throws InternalServerErrorException
3536 function api_statusnet_config($type)
3538 $name = DI::config()->get('config', 'sitename');
3539 $server = DI::baseUrl()->getHostname();
3540 $logo = DI::baseUrl() . '/images/friendica-64.png';
3541 $email = DI::config()->get('config', 'admin_email');
3542 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3543 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3544 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3545 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3546 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3549 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3550 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3551 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3552 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3553 'shorturllength' => '30',
3555 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3556 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3557 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3558 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3563 return api_format_data('config', $type, ['config' => $config]);
3566 /// @TODO move to top of file or somewhere better
3567 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3568 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3572 * @param string $type Return type (atom, rss, xml, json)
3574 * @return array|string
3576 function api_statusnet_version($type)
3579 $fake_statusnet_version = "0.9.7";
3581 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3584 /// @TODO move to top of file or somewhere better
3585 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3586 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3590 * @param string $type Return type (atom, rss, xml, json)
3592 * @param int $rel A contact relationship constant
3593 * @return array|string|void
3594 * @throws BadRequestException
3595 * @throws ForbiddenException
3596 * @throws ImagickException
3597 * @throws InternalServerErrorException
3598 * @throws UnauthorizedException
3599 * @todo use api_format_data() to return data
3601 function api_ff_ids($type, int $rel)
3604 throw new ForbiddenException();
3611 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3613 $contacts = DBA::p("SELECT `pcontact`.`id`
3615 INNER JOIN `contact` AS `pcontact`
3616 ON `contact`.`nurl` = `pcontact`.`nurl`
3617 AND `pcontact`.`uid` = 0
3618 WHERE `contact`.`uid` = ?
3619 AND NOT `contact`.`self`
3620 AND `contact`.`rel` IN (?, ?)",
3627 foreach (DBA::toArray($contacts) as $contact) {
3628 if ($stringify_ids) {
3629 $ids[] = $contact['id'];
3631 $ids[] = intval($contact['id']);
3635 return api_format_data('ids', $type, ['id' => $ids]);
3639 * Returns the ID of every user the user is following.
3641 * @param string $type Return type (atom, rss, xml, json)
3643 * @return array|string
3644 * @throws BadRequestException
3645 * @throws ForbiddenException
3646 * @throws ImagickException
3647 * @throws InternalServerErrorException
3648 * @throws UnauthorizedException
3649 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3651 function api_friends_ids($type)
3653 return api_ff_ids($type, Contact::SHARING);
3657 * Returns the ID of every user following the user.
3659 * @param string $type Return type (atom, rss, xml, json)
3661 * @return array|string
3662 * @throws BadRequestException
3663 * @throws ForbiddenException
3664 * @throws ImagickException
3665 * @throws InternalServerErrorException
3666 * @throws UnauthorizedException
3667 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3669 function api_followers_ids($type)
3671 return api_ff_ids($type, Contact::FOLLOWER);
3674 /// @TODO move to top of file or somewhere better
3675 api_register_func('api/friends/ids', 'api_friends_ids', true);
3676 api_register_func('api/followers/ids', 'api_followers_ids', true);
3679 * Sends a new direct message.
3681 * @param string $type Return type (atom, rss, xml, json)
3683 * @return array|string
3684 * @throws BadRequestException
3685 * @throws ForbiddenException
3686 * @throws ImagickException
3687 * @throws InternalServerErrorException
3688 * @throws NotFoundException
3689 * @throws UnauthorizedException
3690 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3692 function api_direct_messages_new($type)
3696 if (api_user() === false) {
3697 throw new ForbiddenException();
3700 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3704 $sender = api_get_user($a);
3707 if (!empty($_POST['screen_name'])) {
3709 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3711 DBA::escape($_POST['screen_name'])
3714 if (DBA::isResult($r)) {
3715 // Selecting the id by priority, friendica first
3716 api_best_nickname($r);
3718 $recipient = api_get_user($a, $r[0]['nurl']);
3721 $recipient = api_get_user($a, $_POST['user_id']);
3724 if (empty($recipient)) {
3725 throw new NotFoundException('Recipient not found');
3729 if (!empty($_REQUEST['replyto'])) {
3731 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3733 intval($_REQUEST['replyto'])
3735 $replyto = $r[0]['parent-uri'];
3736 $sub = $r[0]['title'];
3738 if (!empty($_REQUEST['title'])) {
3739 $sub = $_REQUEST['title'];
3741 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3745 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3748 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3749 $ret = api_format_messages($r[0], $recipient, $sender);
3751 $ret = ["error"=>$id];
3754 $data = ['direct_message'=>$ret];
3760 $data = api_rss_extra($a, $data, $sender);
3764 return api_format_data("direct-messages", $type, $data);
3767 /// @TODO move to top of file or somewhere better
3768 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3771 * 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 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3858 * @return string|array
3859 * @throws BadRequestException
3860 * @throws ForbiddenException
3861 * @throws ImagickException
3862 * @throws InternalServerErrorException
3863 * @throws NotFoundException
3864 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3866 function api_friendships_destroy($type)
3870 if ($uid === false) {
3871 throw new ForbiddenException();
3874 $contact_id = $_REQUEST['user_id'] ?? 0;
3876 if (empty($contact_id)) {
3877 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3878 throw new BadRequestException("no user_id specified");
3881 // Get Contact by given id
3882 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3884 if(!DBA::isResult($contact)) {
3885 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3886 throw new NotFoundException("no contact found to given ID");
3889 $url = $contact["url"];
3891 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3892 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3893 Strings::normaliseLink($url), $url];
3894 $contact = DBA::selectFirst('contact', [], $condition);
3896 if (!DBA::isResult($contact)) {
3897 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3898 throw new NotFoundException("Not following Contact");
3901 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3902 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3903 throw new ExpectationFailedException("Not supported");
3906 $dissolve = ($contact['rel'] == Contact::SHARING);
3908 $owner = User::getOwnerDataById($uid);
3910 Contact::terminateFriendship($owner, $contact, $dissolve);
3913 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3914 throw new NotFoundException("Error Processing Request");
3917 // Sharing-only contacts get deleted as there no relationship any more
3919 Contact::remove($contact['id']);
3921 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3924 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3925 unset($contact["uid"]);
3926 unset($contact["self"]);
3928 // Set screen_name since Twidere requests it
3929 $contact["screen_name"] = $contact["nick"];
3931 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3933 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3937 * @param string $type Return type (atom, rss, xml, json)
3938 * @param string $box
3939 * @param string $verbose
3941 * @return array|string
3942 * @throws BadRequestException
3943 * @throws ForbiddenException
3944 * @throws ImagickException
3945 * @throws InternalServerErrorException
3946 * @throws UnauthorizedException
3948 function api_direct_messages_box($type, $box, $verbose)
3951 if (api_user() === false) {
3952 throw new ForbiddenException();
3955 $count = $_GET['count'] ?? 20;
3956 $page = $_REQUEST['page'] ?? 1;
3958 $since_id = $_REQUEST['since_id'] ?? 0;
3959 $max_id = $_REQUEST['max_id'] ?? 0;
3961 $user_id = $_REQUEST['user_id'] ?? '';
3962 $screen_name = $_REQUEST['screen_name'] ?? '';
3965 unset($_REQUEST["user_id"]);
3966 unset($_GET["user_id"]);
3968 unset($_REQUEST["screen_name"]);
3969 unset($_GET["screen_name"]);
3971 $user_info = api_get_user($a);
3972 if ($user_info === false) {
3973 throw new ForbiddenException();
3975 $profile_url = $user_info["url"];
3978 $start = max(0, ($page - 1) * $count);
3983 if ($box=="sentbox") {
3984 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3985 } elseif ($box == "conversation") {
3986 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3987 } elseif ($box == "all") {
3988 $sql_extra = "true";
3989 } elseif ($box == "inbox") {
3990 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3994 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3997 if ($user_id != "") {
3998 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3999 } elseif ($screen_name !="") {
4000 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4004 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
4010 if ($verbose == "true" && !DBA::isResult($r)) {
4011 $answer = ['result' => 'error', 'message' => 'no mails available'];
4012 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4016 foreach ($r as $item) {
4017 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4018 $recipient = $user_info;
4019 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4020 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4021 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4022 $sender = $user_info;
4025 if (isset($recipient) && isset($sender)) {
4026 $ret[] = api_format_messages($item, $recipient, $sender);
4031 $data = ['direct_message' => $ret];
4036 $data = api_rss_extra($a, $data, $user_info);
4040 return api_format_data("direct-messages", $type, $data);
4044 * Returns the most recent direct messages sent by the user.
4046 * @param string $type Return type (atom, rss, xml, json)
4048 * @return array|string
4049 * @throws BadRequestException
4050 * @throws ForbiddenException
4051 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4053 function api_direct_messages_sentbox($type)
4055 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4056 return api_direct_messages_box($type, "sentbox", $verbose);
4060 * Returns the most recent direct messages sent to the user.
4062 * @param string $type Return type (atom, rss, xml, json)
4064 * @return array|string
4065 * @throws BadRequestException
4066 * @throws ForbiddenException
4067 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4069 function api_direct_messages_inbox($type)
4071 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4072 return api_direct_messages_box($type, "inbox", $verbose);
4077 * @param string $type Return type (atom, rss, xml, json)
4079 * @return array|string
4080 * @throws BadRequestException
4081 * @throws ForbiddenException
4083 function api_direct_messages_all($type)
4085 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4086 return api_direct_messages_box($type, "all", $verbose);
4091 * @param string $type Return type (atom, rss, xml, json)
4093 * @return array|string
4094 * @throws BadRequestException
4095 * @throws ForbiddenException
4097 function api_direct_messages_conversation($type)
4099 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4100 return api_direct_messages_box($type, "conversation", $verbose);
4103 /// @TODO move to top of file or somewhere better
4104 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4105 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4106 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4107 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4110 * Returns an OAuth Request Token.
4112 * @see https://oauth.net/core/1.0/#auth_step1
4114 function api_oauth_request_token()
4116 $oauth1 = new FKOAuth1();
4118 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4119 } catch (Exception $e) {
4120 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4128 * Returns an OAuth Access Token.
4130 * @return array|string
4131 * @see https://oauth.net/core/1.0/#auth_step3
4133 function api_oauth_access_token()
4135 $oauth1 = new FKOAuth1();
4137 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4138 } catch (Exception $e) {
4139 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4146 /// @TODO move to top of file or somewhere better
4147 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4148 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4152 * delete a complete photoalbum with all containing photos from database through api
4154 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4155 * @return string|array
4156 * @throws BadRequestException
4157 * @throws ForbiddenException
4158 * @throws InternalServerErrorException
4160 function api_fr_photoalbum_delete($type)
4162 if (api_user() === false) {
4163 throw new ForbiddenException();
4166 $album = $_REQUEST['album'] ?? '';
4168 // we do not allow calls without album string
4170 throw new BadRequestException("no albumname specified");
4172 // check if album is existing
4174 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4178 if (!DBA::isResult($r)) {
4179 throw new BadRequestException("album not available");
4182 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4183 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4184 foreach ($r as $rr) {
4185 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4186 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4188 if (!DBA::isResult($photo_item)) {
4189 throw new InternalServerErrorException("problem with deleting items occured");
4191 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4194 // now let's delete all photos from the album
4195 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4197 // return success of deletion or error message
4199 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4200 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4202 throw new InternalServerErrorException("unknown error - deleting from database failed");
4207 * update the name of the album for all photos of an album
4209 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4210 * @return string|array
4211 * @throws BadRequestException
4212 * @throws ForbiddenException
4213 * @throws InternalServerErrorException
4215 function api_fr_photoalbum_update($type)
4217 if (api_user() === false) {
4218 throw new ForbiddenException();
4221 $album = $_REQUEST['album'] ?? '';
4222 $album_new = $_REQUEST['album_new'] ?? '';
4224 // we do not allow calls without album string
4226 throw new BadRequestException("no albumname specified");
4228 if ($album_new == "") {
4229 throw new BadRequestException("no new albumname specified");
4231 // check if album is existing
4232 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4233 throw new BadRequestException("album not available");
4235 // now let's update all photos to the albumname
4236 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4238 // return success of updating or error message
4240 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4241 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4243 throw new InternalServerErrorException("unknown error - updating in database failed");
4249 * list all photos of the authenticated user
4251 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4252 * @return string|array
4253 * @throws ForbiddenException
4254 * @throws InternalServerErrorException
4256 function api_fr_photos_list($type)
4258 if (api_user() === false) {
4259 throw new ForbiddenException();
4262 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4263 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4264 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4265 intval(local_user())
4268 'image/jpeg' => 'jpg',
4269 'image/png' => 'png',
4270 'image/gif' => 'gif'
4272 $data = ['photo'=>[]];
4273 if (DBA::isResult($r)) {
4274 foreach ($r as $rr) {
4276 $photo['id'] = $rr['resource-id'];
4277 $photo['album'] = $rr['album'];
4278 $photo['filename'] = $rr['filename'];
4279 $photo['type'] = $rr['type'];
4280 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4281 $photo['created'] = $rr['created'];
4282 $photo['edited'] = $rr['edited'];
4283 $photo['desc'] = $rr['desc'];
4285 if ($type == "xml") {
4286 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4288 $photo['thumb'] = $thumb;
4289 $data['photo'][] = $photo;
4293 return api_format_data("photos", $type, $data);
4297 * upload a new photo or change an existing photo
4299 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4300 * @return string|array
4301 * @throws BadRequestException
4302 * @throws ForbiddenException
4303 * @throws ImagickException
4304 * @throws InternalServerErrorException
4305 * @throws NotFoundException
4307 function api_fr_photo_create_update($type)
4309 if (api_user() === false) {
4310 throw new ForbiddenException();
4313 $photo_id = $_REQUEST['photo_id'] ?? null;
4314 $desc = $_REQUEST['desc'] ?? null;
4315 $album = $_REQUEST['album'] ?? null;
4316 $album_new = $_REQUEST['album_new'] ?? null;
4317 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4318 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4319 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4320 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4321 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4323 // do several checks on input parameters
4324 // we do not allow calls without album string
4325 if ($album == null) {
4326 throw new BadRequestException("no albumname specified");
4328 // if photo_id == null --> we are uploading a new photo
4329 if ($photo_id == null) {
4332 // error if no media posted in create-mode
4333 if (empty($_FILES['media'])) {
4335 throw new BadRequestException("no media data submitted");
4338 // album_new will be ignored in create-mode
4343 // check if photo is existing in databasei
4344 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4345 throw new BadRequestException("photo not available");
4349 // checks on acl strings provided by clients
4350 $acl_input_error = false;
4351 $acl_input_error |= check_acl_input($allow_cid);
4352 $acl_input_error |= check_acl_input($deny_cid);
4353 $acl_input_error |= check_acl_input($allow_gid);
4354 $acl_input_error |= check_acl_input($deny_gid);
4355 if ($acl_input_error) {
4356 throw new BadRequestException("acl data invalid");
4358 // now let's upload the new media in create-mode
4359 if ($mode == "create") {
4360 $media = $_FILES['media'];
4361 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4363 // return success of updating or error message
4364 if (!is_null($data)) {
4365 return api_format_data("photo_create", $type, $data);
4367 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4371 // now let's do the changes in update-mode
4372 if ($mode == "update") {
4373 $updated_fields = [];
4375 if (!is_null($desc)) {
4376 $updated_fields['desc'] = $desc;
4379 if (!is_null($album_new)) {
4380 $updated_fields['album'] = $album_new;
4383 if (!is_null($allow_cid)) {
4384 $allow_cid = trim($allow_cid);
4385 $updated_fields['allow_cid'] = $allow_cid;
4388 if (!is_null($deny_cid)) {
4389 $deny_cid = trim($deny_cid);
4390 $updated_fields['deny_cid'] = $deny_cid;
4393 if (!is_null($allow_gid)) {
4394 $allow_gid = trim($allow_gid);
4395 $updated_fields['allow_gid'] = $allow_gid;
4398 if (!is_null($deny_gid)) {
4399 $deny_gid = trim($deny_gid);
4400 $updated_fields['deny_gid'] = $deny_gid;
4404 if (count($updated_fields) > 0) {
4405 $nothingtodo = false;
4406 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4408 $nothingtodo = true;
4411 if (!empty($_FILES['media'])) {
4412 $nothingtodo = false;
4413 $media = $_FILES['media'];
4414 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4415 if (!is_null($data)) {
4416 return api_format_data("photo_update", $type, $data);
4420 // return success of updating or error message
4422 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4423 return api_format_data("photo_update", $type, ['$result' => $answer]);
4426 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4427 return api_format_data("photo_update", $type, ['$result' => $answer]);
4429 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4432 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4436 * delete a single photo from the database through api
4438 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4439 * @return string|array
4440 * @throws BadRequestException
4441 * @throws ForbiddenException
4442 * @throws InternalServerErrorException
4444 function api_fr_photo_delete($type)
4446 if (api_user() === false) {
4447 throw new ForbiddenException();
4451 $photo_id = $_REQUEST['photo_id'] ?? null;
4453 // do several checks on input parameters
4454 // we do not allow calls without photo id
4455 if ($photo_id == null) {
4456 throw new BadRequestException("no photo_id specified");
4459 // check if photo is existing in database
4460 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4461 throw new BadRequestException("photo not available");
4464 // now we can perform on the deletion of the photo
4465 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4467 // return success of deletion or error message
4469 // retrieve the id of the parent element (the photo element)
4470 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4471 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4473 if (!DBA::isResult($photo_item)) {
4474 throw new InternalServerErrorException("problem with deleting items occured");
4476 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4477 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4478 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4480 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4481 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4483 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4489 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4491 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4492 * @return string|array
4493 * @throws BadRequestException
4494 * @throws ForbiddenException
4495 * @throws InternalServerErrorException
4496 * @throws NotFoundException
4498 function api_fr_photo_detail($type)
4500 if (api_user() === false) {
4501 throw new ForbiddenException();
4503 if (empty($_REQUEST['photo_id'])) {
4504 throw new BadRequestException("No photo id.");
4507 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4508 $photo_id = $_REQUEST['photo_id'];
4510 // prepare json/xml output with data from database for the requested photo
4511 $data = prepare_photo_data($type, $scale, $photo_id);
4513 return api_format_data("photo_detail", $type, $data);
4518 * updates the profile image for the user (either a specified profile or the default profile)
4520 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4522 * @return string|array
4523 * @throws BadRequestException
4524 * @throws ForbiddenException
4525 * @throws ImagickException
4526 * @throws InternalServerErrorException
4527 * @throws NotFoundException
4528 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4530 function api_account_update_profile_image($type)
4532 if (api_user() === false) {
4533 throw new ForbiddenException();
4536 $profile_id = $_REQUEST['profile_id'] ?? 0;
4538 // error if image data is missing
4539 if (empty($_FILES['image'])) {
4540 throw new BadRequestException("no media data submitted");
4543 // check if specified profile id is valid
4544 if ($profile_id != 0) {
4545 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4546 // error message if specified profile id is not in database
4547 if (!DBA::isResult($profile)) {
4548 throw new BadRequestException("profile_id not available");
4550 $is_default_profile = $profile['is-default'];
4552 $is_default_profile = 1;
4555 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4557 if (!empty($_FILES['image'])) {
4558 $media = $_FILES['image'];
4559 } elseif (!empty($_FILES['media'])) {
4560 $media = $_FILES['media'];
4562 // save new profile image
4563 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4566 if (is_array($media['type'])) {
4567 $filetype = $media['type'][0];
4569 $filetype = $media['type'];
4571 if ($filetype == "image/jpeg") {
4573 } elseif ($filetype == "image/png") {
4576 throw new InternalServerErrorException('Unsupported filetype');
4579 // change specified profile or all profiles to the new resource-id
4580 if ($is_default_profile) {
4581 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4582 Photo::update(['profile' => false], $condition);
4584 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4585 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4586 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4589 Contact::updateSelfFromUserID(api_user(), true);
4591 // Update global directory in background
4592 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4593 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4594 Worker::add(PRIORITY_LOW, "Directory", $url);
4597 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4599 // output for client
4601 return api_account_verify_credentials($type);
4603 // SaveMediaToDatabase failed for some reason
4604 throw new InternalServerErrorException("image upload failed");
4608 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4609 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4610 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4611 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4612 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4613 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4614 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4615 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4616 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4619 * Update user profile
4621 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4623 * @return array|string
4624 * @throws BadRequestException
4625 * @throws ForbiddenException
4626 * @throws ImagickException
4627 * @throws InternalServerErrorException
4628 * @throws UnauthorizedException
4630 function api_account_update_profile($type)
4632 $local_user = api_user();
4633 $api_user = api_get_user(DI::app());
4635 if (!empty($_POST['name'])) {
4636 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4637 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4638 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4639 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4642 if (isset($_POST['description'])) {
4643 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4644 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4645 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4648 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4649 // Update global directory in background
4650 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4651 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4654 return api_account_verify_credentials($type);
4657 /// @TODO move to top of file or somewhere better
4658 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4662 * @param string $acl_string
4666 function check_acl_input($acl_string)
4668 if (empty($acl_string)) {
4672 $contact_not_found = false;
4674 // split <x><y><z> into array of cid's
4675 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4677 // check for each cid if it is available on server
4678 $cid_array = $array[0];
4679 foreach ($cid_array as $cid) {
4680 $cid = str_replace("<", "", $cid);
4681 $cid = str_replace(">", "", $cid);
4682 $condition = ['id' => $cid, 'uid' => api_user()];
4683 $contact_not_found |= !DBA::exists('contact', $condition);
4685 return $contact_not_found;
4689 * @param string $mediatype
4690 * @param array $media
4691 * @param string $type
4692 * @param string $album
4693 * @param string $allow_cid
4694 * @param string $deny_cid
4695 * @param string $allow_gid
4696 * @param string $deny_gid
4697 * @param string $desc
4698 * @param integer $profile
4699 * @param boolean $visibility
4700 * @param string $photo_id
4702 * @throws BadRequestException
4703 * @throws ForbiddenException
4704 * @throws ImagickException
4705 * @throws InternalServerErrorException
4706 * @throws NotFoundException
4707 * @throws UnauthorizedException
4709 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
4717 if (is_array($media)) {
4718 if (is_array($media['tmp_name'])) {
4719 $src = $media['tmp_name'][0];
4721 $src = $media['tmp_name'];
4723 if (is_array($media['name'])) {
4724 $filename = basename($media['name'][0]);
4726 $filename = basename($media['name']);
4728 if (is_array($media['size'])) {
4729 $filesize = intval($media['size'][0]);
4731 $filesize = intval($media['size']);
4733 if (is_array($media['type'])) {
4734 $filetype = $media['type'][0];
4736 $filetype = $media['type'];
4740 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4743 "File upload src: " . $src . " - filename: " . $filename .
4744 " - size: " . $filesize . " - type: " . $filetype,
4748 // check if there was a php upload error
4749 if ($filesize == 0 && $media['error'] == 1) {
4750 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4752 // check against max upload size within Friendica instance
4753 $maximagesize = DI::config()->get('system', 'maximagesize');
4754 if ($maximagesize && ($filesize > $maximagesize)) {
4755 $formattedBytes = Strings::formatBytes($maximagesize);
4756 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4759 // create Photo instance with the data of the image
4760 $imagedata = @file_get_contents($src);
4761 $Image = new Image($imagedata, $filetype);
4762 if (!$Image->isValid()) {
4763 throw new InternalServerErrorException("unable to process image data");
4766 // check orientation of image
4767 $Image->orient($src);
4770 // check max length of images on server
4771 $max_length = DI::config()->get('system', 'max_image_length');
4773 $max_length = MAX_IMAGE_LENGTH;
4775 if ($max_length > 0) {
4776 $Image->scaleDown($max_length);
4777 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4779 $width = $Image->getWidth();
4780 $height = $Image->getHeight();
4782 // create a new resource-id if not already provided
4783 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4785 if ($mediatype == "photo") {
4786 // upload normal image (scales 0, 1, 2)
4787 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4789 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4791 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4793 if ($width > 640 || $height > 640) {
4794 $Image->scaleDown(640);
4795 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4797 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4801 if ($width > 320 || $height > 320) {
4802 $Image->scaleDown(320);
4803 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4805 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4808 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4809 } elseif ($mediatype == "profileimage") {
4810 // upload profile image (scales 4, 5, 6)
4811 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4813 if ($width > 300 || $height > 300) {
4814 $Image->scaleDown(300);
4815 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4817 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4821 if ($width > 80 || $height > 80) {
4822 $Image->scaleDown(80);
4823 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4825 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4829 if ($width > 48 || $height > 48) {
4830 $Image->scaleDown(48);
4831 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4833 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4836 $Image->__destruct();
4837 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4840 if (isset($r) && $r) {
4841 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4842 if ($photo_id == null && $mediatype == "photo") {
4843 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4845 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4846 return prepare_photo_data($type, false, $resource_id);
4848 throw new InternalServerErrorException("image upload failed");
4854 * @param string $hash
4855 * @param string $allow_cid
4856 * @param string $deny_cid
4857 * @param string $allow_gid
4858 * @param string $deny_gid
4859 * @param string $filetype
4860 * @param boolean $visibility
4861 * @throws InternalServerErrorException
4863 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4865 // get data about the api authenticated user
4866 $uri = Item::newURI(intval(api_user()));
4867 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4870 $arr['guid'] = System::createUUID();
4871 $arr['uid'] = intval(api_user());
4873 $arr['parent-uri'] = $uri;
4874 $arr['type'] = 'photo';
4876 $arr['resource-id'] = $hash;
4877 $arr['contact-id'] = $owner_record['id'];
4878 $arr['owner-name'] = $owner_record['name'];
4879 $arr['owner-link'] = $owner_record['url'];
4880 $arr['owner-avatar'] = $owner_record['thumb'];
4881 $arr['author-name'] = $owner_record['name'];
4882 $arr['author-link'] = $owner_record['url'];
4883 $arr['author-avatar'] = $owner_record['thumb'];
4885 $arr['allow_cid'] = $allow_cid;
4886 $arr['allow_gid'] = $allow_gid;
4887 $arr['deny_cid'] = $deny_cid;
4888 $arr['deny_gid'] = $deny_gid;
4889 $arr['visible'] = $visibility;
4893 'image/jpeg' => 'jpg',
4894 'image/png' => 'png',
4895 'image/gif' => 'gif'
4898 // adds link to the thumbnail scale photo
4899 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4900 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4903 // do the magic for storing the item in the database and trigger the federation to other contacts
4909 * @param string $type
4911 * @param string $photo_id
4914 * @throws BadRequestException
4915 * @throws ForbiddenException
4916 * @throws ImagickException
4917 * @throws InternalServerErrorException
4918 * @throws NotFoundException
4919 * @throws UnauthorizedException
4921 function prepare_photo_data($type, $scale, $photo_id)
4924 $user_info = api_get_user($a);
4926 if ($user_info === false) {
4927 throw new ForbiddenException();
4930 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4931 $data_sql = ($scale === false ? "" : "data, ");
4933 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4934 // clients needs to convert this in their way for further processing
4936 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4937 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4938 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4939 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4940 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4941 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4943 intval(local_user()),
4944 DBA::escape($photo_id),
4949 'image/jpeg' => 'jpg',
4950 'image/png' => 'png',
4951 'image/gif' => 'gif'
4954 // prepare output data for photo
4955 if (DBA::isResult($r)) {
4956 $data = ['photo' => $r[0]];
4957 $data['photo']['id'] = $data['photo']['resource-id'];
4958 if ($scale !== false) {
4959 $data['photo']['data'] = base64_encode($data['photo']['data']);
4961 unset($data['photo']['datasize']); //needed only with scale param
4963 if ($type == "xml") {
4964 $data['photo']['links'] = [];
4965 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4966 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4968 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4971 $data['photo']['link'] = [];
4972 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4974 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4975 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4979 unset($data['photo']['resource-id']);
4980 unset($data['photo']['minscale']);
4981 unset($data['photo']['maxscale']);
4983 throw new NotFoundException();
4986 // retrieve item element for getting activities (like, dislike etc.) related to photo
4987 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4988 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4989 if (!DBA::isResult($item)) {
4990 throw new NotFoundException('Photo-related item not found.');
4993 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4995 // retrieve comments on photo
4996 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4997 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4999 $statuses = Item::selectForUser(api_user(), [], $condition);
5001 // prepare output of comments
5002 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5004 if ($type == "xml") {
5006 foreach ($commentData as $comment) {
5007 $comments[$k++ . ":comment"] = $comment;
5010 foreach ($commentData as $comment) {
5011 $comments[] = $comment;
5014 $data['photo']['friendica_comments'] = $comments;
5016 // include info if rights on photo and rights on item are mismatching
5017 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5018 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5019 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5020 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5021 $data['photo']['rights_mismatch'] = $rights_mismatch;
5028 * Similar as /mod/redir.php
5029 * redirect to 'url' after dfrn auth
5031 * Why this when there is mod/redir.php already?
5032 * This use api_user() and api_login()
5035 * c_url: url of remote contact to auth to
5036 * url: string, url to redirect after auth
5038 function api_friendica_remoteauth()
5040 $url = $_GET['url'] ?? '';
5041 $c_url = $_GET['c_url'] ?? '';
5043 if ($url === '' || $c_url === '') {
5044 throw new BadRequestException("Wrong parameters.");
5047 $c_url = Strings::normaliseLink($c_url);
5051 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5052 if (!DBA::isResult($contact)) {
5053 throw new BadRequestException("Unknown contact");
5056 $cid = $contact['id'];
5058 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5060 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5061 System::externalRedirect($url ?: $c_url);
5064 if ($contact['duplex'] && $contact['issued-id']) {
5065 $orig_id = $contact['issued-id'];
5066 $dfrn_id = '1:' . $orig_id;
5068 if ($contact['duplex'] && $contact['dfrn-id']) {
5069 $orig_id = $contact['dfrn-id'];
5070 $dfrn_id = '0:' . $orig_id;
5073 $sec = Strings::getRandomHex();
5075 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5076 'sec' => $sec, 'expire' => time() + 45];
5077 DBA::insert('profile_check', $fields);
5079 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5080 $dest = ($url ? '&destination_url=' . $url : '');
5082 System::externalRedirect(
5083 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5084 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5085 . '&type=profile&sec=' . $sec . $dest
5088 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5091 * Return an item with announcer data if it had been announced
5093 * @param array $item Item array
5094 * @return array Item array with announce data
5096 function api_get_announce($item)
5098 // Quit if the item already has got a different owner and author
5099 if ($item['owner-id'] != $item['author-id']) {
5103 // Don't change original or Diaspora posts
5104 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5108 // Quit if we do now the original author and it had been a post from a native network
5109 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5113 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5114 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5115 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5116 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5117 if (!DBA::isResult($announce)) {
5121 return array_merge($item, $announce);
5125 * Return the item shared, if the item contains only the [share] tag
5127 * @param array $item Sharer item
5128 * @return array|false Shared item or false if not a reshare
5129 * @throws ImagickException
5130 * @throws InternalServerErrorException
5132 function api_share_as_retweet(&$item)
5134 $body = trim($item["body"]);
5136 if (Diaspora::isReshare($body, false) === false) {
5137 if ($item['author-id'] == $item['owner-id']) {
5140 // Reshares from OStatus, ActivityPub and Twitter
5141 $reshared_item = $item;
5142 $reshared_item['owner-id'] = $reshared_item['author-id'];
5143 $reshared_item['owner-link'] = $reshared_item['author-link'];
5144 $reshared_item['owner-name'] = $reshared_item['author-name'];
5145 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5146 return $reshared_item;
5150 $reshared = Item::getShareArray($item);
5151 if (empty($reshared)) {
5155 $reshared_item = $item;
5157 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5161 if (!empty($reshared['comment'])) {
5162 $item['body'] = $reshared['comment'];
5165 $reshared_item["share-pre-body"] = $reshared['comment'];
5166 $reshared_item["body"] = $reshared['shared'];
5167 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5168 $reshared_item["author-name"] = $reshared['author'];
5169 $reshared_item["author-link"] = $reshared['profile'];
5170 $reshared_item["author-avatar"] = $reshared['avatar'];
5171 $reshared_item["plink"] = $reshared['link'] ?? '';
5172 $reshared_item["created"] = $reshared['posted'];
5173 $reshared_item["edited"] = $reshared['posted'];
5175 // Try to fetch the original item
5176 if (!empty($reshared['guid'])) {
5177 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5178 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5179 $condition = ['id' => $original_id];
5184 if (!empty($condition)) {
5185 $original_item = Item::selectFirst([], $condition);
5186 if (DBA::isResult($original_item)) {
5187 $reshared_item = array_merge($reshared_item, $original_item);
5191 return $reshared_item;
5196 * @param array $item
5201 function api_in_reply_to($item)
5205 $in_reply_to['status_id'] = null;
5206 $in_reply_to['user_id'] = null;
5207 $in_reply_to['status_id_str'] = null;
5208 $in_reply_to['user_id_str'] = null;
5209 $in_reply_to['screen_name'] = null;
5211 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5212 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5213 if (DBA::isResult($parent)) {
5214 $in_reply_to['status_id'] = intval($parent['id']);
5216 $in_reply_to['status_id'] = intval($item['parent']);
5219 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5221 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5222 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5224 if (DBA::isResult($parent)) {
5225 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5226 $in_reply_to['user_id'] = intval($parent['author-id']);
5227 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5230 // There seems to be situation, where both fields are identical:
5231 // https://github.com/friendica/friendica/issues/1010
5232 // This is a bugfix for that.
5233 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5234 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']]);
5235 $in_reply_to['status_id'] = null;
5236 $in_reply_to['user_id'] = null;
5237 $in_reply_to['status_id_str'] = null;
5238 $in_reply_to['user_id_str'] = null;
5239 $in_reply_to['screen_name'] = null;
5243 return $in_reply_to;
5248 * @param string $text
5251 * @throws InternalServerErrorException
5253 function api_clean_plain_items($text)
5255 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5257 $text = BBCode::cleanPictureLinks($text);
5258 $URLSearchString = "^\[\]";
5260 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5262 if ($include_entities == "true") {
5263 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5266 // Simplify "attachment" element
5267 $text = BBCode::removeAttachment($text);
5274 * @param array $contacts
5278 function api_best_nickname(&$contacts)
5282 if (count($contacts) == 0) {
5286 foreach ($contacts as $contact) {
5287 if ($contact["network"] == "") {
5288 $contact["network"] = "dfrn";
5289 $best_contact = [$contact];
5293 if (sizeof($best_contact) == 0) {
5294 foreach ($contacts as $contact) {
5295 if ($contact["network"] == "dfrn") {
5296 $best_contact = [$contact];
5301 if (sizeof($best_contact) == 0) {
5302 foreach ($contacts as $contact) {
5303 if ($contact["network"] == "dspr") {
5304 $best_contact = [$contact];
5309 if (sizeof($best_contact) == 0) {
5310 foreach ($contacts as $contact) {
5311 if ($contact["network"] == "stat") {
5312 $best_contact = [$contact];
5317 if (sizeof($best_contact) == 0) {
5318 foreach ($contacts as $contact) {
5319 if ($contact["network"] == "pump") {
5320 $best_contact = [$contact];
5325 if (sizeof($best_contact) == 0) {
5326 foreach ($contacts as $contact) {
5327 if ($contact["network"] == "twit") {
5328 $best_contact = [$contact];
5333 if (sizeof($best_contact) == 1) {
5334 $contacts = $best_contact;
5336 $contacts = [$contacts[0]];
5341 * Return all or a specified group of the user with the containing contacts.
5343 * @param string $type Return type (atom, rss, xml, json)
5345 * @return array|string
5346 * @throws BadRequestException
5347 * @throws ForbiddenException
5348 * @throws ImagickException
5349 * @throws InternalServerErrorException
5350 * @throws UnauthorizedException
5352 function api_friendica_group_show($type)
5356 if (api_user() === false) {
5357 throw new ForbiddenException();
5361 $user_info = api_get_user($a);
5362 $gid = $_REQUEST['gid'] ?? 0;
5363 $uid = $user_info['uid'];
5365 // get data of the specified group id or all groups if not specified
5368 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5372 // error message if specified gid is not in database
5373 if (!DBA::isResult($r)) {
5374 throw new BadRequestException("gid not available");
5378 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5383 // loop through all groups and retrieve all members for adding data in the user array
5385 foreach ($r as $rr) {
5386 $members = Contact::getByGroupId($rr['id']);
5389 if ($type == "xml") {
5390 $user_element = "users";
5392 foreach ($members as $member) {
5393 $user = api_get_user($a, $member['nurl']);
5394 $users[$k++.":user"] = $user;
5397 $user_element = "user";
5398 foreach ($members as $member) {
5399 $user = api_get_user($a, $member['nurl']);
5403 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5405 return api_format_data("groups", $type, ['group' => $grps]);
5407 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5411 * Delete the specified group of the user.
5413 * @param string $type Return type (atom, rss, xml, json)
5415 * @return array|string
5416 * @throws BadRequestException
5417 * @throws ForbiddenException
5418 * @throws ImagickException
5419 * @throws InternalServerErrorException
5420 * @throws UnauthorizedException
5422 function api_friendica_group_delete($type)
5426 if (api_user() === false) {
5427 throw new ForbiddenException();
5431 $user_info = api_get_user($a);
5432 $gid = $_REQUEST['gid'] ?? 0;
5433 $name = $_REQUEST['name'] ?? '';
5434 $uid = $user_info['uid'];
5436 // error if no gid specified
5437 if ($gid == 0 || $name == "") {
5438 throw new BadRequestException('gid or name not specified');
5441 // get data of the specified group id
5443 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5447 // error message if specified gid is not in database
5448 if (!DBA::isResult($r)) {
5449 throw new BadRequestException('gid not available');
5452 // get data of the specified group id and group name
5454 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5459 // error message if specified gid is not in database
5460 if (!DBA::isResult($rname)) {
5461 throw new BadRequestException('wrong group name');
5465 $ret = Group::removeByName($uid, $name);
5468 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5469 return api_format_data("group_delete", $type, ['result' => $success]);
5471 throw new BadRequestException('other API error');
5474 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5479 * @param string $type Return type (atom, rss, xml, json)
5481 * @return array|string
5482 * @throws BadRequestException
5483 * @throws ForbiddenException
5484 * @throws ImagickException
5485 * @throws InternalServerErrorException
5486 * @throws UnauthorizedException
5487 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5489 function api_lists_destroy($type)
5493 if (api_user() === false) {
5494 throw new ForbiddenException();
5498 $user_info = api_get_user($a);
5499 $gid = $_REQUEST['list_id'] ?? 0;
5500 $uid = $user_info['uid'];
5502 // error if no gid specified
5504 throw new BadRequestException('gid not specified');
5507 // get data of the specified group id
5508 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5509 // error message if specified gid is not in database
5511 throw new BadRequestException('gid not available');
5514 if (Group::remove($gid)) {
5516 'name' => $group['name'],
5517 'id' => intval($gid),
5518 'id_str' => (string) $gid,
5519 'user' => $user_info
5522 return api_format_data("lists", $type, ['lists' => $list]);
5525 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5528 * Add a new group to the database.
5530 * @param string $name Group name
5531 * @param int $uid User ID
5532 * @param array $users List of users to add to the group
5535 * @throws BadRequestException
5537 function group_create($name, $uid, $users = [])
5539 // error if no name specified
5541 throw new BadRequestException('group name not specified');
5544 // get data of the specified group name
5546 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5550 // error message if specified group name already exists
5551 if (DBA::isResult($rname)) {
5552 throw new BadRequestException('group name already exists');
5555 // check if specified group name is a deleted group
5557 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5561 // error message if specified group name already exists
5562 if (DBA::isResult($rname)) {
5563 $reactivate_group = true;
5567 $ret = Group::create($uid, $name);
5569 $gid = Group::getIdByName($uid, $name);
5571 throw new BadRequestException('other API error');
5575 $erroraddinguser = false;
5577 foreach ($users as $user) {
5578 $cid = $user['cid'];
5579 // check if user really exists as contact
5581 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5585 if (count($contact)) {
5586 Group::addMember($gid, $cid);
5588 $erroraddinguser = true;
5589 $errorusers[] = $cid;
5593 // return success message incl. missing users in array
5594 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5596 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5600 * Create the specified group with the posted array of contacts.
5602 * @param string $type Return type (atom, rss, xml, json)
5604 * @return array|string
5605 * @throws BadRequestException
5606 * @throws ForbiddenException
5607 * @throws ImagickException
5608 * @throws InternalServerErrorException
5609 * @throws UnauthorizedException
5611 function api_friendica_group_create($type)
5615 if (api_user() === false) {
5616 throw new ForbiddenException();
5620 $user_info = api_get_user($a);
5621 $name = $_REQUEST['name'] ?? '';
5622 $uid = $user_info['uid'];
5623 $json = json_decode($_POST['json'], true);
5624 $users = $json['user'];
5626 $success = group_create($name, $uid, $users);
5628 return api_format_data("group_create", $type, ['result' => $success]);
5630 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5633 * Create a new group.
5635 * @param string $type Return type (atom, rss, xml, json)
5637 * @return array|string
5638 * @throws BadRequestException
5639 * @throws ForbiddenException
5640 * @throws ImagickException
5641 * @throws InternalServerErrorException
5642 * @throws UnauthorizedException
5643 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5645 function api_lists_create($type)
5649 if (api_user() === false) {
5650 throw new ForbiddenException();
5654 $user_info = api_get_user($a);
5655 $name = $_REQUEST['name'] ?? '';
5656 $uid = $user_info['uid'];
5658 $success = group_create($name, $uid);
5659 if ($success['success']) {
5661 'name' => $success['name'],
5662 'id' => intval($success['gid']),
5663 'id_str' => (string) $success['gid'],
5664 'user' => $user_info
5667 return api_format_data("lists", $type, ['lists'=>$grp]);
5670 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5673 * Update the specified group with the posted array of contacts.
5675 * @param string $type Return type (atom, rss, xml, json)
5677 * @return array|string
5678 * @throws BadRequestException
5679 * @throws ForbiddenException
5680 * @throws ImagickException
5681 * @throws InternalServerErrorException
5682 * @throws UnauthorizedException
5684 function api_friendica_group_update($type)
5688 if (api_user() === false) {
5689 throw new ForbiddenException();
5693 $user_info = api_get_user($a);
5694 $uid = $user_info['uid'];
5695 $gid = $_REQUEST['gid'] ?? 0;
5696 $name = $_REQUEST['name'] ?? '';
5697 $json = json_decode($_POST['json'], true);
5698 $users = $json['user'];
5700 // error if no name specified
5702 throw new BadRequestException('group name not specified');
5705 // error if no gid specified
5707 throw new BadRequestException('gid not specified');
5711 $members = Contact::getByGroupId($gid);
5712 foreach ($members as $member) {
5713 $cid = $member['id'];
5714 foreach ($users as $user) {
5715 $found = ($user['cid'] == $cid ? true : false);
5717 if (!isset($found) || !$found) {
5718 Group::removeMemberByName($uid, $name, $cid);
5723 $erroraddinguser = false;
5725 foreach ($users as $user) {
5726 $cid = $user['cid'];
5727 // check if user really exists as contact
5729 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5734 if (count($contact)) {
5735 Group::addMember($gid, $cid);
5737 $erroraddinguser = true;
5738 $errorusers[] = $cid;
5742 // return success message incl. missing users in array
5743 $status = ($erroraddinguser ? "missing user" : "ok");
5744 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5745 return api_format_data("group_update", $type, ['result' => $success]);
5748 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5751 * Update information about a group.
5753 * @param string $type Return type (atom, rss, xml, json)
5755 * @return array|string
5756 * @throws BadRequestException
5757 * @throws ForbiddenException
5758 * @throws ImagickException
5759 * @throws InternalServerErrorException
5760 * @throws UnauthorizedException
5761 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5763 function api_lists_update($type)
5767 if (api_user() === false) {
5768 throw new ForbiddenException();
5772 $user_info = api_get_user($a);
5773 $gid = $_REQUEST['list_id'] ?? 0;
5774 $name = $_REQUEST['name'] ?? '';
5775 $uid = $user_info['uid'];
5777 // error if no gid specified
5779 throw new BadRequestException('gid not specified');
5782 // get data of the specified group id
5783 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5784 // error message if specified gid is not in database
5786 throw new BadRequestException('gid not available');
5789 if (Group::update($gid, $name)) {
5792 'id' => intval($gid),
5793 'id_str' => (string) $gid,
5794 'user' => $user_info
5797 return api_format_data("lists", $type, ['lists' => $list]);
5801 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5805 * @param string $type Return type (atom, rss, xml, json)
5807 * @return array|string
5808 * @throws BadRequestException
5809 * @throws ForbiddenException
5810 * @throws ImagickException
5811 * @throws InternalServerErrorException
5813 function api_friendica_activity($type)
5817 if (api_user() === false) {
5818 throw new ForbiddenException();
5820 $verb = strtolower($a->argv[3]);
5821 $verb = preg_replace("|\..*$|", "", $verb);
5823 $id = $_REQUEST['id'] ?? 0;
5825 $res = Item::performActivity($id, $verb);
5828 if ($type == "xml") {
5833 return api_format_data('ok', $type, ['ok' => $ok]);
5835 throw new BadRequestException('Error adding activity');
5839 /// @TODO move to top of file or somewhere better
5840 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5841 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5842 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5843 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5844 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5845 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5846 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5847 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5848 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5849 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5852 * Returns notifications
5854 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5856 * @return string|array
5857 * @throws ForbiddenException
5858 * @throws BadRequestException
5861 function api_friendica_notification($type)
5865 if (api_user() === false) {
5866 throw new ForbiddenException();
5869 throw new BadRequestException("Invalid argument count");
5872 $notifications = DI::notification()->getApiList(local_user());
5874 if ($type == "xml") {
5876 if (!empty($notifications)) {
5877 foreach ($notifications as $notification) {
5878 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5882 $result = $xmlnotes;
5883 } elseif (count($notifications) > 0) {
5884 $result = $notifications->getArrayCopy();
5889 return api_format_data("notes", $type, ['note' => $result]);
5893 * Set notification as seen and returns associated item (if possible)
5895 * POST request with 'id' param as notification id
5897 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5898 * @return string|array
5899 * @throws BadRequestException
5900 * @throws ForbiddenException
5901 * @throws ImagickException
5902 * @throws InternalServerErrorException
5903 * @throws UnauthorizedException
5905 function api_friendica_notification_seen($type)
5908 $user_info = api_get_user($a);
5910 if (api_user() === false || $user_info === false) {
5911 throw new ForbiddenException();
5913 if ($a->argc !== 4) {
5914 throw new BadRequestException("Invalid argument count");
5917 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5920 $notify = DI::notify()->getByID($id, api_user());
5921 DI::notify()->setSeen(true, $notify);
5923 if ($notify->otype === Notify\ObjectType::ITEM) {
5924 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5925 if (DBA::isResult($item)) {
5926 // we found the item, return it to the user
5927 $ret = api_format_items([$item], $user_info, false, $type);
5928 $data = ['status' => $ret];
5929 return api_format_data("status", $type, $data);
5931 // the item can't be found, but we set the notification as seen, so we count this as a success
5933 return api_format_data('result', $type, ['result' => "success"]);
5934 } catch (NotFoundException $e) {
5935 throw new BadRequestException('Invalid argument', $e);
5936 } catch (Exception $e) {
5937 throw new InternalServerErrorException('Internal Server exception', $e);
5941 /// @TODO move to top of file or somewhere better
5942 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5943 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5946 * update a direct_message to seen state
5948 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5949 * @return string|array (success result=ok, error result=error with error message)
5950 * @throws BadRequestException
5951 * @throws ForbiddenException
5952 * @throws ImagickException
5953 * @throws InternalServerErrorException
5954 * @throws UnauthorizedException
5956 function api_friendica_direct_messages_setseen($type)
5959 if (api_user() === false) {
5960 throw new ForbiddenException();
5964 $user_info = api_get_user($a);
5965 $uid = $user_info['uid'];
5966 $id = $_REQUEST['id'] ?? 0;
5968 // return error if id is zero
5970 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5971 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5974 // error message if specified id is not in database
5975 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5976 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5977 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5980 // update seen indicator
5981 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5985 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5986 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5988 $answer = ['result' => 'error', 'message' => 'unknown error'];
5989 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5993 /// @TODO move to top of file or somewhere better
5994 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5997 * search for direct_messages containing a searchstring through api
5999 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6000 * @param string $box
6001 * @return string|array (success: success=true if found and search_result contains found messages,
6002 * success=false if nothing was found, search_result='nothing found',
6003 * error: result=error with error message)
6004 * @throws BadRequestException
6005 * @throws ForbiddenException
6006 * @throws ImagickException
6007 * @throws InternalServerErrorException
6008 * @throws UnauthorizedException
6010 function api_friendica_direct_messages_search($type, $box = "")
6014 if (api_user() === false) {
6015 throw new ForbiddenException();
6019 $user_info = api_get_user($a);
6020 $searchstring = $_REQUEST['searchstring'] ?? '';
6021 $uid = $user_info['uid'];
6023 // error if no searchstring specified
6024 if ($searchstring == "") {
6025 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6026 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6029 // get data for the specified searchstring
6031 "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",
6033 DBA::escape('%'.$searchstring.'%')
6036 $profile_url = $user_info["url"];
6038 // message if nothing was found
6039 if (!DBA::isResult($r)) {
6040 $success = ['success' => false, 'search_results' => 'problem with query'];
6041 } elseif (count($r) == 0) {
6042 $success = ['success' => false, 'search_results' => 'nothing found'];
6045 foreach ($r as $item) {
6046 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6047 $recipient = $user_info;
6048 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6049 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6050 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6051 $sender = $user_info;
6054 if (isset($recipient) && isset($sender)) {
6055 $ret[] = api_format_messages($item, $recipient, $sender);
6058 $success = ['success' => true, 'search_results' => $ret];
6061 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6064 /// @TODO move to top of file or somewhere better
6065 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6068 * Returns a list of saved searches.
6070 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6072 * @param string $type Return format: json or xml
6074 * @return string|array
6077 function api_saved_searches_list($type)
6079 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6082 while ($term = DBA::fetch($terms)) {
6084 'created_at' => api_date(time()),
6085 'id' => intval($term['id']),
6086 'id_str' => $term['id'],
6087 'name' => $term['term'],
6089 'query' => $term['term']
6095 return api_format_data("terms", $type, ['terms' => $result]);
6098 /// @TODO move to top of file or somewhere better
6099 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6102 * Number of comments
6104 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6106 * @param object $data [Status, Status]
6110 function bindComments(&$data)
6112 if (count($data) == 0) {
6118 foreach ($data as $item) {
6119 $ids[] = $item['id'];
6122 $idStr = DBA::escape(implode(', ', $ids));
6123 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6124 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6125 $itemsData = DBA::toArray($items);
6127 foreach ($itemsData as $item) {
6128 $comments[$item['parent']] = $item['comments'];
6131 foreach ($data as $idx => $item) {
6133 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6138 @TODO Maybe open to implement?
6140 [pagename] => api/1.1/statuses/lookup.json
6141 [id] => 605138389168451584
6142 [include_cards] => true
6143 [cards_platform] => Android-12
6144 [include_entities] => true
6145 [include_my_retweet] => 1
6147 [include_reply_count] => true
6148 [include_descendent_reply_count] => true
6152 Not implemented by now:
6153 statuses/retweets_of_me
6158 account/update_location
6159 account/update_profile_background_image
6162 friendica/profile/update
6163 friendica/profile/create
6164 friendica/profile/delete
6166 Not implemented in status.net:
6167 statuses/retweeted_to_me
6168 statuses/retweeted_by_me
6169 direct_messages/destroy
6171 account/update_delivery_device
6172 notifications/follow