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\Feature;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Content\Text\HTML;
31 use Friendica\Core\Hook;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Session;
35 use Friendica\Core\System;
36 use Friendica\Core\Worker;
37 use Friendica\Database\DBA;
39 use Friendica\Model\Contact;
40 use Friendica\Model\Group;
41 use Friendica\Model\Item;
42 use Friendica\Model\Mail;
43 use Friendica\Model\Notify;
44 use Friendica\Model\Photo;
45 use Friendica\Model\Profile;
46 use Friendica\Model\User;
47 use Friendica\Model\UserItem;
48 use Friendica\Network\FKOAuth1;
49 use Friendica\Network\HTTPException;
50 use Friendica\Network\HTTPException\BadRequestException;
51 use Friendica\Network\HTTPException\ExpectationFailedException;
52 use Friendica\Network\HTTPException\ForbiddenException;
53 use Friendica\Network\HTTPException\InternalServerErrorException;
54 use Friendica\Network\HTTPException\MethodNotAllowedException;
55 use Friendica\Network\HTTPException\NotFoundException;
56 use Friendica\Network\HTTPException\NotImplementedException;
57 use Friendica\Network\HTTPException\TooManyRequestsException;
58 use Friendica\Network\HTTPException\UnauthorizedException;
59 use Friendica\Object\Image;
60 use Friendica\Protocol\Activity;
61 use Friendica\Protocol\Diaspora;
62 use Friendica\Util\DateTimeFormat;
63 use Friendica\Util\Images;
64 use Friendica\Util\Network;
65 use Friendica\Util\Proxy as ProxyUtils;
66 use Friendica\Util\Strings;
67 use Friendica\Util\XML;
69 require_once __DIR__ . '/../mod/share.php';
70 require_once __DIR__ . '/../mod/item.php';
71 require_once __DIR__ . '/../mod/wall_upload.php';
73 define('API_METHOD_ANY', '*');
74 define('API_METHOD_GET', 'GET');
75 define('API_METHOD_POST', 'POST,PUT');
76 define('API_METHOD_DELETE', 'POST,DELETE');
78 define('API_LOG_PREFIX', 'API {action} - ');
86 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
87 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
88 * into a page, and visitors will post something without noticing it).
92 if (!empty($_SESSION['allow_api'])) {
100 * Get source name from API client
102 * Clients can send 'source' parameter to be show in post metadata
103 * as "sent via <source>".
104 * Some clients doesn't send a source param, we support ones we know
105 * (only Twidere, atm)
108 * Client source name, default to "api" if unset/unknown
111 function api_source()
113 if (requestdata('source')) {
114 return requestdata('source');
117 // Support for known clients that doesn't send a source name
118 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
119 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
123 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
125 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
132 * Format date for API
134 * @param string $str Source date, as UTC
135 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
138 function api_date($str)
140 // Wed May 23 06:01:13 +0000 2007
141 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
145 * Register a function to be the endpoint for defined API path.
147 * @param string $path API URL path, relative to DI::baseUrl()
148 * @param string $func Function name to call on path request
149 * @param bool $auth API need logged user
150 * @param string $method HTTP method reqiured to call this endpoint.
151 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152 * Default to API_METHOD_ANY
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
164 // Workaround for hotot
165 $path = str_replace("api/", "api/1.1/", $path);
175 * Log in user via OAuth1 or Simple HTTP Auth.
176 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
179 * @throws ForbiddenException
180 * @throws InternalServerErrorException
181 * @throws UnauthorizedException
182 * @hook 'authenticate'
184 * 'username' => username from login form
185 * 'password' => password from login form
186 * 'authenticated' => return status,
187 * 'user_record' => return authenticated user record
189 function api_login(App $a)
191 $oauth1 = new FKOAuth1();
194 $request = OAuthRequest::from_request();
195 list($consumer, $token) = $oauth1->verify_request($request);
196 if (!is_null($token)) {
197 $oauth1->loginUser($token->uid);
198 Session::set('allow_api', true);
201 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
202 var_dump($consumer, $token);
204 } catch (Exception $e) {
205 Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
208 // workaround for HTTP-auth in CGI mode
209 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
210 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
211 if (strlen($userpass)) {
212 list($name, $password) = explode(':', $userpass);
213 $_SERVER['PHP_AUTH_USER'] = $name;
214 $_SERVER['PHP_AUTH_PW'] = $password;
218 if (empty($_SERVER['PHP_AUTH_USER'])) {
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"] = $item['private'] ?? 0;
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],
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_OBJ_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 NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`",
1738 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
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 NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`",
1751 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
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 NOT `private`",
1817 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
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 = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2045 $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
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 throw new ForbiddenException();
2076 // output the post that we just posted.
2078 return api_status_show($type, $item_id);
2081 /// @TODO move to top of file or somewhere better
2082 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2085 * Destroys a specific status.
2087 * @param string $type Return type (atom, rss, xml, json)
2089 * @return array|string
2090 * @throws BadRequestException
2091 * @throws ForbiddenException
2092 * @throws ImagickException
2093 * @throws InternalServerErrorException
2094 * @throws UnauthorizedException
2095 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2097 function api_statuses_destroy($type)
2101 if (api_user() === false) {
2102 throw new ForbiddenException();
2108 $id = intval($a->argv[3] ?? 0);
2111 $id = intval($_REQUEST['id'] ?? 0);
2116 $id = intval($a->argv[4] ?? 0);
2119 Logger::log('API: api_statuses_destroy: '.$id);
2121 $ret = api_statuses_show($type);
2123 Item::deleteForUser(['id' => $id], api_user());
2128 /// @TODO move to top of file or somewhere better
2129 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2132 * Returns the most recent mentions.
2134 * @param string $type Return type (atom, rss, xml, json)
2136 * @return array|string
2137 * @throws BadRequestException
2138 * @throws ForbiddenException
2139 * @throws ImagickException
2140 * @throws InternalServerErrorException
2141 * @throws UnauthorizedException
2142 * @see http://developer.twitter.com/doc/get/statuses/mentions
2144 function api_statuses_mentions($type)
2147 $user_info = api_get_user($a);
2149 if (api_user() === false || $user_info === false) {
2150 throw new ForbiddenException();
2153 unset($_REQUEST["user_id"]);
2154 unset($_GET["user_id"]);
2156 unset($_REQUEST["screen_name"]);
2157 unset($_GET["screen_name"]);
2159 // get last network messages
2162 $since_id = $_REQUEST['since_id'] ?? 0;
2163 $max_id = $_REQUEST['max_id'] ?? 0;
2164 $count = $_REQUEST['count'] ?? 20;
2165 $page = $_REQUEST['page'] ?? 1;
2167 $start = max(0, ($page - 1) * $count);
2169 $query = "SELECT `item`.`id` FROM `user-item`
2170 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2171 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2172 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2173 AND `user-item`.`iid` > ?";
2174 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2175 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2176 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2177 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2181 $query .= " AND `item`.`id` <= ?";
2182 $condition[] = $max_id;
2185 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2186 $condition[] = $start;
2187 $condition[] = $count;
2189 $useritems = DBA::p($query, $condition);
2191 while ($useritem = DBA::fetch($useritems)) {
2192 $itemids[] = $useritem['id'];
2194 DBA::close($useritems);
2196 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2197 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2199 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2201 $data = ['status' => $ret];
2206 $data = api_rss_extra($a, $data, $user_info);
2210 return api_format_data("statuses", $type, $data);
2213 /// @TODO move to top of file or somewhere better
2214 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2215 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2218 * Returns the most recent statuses posted by the user.
2220 * @param string $type Either "json" or "xml"
2221 * @return string|array
2222 * @throws BadRequestException
2223 * @throws ForbiddenException
2224 * @throws ImagickException
2225 * @throws InternalServerErrorException
2226 * @throws UnauthorizedException
2227 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2229 function api_statuses_user_timeline($type)
2232 $user_info = api_get_user($a);
2234 if (api_user() === false || $user_info === false) {
2235 throw new ForbiddenException();
2239 "api_statuses_user_timeline: api_user: ". api_user() .
2240 "\nuser_info: ".print_r($user_info, true) .
2241 "\n_REQUEST: ".print_r($_REQUEST, true),
2245 $since_id = $_REQUEST['since_id'] ?? 0;
2246 $max_id = $_REQUEST['max_id'] ?? 0;
2247 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2248 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2251 $count = $_REQUEST['count'] ?? 20;
2252 $page = $_REQUEST['page'] ?? 1;
2254 $start = max(0, ($page - 1) * $count);
2256 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2257 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2259 if ($user_info['self'] == 1) {
2260 $condition[0] .= ' AND `item`.`wall` ';
2263 if ($exclude_replies) {
2264 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2267 if ($conversation_id > 0) {
2268 $condition[0] .= " AND `item`.`parent` = ?";
2269 $condition[] = $conversation_id;
2273 $condition[0] .= " AND `item`.`id` <= ?";
2274 $condition[] = $max_id;
2277 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2278 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2280 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2284 $data = ['status' => $ret];
2289 $data = api_rss_extra($a, $data, $user_info);
2293 return api_format_data("statuses", $type, $data);
2296 /// @TODO move to top of file or somewhere better
2297 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2300 * Star/unstar an item.
2301 * param: id : id of the item
2303 * @param string $type Return type (atom, rss, xml, json)
2305 * @return array|string
2306 * @throws BadRequestException
2307 * @throws ForbiddenException
2308 * @throws ImagickException
2309 * @throws InternalServerErrorException
2310 * @throws UnauthorizedException
2311 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2313 function api_favorites_create_destroy($type)
2317 if (api_user() === false) {
2318 throw new ForbiddenException();
2321 // for versioned api.
2322 /// @TODO We need a better global soluton
2323 $action_argv_id = 2;
2324 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2325 $action_argv_id = 3;
2328 if ($a->argc <= $action_argv_id) {
2329 throw new BadRequestException("Invalid request.");
2331 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2332 if ($a->argc == $action_argv_id + 2) {
2333 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2335 $itemid = intval($_REQUEST['id'] ?? 0);
2338 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2340 if (!DBA::isResult($item)) {
2341 throw new BadRequestException("Invalid item.");
2346 $item['starred'] = 1;
2349 $item['starred'] = 0;
2352 throw new BadRequestException("Invalid action ".$action);
2355 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2358 throw new InternalServerErrorException("DB error");
2362 $user_info = api_get_user($a);
2363 $rets = api_format_items([$item], $user_info, false, $type);
2366 $data = ['status' => $ret];
2371 $data = api_rss_extra($a, $data, $user_info);
2375 return api_format_data("status", $type, $data);
2378 /// @TODO move to top of file or somewhere better
2379 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2380 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2383 * Returns the most recent favorite statuses.
2385 * @param string $type Return type (atom, rss, xml, json)
2387 * @return string|array
2388 * @throws BadRequestException
2389 * @throws ForbiddenException
2390 * @throws ImagickException
2391 * @throws InternalServerErrorException
2392 * @throws UnauthorizedException
2394 function api_favorites($type)
2399 $user_info = api_get_user($a);
2401 if (api_user() === false || $user_info === false) {
2402 throw new ForbiddenException();
2407 // in friendica starred item are private
2408 // return favorites only for self
2409 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2411 if ($user_info['self'] == 0) {
2415 $since_id = $_REQUEST['since_id'] ?? 0;
2416 $max_id = $_REQUEST['max_id'] ?? 0;
2417 $count = $_GET['count'] ?? 20;
2418 $page = $_REQUEST['page'] ?? 1;
2420 $start = max(0, ($page - 1) * $count);
2422 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2423 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2425 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2428 $condition[0] .= " AND `item`.`id` <= ?";
2429 $condition[] = $max_id;
2432 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2434 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2439 $data = ['status' => $ret];
2444 $data = api_rss_extra($a, $data, $user_info);
2448 return api_format_data("statuses", $type, $data);
2451 /// @TODO move to top of file or somewhere better
2452 api_register_func('api/favorites', 'api_favorites', true);
2456 * @param array $item
2457 * @param array $recipient
2458 * @param array $sender
2461 * @throws InternalServerErrorException
2463 function api_format_messages($item, $recipient, $sender)
2465 // standard meta information
2467 'id' => $item['id'],
2468 'sender_id' => $sender['id'],
2470 'recipient_id' => $recipient['id'],
2471 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2472 'sender_screen_name' => $sender['screen_name'],
2473 'recipient_screen_name' => $recipient['screen_name'],
2474 'sender' => $sender,
2475 'recipient' => $recipient,
2477 'friendica_seen' => $item['seen'] ?? 0,
2478 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2481 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2482 if (isset($ret['sender']['uid'])) {
2483 unset($ret['sender']['uid']);
2485 if (isset($ret['sender']['self'])) {
2486 unset($ret['sender']['self']);
2488 if (isset($ret['recipient']['uid'])) {
2489 unset($ret['recipient']['uid']);
2491 if (isset($ret['recipient']['self'])) {
2492 unset($ret['recipient']['self']);
2495 //don't send title to regular StatusNET requests to avoid confusing these apps
2496 if (!empty($_GET['getText'])) {
2497 $ret['title'] = $item['title'];
2498 if ($_GET['getText'] == 'html') {
2499 $ret['text'] = BBCode::convert($item['body'], false);
2500 } elseif ($_GET['getText'] == 'plain') {
2501 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2504 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2506 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2507 unset($ret['sender']);
2508 unset($ret['recipient']);
2516 * @param array $item
2519 * @throws InternalServerErrorException
2521 function api_convert_item($item)
2523 $body = $item['body'];
2524 $entities = api_get_entitities($statustext, $body);
2526 // Add pictures to the attachment array and remove them from the body
2527 $attachments = api_get_attachments($body);
2529 // Workaround for ostatus messages where the title is identically to the body
2530 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2531 $statusbody = trim(HTML::toPlaintext($html, 0));
2533 // handle data: images
2534 $statusbody = api_format_items_embeded_images($item, $statusbody);
2536 $statustitle = trim($item['title']);
2538 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2539 $statustext = trim($statusbody);
2541 $statustext = trim($statustitle."\n\n".$statusbody);
2544 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2545 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2548 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2550 // Workaround for clients with limited HTML parser functionality
2551 $search = ["<br>", "<blockquote>", "</blockquote>",
2552 "<h1>", "</h1>", "<h2>", "</h2>",
2553 "<h3>", "</h3>", "<h4>", "</h4>",
2554 "<h5>", "</h5>", "<h6>", "</h6>"];
2555 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2556 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2557 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2558 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2559 $statushtml = str_replace($search, $replace, $statushtml);
2561 if ($item['title'] != "") {
2562 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2566 $oldtext = $statushtml;
2567 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2568 } while ($oldtext != $statushtml);
2570 if (substr($statushtml, 0, 4) == '<br>') {
2571 $statushtml = substr($statushtml, 4);
2574 if (substr($statushtml, 0, -4) == '<br>') {
2575 $statushtml = substr($statushtml, -4);
2578 // feeds without body should contain the link
2579 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2580 $statushtml .= BBCode::convert($item['plink']);
2584 "text" => $statustext,
2585 "html" => $statushtml,
2586 "attachments" => $attachments,
2587 "entities" => $entities
2593 * @param string $body
2596 * @throws InternalServerErrorException
2598 function api_get_attachments(&$body)
2600 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2601 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2603 $URLSearchString = "^\[\]";
2604 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2608 // Remove all embedded pictures, since they are added as attachments
2609 foreach ($images[0] as $orig) {
2610 $body = str_replace($orig, '', $body);
2615 foreach ($images[1] as $image) {
2616 $imagedata = Images::getInfoFromURLCached($image);
2619 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2623 return $attachments;
2628 * @param string $text
2629 * @param string $bbcode
2632 * @throws InternalServerErrorException
2633 * @todo Links at the first character of the post
2635 function api_get_entitities(&$text, $bbcode)
2637 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2639 if ($include_entities != "true") {
2640 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2642 foreach ($images[1] as $image) {
2643 $replace = ProxyUtils::proxifyUrl($image);
2644 $text = str_replace($image, $replace, $text);
2649 $bbcode = BBCode::cleanPictureLinks($bbcode);
2651 // Change pure links in text to bbcode uris
2652 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2655 $entities["hashtags"] = [];
2656 $entities["symbols"] = [];
2657 $entities["urls"] = [];
2658 $entities["user_mentions"] = [];
2660 $URLSearchString = "^\[\]";
2662 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2664 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2665 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2667 $bbcode = preg_replace(
2668 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2669 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2672 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2674 $bbcode = preg_replace(
2675 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2676 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2679 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2681 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2683 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2686 foreach ($urls[1] as $id => $url) {
2687 $start = iconv_strpos($text, $url, 0, "UTF-8");
2688 if (!($start === false)) {
2689 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2693 ksort($ordered_urls);
2697 foreach ($ordered_urls as $url) {
2698 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2699 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2701 $display_url = $url["title"];
2703 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2704 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2706 if (strlen($display_url) > 26) {
2707 $display_url = substr($display_url, 0, 25)."…";
2711 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2712 if (!($start === false)) {
2713 $entities["urls"][] = ["url" => $url["url"],
2714 "expanded_url" => $url["url"],
2715 "display_url" => $display_url,
2716 "indices" => [$start, $start+strlen($url["url"])]];
2717 $offset = $start + 1;
2721 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2722 $ordered_images = [];
2723 foreach ($images as $image) {
2724 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2725 if (!($start === false)) {
2726 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2730 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2731 foreach ($images[1] as $image) {
2732 $start = iconv_strpos($text, $image, 0, "UTF-8");
2733 if (!($start === false)) {
2734 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2740 foreach ($ordered_images as $image) {
2741 $url = $image['url'];
2742 $ext_alt_text = $image['alt'];
2744 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2745 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2747 if (strlen($display_url) > 26) {
2748 $display_url = substr($display_url, 0, 25)."…";
2751 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2752 if (!($start === false)) {
2753 $image = Images::getInfoFromURLCached($url);
2755 // If image cache is activated, then use the following sizes:
2756 // thumb (150), small (340), medium (600) and large (1024)
2757 if (!DI::config()->get("system", "proxy_disabled")) {
2758 $media_url = ProxyUtils::proxifyUrl($url);
2761 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2762 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2764 if (($image[0] > 150) || ($image[1] > 150)) {
2765 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2766 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2769 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2770 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2772 if (($image[0] > 600) || ($image[1] > 600)) {
2773 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2774 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2778 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2781 $entities["media"][] = [
2783 "id_str" => (string) ($start + 1),
2784 "indices" => [$start, $start+strlen($url)],
2785 "media_url" => Strings::normaliseLink($media_url),
2786 "media_url_https" => $media_url,
2788 "display_url" => $display_url,
2789 "expanded_url" => $url,
2790 "ext_alt_text" => $ext_alt_text,
2794 $offset = $start + 1;
2803 * @param array $item
2804 * @param string $text
2808 function api_format_items_embeded_images($item, $text)
2810 $text = preg_replace_callback(
2811 '|data:image/([^;]+)[^=]+=*|m',
2812 function () use ($item) {
2813 return DI::baseUrl() . '/display/' . $item['guid'];
2821 * return <a href='url'>name</a> as array
2823 * @param string $txt text
2828 function api_contactlink_to_array($txt)
2831 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2832 if ($r && count($match)==3) {
2834 'name' => $match[2],
2848 * return likes, dislikes and attend status for item
2850 * @param array $item array
2851 * @param string $type Return type (atom, rss, xml, json)
2854 * likes => int count,
2855 * dislikes => int count
2856 * @throws BadRequestException
2857 * @throws ImagickException
2858 * @throws InternalServerErrorException
2859 * @throws UnauthorizedException
2861 function api_format_items_activities($item, $type = "json")
2870 'attendmaybe' => [],
2874 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2875 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2877 while ($parent_item = Item::fetch($ret)) {
2878 // not used as result should be structured like other user data
2879 //builtin_activity_puller($i, $activities);
2881 // get user data and add it to the array of the activity
2882 $user = api_get_user($a, $parent_item['author-id']);
2883 switch ($parent_item['verb']) {
2884 case Activity::LIKE:
2885 $activities['like'][] = $user;
2887 case Activity::DISLIKE:
2888 $activities['dislike'][] = $user;
2890 case Activity::ATTEND:
2891 $activities['attendyes'][] = $user;
2893 case Activity::ATTENDNO:
2894 $activities['attendno'][] = $user;
2896 case Activity::ATTENDMAYBE:
2897 $activities['attendmaybe'][] = $user;
2899 case Activity::ANNOUNCE:
2900 $activities['announce'][] = $user;
2909 if ($type == "xml") {
2910 $xml_activities = [];
2911 foreach ($activities as $k => $v) {
2912 // change xml element from "like" to "friendica:like"
2913 $xml_activities["friendica:".$k] = $v;
2914 // add user data into xml output
2916 foreach ($v as $user) {
2917 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2920 $activities = $xml_activities;
2927 * format items to be returned by api
2929 * @param array $items array of items
2930 * @param array $user_info
2931 * @param bool $filter_user filter items by $user_info
2932 * @param string $type Return type (atom, rss, xml, json)
2934 * @throws BadRequestException
2935 * @throws ImagickException
2936 * @throws InternalServerErrorException
2937 * @throws UnauthorizedException
2939 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2941 $a = Friendica\DI::app();
2945 foreach ((array)$items as $item) {
2946 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2948 // Look if the posts are matching if they should be filtered by user id
2949 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2953 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2962 * @param array $item Item record
2963 * @param string $type Return format (atom, rss, xml, json)
2964 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2965 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2966 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2967 * @return array API-formatted status
2968 * @throws BadRequestException
2969 * @throws ImagickException
2970 * @throws InternalServerErrorException
2971 * @throws UnauthorizedException
2973 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2975 $a = Friendica\DI::app();
2977 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2978 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2981 localize_item($item);
2983 $in_reply_to = api_in_reply_to($item);
2985 $converted = api_convert_item($item);
2987 if ($type == "xml") {
2988 $geo = "georss:point";
2994 'text' => $converted["text"],
2995 'truncated' => false,
2996 'created_at'=> api_date($item['created']),
2997 'in_reply_to_status_id' => $in_reply_to['status_id'],
2998 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2999 'source' => (($item['app']) ? $item['app'] : 'web'),
3000 'id' => intval($item['id']),
3001 'id_str' => (string) intval($item['id']),
3002 'in_reply_to_user_id' => $in_reply_to['user_id'],
3003 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3004 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3006 'favorited' => $item['starred'] ? true : false,
3007 'user' => $status_user,
3008 'friendica_author' => $author_user,
3009 'friendica_owner' => $owner_user,
3010 'friendica_private' => $item['private'] == 1,
3011 //'entities' => NULL,
3012 'statusnet_html' => $converted["html"],
3013 'statusnet_conversation_id' => $item['parent'],
3014 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3015 'friendica_activities' => api_format_items_activities($item, $type),
3016 'friendica_title' => $item['title'],
3017 'friendica_html' => BBCode::convert($item['body'], false)
3020 if (count($converted["attachments"]) > 0) {
3021 $status["attachments"] = $converted["attachments"];
3024 if (count($converted["entities"]) > 0) {
3025 $status["entities"] = $converted["entities"];
3028 if ($status["source"] == 'web') {
3029 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3030 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3031 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3034 $retweeted_item = [];
3037 if ($item["id"] == $item["parent"]) {
3038 $body = $item['body'];
3039 $retweeted_item = api_share_as_retweet($item);
3040 if ($body != $item['body']) {
3041 $quoted_item = $retweeted_item;
3042 $retweeted_item = [];
3046 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3047 $announce = api_get_announce($item);
3048 if (!empty($announce)) {
3049 $retweeted_item = $item;
3051 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3055 if (!empty($quoted_item)) {
3056 if ($quoted_item['id'] != $item['id']) {
3057 $quoted_status = api_format_item($quoted_item);
3058 /// @todo Only remove the attachments that are also contained in the quotes status
3059 unset($status['attachments']);
3060 unset($status['entities']);
3062 $conv_quoted = api_convert_item($quoted_item);
3063 $quoted_status = $status;
3064 unset($quoted_status['attachments']);
3065 unset($quoted_status['entities']);
3066 unset($quoted_status['statusnet_conversation_id']);
3067 $quoted_status['text'] = $conv_quoted['text'];
3068 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3070 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3071 } catch (BadRequestException $e) {
3072 // user not found. should be found?
3073 /// @todo check if the user should be always found
3074 $quoted_status["user"] = [];
3077 unset($quoted_status['friendica_author']);
3078 unset($quoted_status['friendica_owner']);
3079 unset($quoted_status['friendica_activities']);
3080 unset($quoted_status['friendica_private']);
3083 if (!empty($retweeted_item)) {
3084 $retweeted_status = $status;
3085 unset($retweeted_status['friendica_author']);
3086 unset($retweeted_status['friendica_owner']);
3087 unset($retweeted_status['friendica_activities']);
3088 unset($retweeted_status['friendica_private']);
3089 unset($retweeted_status['statusnet_conversation_id']);
3090 $status['user'] = $status['friendica_owner'];
3092 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3093 } catch (BadRequestException $e) {
3094 // user not found. should be found?
3095 /// @todo check if the user should be always found
3096 $retweeted_status["user"] = [];
3099 $rt_converted = api_convert_item($retweeted_item);
3101 $retweeted_status['text'] = $rt_converted["text"];
3102 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3103 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3105 if (!empty($quoted_status)) {
3106 $retweeted_status['quoted_status'] = $quoted_status;
3109 $status['friendica_author'] = $retweeted_status['user'];
3110 $status['retweeted_status'] = $retweeted_status;
3111 } elseif (!empty($quoted_status)) {
3112 $root_status = api_convert_item($item);
3114 $status['text'] = $root_status["text"];
3115 $status['statusnet_html'] = $root_status["html"];
3116 $status['quoted_status'] = $quoted_status;
3119 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3120 unset($status["user"]["uid"]);
3121 unset($status["user"]["self"]);
3123 if ($item["coord"] != "") {
3124 $coords = explode(' ', $item["coord"]);
3125 if (count($coords) == 2) {
3126 if ($type == "json") {
3127 $status["geo"] = ['type' => 'Point',
3128 'coordinates' => [(float) $coords[0],
3129 (float) $coords[1]]];
3130 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3131 $status["georss:point"] = $item["coord"];
3140 * Returns the remaining number of API requests available to the user before the API limit is reached.
3142 * @param string $type Return type (atom, rss, xml, json)
3144 * @return array|string
3147 function api_account_rate_limit_status($type)
3149 if ($type == "xml") {
3151 'remaining-hits' => '150',
3152 '@attributes' => ["type" => "integer"],
3153 'hourly-limit' => '150',
3154 '@attributes2' => ["type" => "integer"],
3155 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3156 '@attributes3' => ["type" => "datetime"],
3157 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3158 '@attributes4' => ["type" => "integer"],
3162 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3163 'remaining_hits' => '150',
3164 'hourly_limit' => '150',
3165 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3169 return api_format_data('hash', $type, ['hash' => $hash]);
3172 /// @TODO move to top of file or somewhere better
3173 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3176 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3178 * @param string $type Return type (atom, rss, xml, json)
3180 * @return array|string
3182 function api_help_test($type)
3184 if ($type == 'xml') {
3190 return api_format_data('ok', $type, ["ok" => $ok]);
3193 /// @TODO move to top of file or somewhere better
3194 api_register_func('api/help/test', 'api_help_test', false);
3197 * Returns all lists the user subscribes to.
3199 * @param string $type Return type (atom, rss, xml, json)
3201 * @return array|string
3202 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3204 function api_lists_list($type)
3207 /// @TODO $ret is not filled here?
3208 return api_format_data('lists', $type, ["lists_list" => $ret]);
3211 /// @TODO move to top of file or somewhere better
3212 api_register_func('api/lists/list', 'api_lists_list', true);
3213 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3216 * Returns all groups the user owns.
3218 * @param string $type Return type (atom, rss, xml, json)
3220 * @return array|string
3221 * @throws BadRequestException
3222 * @throws ForbiddenException
3223 * @throws ImagickException
3224 * @throws InternalServerErrorException
3225 * @throws UnauthorizedException
3226 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3228 function api_lists_ownerships($type)
3232 if (api_user() === false) {
3233 throw new ForbiddenException();
3237 $user_info = api_get_user($a);
3238 $uid = $user_info['uid'];
3240 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3242 // loop through all groups
3244 foreach ($groups as $group) {
3245 if ($group['visible']) {
3251 'name' => $group['name'],
3252 'id' => intval($group['id']),
3253 'id_str' => (string) $group['id'],
3254 'user' => $user_info,
3258 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3261 /// @TODO move to top of file or somewhere better
3262 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3265 * Returns recent statuses from users in the specified group.
3267 * @param string $type Return type (atom, rss, xml, json)
3269 * @return array|string
3270 * @throws BadRequestException
3271 * @throws ForbiddenException
3272 * @throws ImagickException
3273 * @throws InternalServerErrorException
3274 * @throws UnauthorizedException
3275 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3277 function api_lists_statuses($type)
3281 $user_info = api_get_user($a);
3282 if (api_user() === false || $user_info === false) {
3283 throw new ForbiddenException();
3286 unset($_REQUEST["user_id"]);
3287 unset($_GET["user_id"]);
3289 unset($_REQUEST["screen_name"]);
3290 unset($_GET["screen_name"]);
3292 if (empty($_REQUEST['list_id'])) {
3293 throw new BadRequestException('list_id not specified');
3297 $count = $_REQUEST['count'] ?? 20;
3298 $page = $_REQUEST['page'] ?? 1;
3299 $since_id = $_REQUEST['since_id'] ?? 0;
3300 $max_id = $_REQUEST['max_id'] ?? 0;
3301 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3302 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3304 $start = max(0, ($page - 1) * $count);
3306 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3307 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3310 $condition[0] .= " AND `item`.`id` <= ?";
3311 $condition[] = $max_id;
3313 if ($exclude_replies > 0) {
3314 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3316 if ($conversation_id > 0) {
3317 $condition[0] .= " AND `item`.`parent` = ?";
3318 $condition[] = $conversation_id;
3321 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3322 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3324 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3326 $data = ['status' => $items];
3331 $data = api_rss_extra($a, $data, $user_info);
3335 return api_format_data("statuses", $type, $data);
3338 /// @TODO move to top of file or somewhere better
3339 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3342 * Returns either the friends of the follower list
3344 * Considers friends and followers lists to be private and won't return
3345 * anything if any user_id parameter is passed.
3347 * @param string $qtype Either "friends" or "followers"
3348 * @return boolean|array
3349 * @throws BadRequestException
3350 * @throws ForbiddenException
3351 * @throws ImagickException
3352 * @throws InternalServerErrorException
3353 * @throws UnauthorizedException
3355 function api_statuses_f($qtype)
3359 if (api_user() === false) {
3360 throw new ForbiddenException();
3364 $count = $_GET['count'] ?? 20;
3365 $page = $_GET['page'] ?? 1;
3367 $start = max(0, ($page - 1) * $count);
3369 $user_info = api_get_user($a);
3371 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3372 /* this is to stop Hotot to load friends multiple times
3373 * I'm not sure if I'm missing return something or
3374 * is a bug in hotot. Workaround, meantime
3378 return array('$users' => $ret);*/
3383 if ($qtype == 'friends') {
3384 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3385 } elseif ($qtype == 'followers') {
3386 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3389 // friends and followers only for self
3390 if ($user_info['self'] == 0) {
3391 $sql_extra = " AND false ";
3394 if ($qtype == 'blocks') {
3395 $sql_filter = 'AND `blocked` AND NOT `pending`';
3396 } elseif ($qtype == 'incoming') {
3397 $sql_filter = 'AND `pending`';
3399 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3417 foreach ($r as $cid) {
3418 $user = api_get_user($a, $cid['nurl']);
3419 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3420 unset($user["uid"]);
3421 unset($user["self"]);
3428 return ['user' => $ret];
3433 * Returns the list of friends of the provided user
3435 * @deprecated By Twitter API in favor of friends/list
3437 * @param string $type Either "json" or "xml"
3438 * @return boolean|string|array
3439 * @throws BadRequestException
3440 * @throws ForbiddenException
3442 function api_statuses_friends($type)
3444 $data = api_statuses_f("friends");
3445 if ($data === false) {
3448 return api_format_data("users", $type, $data);
3452 * Returns the list of followers of the provided user
3454 * @deprecated By Twitter API in favor of friends/list
3456 * @param string $type Either "json" or "xml"
3457 * @return boolean|string|array
3458 * @throws BadRequestException
3459 * @throws ForbiddenException
3461 function api_statuses_followers($type)
3463 $data = api_statuses_f("followers");
3464 if ($data === false) {
3467 return api_format_data("users", $type, $data);
3470 /// @TODO move to top of file or somewhere better
3471 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3472 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3475 * Returns the list of blocked users
3477 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3479 * @param string $type Either "json" or "xml"
3481 * @return boolean|string|array
3482 * @throws BadRequestException
3483 * @throws ForbiddenException
3485 function api_blocks_list($type)
3487 $data = api_statuses_f('blocks');
3488 if ($data === false) {
3491 return api_format_data("users", $type, $data);
3494 /// @TODO move to top of file or somewhere better
3495 api_register_func('api/blocks/list', 'api_blocks_list', true);
3498 * Returns the list of pending users IDs
3500 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3502 * @param string $type Either "json" or "xml"
3504 * @return boolean|string|array
3505 * @throws BadRequestException
3506 * @throws ForbiddenException
3508 function api_friendships_incoming($type)
3510 $data = api_statuses_f('incoming');
3511 if ($data === false) {
3516 foreach ($data['user'] as $user) {
3517 $ids[] = $user['id'];
3520 return api_format_data("ids", $type, ['id' => $ids]);
3523 /// @TODO move to top of file or somewhere better
3524 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3527 * Returns the instance's configuration information.
3529 * @param string $type Return type (atom, rss, xml, json)
3531 * @return array|string
3532 * @throws InternalServerErrorException
3534 function api_statusnet_config($type)
3536 $name = DI::config()->get('config', 'sitename');
3537 $server = DI::baseUrl()->getHostname();
3538 $logo = DI::baseUrl() . '/images/friendica-64.png';
3539 $email = DI::config()->get('config', 'admin_email');
3540 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3541 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3542 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3543 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3544 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3547 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3548 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3549 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3550 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3551 'shorturllength' => '30',
3553 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3554 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3555 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3556 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3561 return api_format_data('config', $type, ['config' => $config]);
3564 /// @TODO move to top of file or somewhere better
3565 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3566 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3570 * @param string $type Return type (atom, rss, xml, json)
3572 * @return array|string
3574 function api_statusnet_version($type)
3577 $fake_statusnet_version = "0.9.7";
3579 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3582 /// @TODO move to top of file or somewhere better
3583 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3584 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3588 * @param string $type Return type (atom, rss, xml, json)
3590 * @param int $rel A contact relationship constant
3591 * @return array|string|void
3592 * @throws BadRequestException
3593 * @throws ForbiddenException
3594 * @throws ImagickException
3595 * @throws InternalServerErrorException
3596 * @throws UnauthorizedException
3597 * @todo use api_format_data() to return data
3599 function api_ff_ids($type, int $rel)
3602 throw new ForbiddenException();
3609 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3611 $contacts = DBA::p("SELECT `pcontact`.`id`
3613 INNER JOIN `contact` AS `pcontact`
3614 ON `contact`.`nurl` = `pcontact`.`nurl`
3615 AND `pcontact`.`uid` = 0
3616 WHERE `contact`.`uid` = ?
3617 AND NOT `contact`.`self`
3618 AND `contact`.`rel` IN (?, ?)",
3625 foreach (DBA::toArray($contacts) as $contact) {
3626 if ($stringify_ids) {
3627 $ids[] = $contact['id'];
3629 $ids[] = intval($contact['id']);
3633 return api_format_data('ids', $type, ['id' => $ids]);
3637 * Returns the ID of every user the user is following.
3639 * @param string $type Return type (atom, rss, xml, json)
3641 * @return array|string
3642 * @throws BadRequestException
3643 * @throws ForbiddenException
3644 * @throws ImagickException
3645 * @throws InternalServerErrorException
3646 * @throws UnauthorizedException
3647 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3649 function api_friends_ids($type)
3651 return api_ff_ids($type, Contact::SHARING);
3655 * Returns the ID of every user following the user.
3657 * @param string $type Return type (atom, rss, xml, json)
3659 * @return array|string
3660 * @throws BadRequestException
3661 * @throws ForbiddenException
3662 * @throws ImagickException
3663 * @throws InternalServerErrorException
3664 * @throws UnauthorizedException
3665 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3667 function api_followers_ids($type)
3669 return api_ff_ids($type, Contact::FOLLOWER);
3672 /// @TODO move to top of file or somewhere better
3673 api_register_func('api/friends/ids', 'api_friends_ids', true);
3674 api_register_func('api/followers/ids', 'api_followers_ids', true);
3677 * Sends a new direct message.
3679 * @param string $type Return type (atom, rss, xml, json)
3681 * @return array|string
3682 * @throws BadRequestException
3683 * @throws ForbiddenException
3684 * @throws ImagickException
3685 * @throws InternalServerErrorException
3686 * @throws NotFoundException
3687 * @throws UnauthorizedException
3688 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3690 function api_direct_messages_new($type)
3694 if (api_user() === false) {
3695 throw new ForbiddenException();
3698 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3702 $sender = api_get_user($a);
3705 if (!empty($_POST['screen_name'])) {
3707 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3709 DBA::escape($_POST['screen_name'])
3712 if (DBA::isResult($r)) {
3713 // Selecting the id by priority, friendica first
3714 api_best_nickname($r);
3716 $recipient = api_get_user($a, $r[0]['nurl']);
3719 $recipient = api_get_user($a, $_POST['user_id']);
3722 if (empty($recipient)) {
3723 throw new NotFoundException('Recipient not found');
3727 if (!empty($_REQUEST['replyto'])) {
3729 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3731 intval($_REQUEST['replyto'])
3733 $replyto = $r[0]['parent-uri'];
3734 $sub = $r[0]['title'];
3736 if (!empty($_REQUEST['title'])) {
3737 $sub = $_REQUEST['title'];
3739 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3743 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3746 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3747 $ret = api_format_messages($r[0], $recipient, $sender);
3749 $ret = ["error"=>$id];
3752 $data = ['direct_message'=>$ret];
3758 $data = api_rss_extra($a, $data, $sender);
3762 return api_format_data("direct-messages", $type, $data);
3765 /// @TODO move to top of file or somewhere better
3766 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3769 * delete a direct_message from mail table through api
3771 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3772 * @return string|array
3773 * @throws BadRequestException
3774 * @throws ForbiddenException
3775 * @throws ImagickException
3776 * @throws InternalServerErrorException
3777 * @throws UnauthorizedException
3778 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3780 function api_direct_messages_destroy($type)
3784 if (api_user() === false) {
3785 throw new ForbiddenException();
3789 $user_info = api_get_user($a);
3791 $id = $_REQUEST['id'] ?? 0;
3793 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3794 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3795 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3797 $uid = $user_info['uid'];
3798 // error if no id or parenturi specified (for clients posting parent-uri as well)
3799 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3800 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3801 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3804 // BadRequestException if no id specified (for clients using Twitter API)
3806 throw new BadRequestException('Message id not specified');
3809 // add parent-uri to sql command if specified by calling app
3810 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3812 // get data of the specified message id
3814 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3819 // error message if specified id is not in database
3820 if (!DBA::isResult($r)) {
3821 if ($verbose == "true") {
3822 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3823 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3825 /// @todo BadRequestException ok for Twitter API clients?
3826 throw new BadRequestException('message id not in database');
3831 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3836 if ($verbose == "true") {
3839 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3840 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3842 $answer = ['result' => 'error', 'message' => 'unknown error'];
3843 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3846 /// @todo return JSON data like Twitter API not yet implemented
3849 /// @TODO move to top of file or somewhere better
3850 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3855 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3856 * @return string|array
3857 * @throws BadRequestException
3858 * @throws ForbiddenException
3859 * @throws ImagickException
3860 * @throws InternalServerErrorException
3861 * @throws NotFoundException
3862 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3864 function api_friendships_destroy($type)
3868 if ($uid === false) {
3869 throw new ForbiddenException();
3872 $contact_id = $_REQUEST['user_id'] ?? 0;
3874 if (empty($contact_id)) {
3875 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3876 throw new BadRequestException("no user_id specified");
3879 // Get Contact by given id
3880 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3882 if(!DBA::isResult($contact)) {
3883 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3884 throw new NotFoundException("no contact found to given ID");
3887 $url = $contact["url"];
3889 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3890 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3891 Strings::normaliseLink($url), $url];
3892 $contact = DBA::selectFirst('contact', [], $condition);
3894 if (!DBA::isResult($contact)) {
3895 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3896 throw new NotFoundException("Not following Contact");
3899 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3900 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3901 throw new ExpectationFailedException("Not supported");
3904 $dissolve = ($contact['rel'] == Contact::SHARING);
3906 $owner = User::getOwnerDataById($uid);
3908 Contact::terminateFriendship($owner, $contact, $dissolve);
3911 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3912 throw new NotFoundException("Error Processing Request");
3915 // Sharing-only contacts get deleted as there no relationship any more
3917 Contact::remove($contact['id']);
3919 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3922 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3923 unset($contact["uid"]);
3924 unset($contact["self"]);
3926 // Set screen_name since Twidere requests it
3927 $contact["screen_name"] = $contact["nick"];
3929 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3931 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3935 * @param string $type Return type (atom, rss, xml, json)
3936 * @param string $box
3937 * @param string $verbose
3939 * @return array|string
3940 * @throws BadRequestException
3941 * @throws ForbiddenException
3942 * @throws ImagickException
3943 * @throws InternalServerErrorException
3944 * @throws UnauthorizedException
3946 function api_direct_messages_box($type, $box, $verbose)
3949 if (api_user() === false) {
3950 throw new ForbiddenException();
3953 $count = $_GET['count'] ?? 20;
3954 $page = $_REQUEST['page'] ?? 1;
3956 $since_id = $_REQUEST['since_id'] ?? 0;
3957 $max_id = $_REQUEST['max_id'] ?? 0;
3959 $user_id = $_REQUEST['user_id'] ?? '';
3960 $screen_name = $_REQUEST['screen_name'] ?? '';
3963 unset($_REQUEST["user_id"]);
3964 unset($_GET["user_id"]);
3966 unset($_REQUEST["screen_name"]);
3967 unset($_GET["screen_name"]);
3969 $user_info = api_get_user($a);
3970 if ($user_info === false) {
3971 throw new ForbiddenException();
3973 $profile_url = $user_info["url"];
3976 $start = max(0, ($page - 1) * $count);
3981 if ($box=="sentbox") {
3982 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3983 } elseif ($box == "conversation") {
3984 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3985 } elseif ($box == "all") {
3986 $sql_extra = "true";
3987 } elseif ($box == "inbox") {
3988 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3992 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3995 if ($user_id != "") {
3996 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3997 } elseif ($screen_name !="") {
3998 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4002 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
4008 if ($verbose == "true" && !DBA::isResult($r)) {
4009 $answer = ['result' => 'error', 'message' => 'no mails available'];
4010 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4014 foreach ($r as $item) {
4015 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4016 $recipient = $user_info;
4017 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4018 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4019 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4020 $sender = $user_info;
4023 if (isset($recipient) && isset($sender)) {
4024 $ret[] = api_format_messages($item, $recipient, $sender);
4029 $data = ['direct_message' => $ret];
4034 $data = api_rss_extra($a, $data, $user_info);
4038 return api_format_data("direct-messages", $type, $data);
4042 * Returns the most recent direct messages sent by the user.
4044 * @param string $type Return type (atom, rss, xml, json)
4046 * @return array|string
4047 * @throws BadRequestException
4048 * @throws ForbiddenException
4049 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4051 function api_direct_messages_sentbox($type)
4053 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4054 return api_direct_messages_box($type, "sentbox", $verbose);
4058 * Returns the most recent direct messages sent to the user.
4060 * @param string $type Return type (atom, rss, xml, json)
4062 * @return array|string
4063 * @throws BadRequestException
4064 * @throws ForbiddenException
4065 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4067 function api_direct_messages_inbox($type)
4069 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4070 return api_direct_messages_box($type, "inbox", $verbose);
4075 * @param string $type Return type (atom, rss, xml, json)
4077 * @return array|string
4078 * @throws BadRequestException
4079 * @throws ForbiddenException
4081 function api_direct_messages_all($type)
4083 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4084 return api_direct_messages_box($type, "all", $verbose);
4089 * @param string $type Return type (atom, rss, xml, json)
4091 * @return array|string
4092 * @throws BadRequestException
4093 * @throws ForbiddenException
4095 function api_direct_messages_conversation($type)
4097 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4098 return api_direct_messages_box($type, "conversation", $verbose);
4101 /// @TODO move to top of file or somewhere better
4102 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4103 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4104 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4105 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4108 * Returns an OAuth Request Token.
4110 * @see https://oauth.net/core/1.0/#auth_step1
4112 function api_oauth_request_token()
4114 $oauth1 = new FKOAuth1();
4116 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4117 } catch (Exception $e) {
4118 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4126 * Returns an OAuth Access Token.
4128 * @return array|string
4129 * @see https://oauth.net/core/1.0/#auth_step3
4131 function api_oauth_access_token()
4133 $oauth1 = new FKOAuth1();
4135 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4136 } catch (Exception $e) {
4137 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4144 /// @TODO move to top of file or somewhere better
4145 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4146 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4150 * delete a complete photoalbum with all containing photos from database through api
4152 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4153 * @return string|array
4154 * @throws BadRequestException
4155 * @throws ForbiddenException
4156 * @throws InternalServerErrorException
4158 function api_fr_photoalbum_delete($type)
4160 if (api_user() === false) {
4161 throw new ForbiddenException();
4164 $album = $_REQUEST['album'] ?? '';
4166 // we do not allow calls without album string
4168 throw new BadRequestException("no albumname specified");
4170 // check if album is existing
4172 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4176 if (!DBA::isResult($r)) {
4177 throw new BadRequestException("album not available");
4180 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4181 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4182 foreach ($r as $rr) {
4183 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4184 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4186 if (!DBA::isResult($photo_item)) {
4187 throw new InternalServerErrorException("problem with deleting items occured");
4189 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4192 // now let's delete all photos from the album
4193 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4195 // return success of deletion or error message
4197 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4198 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4200 throw new InternalServerErrorException("unknown error - deleting from database failed");
4205 * update the name of the album for all photos of an album
4207 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4208 * @return string|array
4209 * @throws BadRequestException
4210 * @throws ForbiddenException
4211 * @throws InternalServerErrorException
4213 function api_fr_photoalbum_update($type)
4215 if (api_user() === false) {
4216 throw new ForbiddenException();
4219 $album = $_REQUEST['album'] ?? '';
4220 $album_new = $_REQUEST['album_new'] ?? '';
4222 // we do not allow calls without album string
4224 throw new BadRequestException("no albumname specified");
4226 if ($album_new == "") {
4227 throw new BadRequestException("no new albumname specified");
4229 // check if album is existing
4230 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4231 throw new BadRequestException("album not available");
4233 // now let's update all photos to the albumname
4234 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4236 // return success of updating or error message
4238 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4239 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4241 throw new InternalServerErrorException("unknown error - updating in database failed");
4247 * list all photos of the authenticated user
4249 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4250 * @return string|array
4251 * @throws ForbiddenException
4252 * @throws InternalServerErrorException
4254 function api_fr_photos_list($type)
4256 if (api_user() === false) {
4257 throw new ForbiddenException();
4260 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4261 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4262 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4263 intval(local_user())
4266 'image/jpeg' => 'jpg',
4267 'image/png' => 'png',
4268 'image/gif' => 'gif'
4270 $data = ['photo'=>[]];
4271 if (DBA::isResult($r)) {
4272 foreach ($r as $rr) {
4274 $photo['id'] = $rr['resource-id'];
4275 $photo['album'] = $rr['album'];
4276 $photo['filename'] = $rr['filename'];
4277 $photo['type'] = $rr['type'];
4278 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4279 $photo['created'] = $rr['created'];
4280 $photo['edited'] = $rr['edited'];
4281 $photo['desc'] = $rr['desc'];
4283 if ($type == "xml") {
4284 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4286 $photo['thumb'] = $thumb;
4287 $data['photo'][] = $photo;
4291 return api_format_data("photos", $type, $data);
4295 * upload a new photo or change an existing photo
4297 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4298 * @return string|array
4299 * @throws BadRequestException
4300 * @throws ForbiddenException
4301 * @throws ImagickException
4302 * @throws InternalServerErrorException
4303 * @throws NotFoundException
4305 function api_fr_photo_create_update($type)
4307 if (api_user() === false) {
4308 throw new ForbiddenException();
4311 $photo_id = $_REQUEST['photo_id'] ?? null;
4312 $desc = $_REQUEST['desc'] ?? null;
4313 $album = $_REQUEST['album'] ?? null;
4314 $album_new = $_REQUEST['album_new'] ?? null;
4315 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4316 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4317 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4318 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4319 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4321 // do several checks on input parameters
4322 // we do not allow calls without album string
4323 if ($album == null) {
4324 throw new BadRequestException("no albumname specified");
4326 // if photo_id == null --> we are uploading a new photo
4327 if ($photo_id == null) {
4330 // error if no media posted in create-mode
4331 if (empty($_FILES['media'])) {
4333 throw new BadRequestException("no media data submitted");
4336 // album_new will be ignored in create-mode
4341 // check if photo is existing in databasei
4342 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4343 throw new BadRequestException("photo not available");
4347 // checks on acl strings provided by clients
4348 $acl_input_error = false;
4349 $acl_input_error |= check_acl_input($allow_cid);
4350 $acl_input_error |= check_acl_input($deny_cid);
4351 $acl_input_error |= check_acl_input($allow_gid);
4352 $acl_input_error |= check_acl_input($deny_gid);
4353 if ($acl_input_error) {
4354 throw new BadRequestException("acl data invalid");
4356 // now let's upload the new media in create-mode
4357 if ($mode == "create") {
4358 $media = $_FILES['media'];
4359 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4361 // return success of updating or error message
4362 if (!is_null($data)) {
4363 return api_format_data("photo_create", $type, $data);
4365 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4369 // now let's do the changes in update-mode
4370 if ($mode == "update") {
4371 $updated_fields = [];
4373 if (!is_null($desc)) {
4374 $updated_fields['desc'] = $desc;
4377 if (!is_null($album_new)) {
4378 $updated_fields['album'] = $album_new;
4381 if (!is_null($allow_cid)) {
4382 $allow_cid = trim($allow_cid);
4383 $updated_fields['allow_cid'] = $allow_cid;
4386 if (!is_null($deny_cid)) {
4387 $deny_cid = trim($deny_cid);
4388 $updated_fields['deny_cid'] = $deny_cid;
4391 if (!is_null($allow_gid)) {
4392 $allow_gid = trim($allow_gid);
4393 $updated_fields['allow_gid'] = $allow_gid;
4396 if (!is_null($deny_gid)) {
4397 $deny_gid = trim($deny_gid);
4398 $updated_fields['deny_gid'] = $deny_gid;
4402 if (count($updated_fields) > 0) {
4403 $nothingtodo = false;
4404 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4406 $nothingtodo = true;
4409 if (!empty($_FILES['media'])) {
4410 $nothingtodo = false;
4411 $media = $_FILES['media'];
4412 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4413 if (!is_null($data)) {
4414 return api_format_data("photo_update", $type, $data);
4418 // return success of updating or error message
4420 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4421 return api_format_data("photo_update", $type, ['$result' => $answer]);
4424 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4425 return api_format_data("photo_update", $type, ['$result' => $answer]);
4427 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4430 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4434 * delete a single photo from the database through api
4436 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4437 * @return string|array
4438 * @throws BadRequestException
4439 * @throws ForbiddenException
4440 * @throws InternalServerErrorException
4442 function api_fr_photo_delete($type)
4444 if (api_user() === false) {
4445 throw new ForbiddenException();
4449 $photo_id = $_REQUEST['photo_id'] ?? null;
4451 // do several checks on input parameters
4452 // we do not allow calls without photo id
4453 if ($photo_id == null) {
4454 throw new BadRequestException("no photo_id specified");
4457 // check if photo is existing in database
4458 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4459 throw new BadRequestException("photo not available");
4462 // now we can perform on the deletion of the photo
4463 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4465 // return success of deletion or error message
4467 // retrieve the id of the parent element (the photo element)
4468 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4469 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4471 if (!DBA::isResult($photo_item)) {
4472 throw new InternalServerErrorException("problem with deleting items occured");
4474 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4475 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4476 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4478 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4479 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4481 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4487 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4489 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4490 * @return string|array
4491 * @throws BadRequestException
4492 * @throws ForbiddenException
4493 * @throws InternalServerErrorException
4494 * @throws NotFoundException
4496 function api_fr_photo_detail($type)
4498 if (api_user() === false) {
4499 throw new ForbiddenException();
4501 if (empty($_REQUEST['photo_id'])) {
4502 throw new BadRequestException("No photo id.");
4505 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4506 $photo_id = $_REQUEST['photo_id'];
4508 // prepare json/xml output with data from database for the requested photo
4509 $data = prepare_photo_data($type, $scale, $photo_id);
4511 return api_format_data("photo_detail", $type, $data);
4516 * updates the profile image for the user (either a specified profile or the default profile)
4518 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4520 * @return string|array
4521 * @throws BadRequestException
4522 * @throws ForbiddenException
4523 * @throws ImagickException
4524 * @throws InternalServerErrorException
4525 * @throws NotFoundException
4526 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4528 function api_account_update_profile_image($type)
4530 if (api_user() === false) {
4531 throw new ForbiddenException();
4534 $profile_id = $_REQUEST['profile_id'] ?? 0;
4536 // error if image data is missing
4537 if (empty($_FILES['image'])) {
4538 throw new BadRequestException("no media data submitted");
4541 // check if specified profile id is valid
4542 if ($profile_id != 0) {
4543 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4544 // error message if specified profile id is not in database
4545 if (!DBA::isResult($profile)) {
4546 throw new BadRequestException("profile_id not available");
4548 $is_default_profile = $profile['is-default'];
4550 $is_default_profile = 1;
4553 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4555 if (!empty($_FILES['image'])) {
4556 $media = $_FILES['image'];
4557 } elseif (!empty($_FILES['media'])) {
4558 $media = $_FILES['media'];
4560 // save new profile image
4561 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4564 if (is_array($media['type'])) {
4565 $filetype = $media['type'][0];
4567 $filetype = $media['type'];
4569 if ($filetype == "image/jpeg") {
4571 } elseif ($filetype == "image/png") {
4574 throw new InternalServerErrorException('Unsupported filetype');
4577 // change specified profile or all profiles to the new resource-id
4578 if ($is_default_profile) {
4579 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4580 Photo::update(['profile' => false], $condition);
4582 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4583 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4584 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4587 Contact::updateSelfFromUserID(api_user(), true);
4589 // Update global directory in background
4590 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4591 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4592 Worker::add(PRIORITY_LOW, "Directory", $url);
4595 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4597 // output for client
4599 return api_account_verify_credentials($type);
4601 // SaveMediaToDatabase failed for some reason
4602 throw new InternalServerErrorException("image upload failed");
4606 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4607 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4608 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4609 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4610 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4611 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4612 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4613 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4614 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4617 * Update user profile
4619 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4621 * @return array|string
4622 * @throws BadRequestException
4623 * @throws ForbiddenException
4624 * @throws ImagickException
4625 * @throws InternalServerErrorException
4626 * @throws UnauthorizedException
4628 function api_account_update_profile($type)
4630 $local_user = api_user();
4631 $api_user = api_get_user(DI::app());
4633 if (!empty($_POST['name'])) {
4634 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4635 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4636 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4637 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4640 if (isset($_POST['description'])) {
4641 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4642 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4643 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4646 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4647 // Update global directory in background
4648 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4649 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4652 return api_account_verify_credentials($type);
4655 /// @TODO move to top of file or somewhere better
4656 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4660 * @param string $acl_string
4664 function check_acl_input($acl_string)
4666 if (empty($acl_string)) {
4670 $contact_not_found = false;
4672 // split <x><y><z> into array of cid's
4673 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4675 // check for each cid if it is available on server
4676 $cid_array = $array[0];
4677 foreach ($cid_array as $cid) {
4678 $cid = str_replace("<", "", $cid);
4679 $cid = str_replace(">", "", $cid);
4680 $condition = ['id' => $cid, 'uid' => api_user()];
4681 $contact_not_found |= !DBA::exists('contact', $condition);
4683 return $contact_not_found;
4687 * @param string $mediatype
4688 * @param array $media
4689 * @param string $type
4690 * @param string $album
4691 * @param string $allow_cid
4692 * @param string $deny_cid
4693 * @param string $allow_gid
4694 * @param string $deny_gid
4695 * @param string $desc
4696 * @param integer $profile
4697 * @param boolean $visibility
4698 * @param string $photo_id
4700 * @throws BadRequestException
4701 * @throws ForbiddenException
4702 * @throws ImagickException
4703 * @throws InternalServerErrorException
4704 * @throws NotFoundException
4705 * @throws UnauthorizedException
4707 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)
4715 if (is_array($media)) {
4716 if (is_array($media['tmp_name'])) {
4717 $src = $media['tmp_name'][0];
4719 $src = $media['tmp_name'];
4721 if (is_array($media['name'])) {
4722 $filename = basename($media['name'][0]);
4724 $filename = basename($media['name']);
4726 if (is_array($media['size'])) {
4727 $filesize = intval($media['size'][0]);
4729 $filesize = intval($media['size']);
4731 if (is_array($media['type'])) {
4732 $filetype = $media['type'][0];
4734 $filetype = $media['type'];
4738 if ($filetype == "") {
4739 $filetype = Images::guessType($filename);
4741 $imagedata = @getimagesize($src);
4743 $filetype = $imagedata['mime'];
4746 "File upload src: " . $src . " - filename: " . $filename .
4747 " - size: " . $filesize . " - type: " . $filetype,
4751 // check if there was a php upload error
4752 if ($filesize == 0 && $media['error'] == 1) {
4753 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4755 // check against max upload size within Friendica instance
4756 $maximagesize = DI::config()->get('system', 'maximagesize');
4757 if ($maximagesize && ($filesize > $maximagesize)) {
4758 $formattedBytes = Strings::formatBytes($maximagesize);
4759 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4762 // create Photo instance with the data of the image
4763 $imagedata = @file_get_contents($src);
4764 $Image = new Image($imagedata, $filetype);
4765 if (!$Image->isValid()) {
4766 throw new InternalServerErrorException("unable to process image data");
4769 // check orientation of image
4770 $Image->orient($src);
4773 // check max length of images on server
4774 $max_length = DI::config()->get('system', 'max_image_length');
4776 $max_length = MAX_IMAGE_LENGTH;
4778 if ($max_length > 0) {
4779 $Image->scaleDown($max_length);
4780 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4782 $width = $Image->getWidth();
4783 $height = $Image->getHeight();
4785 // create a new resource-id if not already provided
4786 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4788 if ($mediatype == "photo") {
4789 // upload normal image (scales 0, 1, 2)
4790 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4792 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4794 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4796 if ($width > 640 || $height > 640) {
4797 $Image->scaleDown(640);
4798 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4800 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4804 if ($width > 320 || $height > 320) {
4805 $Image->scaleDown(320);
4806 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4808 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4811 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4812 } elseif ($mediatype == "profileimage") {
4813 // upload profile image (scales 4, 5, 6)
4814 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4816 if ($width > 300 || $height > 300) {
4817 $Image->scaleDown(300);
4818 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4820 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4824 if ($width > 80 || $height > 80) {
4825 $Image->scaleDown(80);
4826 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4828 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4832 if ($width > 48 || $height > 48) {
4833 $Image->scaleDown(48);
4834 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4836 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4839 $Image->__destruct();
4840 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4843 if (isset($r) && $r) {
4844 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4845 if ($photo_id == null && $mediatype == "photo") {
4846 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4848 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4849 return prepare_photo_data($type, false, $resource_id);
4851 throw new InternalServerErrorException("image upload failed");
4857 * @param string $hash
4858 * @param string $allow_cid
4859 * @param string $deny_cid
4860 * @param string $allow_gid
4861 * @param string $deny_gid
4862 * @param string $filetype
4863 * @param boolean $visibility
4864 * @throws InternalServerErrorException
4866 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4868 // get data about the api authenticated user
4869 $uri = Item::newURI(intval(api_user()));
4870 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4873 $arr['guid'] = System::createUUID();
4874 $arr['uid'] = intval(api_user());
4876 $arr['parent-uri'] = $uri;
4877 $arr['type'] = 'photo';
4879 $arr['resource-id'] = $hash;
4880 $arr['contact-id'] = $owner_record['id'];
4881 $arr['owner-name'] = $owner_record['name'];
4882 $arr['owner-link'] = $owner_record['url'];
4883 $arr['owner-avatar'] = $owner_record['thumb'];
4884 $arr['author-name'] = $owner_record['name'];
4885 $arr['author-link'] = $owner_record['url'];
4886 $arr['author-avatar'] = $owner_record['thumb'];
4888 $arr['allow_cid'] = $allow_cid;
4889 $arr['allow_gid'] = $allow_gid;
4890 $arr['deny_cid'] = $deny_cid;
4891 $arr['deny_gid'] = $deny_gid;
4892 $arr['visible'] = $visibility;
4896 'image/jpeg' => 'jpg',
4897 'image/png' => 'png',
4898 'image/gif' => 'gif'
4901 // adds link to the thumbnail scale photo
4902 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4903 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4906 // do the magic for storing the item in the database and trigger the federation to other contacts
4912 * @param string $type
4914 * @param string $photo_id
4917 * @throws BadRequestException
4918 * @throws ForbiddenException
4919 * @throws ImagickException
4920 * @throws InternalServerErrorException
4921 * @throws NotFoundException
4922 * @throws UnauthorizedException
4924 function prepare_photo_data($type, $scale, $photo_id)
4927 $user_info = api_get_user($a);
4929 if ($user_info === false) {
4930 throw new ForbiddenException();
4933 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4934 $data_sql = ($scale === false ? "" : "data, ");
4936 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4937 // clients needs to convert this in their way for further processing
4939 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4940 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4941 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4942 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4943 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4944 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4946 intval(local_user()),
4947 DBA::escape($photo_id),
4952 'image/jpeg' => 'jpg',
4953 'image/png' => 'png',
4954 'image/gif' => 'gif'
4957 // prepare output data for photo
4958 if (DBA::isResult($r)) {
4959 $data = ['photo' => $r[0]];
4960 $data['photo']['id'] = $data['photo']['resource-id'];
4961 if ($scale !== false) {
4962 $data['photo']['data'] = base64_encode($data['photo']['data']);
4964 unset($data['photo']['datasize']); //needed only with scale param
4966 if ($type == "xml") {
4967 $data['photo']['links'] = [];
4968 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4969 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4971 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4974 $data['photo']['link'] = [];
4975 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4977 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4978 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4982 unset($data['photo']['resource-id']);
4983 unset($data['photo']['minscale']);
4984 unset($data['photo']['maxscale']);
4986 throw new NotFoundException();
4989 // retrieve item element for getting activities (like, dislike etc.) related to photo
4990 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4991 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4992 if (!DBA::isResult($item)) {
4993 throw new NotFoundException('Photo-related item not found.');
4996 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4998 // retrieve comments on photo
4999 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
5000 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5002 $statuses = Item::selectForUser(api_user(), [], $condition);
5004 // prepare output of comments
5005 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5007 if ($type == "xml") {
5009 foreach ($commentData as $comment) {
5010 $comments[$k++ . ":comment"] = $comment;
5013 foreach ($commentData as $comment) {
5014 $comments[] = $comment;
5017 $data['photo']['friendica_comments'] = $comments;
5019 // include info if rights on photo and rights on item are mismatching
5020 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5021 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5022 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5023 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5024 $data['photo']['rights_mismatch'] = $rights_mismatch;
5031 * Similar as /mod/redir.php
5032 * redirect to 'url' after dfrn auth
5034 * Why this when there is mod/redir.php already?
5035 * This use api_user() and api_login()
5038 * c_url: url of remote contact to auth to
5039 * url: string, url to redirect after auth
5041 function api_friendica_remoteauth()
5043 $url = $_GET['url'] ?? '';
5044 $c_url = $_GET['c_url'] ?? '';
5046 if ($url === '' || $c_url === '') {
5047 throw new BadRequestException("Wrong parameters.");
5050 $c_url = Strings::normaliseLink($c_url);
5054 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5055 if (!DBA::isResult($contact)) {
5056 throw new BadRequestException("Unknown contact");
5059 $cid = $contact['id'];
5061 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5063 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5064 System::externalRedirect($url ?: $c_url);
5067 if ($contact['duplex'] && $contact['issued-id']) {
5068 $orig_id = $contact['issued-id'];
5069 $dfrn_id = '1:' . $orig_id;
5071 if ($contact['duplex'] && $contact['dfrn-id']) {
5072 $orig_id = $contact['dfrn-id'];
5073 $dfrn_id = '0:' . $orig_id;
5076 $sec = Strings::getRandomHex();
5078 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5079 'sec' => $sec, 'expire' => time() + 45];
5080 DBA::insert('profile_check', $fields);
5082 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5083 $dest = ($url ? '&destination_url=' . $url : '');
5085 System::externalRedirect(
5086 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5087 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5088 . '&type=profile&sec=' . $sec . $dest
5091 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5094 * Return an item with announcer data if it had been announced
5096 * @param array $item Item array
5097 * @return array Item array with announce data
5099 function api_get_announce($item)
5101 // Quit if the item already has got a different owner and author
5102 if ($item['owner-id'] != $item['author-id']) {
5106 // Don't change original or Diaspora posts
5107 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5111 // Quit if we do now the original author and it had been a post from a native network
5112 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5116 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5117 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5118 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5119 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5120 if (!DBA::isResult($announce)) {
5124 return array_merge($item, $announce);
5128 * Return the item shared, if the item contains only the [share] tag
5130 * @param array $item Sharer item
5131 * @return array|false Shared item or false if not a reshare
5132 * @throws ImagickException
5133 * @throws InternalServerErrorException
5135 function api_share_as_retweet(&$item)
5137 $body = trim($item["body"]);
5139 if (Diaspora::isReshare($body, false) === false) {
5140 if ($item['author-id'] == $item['owner-id']) {
5143 // Reshares from OStatus, ActivityPub and Twitter
5144 $reshared_item = $item;
5145 $reshared_item['owner-id'] = $reshared_item['author-id'];
5146 $reshared_item['owner-link'] = $reshared_item['author-link'];
5147 $reshared_item['owner-name'] = $reshared_item['author-name'];
5148 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5149 return $reshared_item;
5153 $reshared = Item::getShareArray($item);
5154 if (empty($reshared)) {
5158 $reshared_item = $item;
5160 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5164 if (!empty($reshared['comment'])) {
5165 $item['body'] = $reshared['comment'];
5168 $reshared_item["share-pre-body"] = $reshared['comment'];
5169 $reshared_item["body"] = $reshared['shared'];
5170 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5171 $reshared_item["author-name"] = $reshared['author'];
5172 $reshared_item["author-link"] = $reshared['profile'];
5173 $reshared_item["author-avatar"] = $reshared['avatar'];
5174 $reshared_item["plink"] = $reshared['link'] ?? '';
5175 $reshared_item["created"] = $reshared['posted'];
5176 $reshared_item["edited"] = $reshared['posted'];
5178 // Try to fetch the original item
5179 if (!empty($reshared['guid'])) {
5180 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5181 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5182 $condition = ['id' => $original_id];
5187 if (!empty($condition)) {
5188 $original_item = Item::selectFirst([], $condition);
5189 if (DBA::isResult($original_item)) {
5190 $reshared_item = array_merge($reshared_item, $original_item);
5194 return $reshared_item;
5199 * @param array $item
5204 function api_in_reply_to($item)
5208 $in_reply_to['status_id'] = null;
5209 $in_reply_to['user_id'] = null;
5210 $in_reply_to['status_id_str'] = null;
5211 $in_reply_to['user_id_str'] = null;
5212 $in_reply_to['screen_name'] = null;
5214 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5215 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5216 if (DBA::isResult($parent)) {
5217 $in_reply_to['status_id'] = intval($parent['id']);
5219 $in_reply_to['status_id'] = intval($item['parent']);
5222 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5224 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5225 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5227 if (DBA::isResult($parent)) {
5228 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5229 $in_reply_to['user_id'] = intval($parent['author-id']);
5230 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5233 // There seems to be situation, where both fields are identical:
5234 // https://github.com/friendica/friendica/issues/1010
5235 // This is a bugfix for that.
5236 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5237 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']]);
5238 $in_reply_to['status_id'] = null;
5239 $in_reply_to['user_id'] = null;
5240 $in_reply_to['status_id_str'] = null;
5241 $in_reply_to['user_id_str'] = null;
5242 $in_reply_to['screen_name'] = null;
5246 return $in_reply_to;
5251 * @param string $text
5254 * @throws InternalServerErrorException
5256 function api_clean_plain_items($text)
5258 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5260 $text = BBCode::cleanPictureLinks($text);
5261 $URLSearchString = "^\[\]";
5263 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5265 if ($include_entities == "true") {
5266 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5269 // Simplify "attachment" element
5270 $text = BBCode::removeAttachment($text);
5277 * @param array $contacts
5281 function api_best_nickname(&$contacts)
5285 if (count($contacts) == 0) {
5289 foreach ($contacts as $contact) {
5290 if ($contact["network"] == "") {
5291 $contact["network"] = "dfrn";
5292 $best_contact = [$contact];
5296 if (sizeof($best_contact) == 0) {
5297 foreach ($contacts as $contact) {
5298 if ($contact["network"] == "dfrn") {
5299 $best_contact = [$contact];
5304 if (sizeof($best_contact) == 0) {
5305 foreach ($contacts as $contact) {
5306 if ($contact["network"] == "dspr") {
5307 $best_contact = [$contact];
5312 if (sizeof($best_contact) == 0) {
5313 foreach ($contacts as $contact) {
5314 if ($contact["network"] == "stat") {
5315 $best_contact = [$contact];
5320 if (sizeof($best_contact) == 0) {
5321 foreach ($contacts as $contact) {
5322 if ($contact["network"] == "pump") {
5323 $best_contact = [$contact];
5328 if (sizeof($best_contact) == 0) {
5329 foreach ($contacts as $contact) {
5330 if ($contact["network"] == "twit") {
5331 $best_contact = [$contact];
5336 if (sizeof($best_contact) == 1) {
5337 $contacts = $best_contact;
5339 $contacts = [$contacts[0]];
5344 * Return all or a specified group of the user with the containing contacts.
5346 * @param string $type Return type (atom, rss, xml, json)
5348 * @return array|string
5349 * @throws BadRequestException
5350 * @throws ForbiddenException
5351 * @throws ImagickException
5352 * @throws InternalServerErrorException
5353 * @throws UnauthorizedException
5355 function api_friendica_group_show($type)
5359 if (api_user() === false) {
5360 throw new ForbiddenException();
5364 $user_info = api_get_user($a);
5365 $gid = $_REQUEST['gid'] ?? 0;
5366 $uid = $user_info['uid'];
5368 // get data of the specified group id or all groups if not specified
5371 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5375 // error message if specified gid is not in database
5376 if (!DBA::isResult($r)) {
5377 throw new BadRequestException("gid not available");
5381 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5386 // loop through all groups and retrieve all members for adding data in the user array
5388 foreach ($r as $rr) {
5389 $members = Contact::getByGroupId($rr['id']);
5392 if ($type == "xml") {
5393 $user_element = "users";
5395 foreach ($members as $member) {
5396 $user = api_get_user($a, $member['nurl']);
5397 $users[$k++.":user"] = $user;
5400 $user_element = "user";
5401 foreach ($members as $member) {
5402 $user = api_get_user($a, $member['nurl']);
5406 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5408 return api_format_data("groups", $type, ['group' => $grps]);
5410 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5414 * Delete the specified group of the user.
5416 * @param string $type Return type (atom, rss, xml, json)
5418 * @return array|string
5419 * @throws BadRequestException
5420 * @throws ForbiddenException
5421 * @throws ImagickException
5422 * @throws InternalServerErrorException
5423 * @throws UnauthorizedException
5425 function api_friendica_group_delete($type)
5429 if (api_user() === false) {
5430 throw new ForbiddenException();
5434 $user_info = api_get_user($a);
5435 $gid = $_REQUEST['gid'] ?? 0;
5436 $name = $_REQUEST['name'] ?? '';
5437 $uid = $user_info['uid'];
5439 // error if no gid specified
5440 if ($gid == 0 || $name == "") {
5441 throw new BadRequestException('gid or name not specified');
5444 // get data of the specified group id
5446 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5450 // error message if specified gid is not in database
5451 if (!DBA::isResult($r)) {
5452 throw new BadRequestException('gid not available');
5455 // get data of the specified group id and group name
5457 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5462 // error message if specified gid is not in database
5463 if (!DBA::isResult($rname)) {
5464 throw new BadRequestException('wrong group name');
5468 $ret = Group::removeByName($uid, $name);
5471 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5472 return api_format_data("group_delete", $type, ['result' => $success]);
5474 throw new BadRequestException('other API error');
5477 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5482 * @param string $type Return type (atom, rss, xml, json)
5484 * @return array|string
5485 * @throws BadRequestException
5486 * @throws ForbiddenException
5487 * @throws ImagickException
5488 * @throws InternalServerErrorException
5489 * @throws UnauthorizedException
5490 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5492 function api_lists_destroy($type)
5496 if (api_user() === false) {
5497 throw new ForbiddenException();
5501 $user_info = api_get_user($a);
5502 $gid = $_REQUEST['list_id'] ?? 0;
5503 $uid = $user_info['uid'];
5505 // error if no gid specified
5507 throw new BadRequestException('gid not specified');
5510 // get data of the specified group id
5511 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5512 // error message if specified gid is not in database
5514 throw new BadRequestException('gid not available');
5517 if (Group::remove($gid)) {
5519 'name' => $group['name'],
5520 'id' => intval($gid),
5521 'id_str' => (string) $gid,
5522 'user' => $user_info
5525 return api_format_data("lists", $type, ['lists' => $list]);
5528 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5531 * Add a new group to the database.
5533 * @param string $name Group name
5534 * @param int $uid User ID
5535 * @param array $users List of users to add to the group
5538 * @throws BadRequestException
5540 function group_create($name, $uid, $users = [])
5542 // error if no name specified
5544 throw new BadRequestException('group name not specified');
5547 // get data of the specified group name
5549 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5553 // error message if specified group name already exists
5554 if (DBA::isResult($rname)) {
5555 throw new BadRequestException('group name already exists');
5558 // check if specified group name is a deleted group
5560 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5564 // error message if specified group name already exists
5565 if (DBA::isResult($rname)) {
5566 $reactivate_group = true;
5570 $ret = Group::create($uid, $name);
5572 $gid = Group::getIdByName($uid, $name);
5574 throw new BadRequestException('other API error');
5578 $erroraddinguser = false;
5580 foreach ($users as $user) {
5581 $cid = $user['cid'];
5582 // check if user really exists as contact
5584 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5588 if (count($contact)) {
5589 Group::addMember($gid, $cid);
5591 $erroraddinguser = true;
5592 $errorusers[] = $cid;
5596 // return success message incl. missing users in array
5597 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5599 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5603 * Create the specified group with the posted array of contacts.
5605 * @param string $type Return type (atom, rss, xml, json)
5607 * @return array|string
5608 * @throws BadRequestException
5609 * @throws ForbiddenException
5610 * @throws ImagickException
5611 * @throws InternalServerErrorException
5612 * @throws UnauthorizedException
5614 function api_friendica_group_create($type)
5618 if (api_user() === false) {
5619 throw new ForbiddenException();
5623 $user_info = api_get_user($a);
5624 $name = $_REQUEST['name'] ?? '';
5625 $uid = $user_info['uid'];
5626 $json = json_decode($_POST['json'], true);
5627 $users = $json['user'];
5629 $success = group_create($name, $uid, $users);
5631 return api_format_data("group_create", $type, ['result' => $success]);
5633 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5636 * Create a new group.
5638 * @param string $type Return type (atom, rss, xml, json)
5640 * @return array|string
5641 * @throws BadRequestException
5642 * @throws ForbiddenException
5643 * @throws ImagickException
5644 * @throws InternalServerErrorException
5645 * @throws UnauthorizedException
5646 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5648 function api_lists_create($type)
5652 if (api_user() === false) {
5653 throw new ForbiddenException();
5657 $user_info = api_get_user($a);
5658 $name = $_REQUEST['name'] ?? '';
5659 $uid = $user_info['uid'];
5661 $success = group_create($name, $uid);
5662 if ($success['success']) {
5664 'name' => $success['name'],
5665 'id' => intval($success['gid']),
5666 'id_str' => (string) $success['gid'],
5667 'user' => $user_info
5670 return api_format_data("lists", $type, ['lists'=>$grp]);
5673 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5676 * Update the specified group with the posted array of contacts.
5678 * @param string $type Return type (atom, rss, xml, json)
5680 * @return array|string
5681 * @throws BadRequestException
5682 * @throws ForbiddenException
5683 * @throws ImagickException
5684 * @throws InternalServerErrorException
5685 * @throws UnauthorizedException
5687 function api_friendica_group_update($type)
5691 if (api_user() === false) {
5692 throw new ForbiddenException();
5696 $user_info = api_get_user($a);
5697 $uid = $user_info['uid'];
5698 $gid = $_REQUEST['gid'] ?? 0;
5699 $name = $_REQUEST['name'] ?? '';
5700 $json = json_decode($_POST['json'], true);
5701 $users = $json['user'];
5703 // error if no name specified
5705 throw new BadRequestException('group name not specified');
5708 // error if no gid specified
5710 throw new BadRequestException('gid not specified');
5714 $members = Contact::getByGroupId($gid);
5715 foreach ($members as $member) {
5716 $cid = $member['id'];
5717 foreach ($users as $user) {
5718 $found = ($user['cid'] == $cid ? true : false);
5720 if (!isset($found) || !$found) {
5721 Group::removeMemberByName($uid, $name, $cid);
5726 $erroraddinguser = false;
5728 foreach ($users as $user) {
5729 $cid = $user['cid'];
5730 // check if user really exists as contact
5732 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5737 if (count($contact)) {
5738 Group::addMember($gid, $cid);
5740 $erroraddinguser = true;
5741 $errorusers[] = $cid;
5745 // return success message incl. missing users in array
5746 $status = ($erroraddinguser ? "missing user" : "ok");
5747 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5748 return api_format_data("group_update", $type, ['result' => $success]);
5751 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5754 * Update information about a group.
5756 * @param string $type Return type (atom, rss, xml, json)
5758 * @return array|string
5759 * @throws BadRequestException
5760 * @throws ForbiddenException
5761 * @throws ImagickException
5762 * @throws InternalServerErrorException
5763 * @throws UnauthorizedException
5764 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5766 function api_lists_update($type)
5770 if (api_user() === false) {
5771 throw new ForbiddenException();
5775 $user_info = api_get_user($a);
5776 $gid = $_REQUEST['list_id'] ?? 0;
5777 $name = $_REQUEST['name'] ?? '';
5778 $uid = $user_info['uid'];
5780 // error if no gid specified
5782 throw new BadRequestException('gid not specified');
5785 // get data of the specified group id
5786 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5787 // error message if specified gid is not in database
5789 throw new BadRequestException('gid not available');
5792 if (Group::update($gid, $name)) {
5795 'id' => intval($gid),
5796 'id_str' => (string) $gid,
5797 'user' => $user_info
5800 return api_format_data("lists", $type, ['lists' => $list]);
5804 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5808 * @param string $type Return type (atom, rss, xml, json)
5810 * @return array|string
5811 * @throws BadRequestException
5812 * @throws ForbiddenException
5813 * @throws ImagickException
5814 * @throws InternalServerErrorException
5816 function api_friendica_activity($type)
5820 if (api_user() === false) {
5821 throw new ForbiddenException();
5823 $verb = strtolower($a->argv[3]);
5824 $verb = preg_replace("|\..*$|", "", $verb);
5826 $id = $_REQUEST['id'] ?? 0;
5828 $res = Item::performLike($id, $verb);
5831 if ($type == "xml") {
5836 return api_format_data('ok', $type, ['ok' => $ok]);
5838 throw new BadRequestException('Error adding activity');
5842 /// @TODO move to top of file or somewhere better
5843 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5844 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5845 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5846 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5847 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5848 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5849 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5850 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5851 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5852 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5855 * Returns notifications
5857 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5859 * @return string|array
5860 * @throws ForbiddenException
5861 * @throws BadRequestException
5864 function api_friendica_notification($type)
5868 if (api_user() === false) {
5869 throw new ForbiddenException();
5872 throw new BadRequestException("Invalid argument count");
5875 $notifications = DI::notification()->getApiList(local_user());
5877 if ($type == "xml") {
5879 if (!empty($notifications)) {
5880 foreach ($notifications as $notification) {
5881 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5885 $result = $xmlnotes;
5886 } elseif (count($notifications) > 0) {
5887 $result = $notifications->getArrayCopy();
5892 return api_format_data("notes", $type, ['note' => $result]);
5896 * Set notification as seen and returns associated item (if possible)
5898 * POST request with 'id' param as notification id
5900 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5901 * @return string|array
5902 * @throws BadRequestException
5903 * @throws ForbiddenException
5904 * @throws ImagickException
5905 * @throws InternalServerErrorException
5906 * @throws UnauthorizedException
5908 function api_friendica_notification_seen($type)
5911 $user_info = api_get_user($a);
5913 if (api_user() === false || $user_info === false) {
5914 throw new ForbiddenException();
5916 if ($a->argc !== 4) {
5917 throw new BadRequestException("Invalid argument count");
5920 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5923 $notify = DI::notify()->getByID($id);
5924 DI::notify()->setSeen(true, $notify);
5926 if ($notify->otype === Notify\ObjectType::ITEM) {
5927 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5928 if (DBA::isResult($item)) {
5929 // we found the item, return it to the user
5930 $ret = api_format_items([$item], $user_info, false, $type);
5931 $data = ['status' => $ret];
5932 return api_format_data("status", $type, $data);
5934 // the item can't be found, but we set the notification as seen, so we count this as a success
5936 return api_format_data('result', $type, ['result' => "success"]);
5937 } catch (NotFoundException $e) {
5938 throw new BadRequestException('Invalid argument', $e);
5939 } catch (Exception $e) {
5940 throw new InternalServerErrorException('Internal Server exception', $e);
5944 /// @TODO move to top of file or somewhere better
5945 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5946 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5949 * update a direct_message to seen state
5951 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5952 * @return string|array (success result=ok, error result=error with error message)
5953 * @throws BadRequestException
5954 * @throws ForbiddenException
5955 * @throws ImagickException
5956 * @throws InternalServerErrorException
5957 * @throws UnauthorizedException
5959 function api_friendica_direct_messages_setseen($type)
5962 if (api_user() === false) {
5963 throw new ForbiddenException();
5967 $user_info = api_get_user($a);
5968 $uid = $user_info['uid'];
5969 $id = $_REQUEST['id'] ?? 0;
5971 // return error if id is zero
5973 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5974 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5977 // error message if specified id is not in database
5978 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5979 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5980 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5983 // update seen indicator
5984 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5988 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5989 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5991 $answer = ['result' => 'error', 'message' => 'unknown error'];
5992 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5996 /// @TODO move to top of file or somewhere better
5997 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
6000 * search for direct_messages containing a searchstring through api
6002 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6003 * @param string $box
6004 * @return string|array (success: success=true if found and search_result contains found messages,
6005 * success=false if nothing was found, search_result='nothing found',
6006 * error: result=error with error message)
6007 * @throws BadRequestException
6008 * @throws ForbiddenException
6009 * @throws ImagickException
6010 * @throws InternalServerErrorException
6011 * @throws UnauthorizedException
6013 function api_friendica_direct_messages_search($type, $box = "")
6017 if (api_user() === false) {
6018 throw new ForbiddenException();
6022 $user_info = api_get_user($a);
6023 $searchstring = $_REQUEST['searchstring'] ?? '';
6024 $uid = $user_info['uid'];
6026 // error if no searchstring specified
6027 if ($searchstring == "") {
6028 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6029 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6032 // get data for the specified searchstring
6034 "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",
6036 DBA::escape('%'.$searchstring.'%')
6039 $profile_url = $user_info["url"];
6041 // message if nothing was found
6042 if (!DBA::isResult($r)) {
6043 $success = ['success' => false, 'search_results' => 'problem with query'];
6044 } elseif (count($r) == 0) {
6045 $success = ['success' => false, 'search_results' => 'nothing found'];
6048 foreach ($r as $item) {
6049 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6050 $recipient = $user_info;
6051 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6052 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6053 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6054 $sender = $user_info;
6057 if (isset($recipient) && isset($sender)) {
6058 $ret[] = api_format_messages($item, $recipient, $sender);
6061 $success = ['success' => true, 'search_results' => $ret];
6064 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6067 /// @TODO move to top of file or somewhere better
6068 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6071 * Returns a list of saved searches.
6073 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6075 * @param string $type Return format: json or xml
6077 * @return string|array
6080 function api_saved_searches_list($type)
6082 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6085 while ($term = DBA::fetch($terms)) {
6087 'created_at' => api_date(time()),
6088 'id' => intval($term['id']),
6089 'id_str' => $term['id'],
6090 'name' => $term['term'],
6092 'query' => $term['term']
6098 return api_format_data("terms", $type, ['terms' => $result]);
6101 /// @TODO move to top of file or somewhere better
6102 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6105 * Number of comments
6107 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6109 * @param object $data [Status, Status]
6113 function bindComments(&$data)
6115 if (count($data) == 0) {
6121 foreach ($data as $item) {
6122 $ids[] = $item['id'];
6125 $idStr = DBA::escape(implode(', ', $ids));
6126 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6127 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6128 $itemsData = DBA::toArray($items);
6130 foreach ($itemsData as $item) {
6131 $comments[$item['parent']] = $item['comments'];
6134 foreach ($data as $idx => $item) {
6136 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6141 @TODO Maybe open to implement?
6143 [pagename] => api/1.1/statuses/lookup.json
6144 [id] => 605138389168451584
6145 [include_cards] => true
6146 [cards_platform] => Android-12
6147 [include_entities] => true
6148 [include_my_retweet] => 1
6150 [include_reply_count] => true
6151 [include_descendent_reply_count] => true
6155 Not implemented by now:
6156 statuses/retweets_of_me
6161 account/update_location
6162 account/update_profile_background_image
6165 friendica/profile/update
6166 friendica/profile/create
6167 friendica/profile/delete
6169 Not implemented in status.net:
6170 statuses/retweeted_to_me
6171 statuses/retweeted_by_me
6172 direct_messages/destroy
6174 account/update_delivery_device
6175 notifications/follow