3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * Friendica implementation of statusnet/twitter API
22 * @file include/api.php
23 * @todo Automatically detect if incoming data is HTML or BBCode
27 use Friendica\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Session;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Contact;
39 use Friendica\Model\Group;
40 use Friendica\Model\Item;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notify;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Tag;
45 use Friendica\Model\Term;
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 // workaround for HTTP-auth in CGI mode
192 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
193 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
194 if (strlen($userpass)) {
195 list($name, $password) = explode(':', $userpass);
196 $_SERVER['PHP_AUTH_USER'] = $name;
197 $_SERVER['PHP_AUTH_PW'] = $password;
201 if (empty($_SERVER['PHP_AUTH_USER'])) {
202 // Try OAuth when no user is provided
203 $oauth1 = new FKOAuth1();
206 $request = OAuthRequest::from_request();
207 list($consumer, $token) = $oauth1->verify_request($request);
208 if (!is_null($token)) {
209 $oauth1->loginUser($token->uid);
210 Session::set('allow_api', true);
213 echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
214 var_dump($consumer, $token);
216 } catch (Exception $e) {
217 Logger::warning(API_LOG_PREFIX . 'OAuth error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
220 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
221 header('WWW-Authenticate: Basic realm="Friendica"');
222 throw new UnauthorizedException("This API requires login");
225 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
226 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
228 // allow "user@server" login (but ignore 'server' part)
229 $at = strstr($user, "@", true);
234 // next code from mod/auth.php. needs better solution
238 'username' => trim($user),
239 'password' => trim($password),
240 'authenticated' => 0,
241 'user_record' => null,
245 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
246 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
247 * and later addons should not interfere with an earlier one that succeeded.
249 Hook::callAll('authenticate', $addon_auth);
251 if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
252 $record = $addon_auth['user_record'];
254 $user_id = User::authenticate(trim($user), trim($password), true);
255 if ($user_id !== false) {
256 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
260 if (!DBA::isResult($record)) {
261 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
262 header('WWW-Authenticate: Basic realm="Friendica"');
263 //header('HTTP/1.0 401 Unauthorized');
264 //die('This api requires login');
265 throw new UnauthorizedException("This API requires login");
268 DI::auth()->setForUser($a, $record);
270 $_SESSION["allow_api"] = true;
272 Hook::callAll('logged_in', $a->user);
276 * Check HTTP method of called API
278 * API endpoints can define which HTTP method to accept when called.
279 * This function check the current HTTP method agains endpoint
282 * @param string $method Required methods, uppercase, separated by comma
285 function api_check_method($method)
287 if ($method == "*") {
290 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
294 * Main API entry point
296 * Authenticate user, call registered API function, set HTTP headers
299 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
300 * @return string|array API call result
303 function api_call(App $a, App\Arguments $args = null)
305 global $API, $called_api;
312 if (strpos($args->getQueryString(), ".xml") > 0) {
315 if (strpos($args->getQueryString(), ".json") > 0) {
318 if (strpos($args->getQueryString(), ".rss") > 0) {
321 if (strpos($args->getQueryString(), ".atom") > 0) {
326 foreach ($API as $p => $info) {
327 if (strpos($args->getQueryString(), $p) === 0) {
328 if (!api_check_method($info['method'])) {
329 throw new MethodNotAllowedException();
332 $called_api = explode("/", $p);
334 if (!empty($info['auth']) && api_user() === false) {
338 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
339 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
341 $stamp = microtime(true);
342 $return = call_user_func($info['func'], $type);
343 $duration = floatval(microtime(true) - $stamp);
345 Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
347 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
349 if (false === $return) {
351 * api function returned false withour throw an
352 * exception. This should not happend, throw a 500
354 throw new InternalServerErrorException();
359 header("Content-Type: text/xml");
362 header("Content-Type: application/json");
363 if (!empty($return)) {
364 $json = json_encode(end($return));
365 if (!empty($_GET['callback'])) {
366 $json = $_GET['callback'] . "(" . $json . ")";
372 header("Content-Type: application/rss+xml");
373 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
376 header("Content-Type: application/atom+xml");
377 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
384 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
385 throw new NotImplementedException();
386 } catch (HTTPException $e) {
387 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
388 return api_error($type, $e, $args);
393 * Format API error string
395 * @param string $type Return type (xml, json, rss, as)
396 * @param object $e HTTPException Error object
397 * @param App\Arguments $args The App arguments
398 * @return string|array error message formatted as $type
400 function api_error($type, $e, App\Arguments $args)
402 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
403 /// @TODO: https://dev.twitter.com/overview/api/response-codes
405 $error = ["error" => $error,
406 "code" => $e->getCode() . " " . $e->httpdesc,
407 "request" => $args->getQueryString()];
409 $return = api_format_data('status', $type, ['status' => $error]);
413 header("Content-Type: text/xml");
416 header("Content-Type: application/json");
417 $return = json_encode($return);
420 header("Content-Type: application/rss+xml");
423 header("Content-Type: application/atom+xml");
431 * Set values for RSS template
434 * @param array $arr Array to be passed to template
435 * @param array $user_info User info
437 * @throws BadRequestException
438 * @throws ImagickException
439 * @throws InternalServerErrorException
440 * @throws UnauthorizedException
441 * @todo find proper type-hints
443 function api_rss_extra(App $a, $arr, $user_info)
445 if (is_null($user_info)) {
446 $user_info = api_get_user($a);
449 $arr['$user'] = $user_info;
451 'alternate' => $user_info['url'],
452 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
453 'base' => DI::baseUrl(),
454 'updated' => api_date(null),
455 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
456 'language' => $user_info['lang'],
457 'logo' => DI::baseUrl() . "/images/friendica-32.png",
465 * Unique contact to contact url.
467 * @param int $id Contact id
468 * @return bool|string
469 * Contact url or False if contact id is unknown
472 function api_unique_id_to_nurl($id)
474 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
476 if (DBA::isResult($r)) {
484 * Get user info array.
487 * @param int|string $contact_id Contact ID or URL
489 * @throws BadRequestException
490 * @throws ImagickException
491 * @throws InternalServerErrorException
492 * @throws UnauthorizedException
494 function api_get_user(App $a, $contact_id = null)
502 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
504 // Searching for contact URL
505 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
506 $user = DBA::escape(Strings::normaliseLink($contact_id));
508 $extra_query = "AND `contact`.`nurl` = '%s' ";
509 if (api_user() !== false) {
510 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
514 // Searching for contact id with uid = 0
515 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
516 $user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
519 throw new BadRequestException("User ID ".$contact_id." not found.");
523 $extra_query = "AND `contact`.`nurl` = '%s' ";
524 if (api_user() !== false) {
525 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
529 if (is_null($user) && !empty($_GET['user_id'])) {
530 $user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
533 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
537 $extra_query = "AND `contact`.`nurl` = '%s' ";
538 if (api_user() !== false) {
539 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
542 if (is_null($user) && !empty($_GET['screen_name'])) {
543 $user = DBA::escape($_GET['screen_name']);
544 $extra_query = "AND `contact`.`nick` = '%s' ";
545 if (api_user() !== false) {
546 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
550 if (is_null($user) && !empty($_GET['profileurl'])) {
551 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
552 $extra_query = "AND `contact`.`nurl` = '%s' ";
553 if (api_user() !== false) {
554 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
558 // $called_api is the API path exploded on / and is expected to have at least 2 elements
559 if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
560 $argid = count($called_api);
561 if (!empty($a->argv[$argid])) {
562 $data = explode(".", $a->argv[$argid]);
563 if (count($data) > 1) {
564 list($user, $null) = $data;
567 if (is_numeric($user)) {
568 $user = DBA::escape(api_unique_id_to_nurl(intval($user)));
572 $extra_query = "AND `contact`.`nurl` = '%s' ";
573 if (api_user() !== false) {
574 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
578 $user = DBA::escape($user);
579 $extra_query = "AND `contact`.`nick` = '%s' ";
580 if (api_user() !== false) {
581 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
586 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
589 if (api_user() === false) {
593 $user = $_SESSION['uid'];
594 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
598 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
602 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
608 // Selecting the id by priority, friendica first
609 if (is_array($uinfo)) {
610 api_best_nickname($uinfo);
613 // if the contact wasn't found, fetch it from the contacts with uid = 0
614 if (!DBA::isResult($uinfo)) {
616 throw new BadRequestException("User not found.");
619 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
621 if (DBA::isResult($contact)) {
623 'id' => $contact["id"],
624 'id_str' => (string) $contact["id"],
625 'name' => $contact["name"],
626 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
627 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
628 'description' => BBCode::toPlaintext($contact["about"]),
629 'profile_image_url' => $contact["micro"],
630 'profile_image_url_https' => $contact["micro"],
631 'profile_image_url_profile_size' => $contact["thumb"],
632 'profile_image_url_large' => $contact["photo"],
633 'url' => $contact["url"],
634 'protected' => false,
635 'followers_count' => 0,
636 'friends_count' => 0,
638 'created_at' => api_date($contact["created"]),
639 'favourites_count' => 0,
641 'time_zone' => 'UTC',
642 'geo_enabled' => false,
644 'statuses_count' => 0,
646 'contributors_enabled' => false,
647 'is_translator' => false,
648 'is_translation_enabled' => false,
649 'following' => false,
650 'follow_request_sent' => false,
651 'statusnet_blocking' => false,
652 'notifications' => false,
653 'statusnet_profile_url' => $contact["url"],
655 'cid' => Contact::getIdForURL($contact["url"], api_user(), true),
656 'pid' => Contact::getIdForURL($contact["url"], 0, true),
658 'network' => $contact["network"],
663 throw new BadRequestException("User ".$url." not found.");
667 if ($uinfo[0]['self']) {
668 if ($uinfo[0]['network'] == "") {
669 $uinfo[0]['network'] = Protocol::DFRN;
672 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
673 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
680 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, true);
682 if (!empty($profile['about'])) {
683 $description = $profile['about'];
685 $description = $uinfo[0]["about"];
688 if (!empty($usr['default-location'])) {
689 $location = $usr['default-location'];
690 } elseif (!empty($uinfo[0]["location"])) {
691 $location = $uinfo[0]["location"];
693 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
697 'id' => intval($pcontact_id),
698 'id_str' => (string) intval($pcontact_id),
699 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
700 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
701 'location' => $location,
702 'description' => BBCode::toPlaintext($description),
703 'profile_image_url' => $uinfo[0]['micro'],
704 'profile_image_url_https' => $uinfo[0]['micro'],
705 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
706 'profile_image_url_large' => $uinfo[0]["photo"],
707 'url' => $uinfo[0]['url'],
708 'protected' => false,
709 'followers_count' => intval($countfollowers),
710 'friends_count' => intval($countfriends),
712 'created_at' => api_date($uinfo[0]['created']),
713 'favourites_count' => intval($starred),
715 'time_zone' => 'UTC',
716 'geo_enabled' => false,
718 'statuses_count' => intval($countitems),
720 'contributors_enabled' => false,
721 'is_translator' => false,
722 'is_translation_enabled' => false,
723 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
724 'follow_request_sent' => false,
725 'statusnet_blocking' => false,
726 'notifications' => false,
728 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
729 'statusnet_profile_url' => $uinfo[0]['url'],
730 'uid' => intval($uinfo[0]['uid']),
731 'cid' => intval($uinfo[0]['cid']),
732 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, true),
733 'self' => $uinfo[0]['self'],
734 'network' => $uinfo[0]['network'],
737 // If this is a local user and it uses Frio, we can get its color preferences.
739 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
740 if ($theme_info['theme'] === 'frio') {
741 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
743 if ($schema && ($schema != '---')) {
744 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
745 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
746 require_once $schemefile;
749 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
750 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
751 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
753 if (empty($nav_bg)) {
756 if (empty($link_color)) {
757 $link_color = "#6fdbe8";
759 if (empty($bgcolor)) {
760 $bgcolor = "#ededed";
763 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
764 $ret['profile_link_color'] = str_replace('#', '', $link_color);
765 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
773 * return api-formatted array for item's author and owner
776 * @param array $item item from db
777 * @return array(array:author, array:owner)
778 * @throws BadRequestException
779 * @throws ImagickException
780 * @throws InternalServerErrorException
781 * @throws UnauthorizedException
783 function api_item_get_user(App $a, $item)
785 $status_user = api_get_user($a, $item['author-id'] ?? null);
787 $author_user = $status_user;
789 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
791 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
792 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
794 $owner_user = $author_user;
797 return ([$status_user, $author_user, $owner_user]);
801 * walks recursively through an array with the possibility to change value and key
803 * @param array $array The array to walk through
804 * @param callable $callback The callback function
806 * @return array the transformed array
808 function api_walk_recursive(array &$array, callable $callback)
812 foreach ($array as $k => $v) {
814 if ($callback($v, $k)) {
815 $new_array[$k] = api_walk_recursive($v, $callback);
818 if ($callback($v, $k)) {
829 * Callback function to transform the array in an array that can be transformed in a XML file
831 * @param mixed $item Array item value
832 * @param string $key Array key
834 * @return boolean Should the array item be deleted?
836 function api_reformat_xml(&$item, &$key)
838 if (is_bool($item)) {
839 $item = ($item ? "true" : "false");
842 if (substr($key, 0, 10) == "statusnet_") {
843 $key = "statusnet:".substr($key, 10);
844 } elseif (substr($key, 0, 10) == "friendica_") {
845 $key = "friendica:".substr($key, 10);
847 /// @TODO old-lost code?
849 // $key = "default:".$key;
855 * Creates the XML from a JSON style array
857 * @param array $data JSON style array
858 * @param string $root_element Name of the root element
860 * @return string The XML data
862 function api_create_xml(array $data, $root_element)
864 $childname = key($data);
865 $data2 = array_pop($data);
867 $namespaces = ["" => "http://api.twitter.com",
868 "statusnet" => "http://status.net/schema/api/1/",
869 "friendica" => "http://friendi.ca/schema/api/1/",
870 "georss" => "http://www.georss.org/georss"];
872 /// @todo Auto detection of needed namespaces
873 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
877 if (is_array($data2)) {
879 api_walk_recursive($data2, "api_reformat_xml");
885 foreach ($data2 as $item) {
886 $data4[$i++ . ":" . $childname] = $item;
893 $data3 = [$root_element => $data2];
895 $ret = XML::fromArray($data3, $xml, false, $namespaces);
900 * Formats the data according to the data type
902 * @param string $root_element Name of the root element
903 * @param string $type Return type (atom, rss, xml, json)
904 * @param array $data JSON style array
906 * @return array|string (string|array) XML data or JSON data
908 function api_format_data($root_element, $type, $data)
914 $ret = api_create_xml($data, $root_element);
929 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
930 * returns a 401 status code and an error message if not.
932 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
934 * @param string $type Return type (atom, rss, xml, json)
935 * @return array|string
936 * @throws BadRequestException
937 * @throws ForbiddenException
938 * @throws ImagickException
939 * @throws InternalServerErrorException
940 * @throws UnauthorizedException
942 function api_account_verify_credentials($type)
946 if (api_user() === false) {
947 throw new ForbiddenException();
950 unset($_REQUEST["user_id"]);
951 unset($_GET["user_id"]);
953 unset($_REQUEST["screen_name"]);
954 unset($_GET["screen_name"]);
956 $skip_status = $_REQUEST['skip_status'] ?? false;
958 $user_info = api_get_user($a);
960 // "verified" isn't used here in the standard
961 unset($user_info["verified"]);
963 // - Adding last status
965 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
967 $user_info['status'] = api_format_item($item, $type);
971 // "uid" and "self" are only needed for some internal stuff, so remove it from here
972 unset($user_info["uid"]);
973 unset($user_info["self"]);
975 return api_format_data("user", $type, ['user' => $user_info]);
978 /// @TODO move to top of file or somewhere better
979 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
982 * Get data from $_POST or $_GET
987 function requestdata($k)
989 if (!empty($_POST[$k])) {
992 if (!empty($_GET[$k])) {
999 * Deprecated function to upload media.
1001 * @param string $type Return type (atom, rss, xml, json)
1003 * @return array|string
1004 * @throws BadRequestException
1005 * @throws ForbiddenException
1006 * @throws ImagickException
1007 * @throws InternalServerErrorException
1008 * @throws UnauthorizedException
1010 function api_statuses_mediap($type)
1014 if (api_user() === false) {
1015 Logger::log('api_statuses_update: no user');
1016 throw new ForbiddenException();
1018 $user_info = api_get_user($a);
1020 $_REQUEST['profile_uid'] = api_user();
1021 $_REQUEST['api_source'] = true;
1022 $txt = requestdata('status');
1023 /// @TODO old-lost code?
1024 //$txt = urldecode(requestdata('status'));
1026 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1027 $txt = HTML::toBBCodeVideo($txt);
1028 $config = HTMLPurifier_Config::createDefault();
1029 $config->set('Cache.DefinitionImpl', null);
1030 $purifier = new HTMLPurifier($config);
1031 $txt = $purifier->purify($txt);
1033 $txt = HTML::toBBCode($txt);
1035 $a->argv[1] = $user_info['screen_name']; //should be set to username?
1037 $picture = wall_upload_post($a, false);
1039 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1040 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1041 $item_id = item_post($a);
1043 // output the post that we just posted.
1044 return api_status_show($type, $item_id);
1047 /// @TODO move this to top of file or somewhere better!
1048 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1051 * Updates the user’s current status.
1053 * @param string $type Return type (atom, rss, xml, json)
1055 * @return array|string
1056 * @throws BadRequestException
1057 * @throws ForbiddenException
1058 * @throws ImagickException
1059 * @throws InternalServerErrorException
1060 * @throws TooManyRequestsException
1061 * @throws UnauthorizedException
1062 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1064 function api_statuses_update($type)
1068 if (api_user() === false) {
1069 Logger::log('api_statuses_update: no user');
1070 throw new ForbiddenException();
1075 // convert $_POST array items to the form we use for web posts.
1076 if (requestdata('htmlstatus')) {
1077 $txt = requestdata('htmlstatus');
1078 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1079 $txt = HTML::toBBCodeVideo($txt);
1081 $config = HTMLPurifier_Config::createDefault();
1082 $config->set('Cache.DefinitionImpl', null);
1084 $purifier = new HTMLPurifier($config);
1085 $txt = $purifier->purify($txt);
1087 $_REQUEST['body'] = HTML::toBBCode($txt);
1090 $_REQUEST['body'] = requestdata('status');
1093 $_REQUEST['title'] = requestdata('title');
1095 $parent = requestdata('in_reply_to_status_id');
1097 // Twidere sends "-1" if it is no reply ...
1098 if ($parent == -1) {
1102 if (ctype_digit($parent)) {
1103 $_REQUEST['parent'] = $parent;
1105 $_REQUEST['parent_uri'] = $parent;
1108 if (requestdata('lat') && requestdata('long')) {
1109 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1111 $_REQUEST['profile_uid'] = api_user();
1114 // Check for throttling (maximum posts per day, week and month)
1115 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1116 if ($throttle_day > 0) {
1117 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1119 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1120 $posts_day = DBA::count('thread', $condition);
1122 if ($posts_day > $throttle_day) {
1123 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1124 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1125 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));
1129 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1130 if ($throttle_week > 0) {
1131 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1133 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1134 $posts_week = DBA::count('thread', $condition);
1136 if ($posts_week > $throttle_week) {
1137 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1138 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1139 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));
1143 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1144 if ($throttle_month > 0) {
1145 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1147 $condition = ["`uid` = ? AND `wall` AND `received` > ?", api_user(), $datefrom];
1148 $posts_month = DBA::count('thread', $condition);
1150 if ($posts_month > $throttle_month) {
1151 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1152 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1153 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));
1158 if (!empty($_FILES['media'])) {
1159 // upload the image if we have one
1160 $picture = wall_upload_post($a, false);
1161 if (is_array($picture)) {
1162 $_REQUEST['body'] .= "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1166 if (requestdata('media_ids')) {
1167 $ids = explode(',', requestdata('media_ids'));
1168 foreach ($ids as $id) {
1170 "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",
1174 if (DBA::isResult($r)) {
1175 $phototypes = Images::supportedTypes();
1176 $ext = $phototypes[$r[0]['type']];
1177 $description = $r[0]['desc'] ?? '';
1178 $_REQUEST['body'] .= "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $r[0]['nickname'] . '/image/' . $r[0]['resource-id'] . ']';
1179 $_REQUEST['body'] .= '[img=' . DI::baseUrl() . '/photo/' . $r[0]['resource-id'] . '-' . $r[0]['scale'] . '.' . $ext . ']' . $description . '[/img][/url]';
1184 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1186 $_REQUEST['api_source'] = true;
1188 if (empty($_REQUEST['source'])) {
1189 $_REQUEST["source"] = api_source();
1192 // call out normal post function
1193 $item_id = item_post($a);
1195 // output the post that we just posted.
1196 return api_status_show($type, $item_id);
1199 /// @TODO move to top of file or somewhere better
1200 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1201 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1204 * Uploads an image to Friendica.
1207 * @throws BadRequestException
1208 * @throws ForbiddenException
1209 * @throws ImagickException
1210 * @throws InternalServerErrorException
1211 * @throws UnauthorizedException
1212 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1214 function api_media_upload()
1218 if (api_user() === false) {
1219 Logger::log('no user');
1220 throw new ForbiddenException();
1225 if (empty($_FILES['media'])) {
1227 throw new BadRequestException("No media.");
1230 $media = wall_upload_post($a, false);
1233 throw new InternalServerErrorException();
1237 $returndata["media_id"] = $media["id"];
1238 $returndata["media_id_string"] = (string)$media["id"];
1239 $returndata["size"] = $media["size"];
1240 $returndata["image"] = ["w" => $media["width"],
1241 "h" => $media["height"],
1242 "image_type" => $media["type"],
1243 "friendica_preview_url" => $media["preview"]];
1245 Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
1247 return ["media" => $returndata];
1250 /// @TODO move to top of file or somewhere better
1251 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1254 * Updates media meta data (picture descriptions)
1256 * @param string $type Return type (atom, rss, xml, json)
1258 * @return array|string
1259 * @throws BadRequestException
1260 * @throws ForbiddenException
1261 * @throws ImagickException
1262 * @throws InternalServerErrorException
1263 * @throws TooManyRequestsException
1264 * @throws UnauthorizedException
1265 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1267 * @todo Compare the corresponding Twitter function for correct return values
1269 function api_media_metadata_create($type)
1273 if (api_user() === false) {
1274 Logger::info('no user');
1275 throw new ForbiddenException();
1280 $postdata = Network::postdata();
1282 if (empty($postdata)) {
1283 throw new BadRequestException("No post data");
1286 $data = json_decode($postdata, true);
1288 throw new BadRequestException("Invalid post data");
1291 if (empty($data['media_id']) || empty($data['alt_text'])) {
1292 throw new BadRequestException("Missing post data values");
1295 if (empty($data['alt_text']['text'])) {
1296 throw new BadRequestException("No alt text.");
1299 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1301 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1302 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1303 if (!DBA::isResult($photo)) {
1304 throw new BadRequestException("Metadata not found.");
1307 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1310 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1313 * @param string $type Return format (atom, rss, xml, json)
1314 * @param int $item_id
1318 function api_status_show($type, $item_id)
1320 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1324 $item = api_get_item(['id' => $item_id]);
1325 if (!empty($item)) {
1326 $status_info = api_format_item($item, $type);
1329 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1331 return api_format_data('statuses', $type, ['status' => $status_info]);
1335 * Retrieves the last public status of the provided user info
1337 * @param int $ownerId Public contact Id
1338 * @param int $uid User Id
1342 function api_get_last_status($ownerId, $uid)
1345 'author-id'=> $ownerId,
1347 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1348 'private' => [Item::PUBLIC, Item::UNLISTED]
1351 $item = api_get_item($condition);
1357 * Retrieves a single item record based on the provided condition and converts it for API use.
1359 * @param array $condition Item table condition array
1363 function api_get_item(array $condition)
1365 $item = Item::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1371 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1372 * The author's most recent status will be returned inline.
1374 * @param string $type Return type (atom, rss, xml, json)
1375 * @return array|string
1376 * @throws BadRequestException
1377 * @throws ImagickException
1378 * @throws InternalServerErrorException
1379 * @throws UnauthorizedException
1380 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1382 function api_users_show($type)
1384 $a = Friendica\DI::app();
1386 $user_info = api_get_user($a);
1388 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1389 if (!empty($item)) {
1390 $user_info['status'] = api_format_item($item, $type);
1393 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1394 unset($user_info['uid']);
1395 unset($user_info['self']);
1397 return api_format_data('user', $type, ['user' => $user_info]);
1400 /// @TODO move to top of file or somewhere better
1401 api_register_func('api/users/show', 'api_users_show');
1402 api_register_func('api/externalprofile/show', 'api_users_show');
1405 * Search a public user account.
1407 * @param string $type Return type (atom, rss, xml, json)
1409 * @return array|string
1410 * @throws BadRequestException
1411 * @throws ImagickException
1412 * @throws InternalServerErrorException
1413 * @throws UnauthorizedException
1414 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1416 function api_users_search($type)
1422 if (!empty($_GET['q'])) {
1423 $contacts = Contact::selectToArray(
1426 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1434 if (DBA::isResult($contacts)) {
1436 foreach ($contacts as $contact) {
1437 $user_info = api_get_user($a, $contact['id']);
1439 if ($type == 'xml') {
1440 $userlist[$k++ . ':user'] = $user_info;
1442 $userlist[] = $user_info;
1445 $userlist = ['users' => $userlist];
1447 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1450 throw new BadRequestException('No search term specified.');
1453 return api_format_data('users', $type, $userlist);
1456 /// @TODO move to top of file or somewhere better
1457 api_register_func('api/users/search', 'api_users_search');
1460 * Return user objects
1462 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1464 * @param string $type Return format: json or xml
1466 * @return array|string
1467 * @throws BadRequestException
1468 * @throws ImagickException
1469 * @throws InternalServerErrorException
1470 * @throws NotFoundException if the results are empty.
1471 * @throws UnauthorizedException
1473 function api_users_lookup($type)
1477 if (!empty($_REQUEST['user_id'])) {
1478 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1480 $users[] = api_get_user(DI::app(), $id);
1485 if (empty($users)) {
1486 throw new NotFoundException;
1489 return api_format_data("users", $type, ['users' => $users]);
1492 /// @TODO move to top of file or somewhere better
1493 api_register_func('api/users/lookup', 'api_users_lookup', true);
1496 * Returns statuses that match a specified query.
1498 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1500 * @param string $type Return format: json, xml, atom, rss
1502 * @return array|string
1503 * @throws BadRequestException if the "q" parameter is missing.
1504 * @throws ForbiddenException
1505 * @throws ImagickException
1506 * @throws InternalServerErrorException
1507 * @throws UnauthorizedException
1509 function api_search($type)
1512 $user_info = api_get_user($a);
1514 if (api_user() === false || $user_info === false) {
1515 throw new ForbiddenException();
1518 if (empty($_REQUEST['q'])) {
1519 throw new BadRequestException('q parameter is required.');
1522 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1525 $data['status'] = [];
1527 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1528 if (!empty($_REQUEST['rpp'])) {
1529 $count = $_REQUEST['rpp'];
1530 } elseif (!empty($_REQUEST['count'])) {
1531 $count = $_REQUEST['count'];
1534 $since_id = $_REQUEST['since_id'] ?? 0;
1535 $max_id = $_REQUEST['max_id'] ?? 0;
1536 $page = $_REQUEST['page'] ?? 1;
1538 $start = max(0, ($page - 1) * $count);
1540 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1541 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1542 $searchTerm = $matches[1];
1543 $condition = ["`oid` > ?
1544 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1545 AND `otype` = ? AND `type` = ? AND `term` = ?",
1546 $since_id, local_user(), Term::OBJECT_TYPE_POST, Tag::HASHTAG, $searchTerm];
1548 $condition[0] .= ' AND `oid` <= ?';
1549 $condition[] = $max_id;
1551 $terms = DBA::select('term', ['oid'], $condition, []);
1553 while ($term = DBA::fetch($terms)) {
1554 $itemIds[] = $term['oid'];
1558 if (empty($itemIds)) {
1559 return api_format_data('statuses', $type, $data);
1562 $preCondition = ['`id` IN (' . implode(', ', $itemIds) . ')'];
1563 if ($exclude_replies) {
1564 $preCondition[] = '`id` = `parent`';
1567 $condition = [implode(' AND ', $preCondition)];
1569 $condition = ["`id` > ?
1570 " . ($exclude_replies ? " AND `id` = `parent` " : ' ') . "
1571 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1572 AND `body` LIKE CONCAT('%',?,'%')",
1573 $since_id, api_user(), $_REQUEST['q']];
1575 $condition[0] .= ' AND `id` <= ?';
1576 $condition[] = $max_id;
1582 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1583 $id = Item::fetchByLink($searchTerm, api_user());
1586 $id = Item::fetchByLink($searchTerm);
1590 $statuses = Item::select([], ['id' => $id]);
1594 $statuses = $statuses ?: Item::selectForUser(api_user(), [], $condition, $params);
1596 $data['status'] = api_format_items(Item::inArray($statuses), $user_info);
1598 bindComments($data['status']);
1600 return api_format_data('statuses', $type, $data);
1603 /// @TODO move to top of file or somewhere better
1604 api_register_func('api/search/tweets', 'api_search', true);
1605 api_register_func('api/search', 'api_search', true);
1608 * Returns the most recent statuses posted by the user and the users they follow.
1610 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1612 * @param string $type Return type (atom, rss, xml, json)
1614 * @return array|string
1615 * @throws BadRequestException
1616 * @throws ForbiddenException
1617 * @throws ImagickException
1618 * @throws InternalServerErrorException
1619 * @throws UnauthorizedException
1620 * @todo Optional parameters
1621 * @todo Add reply info
1623 function api_statuses_home_timeline($type)
1626 $user_info = api_get_user($a);
1628 if (api_user() === false || $user_info === false) {
1629 throw new ForbiddenException();
1632 unset($_REQUEST["user_id"]);
1633 unset($_GET["user_id"]);
1635 unset($_REQUEST["screen_name"]);
1636 unset($_GET["screen_name"]);
1638 // get last network messages
1641 $count = $_REQUEST['count'] ?? 20;
1642 $page = $_REQUEST['page']?? 0;
1643 $since_id = $_REQUEST['since_id'] ?? 0;
1644 $max_id = $_REQUEST['max_id'] ?? 0;
1645 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1646 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1648 $start = max(0, ($page - 1) * $count);
1650 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1651 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1654 $condition[0] .= " AND `item`.`id` <= ?";
1655 $condition[] = $max_id;
1657 if ($exclude_replies) {
1658 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
1660 if ($conversation_id > 0) {
1661 $condition[0] .= " AND `item`.`parent` = ?";
1662 $condition[] = $conversation_id;
1665 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1666 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1668 $items = Item::inArray($statuses);
1670 $ret = api_format_items($items, $user_info, false, $type);
1672 // Set all posts from the query above to seen
1674 foreach ($items as $item) {
1675 $idarray[] = intval($item["id"]);
1678 if (!empty($idarray)) {
1679 $unseen = Item::exists(['unseen' => true, 'id' => $idarray]);
1681 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1687 $data = ['status' => $ret];
1692 $data = api_rss_extra($a, $data, $user_info);
1696 return api_format_data("statuses", $type, $data);
1700 /// @TODO move to top of file or somewhere better
1701 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1702 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1705 * Returns the most recent statuses from public users.
1707 * @param string $type Return type (atom, rss, xml, json)
1709 * @return array|string
1710 * @throws BadRequestException
1711 * @throws ForbiddenException
1712 * @throws ImagickException
1713 * @throws InternalServerErrorException
1714 * @throws UnauthorizedException
1716 function api_statuses_public_timeline($type)
1719 $user_info = api_get_user($a);
1721 if (api_user() === false || $user_info === false) {
1722 throw new ForbiddenException();
1725 // get last network messages
1728 $count = $_REQUEST['count'] ?? 20;
1729 $page = $_REQUEST['page'] ?? 1;
1730 $since_id = $_REQUEST['since_id'] ?? 0;
1731 $max_id = $_REQUEST['max_id'] ?? 0;
1732 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1733 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1735 $start = max(0, ($page - 1) * $count);
1737 if ($exclude_replies && !$conversation_id) {
1738 $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`",
1739 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1742 $condition[0] .= " AND `thread`.`iid` <= ?";
1743 $condition[] = $max_id;
1746 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1747 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1749 $r = Item::inArray($statuses);
1751 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`",
1752 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1755 $condition[0] .= " AND `item`.`id` <= ?";
1756 $condition[] = $max_id;
1758 if ($conversation_id > 0) {
1759 $condition[0] .= " AND `item`.`parent` = ?";
1760 $condition[] = $conversation_id;
1763 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1764 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1766 $r = Item::inArray($statuses);
1769 $ret = api_format_items($r, $user_info, false, $type);
1773 $data = ['status' => $ret];
1778 $data = api_rss_extra($a, $data, $user_info);
1782 return api_format_data("statuses", $type, $data);
1785 /// @TODO move to top of file or somewhere better
1786 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1789 * Returns the most recent statuses posted by users this node knows about.
1791 * @param string $type Return format: json, xml, atom, rss
1792 * @return array|string
1793 * @throws BadRequestException
1794 * @throws ForbiddenException
1795 * @throws ImagickException
1796 * @throws InternalServerErrorException
1797 * @throws UnauthorizedException
1799 function api_statuses_networkpublic_timeline($type)
1802 $user_info = api_get_user($a);
1804 if (api_user() === false || $user_info === false) {
1805 throw new ForbiddenException();
1808 $since_id = $_REQUEST['since_id'] ?? 0;
1809 $max_id = $_REQUEST['max_id'] ?? 0;
1812 $count = $_REQUEST['count'] ?? 20;
1813 $page = $_REQUEST['page'] ?? 1;
1815 $start = max(0, ($page - 1) * $count);
1817 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?",
1818 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1821 $condition[0] .= " AND `thread`.`iid` <= ?";
1822 $condition[] = $max_id;
1825 $params = ['order' => ['iid' => true], 'limit' => [$start, $count]];
1826 $statuses = Item::selectThreadForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params);
1828 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1832 $data = ['status' => $ret];
1837 $data = api_rss_extra($a, $data, $user_info);
1841 return api_format_data("statuses", $type, $data);
1844 /// @TODO move to top of file or somewhere better
1845 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1848 * Returns a single status.
1850 * @param string $type Return type (atom, rss, xml, json)
1852 * @return array|string
1853 * @throws BadRequestException
1854 * @throws ForbiddenException
1855 * @throws ImagickException
1856 * @throws InternalServerErrorException
1857 * @throws UnauthorizedException
1858 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1860 function api_statuses_show($type)
1863 $user_info = api_get_user($a);
1865 if (api_user() === false || $user_info === false) {
1866 throw new ForbiddenException();
1870 $id = intval($a->argv[3] ?? 0);
1873 $id = intval($_REQUEST['id'] ?? 0);
1878 $id = intval($a->argv[4] ?? 0);
1881 Logger::log('API: api_statuses_show: ' . $id);
1883 $conversation = !empty($_REQUEST['conversation']);
1885 // try to fetch the item for the local user - or the public item, if there is no local one
1886 $uri_item = Item::selectFirst(['uri'], ['id' => $id]);
1887 if (!DBA::isResult($uri_item)) {
1888 throw new BadRequestException("There is no status with this id.");
1891 $item = Item::selectFirst(['id'], ['uri' => $uri_item['uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1892 if (!DBA::isResult($item)) {
1893 throw new BadRequestException("There is no status with this id.");
1898 if ($conversation) {
1899 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1900 $params = ['order' => ['id' => true]];
1902 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1906 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1908 /// @TODO How about copying this to above methods which don't check $r ?
1909 if (!DBA::isResult($statuses)) {
1910 throw new BadRequestException("There is no status with this id.");
1913 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1915 if ($conversation) {
1916 $data = ['status' => $ret];
1917 return api_format_data("statuses", $type, $data);
1919 $data = ['status' => $ret[0]];
1920 return api_format_data("status", $type, $data);
1924 /// @TODO move to top of file or somewhere better
1925 api_register_func('api/statuses/show', 'api_statuses_show', true);
1929 * @param string $type Return type (atom, rss, xml, json)
1931 * @return array|string
1932 * @throws BadRequestException
1933 * @throws ForbiddenException
1934 * @throws ImagickException
1935 * @throws InternalServerErrorException
1936 * @throws UnauthorizedException
1937 * @todo nothing to say?
1939 function api_conversation_show($type)
1942 $user_info = api_get_user($a);
1944 if (api_user() === false || $user_info === false) {
1945 throw new ForbiddenException();
1949 $id = intval($a->argv[3] ?? 0);
1950 $since_id = intval($_REQUEST['since_id'] ?? 0);
1951 $max_id = intval($_REQUEST['max_id'] ?? 0);
1952 $count = intval($_REQUEST['count'] ?? 20);
1953 $page = intval($_REQUEST['page'] ?? 1);
1955 $start = max(0, ($page - 1) * $count);
1958 $id = intval($_REQUEST['id'] ?? 0);
1963 $id = intval($a->argv[4] ?? 0);
1966 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1968 // try to fetch the item for the local user - or the public item, if there is no local one
1969 $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
1970 if (!DBA::isResult($item)) {
1971 throw new BadRequestException("There is no status with this id.");
1974 $parent = Item::selectFirst(['id'], ['uri' => $item['parent-uri'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1975 if (!DBA::isResult($parent)) {
1976 throw new BadRequestException("There is no status with this id.");
1979 $id = $parent['id'];
1981 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `item`.`id` > ?",
1982 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1985 $condition[0] .= " AND `item`.`id` <= ?";
1986 $condition[] = $max_id;
1989 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1990 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
1992 if (!DBA::isResult($statuses)) {
1993 throw new BadRequestException("There is no status with id $id.");
1996 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
1998 $data = ['status' => $ret];
1999 return api_format_data("statuses", $type, $data);
2002 /// @TODO move to top of file or somewhere better
2003 api_register_func('api/conversation/show', 'api_conversation_show', true);
2004 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2009 * @param string $type Return type (atom, rss, xml, json)
2011 * @return array|string
2012 * @throws BadRequestException
2013 * @throws ForbiddenException
2014 * @throws ImagickException
2015 * @throws InternalServerErrorException
2016 * @throws UnauthorizedException
2017 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2019 function api_statuses_repeat($type)
2025 if (api_user() === false) {
2026 throw new ForbiddenException();
2032 $id = intval($a->argv[3] ?? 0);
2035 $id = intval($_REQUEST['id'] ?? 0);
2040 $id = intval($a->argv[4] ?? 0);
2043 Logger::log('API: api_statuses_repeat: '.$id);
2045 $fields = ['uri-id', 'body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2046 $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2048 if (DBA::isResult($item) && $item['body'] != "") {
2049 if (strpos($item['body'], "[/share]") !== false) {
2050 $pos = strpos($item['body'], "[share");
2051 $post = substr($item['body'], $pos);
2053 $post = share_header($item['author-name'], $item['author-link'], $item['author-avatar'], $item['guid'], $item['created'], $item['plink']);
2055 if (!empty($item['title'])) {
2056 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2059 $post .= $item['body'];
2060 $post .= "[/share]";
2062 $_REQUEST['body'] = $post;
2063 $_REQUEST['tag'] = $item['tag'];
2064 $_REQUEST['attach'] = $item['attach'];
2065 $_REQUEST['profile_uid'] = api_user();
2066 $_REQUEST['api_source'] = true;
2068 if (empty($_REQUEST['source'])) {
2069 $_REQUEST["source"] = api_source();
2072 $item_id = item_post($a);
2074 /// @todo Copy tags from the original post to the new one
2076 throw new ForbiddenException();
2079 // output the post that we just posted.
2081 return api_status_show($type, $item_id);
2084 /// @TODO move to top of file or somewhere better
2085 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2088 * Destroys a specific status.
2090 * @param string $type Return type (atom, rss, xml, json)
2092 * @return array|string
2093 * @throws BadRequestException
2094 * @throws ForbiddenException
2095 * @throws ImagickException
2096 * @throws InternalServerErrorException
2097 * @throws UnauthorizedException
2098 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2100 function api_statuses_destroy($type)
2104 if (api_user() === false) {
2105 throw new ForbiddenException();
2111 $id = intval($a->argv[3] ?? 0);
2114 $id = intval($_REQUEST['id'] ?? 0);
2119 $id = intval($a->argv[4] ?? 0);
2122 Logger::log('API: api_statuses_destroy: '.$id);
2124 $ret = api_statuses_show($type);
2126 Item::deleteForUser(['id' => $id], api_user());
2131 /// @TODO move to top of file or somewhere better
2132 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2135 * Returns the most recent mentions.
2137 * @param string $type Return type (atom, rss, xml, json)
2139 * @return array|string
2140 * @throws BadRequestException
2141 * @throws ForbiddenException
2142 * @throws ImagickException
2143 * @throws InternalServerErrorException
2144 * @throws UnauthorizedException
2145 * @see http://developer.twitter.com/doc/get/statuses/mentions
2147 function api_statuses_mentions($type)
2150 $user_info = api_get_user($a);
2152 if (api_user() === false || $user_info === false) {
2153 throw new ForbiddenException();
2156 unset($_REQUEST["user_id"]);
2157 unset($_GET["user_id"]);
2159 unset($_REQUEST["screen_name"]);
2160 unset($_GET["screen_name"]);
2162 // get last network messages
2165 $since_id = $_REQUEST['since_id'] ?? 0;
2166 $max_id = $_REQUEST['max_id'] ?? 0;
2167 $count = $_REQUEST['count'] ?? 20;
2168 $page = $_REQUEST['page'] ?? 1;
2170 $start = max(0, ($page - 1) * $count);
2172 $query = "SELECT `item`.`id` FROM `user-item`
2173 INNER JOIN `item` ON `item`.`id` = `user-item`.`iid` AND `item`.`gravity` IN (?, ?)
2174 WHERE (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) AND
2175 `user-item`.`uid` = ? AND `user-item`.`notification-type` & ? != 0
2176 AND `user-item`.`iid` > ?";
2177 $condition = [GRAVITY_PARENT, GRAVITY_COMMENT, api_user(),
2178 UserItem::NOTIF_EXPLICIT_TAGGED | UserItem::NOTIF_IMPLICIT_TAGGED |
2179 UserItem::NOTIF_THREAD_COMMENT | UserItem::NOTIF_DIRECT_COMMENT |
2180 UserItem::NOTIF_DIRECT_THREAD_COMMENT,
2184 $query .= " AND `item`.`id` <= ?";
2185 $condition[] = $max_id;
2188 $query .= " ORDER BY `user-item`.`iid` DESC LIMIT ?, ?";
2189 $condition[] = $start;
2190 $condition[] = $count;
2192 $useritems = DBA::p($query, $condition);
2194 while ($useritem = DBA::fetch($useritems)) {
2195 $itemids[] = $useritem['id'];
2197 DBA::close($useritems);
2199 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2200 $statuses = Item::selectForUser(api_user(), [], ['id' => $itemids], $params);
2202 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2204 $data = ['status' => $ret];
2209 $data = api_rss_extra($a, $data, $user_info);
2213 return api_format_data("statuses", $type, $data);
2216 /// @TODO move to top of file or somewhere better
2217 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2218 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2221 * Returns the most recent statuses posted by the user.
2223 * @param string $type Either "json" or "xml"
2224 * @return string|array
2225 * @throws BadRequestException
2226 * @throws ForbiddenException
2227 * @throws ImagickException
2228 * @throws InternalServerErrorException
2229 * @throws UnauthorizedException
2230 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2232 function api_statuses_user_timeline($type)
2235 $user_info = api_get_user($a);
2237 if (api_user() === false || $user_info === false) {
2238 throw new ForbiddenException();
2242 "api_statuses_user_timeline: api_user: ". api_user() .
2243 "\nuser_info: ".print_r($user_info, true) .
2244 "\n_REQUEST: ".print_r($_REQUEST, true),
2248 $since_id = $_REQUEST['since_id'] ?? 0;
2249 $max_id = $_REQUEST['max_id'] ?? 0;
2250 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2251 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2254 $count = $_REQUEST['count'] ?? 20;
2255 $page = $_REQUEST['page'] ?? 1;
2257 $start = max(0, ($page - 1) * $count);
2259 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `item`.`id` > ? AND `item`.`contact-id` = ?",
2260 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2262 if ($user_info['self'] == 1) {
2263 $condition[0] .= ' AND `item`.`wall` ';
2266 if ($exclude_replies) {
2267 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
2270 if ($conversation_id > 0) {
2271 $condition[0] .= " AND `item`.`parent` = ?";
2272 $condition[] = $conversation_id;
2276 $condition[0] .= " AND `item`.`id` <= ?";
2277 $condition[] = $max_id;
2280 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2281 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2283 $ret = api_format_items(Item::inArray($statuses), $user_info, true, $type);
2287 $data = ['status' => $ret];
2292 $data = api_rss_extra($a, $data, $user_info);
2296 return api_format_data("statuses", $type, $data);
2299 /// @TODO move to top of file or somewhere better
2300 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2303 * Star/unstar an item.
2304 * param: id : id of the item
2306 * @param string $type Return type (atom, rss, xml, json)
2308 * @return array|string
2309 * @throws BadRequestException
2310 * @throws ForbiddenException
2311 * @throws ImagickException
2312 * @throws InternalServerErrorException
2313 * @throws UnauthorizedException
2314 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2316 function api_favorites_create_destroy($type)
2320 if (api_user() === false) {
2321 throw new ForbiddenException();
2324 // for versioned api.
2325 /// @TODO We need a better global soluton
2326 $action_argv_id = 2;
2327 if (count($a->argv) > 1 && $a->argv[1] == "1.1") {
2328 $action_argv_id = 3;
2331 if ($a->argc <= $action_argv_id) {
2332 throw new BadRequestException("Invalid request.");
2334 $action = str_replace("." . $type, "", $a->argv[$action_argv_id]);
2335 if ($a->argc == $action_argv_id + 2) {
2336 $itemid = intval($a->argv[$action_argv_id + 1] ?? 0);
2338 $itemid = intval($_REQUEST['id'] ?? 0);
2341 $item = Item::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2343 if (!DBA::isResult($item)) {
2344 throw new BadRequestException("Invalid item.");
2349 $item['starred'] = 1;
2352 $item['starred'] = 0;
2355 throw new BadRequestException("Invalid action ".$action);
2358 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2361 throw new InternalServerErrorException("DB error");
2365 $user_info = api_get_user($a);
2366 $rets = api_format_items([$item], $user_info, false, $type);
2369 $data = ['status' => $ret];
2374 $data = api_rss_extra($a, $data, $user_info);
2378 return api_format_data("status", $type, $data);
2381 /// @TODO move to top of file or somewhere better
2382 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2383 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2386 * Returns the most recent favorite statuses.
2388 * @param string $type Return type (atom, rss, xml, json)
2390 * @return string|array
2391 * @throws BadRequestException
2392 * @throws ForbiddenException
2393 * @throws ImagickException
2394 * @throws InternalServerErrorException
2395 * @throws UnauthorizedException
2397 function api_favorites($type)
2402 $user_info = api_get_user($a);
2404 if (api_user() === false || $user_info === false) {
2405 throw new ForbiddenException();
2410 // in friendica starred item are private
2411 // return favorites only for self
2412 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2414 if ($user_info['self'] == 0) {
2418 $since_id = $_REQUEST['since_id'] ?? 0;
2419 $max_id = $_REQUEST['max_id'] ?? 0;
2420 $count = $_GET['count'] ?? 20;
2421 $page = $_REQUEST['page'] ?? 1;
2423 $start = max(0, ($page - 1) * $count);
2425 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2426 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2428 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2431 $condition[0] .= " AND `item`.`id` <= ?";
2432 $condition[] = $max_id;
2435 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
2437 $ret = api_format_items(Item::inArray($statuses), $user_info, false, $type);
2442 $data = ['status' => $ret];
2447 $data = api_rss_extra($a, $data, $user_info);
2451 return api_format_data("statuses", $type, $data);
2454 /// @TODO move to top of file or somewhere better
2455 api_register_func('api/favorites', 'api_favorites', true);
2459 * @param array $item
2460 * @param array $recipient
2461 * @param array $sender
2464 * @throws InternalServerErrorException
2466 function api_format_messages($item, $recipient, $sender)
2468 // standard meta information
2470 'id' => $item['id'],
2471 'sender_id' => $sender['id'],
2473 'recipient_id' => $recipient['id'],
2474 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2475 'sender_screen_name' => $sender['screen_name'],
2476 'recipient_screen_name' => $recipient['screen_name'],
2477 'sender' => $sender,
2478 'recipient' => $recipient,
2480 'friendica_seen' => $item['seen'] ?? 0,
2481 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2484 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2485 if (isset($ret['sender']['uid'])) {
2486 unset($ret['sender']['uid']);
2488 if (isset($ret['sender']['self'])) {
2489 unset($ret['sender']['self']);
2491 if (isset($ret['recipient']['uid'])) {
2492 unset($ret['recipient']['uid']);
2494 if (isset($ret['recipient']['self'])) {
2495 unset($ret['recipient']['self']);
2498 //don't send title to regular StatusNET requests to avoid confusing these apps
2499 if (!empty($_GET['getText'])) {
2500 $ret['title'] = $item['title'];
2501 if ($_GET['getText'] == 'html') {
2502 $ret['text'] = BBCode::convert($item['body'], false);
2503 } elseif ($_GET['getText'] == 'plain') {
2504 $ret['text'] = trim(HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0));
2507 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convert(api_clean_plain_items($item['body']), false, 2, true), 0);
2509 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2510 unset($ret['sender']);
2511 unset($ret['recipient']);
2519 * @param array $item
2522 * @throws InternalServerErrorException
2524 function api_convert_item($item)
2526 $body = $item['body'];
2527 $entities = api_get_entitities($statustext, $body);
2529 // Add pictures to the attachment array and remove them from the body
2530 $attachments = api_get_attachments($body);
2532 // Workaround for ostatus messages where the title is identically to the body
2533 $html = BBCode::convert(api_clean_plain_items($body), false, 2, true);
2534 $statusbody = trim(HTML::toPlaintext($html, 0));
2536 // handle data: images
2537 $statusbody = api_format_items_embeded_images($item, $statusbody);
2539 $statustitle = trim($item['title']);
2541 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2542 $statustext = trim($statusbody);
2544 $statustext = trim($statustitle."\n\n".$statusbody);
2547 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2548 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2551 $statushtml = BBCode::convert(BBCode::removeAttachment($body), false);
2553 // Workaround for clients with limited HTML parser functionality
2554 $search = ["<br>", "<blockquote>", "</blockquote>",
2555 "<h1>", "</h1>", "<h2>", "</h2>",
2556 "<h3>", "</h3>", "<h4>", "</h4>",
2557 "<h5>", "</h5>", "<h6>", "</h6>"];
2558 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2559 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2560 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2561 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2562 $statushtml = str_replace($search, $replace, $statushtml);
2564 if ($item['title'] != "") {
2565 $statushtml = "<br><h4>" . BBCode::convert($item['title']) . "</h4><br>" . $statushtml;
2569 $oldtext = $statushtml;
2570 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2571 } while ($oldtext != $statushtml);
2573 if (substr($statushtml, 0, 4) == '<br>') {
2574 $statushtml = substr($statushtml, 4);
2577 if (substr($statushtml, 0, -4) == '<br>') {
2578 $statushtml = substr($statushtml, -4);
2581 // feeds without body should contain the link
2582 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2583 $statushtml .= BBCode::convert($item['plink']);
2587 "text" => $statustext,
2588 "html" => $statushtml,
2589 "attachments" => $attachments,
2590 "entities" => $entities
2596 * @param string $body
2599 * @throws InternalServerErrorException
2601 function api_get_attachments(&$body)
2603 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2604 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2606 $URLSearchString = "^\[\]";
2607 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2611 // Remove all embedded pictures, since they are added as attachments
2612 foreach ($images[0] as $orig) {
2613 $body = str_replace($orig, '', $body);
2618 foreach ($images[1] as $image) {
2619 $imagedata = Images::getInfoFromURLCached($image);
2622 $attachments[] = ["url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2626 return $attachments;
2631 * @param string $text
2632 * @param string $bbcode
2635 * @throws InternalServerErrorException
2636 * @todo Links at the first character of the post
2638 function api_get_entitities(&$text, $bbcode)
2640 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2642 if ($include_entities != "true") {
2643 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2645 foreach ($images[1] as $image) {
2646 $replace = ProxyUtils::proxifyUrl($image);
2647 $text = str_replace($image, $replace, $text);
2652 $bbcode = BBCode::cleanPictureLinks($bbcode);
2654 // Change pure links in text to bbcode uris
2655 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2658 $entities["hashtags"] = [];
2659 $entities["symbols"] = [];
2660 $entities["urls"] = [];
2661 $entities["user_mentions"] = [];
2663 $URLSearchString = "^\[\]";
2665 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2667 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2668 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2670 $bbcode = preg_replace(
2671 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2672 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2675 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2677 $bbcode = preg_replace(
2678 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2679 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2682 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2684 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2686 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2689 foreach ($urls[1] as $id => $url) {
2690 $start = iconv_strpos($text, $url, 0, "UTF-8");
2691 if (!($start === false)) {
2692 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2696 ksort($ordered_urls);
2700 foreach ($ordered_urls as $url) {
2701 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2702 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2704 $display_url = $url["title"];
2706 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2707 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2709 if (strlen($display_url) > 26) {
2710 $display_url = substr($display_url, 0, 25)."…";
2714 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2715 if (!($start === false)) {
2716 $entities["urls"][] = ["url" => $url["url"],
2717 "expanded_url" => $url["url"],
2718 "display_url" => $display_url,
2719 "indices" => [$start, $start+strlen($url["url"])]];
2720 $offset = $start + 1;
2724 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2725 $ordered_images = [];
2726 foreach ($images as $image) {
2727 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2728 if (!($start === false)) {
2729 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2733 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2734 foreach ($images[1] as $image) {
2735 $start = iconv_strpos($text, $image, 0, "UTF-8");
2736 if (!($start === false)) {
2737 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2743 foreach ($ordered_images as $image) {
2744 $url = $image['url'];
2745 $ext_alt_text = $image['alt'];
2747 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2748 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2750 if (strlen($display_url) > 26) {
2751 $display_url = substr($display_url, 0, 25)."…";
2754 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2755 if (!($start === false)) {
2756 $image = Images::getInfoFromURLCached($url);
2758 // If image cache is activated, then use the following sizes:
2759 // thumb (150), small (340), medium (600) and large (1024)
2760 if (!DI::config()->get("system", "proxy_disabled")) {
2761 $media_url = ProxyUtils::proxifyUrl($url);
2764 $scale = Images::getScalingDimensions($image[0], $image[1], 150);
2765 $sizes["thumb"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2767 if (($image[0] > 150) || ($image[1] > 150)) {
2768 $scale = Images::getScalingDimensions($image[0], $image[1], 340);
2769 $sizes["small"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2772 $scale = Images::getScalingDimensions($image[0], $image[1], 600);
2773 $sizes["medium"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2775 if (($image[0] > 600) || ($image[1] > 600)) {
2776 $scale = Images::getScalingDimensions($image[0], $image[1], 1024);
2777 $sizes["large"] = ["w" => $scale["width"], "h" => $scale["height"], "resize" => "fit"];
2781 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2784 $entities["media"][] = [
2786 "id_str" => (string) ($start + 1),
2787 "indices" => [$start, $start+strlen($url)],
2788 "media_url" => Strings::normaliseLink($media_url),
2789 "media_url_https" => $media_url,
2791 "display_url" => $display_url,
2792 "expanded_url" => $url,
2793 "ext_alt_text" => $ext_alt_text,
2797 $offset = $start + 1;
2806 * @param array $item
2807 * @param string $text
2811 function api_format_items_embeded_images($item, $text)
2813 $text = preg_replace_callback(
2814 '|data:image/([^;]+)[^=]+=*|m',
2815 function () use ($item) {
2816 return DI::baseUrl() . '/display/' . $item['guid'];
2824 * return <a href='url'>name</a> as array
2826 * @param string $txt text
2831 function api_contactlink_to_array($txt)
2834 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2835 if ($r && count($match)==3) {
2837 'name' => $match[2],
2851 * return likes, dislikes and attend status for item
2853 * @param array $item array
2854 * @param string $type Return type (atom, rss, xml, json)
2857 * likes => int count,
2858 * dislikes => int count
2859 * @throws BadRequestException
2860 * @throws ImagickException
2861 * @throws InternalServerErrorException
2862 * @throws UnauthorizedException
2864 function api_format_items_activities($item, $type = "json")
2873 'attendmaybe' => [],
2877 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2878 $ret = Item::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2880 while ($parent_item = Item::fetch($ret)) {
2881 // not used as result should be structured like other user data
2882 //builtin_activity_puller($i, $activities);
2884 // get user data and add it to the array of the activity
2885 $user = api_get_user($a, $parent_item['author-id']);
2886 switch ($parent_item['verb']) {
2887 case Activity::LIKE:
2888 $activities['like'][] = $user;
2890 case Activity::DISLIKE:
2891 $activities['dislike'][] = $user;
2893 case Activity::ATTEND:
2894 $activities['attendyes'][] = $user;
2896 case Activity::ATTENDNO:
2897 $activities['attendno'][] = $user;
2899 case Activity::ATTENDMAYBE:
2900 $activities['attendmaybe'][] = $user;
2902 case Activity::ANNOUNCE:
2903 $activities['announce'][] = $user;
2912 if ($type == "xml") {
2913 $xml_activities = [];
2914 foreach ($activities as $k => $v) {
2915 // change xml element from "like" to "friendica:like"
2916 $xml_activities["friendica:".$k] = $v;
2917 // add user data into xml output
2919 foreach ($v as $user) {
2920 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2923 $activities = $xml_activities;
2930 * format items to be returned by api
2932 * @param array $items array of items
2933 * @param array $user_info
2934 * @param bool $filter_user filter items by $user_info
2935 * @param string $type Return type (atom, rss, xml, json)
2937 * @throws BadRequestException
2938 * @throws ImagickException
2939 * @throws InternalServerErrorException
2940 * @throws UnauthorizedException
2942 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2944 $a = Friendica\DI::app();
2948 foreach ((array)$items as $item) {
2949 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2951 // Look if the posts are matching if they should be filtered by user id
2952 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2956 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2965 * @param array $item Item record
2966 * @param string $type Return format (atom, rss, xml, json)
2967 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2968 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2969 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2970 * @return array API-formatted status
2971 * @throws BadRequestException
2972 * @throws ImagickException
2973 * @throws InternalServerErrorException
2974 * @throws UnauthorizedException
2976 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2978 $a = Friendica\DI::app();
2980 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2981 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2984 localize_item($item);
2986 $in_reply_to = api_in_reply_to($item);
2988 $converted = api_convert_item($item);
2990 if ($type == "xml") {
2991 $geo = "georss:point";
2997 'text' => $converted["text"],
2998 'truncated' => false,
2999 'created_at'=> api_date($item['created']),
3000 'in_reply_to_status_id' => $in_reply_to['status_id'],
3001 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3002 'source' => (($item['app']) ? $item['app'] : 'web'),
3003 'id' => intval($item['id']),
3004 'id_str' => (string) intval($item['id']),
3005 'in_reply_to_user_id' => $in_reply_to['user_id'],
3006 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3007 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3009 'favorited' => $item['starred'] ? true : false,
3010 'user' => $status_user,
3011 'friendica_author' => $author_user,
3012 'friendica_owner' => $owner_user,
3013 'friendica_private' => $item['private'] == Item::PRIVATE,
3014 //'entities' => NULL,
3015 'statusnet_html' => $converted["html"],
3016 'statusnet_conversation_id' => $item['parent'],
3017 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3018 'friendica_activities' => api_format_items_activities($item, $type),
3019 'friendica_title' => $item['title'],
3020 'friendica_html' => BBCode::convert($item['body'], false)
3023 if (count($converted["attachments"]) > 0) {
3024 $status["attachments"] = $converted["attachments"];
3027 if (count($converted["entities"]) > 0) {
3028 $status["entities"] = $converted["entities"];
3031 if ($status["source"] == 'web') {
3032 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3033 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3034 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3037 $retweeted_item = [];
3040 if ($item["id"] == $item["parent"]) {
3041 $body = $item['body'];
3042 $retweeted_item = api_share_as_retweet($item);
3043 if ($body != $item['body']) {
3044 $quoted_item = $retweeted_item;
3045 $retweeted_item = [];
3049 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3050 $announce = api_get_announce($item);
3051 if (!empty($announce)) {
3052 $retweeted_item = $item;
3054 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3058 if (!empty($quoted_item)) {
3059 if ($quoted_item['id'] != $item['id']) {
3060 $quoted_status = api_format_item($quoted_item);
3061 /// @todo Only remove the attachments that are also contained in the quotes status
3062 unset($status['attachments']);
3063 unset($status['entities']);
3065 $conv_quoted = api_convert_item($quoted_item);
3066 $quoted_status = $status;
3067 unset($quoted_status['attachments']);
3068 unset($quoted_status['entities']);
3069 unset($quoted_status['statusnet_conversation_id']);
3070 $quoted_status['text'] = $conv_quoted['text'];
3071 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3073 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3074 } catch (BadRequestException $e) {
3075 // user not found. should be found?
3076 /// @todo check if the user should be always found
3077 $quoted_status["user"] = [];
3080 unset($quoted_status['friendica_author']);
3081 unset($quoted_status['friendica_owner']);
3082 unset($quoted_status['friendica_activities']);
3083 unset($quoted_status['friendica_private']);
3086 if (!empty($retweeted_item)) {
3087 $retweeted_status = $status;
3088 unset($retweeted_status['friendica_author']);
3089 unset($retweeted_status['friendica_owner']);
3090 unset($retweeted_status['friendica_activities']);
3091 unset($retweeted_status['friendica_private']);
3092 unset($retweeted_status['statusnet_conversation_id']);
3093 $status['user'] = $status['friendica_owner'];
3095 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3096 } catch (BadRequestException $e) {
3097 // user not found. should be found?
3098 /// @todo check if the user should be always found
3099 $retweeted_status["user"] = [];
3102 $rt_converted = api_convert_item($retweeted_item);
3104 $retweeted_status['text'] = $rt_converted["text"];
3105 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3106 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3108 if (!empty($quoted_status)) {
3109 $retweeted_status['quoted_status'] = $quoted_status;
3112 $status['friendica_author'] = $retweeted_status['user'];
3113 $status['retweeted_status'] = $retweeted_status;
3114 } elseif (!empty($quoted_status)) {
3115 $root_status = api_convert_item($item);
3117 $status['text'] = $root_status["text"];
3118 $status['statusnet_html'] = $root_status["html"];
3119 $status['quoted_status'] = $quoted_status;
3122 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3123 unset($status["user"]["uid"]);
3124 unset($status["user"]["self"]);
3126 if ($item["coord"] != "") {
3127 $coords = explode(' ', $item["coord"]);
3128 if (count($coords) == 2) {
3129 if ($type == "json") {
3130 $status["geo"] = ['type' => 'Point',
3131 'coordinates' => [(float) $coords[0],
3132 (float) $coords[1]]];
3133 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3134 $status["georss:point"] = $item["coord"];
3143 * Returns the remaining number of API requests available to the user before the API limit is reached.
3145 * @param string $type Return type (atom, rss, xml, json)
3147 * @return array|string
3150 function api_account_rate_limit_status($type)
3152 if ($type == "xml") {
3154 'remaining-hits' => '150',
3155 '@attributes' => ["type" => "integer"],
3156 'hourly-limit' => '150',
3157 '@attributes2' => ["type" => "integer"],
3158 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3159 '@attributes3' => ["type" => "datetime"],
3160 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3161 '@attributes4' => ["type" => "integer"],
3165 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3166 'remaining_hits' => '150',
3167 'hourly_limit' => '150',
3168 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3172 return api_format_data('hash', $type, ['hash' => $hash]);
3175 /// @TODO move to top of file or somewhere better
3176 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3179 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3181 * @param string $type Return type (atom, rss, xml, json)
3183 * @return array|string
3185 function api_help_test($type)
3187 if ($type == 'xml') {
3193 return api_format_data('ok', $type, ["ok" => $ok]);
3196 /// @TODO move to top of file or somewhere better
3197 api_register_func('api/help/test', 'api_help_test', false);
3200 * Returns all lists the user subscribes to.
3202 * @param string $type Return type (atom, rss, xml, json)
3204 * @return array|string
3205 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3207 function api_lists_list($type)
3210 /// @TODO $ret is not filled here?
3211 return api_format_data('lists', $type, ["lists_list" => $ret]);
3214 /// @TODO move to top of file or somewhere better
3215 api_register_func('api/lists/list', 'api_lists_list', true);
3216 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3219 * Returns all groups the user owns.
3221 * @param string $type Return type (atom, rss, xml, json)
3223 * @return array|string
3224 * @throws BadRequestException
3225 * @throws ForbiddenException
3226 * @throws ImagickException
3227 * @throws InternalServerErrorException
3228 * @throws UnauthorizedException
3229 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3231 function api_lists_ownerships($type)
3235 if (api_user() === false) {
3236 throw new ForbiddenException();
3240 $user_info = api_get_user($a);
3241 $uid = $user_info['uid'];
3243 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3245 // loop through all groups
3247 foreach ($groups as $group) {
3248 if ($group['visible']) {
3254 'name' => $group['name'],
3255 'id' => intval($group['id']),
3256 'id_str' => (string) $group['id'],
3257 'user' => $user_info,
3261 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3264 /// @TODO move to top of file or somewhere better
3265 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3268 * Returns recent statuses from users in the specified group.
3270 * @param string $type Return type (atom, rss, xml, json)
3272 * @return array|string
3273 * @throws BadRequestException
3274 * @throws ForbiddenException
3275 * @throws ImagickException
3276 * @throws InternalServerErrorException
3277 * @throws UnauthorizedException
3278 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3280 function api_lists_statuses($type)
3284 $user_info = api_get_user($a);
3285 if (api_user() === false || $user_info === false) {
3286 throw new ForbiddenException();
3289 unset($_REQUEST["user_id"]);
3290 unset($_GET["user_id"]);
3292 unset($_REQUEST["screen_name"]);
3293 unset($_GET["screen_name"]);
3295 if (empty($_REQUEST['list_id'])) {
3296 throw new BadRequestException('list_id not specified');
3300 $count = $_REQUEST['count'] ?? 20;
3301 $page = $_REQUEST['page'] ?? 1;
3302 $since_id = $_REQUEST['since_id'] ?? 0;
3303 $max_id = $_REQUEST['max_id'] ?? 0;
3304 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3305 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3307 $start = max(0, ($page - 1) * $count);
3309 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `group_member`.`gid` = ?",
3310 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $_REQUEST['list_id']];
3313 $condition[0] .= " AND `item`.`id` <= ?";
3314 $condition[] = $max_id;
3316 if ($exclude_replies > 0) {
3317 $condition[0] .= ' AND `item`.`parent` = `item`.`id`';
3319 if ($conversation_id > 0) {
3320 $condition[0] .= " AND `item`.`parent` = ?";
3321 $condition[] = $conversation_id;
3324 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3325 $statuses = Item::selectForUser(api_user(), [], $condition, $params);
3327 $items = api_format_items(Item::inArray($statuses), $user_info, false, $type);
3329 $data = ['status' => $items];
3334 $data = api_rss_extra($a, $data, $user_info);
3338 return api_format_data("statuses", $type, $data);
3341 /// @TODO move to top of file or somewhere better
3342 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3345 * Returns either the friends of the follower list
3347 * Considers friends and followers lists to be private and won't return
3348 * anything if any user_id parameter is passed.
3350 * @param string $qtype Either "friends" or "followers"
3351 * @return boolean|array
3352 * @throws BadRequestException
3353 * @throws ForbiddenException
3354 * @throws ImagickException
3355 * @throws InternalServerErrorException
3356 * @throws UnauthorizedException
3358 function api_statuses_f($qtype)
3362 if (api_user() === false) {
3363 throw new ForbiddenException();
3367 $count = $_GET['count'] ?? 20;
3368 $page = $_GET['page'] ?? 1;
3370 $start = max(0, ($page - 1) * $count);
3372 $user_info = api_get_user($a);
3374 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3375 /* this is to stop Hotot to load friends multiple times
3376 * I'm not sure if I'm missing return something or
3377 * is a bug in hotot. Workaround, meantime
3381 return array('$users' => $ret);*/
3386 if ($qtype == 'friends') {
3387 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3388 } elseif ($qtype == 'followers') {
3389 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3392 // friends and followers only for self
3393 if ($user_info['self'] == 0) {
3394 $sql_extra = " AND false ";
3397 if ($qtype == 'blocks') {
3398 $sql_filter = 'AND `blocked` AND NOT `pending`';
3399 } elseif ($qtype == 'incoming') {
3400 $sql_filter = 'AND `pending`';
3402 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3420 foreach ($r as $cid) {
3421 $user = api_get_user($a, $cid['nurl']);
3422 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3423 unset($user["uid"]);
3424 unset($user["self"]);
3431 return ['user' => $ret];
3436 * Returns the list of friends of the provided user
3438 * @deprecated By Twitter API in favor of friends/list
3440 * @param string $type Either "json" or "xml"
3441 * @return boolean|string|array
3442 * @throws BadRequestException
3443 * @throws ForbiddenException
3445 function api_statuses_friends($type)
3447 $data = api_statuses_f("friends");
3448 if ($data === false) {
3451 return api_format_data("users", $type, $data);
3455 * Returns the list of followers of the provided user
3457 * @deprecated By Twitter API in favor of friends/list
3459 * @param string $type Either "json" or "xml"
3460 * @return boolean|string|array
3461 * @throws BadRequestException
3462 * @throws ForbiddenException
3464 function api_statuses_followers($type)
3466 $data = api_statuses_f("followers");
3467 if ($data === false) {
3470 return api_format_data("users", $type, $data);
3473 /// @TODO move to top of file or somewhere better
3474 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3475 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3478 * Returns the list of blocked users
3480 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3482 * @param string $type Either "json" or "xml"
3484 * @return boolean|string|array
3485 * @throws BadRequestException
3486 * @throws ForbiddenException
3488 function api_blocks_list($type)
3490 $data = api_statuses_f('blocks');
3491 if ($data === false) {
3494 return api_format_data("users", $type, $data);
3497 /// @TODO move to top of file or somewhere better
3498 api_register_func('api/blocks/list', 'api_blocks_list', true);
3501 * Returns the list of pending users IDs
3503 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3505 * @param string $type Either "json" or "xml"
3507 * @return boolean|string|array
3508 * @throws BadRequestException
3509 * @throws ForbiddenException
3511 function api_friendships_incoming($type)
3513 $data = api_statuses_f('incoming');
3514 if ($data === false) {
3519 foreach ($data['user'] as $user) {
3520 $ids[] = $user['id'];
3523 return api_format_data("ids", $type, ['id' => $ids]);
3526 /// @TODO move to top of file or somewhere better
3527 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3530 * Returns the instance's configuration information.
3532 * @param string $type Return type (atom, rss, xml, json)
3534 * @return array|string
3535 * @throws InternalServerErrorException
3537 function api_statusnet_config($type)
3539 $name = DI::config()->get('config', 'sitename');
3540 $server = DI::baseUrl()->getHostname();
3541 $logo = DI::baseUrl() . '/images/friendica-64.png';
3542 $email = DI::config()->get('config', 'admin_email');
3543 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3544 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3545 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3546 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3547 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3550 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3551 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3552 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3553 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3554 'shorturllength' => '30',
3556 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3557 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3558 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3559 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3564 return api_format_data('config', $type, ['config' => $config]);
3567 /// @TODO move to top of file or somewhere better
3568 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3569 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3573 * @param string $type Return type (atom, rss, xml, json)
3575 * @return array|string
3577 function api_statusnet_version($type)
3580 $fake_statusnet_version = "0.9.7";
3582 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3585 /// @TODO move to top of file or somewhere better
3586 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3587 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3591 * @param string $type Return type (atom, rss, xml, json)
3593 * @param int $rel A contact relationship constant
3594 * @return array|string|void
3595 * @throws BadRequestException
3596 * @throws ForbiddenException
3597 * @throws ImagickException
3598 * @throws InternalServerErrorException
3599 * @throws UnauthorizedException
3600 * @todo use api_format_data() to return data
3602 function api_ff_ids($type, int $rel)
3605 throw new ForbiddenException();
3612 $stringify_ids = $_REQUEST['stringify_ids'] ?? false;
3614 $contacts = DBA::p("SELECT `pcontact`.`id`
3616 INNER JOIN `contact` AS `pcontact`
3617 ON `contact`.`nurl` = `pcontact`.`nurl`
3618 AND `pcontact`.`uid` = 0
3619 WHERE `contact`.`uid` = ?
3620 AND NOT `contact`.`self`
3621 AND `contact`.`rel` IN (?, ?)",
3628 foreach (DBA::toArray($contacts) as $contact) {
3629 if ($stringify_ids) {
3630 $ids[] = $contact['id'];
3632 $ids[] = intval($contact['id']);
3636 return api_format_data('ids', $type, ['id' => $ids]);
3640 * Returns the ID of every user the user is following.
3642 * @param string $type Return type (atom, rss, xml, json)
3644 * @return array|string
3645 * @throws BadRequestException
3646 * @throws ForbiddenException
3647 * @throws ImagickException
3648 * @throws InternalServerErrorException
3649 * @throws UnauthorizedException
3650 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-ids
3652 function api_friends_ids($type)
3654 return api_ff_ids($type, Contact::SHARING);
3658 * Returns the ID of every user following the user.
3660 * @param string $type Return type (atom, rss, xml, json)
3662 * @return array|string
3663 * @throws BadRequestException
3664 * @throws ForbiddenException
3665 * @throws ImagickException
3666 * @throws InternalServerErrorException
3667 * @throws UnauthorizedException
3668 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-followers-ids
3670 function api_followers_ids($type)
3672 return api_ff_ids($type, Contact::FOLLOWER);
3675 /// @TODO move to top of file or somewhere better
3676 api_register_func('api/friends/ids', 'api_friends_ids', true);
3677 api_register_func('api/followers/ids', 'api_followers_ids', true);
3680 * Sends a new direct message.
3682 * @param string $type Return type (atom, rss, xml, json)
3684 * @return array|string
3685 * @throws BadRequestException
3686 * @throws ForbiddenException
3687 * @throws ImagickException
3688 * @throws InternalServerErrorException
3689 * @throws NotFoundException
3690 * @throws UnauthorizedException
3691 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3693 function api_direct_messages_new($type)
3697 if (api_user() === false) {
3698 throw new ForbiddenException();
3701 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3705 $sender = api_get_user($a);
3708 if (!empty($_POST['screen_name'])) {
3710 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3712 DBA::escape($_POST['screen_name'])
3715 if (DBA::isResult($r)) {
3716 // Selecting the id by priority, friendica first
3717 api_best_nickname($r);
3719 $recipient = api_get_user($a, $r[0]['nurl']);
3722 $recipient = api_get_user($a, $_POST['user_id']);
3725 if (empty($recipient)) {
3726 throw new NotFoundException('Recipient not found');
3730 if (!empty($_REQUEST['replyto'])) {
3732 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3734 intval($_REQUEST['replyto'])
3736 $replyto = $r[0]['parent-uri'];
3737 $sub = $r[0]['title'];
3739 if (!empty($_REQUEST['title'])) {
3740 $sub = $_REQUEST['title'];
3742 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3746 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3749 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3750 $ret = api_format_messages($r[0], $recipient, $sender);
3752 $ret = ["error"=>$id];
3755 $data = ['direct_message'=>$ret];
3761 $data = api_rss_extra($a, $data, $sender);
3765 return api_format_data("direct-messages", $type, $data);
3768 /// @TODO move to top of file or somewhere better
3769 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3772 * delete a direct_message from mail table through api
3774 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3775 * @return string|array
3776 * @throws BadRequestException
3777 * @throws ForbiddenException
3778 * @throws ImagickException
3779 * @throws InternalServerErrorException
3780 * @throws UnauthorizedException
3781 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3783 function api_direct_messages_destroy($type)
3787 if (api_user() === false) {
3788 throw new ForbiddenException();
3792 $user_info = api_get_user($a);
3794 $id = $_REQUEST['id'] ?? 0;
3796 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3797 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3798 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3800 $uid = $user_info['uid'];
3801 // error if no id or parenturi specified (for clients posting parent-uri as well)
3802 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3803 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3804 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3807 // BadRequestException if no id specified (for clients using Twitter API)
3809 throw new BadRequestException('Message id not specified');
3812 // add parent-uri to sql command if specified by calling app
3813 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3815 // get data of the specified message id
3817 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3822 // error message if specified id is not in database
3823 if (!DBA::isResult($r)) {
3824 if ($verbose == "true") {
3825 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3826 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3828 /// @todo BadRequestException ok for Twitter API clients?
3829 throw new BadRequestException('message id not in database');
3834 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3839 if ($verbose == "true") {
3842 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3843 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3845 $answer = ['result' => 'error', 'message' => 'unknown error'];
3846 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3849 /// @todo return JSON data like Twitter API not yet implemented
3852 /// @TODO move to top of file or somewhere better
3853 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3858 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3859 * @return string|array
3860 * @throws BadRequestException
3861 * @throws ForbiddenException
3862 * @throws ImagickException
3863 * @throws InternalServerErrorException
3864 * @throws NotFoundException
3865 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3867 function api_friendships_destroy($type)
3871 if ($uid === false) {
3872 throw new ForbiddenException();
3875 $contact_id = $_REQUEST['user_id'] ?? 0;
3877 if (empty($contact_id)) {
3878 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3879 throw new BadRequestException("no user_id specified");
3882 // Get Contact by given id
3883 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3885 if(!DBA::isResult($contact)) {
3886 Logger::notice(API_LOG_PREFIX . 'No contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3887 throw new NotFoundException("no contact found to given ID");
3890 $url = $contact["url"];
3892 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3893 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3894 Strings::normaliseLink($url), $url];
3895 $contact = DBA::selectFirst('contact', [], $condition);
3897 if (!DBA::isResult($contact)) {
3898 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3899 throw new NotFoundException("Not following Contact");
3902 if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
3903 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3904 throw new ExpectationFailedException("Not supported");
3907 $dissolve = ($contact['rel'] == Contact::SHARING);
3909 $owner = User::getOwnerDataById($uid);
3911 Contact::terminateFriendship($owner, $contact, $dissolve);
3914 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3915 throw new NotFoundException("Error Processing Request");
3918 // Sharing-only contacts get deleted as there no relationship any more
3920 Contact::remove($contact['id']);
3922 DBA::update('contact', ['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
3925 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3926 unset($contact["uid"]);
3927 unset($contact["self"]);
3929 // Set screen_name since Twidere requests it
3930 $contact["screen_name"] = $contact["nick"];
3932 return api_format_data("friendships-destroy", $type, ['user' => $contact]);
3934 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3938 * @param string $type Return type (atom, rss, xml, json)
3939 * @param string $box
3940 * @param string $verbose
3942 * @return array|string
3943 * @throws BadRequestException
3944 * @throws ForbiddenException
3945 * @throws ImagickException
3946 * @throws InternalServerErrorException
3947 * @throws UnauthorizedException
3949 function api_direct_messages_box($type, $box, $verbose)
3952 if (api_user() === false) {
3953 throw new ForbiddenException();
3956 $count = $_GET['count'] ?? 20;
3957 $page = $_REQUEST['page'] ?? 1;
3959 $since_id = $_REQUEST['since_id'] ?? 0;
3960 $max_id = $_REQUEST['max_id'] ?? 0;
3962 $user_id = $_REQUEST['user_id'] ?? '';
3963 $screen_name = $_REQUEST['screen_name'] ?? '';
3966 unset($_REQUEST["user_id"]);
3967 unset($_GET["user_id"]);
3969 unset($_REQUEST["screen_name"]);
3970 unset($_GET["screen_name"]);
3972 $user_info = api_get_user($a);
3973 if ($user_info === false) {
3974 throw new ForbiddenException();
3976 $profile_url = $user_info["url"];
3979 $start = max(0, ($page - 1) * $count);
3984 if ($box=="sentbox") {
3985 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3986 } elseif ($box == "conversation") {
3987 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3988 } elseif ($box == "all") {
3989 $sql_extra = "true";
3990 } elseif ($box == "inbox") {
3991 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3995 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3998 if ($user_id != "") {
3999 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
4000 } elseif ($screen_name !="") {
4001 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
4005 "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",
4011 if ($verbose == "true" && !DBA::isResult($r)) {
4012 $answer = ['result' => 'error', 'message' => 'no mails available'];
4013 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
4017 foreach ($r as $item) {
4018 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4019 $recipient = $user_info;
4020 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4021 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4022 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
4023 $sender = $user_info;
4026 if (isset($recipient) && isset($sender)) {
4027 $ret[] = api_format_messages($item, $recipient, $sender);
4032 $data = ['direct_message' => $ret];
4037 $data = api_rss_extra($a, $data, $user_info);
4041 return api_format_data("direct-messages", $type, $data);
4045 * Returns the most recent direct messages sent by the user.
4047 * @param string $type Return type (atom, rss, xml, json)
4049 * @return array|string
4050 * @throws BadRequestException
4051 * @throws ForbiddenException
4052 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
4054 function api_direct_messages_sentbox($type)
4056 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4057 return api_direct_messages_box($type, "sentbox", $verbose);
4061 * Returns the most recent direct messages sent to the user.
4063 * @param string $type Return type (atom, rss, xml, json)
4065 * @return array|string
4066 * @throws BadRequestException
4067 * @throws ForbiddenException
4068 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
4070 function api_direct_messages_inbox($type)
4072 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4073 return api_direct_messages_box($type, "inbox", $verbose);
4078 * @param string $type Return type (atom, rss, xml, json)
4080 * @return array|string
4081 * @throws BadRequestException
4082 * @throws ForbiddenException
4084 function api_direct_messages_all($type)
4086 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4087 return api_direct_messages_box($type, "all", $verbose);
4092 * @param string $type Return type (atom, rss, xml, json)
4094 * @return array|string
4095 * @throws BadRequestException
4096 * @throws ForbiddenException
4098 function api_direct_messages_conversation($type)
4100 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4101 return api_direct_messages_box($type, "conversation", $verbose);
4104 /// @TODO move to top of file or somewhere better
4105 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4106 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4107 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4108 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4111 * Returns an OAuth Request Token.
4113 * @see https://oauth.net/core/1.0/#auth_step1
4115 function api_oauth_request_token()
4117 $oauth1 = new FKOAuth1();
4119 $r = $oauth1->fetch_request_token(OAuthRequest::from_request());
4120 } catch (Exception $e) {
4121 echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage());
4129 * Returns an OAuth Access Token.
4131 * @return array|string
4132 * @see https://oauth.net/core/1.0/#auth_step3
4134 function api_oauth_access_token()
4136 $oauth1 = new FKOAuth1();
4138 $r = $oauth1->fetch_access_token(OAuthRequest::from_request());
4139 } catch (Exception $e) {
4140 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage());
4147 /// @TODO move to top of file or somewhere better
4148 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
4149 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
4153 * delete a complete photoalbum with all containing photos from database through api
4155 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4156 * @return string|array
4157 * @throws BadRequestException
4158 * @throws ForbiddenException
4159 * @throws InternalServerErrorException
4161 function api_fr_photoalbum_delete($type)
4163 if (api_user() === false) {
4164 throw new ForbiddenException();
4167 $album = $_REQUEST['album'] ?? '';
4169 // we do not allow calls without album string
4171 throw new BadRequestException("no albumname specified");
4173 // check if album is existing
4175 "SELECT DISTINCT `resource-id` FROM `photo` WHERE `uid` = %d AND `album` = '%s'",
4179 if (!DBA::isResult($r)) {
4180 throw new BadRequestException("album not available");
4183 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4184 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4185 foreach ($r as $rr) {
4186 $condition = ['uid' => local_user(), 'resource-id' => $rr['resource-id'], 'type' => 'photo'];
4187 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4189 if (!DBA::isResult($photo_item)) {
4190 throw new InternalServerErrorException("problem with deleting items occured");
4192 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4195 // now let's delete all photos from the album
4196 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4198 // return success of deletion or error message
4200 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4201 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4203 throw new InternalServerErrorException("unknown error - deleting from database failed");
4208 * update the name of the album for all photos of an album
4210 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4211 * @return string|array
4212 * @throws BadRequestException
4213 * @throws ForbiddenException
4214 * @throws InternalServerErrorException
4216 function api_fr_photoalbum_update($type)
4218 if (api_user() === false) {
4219 throw new ForbiddenException();
4222 $album = $_REQUEST['album'] ?? '';
4223 $album_new = $_REQUEST['album_new'] ?? '';
4225 // we do not allow calls without album string
4227 throw new BadRequestException("no albumname specified");
4229 if ($album_new == "") {
4230 throw new BadRequestException("no new albumname specified");
4232 // check if album is existing
4233 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4234 throw new BadRequestException("album not available");
4236 // now let's update all photos to the albumname
4237 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4239 // return success of updating or error message
4241 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4242 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4244 throw new InternalServerErrorException("unknown error - updating in database failed");
4250 * list all photos of the authenticated user
4252 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4253 * @return string|array
4254 * @throws ForbiddenException
4255 * @throws InternalServerErrorException
4257 function api_fr_photos_list($type)
4259 if (api_user() === false) {
4260 throw new ForbiddenException();
4263 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4264 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4265 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4266 intval(local_user())
4269 'image/jpeg' => 'jpg',
4270 'image/png' => 'png',
4271 'image/gif' => 'gif'
4273 $data = ['photo'=>[]];
4274 if (DBA::isResult($r)) {
4275 foreach ($r as $rr) {
4277 $photo['id'] = $rr['resource-id'];
4278 $photo['album'] = $rr['album'];
4279 $photo['filename'] = $rr['filename'];
4280 $photo['type'] = $rr['type'];
4281 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4282 $photo['created'] = $rr['created'];
4283 $photo['edited'] = $rr['edited'];
4284 $photo['desc'] = $rr['desc'];
4286 if ($type == "xml") {
4287 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4289 $photo['thumb'] = $thumb;
4290 $data['photo'][] = $photo;
4294 return api_format_data("photos", $type, $data);
4298 * upload a new photo or change an existing photo
4300 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4301 * @return string|array
4302 * @throws BadRequestException
4303 * @throws ForbiddenException
4304 * @throws ImagickException
4305 * @throws InternalServerErrorException
4306 * @throws NotFoundException
4308 function api_fr_photo_create_update($type)
4310 if (api_user() === false) {
4311 throw new ForbiddenException();
4314 $photo_id = $_REQUEST['photo_id'] ?? null;
4315 $desc = $_REQUEST['desc'] ?? null;
4316 $album = $_REQUEST['album'] ?? null;
4317 $album_new = $_REQUEST['album_new'] ?? null;
4318 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4319 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4320 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4321 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4322 $visibility = !empty($_REQUEST['visibility']) && $_REQUEST['visibility'] !== "false";
4324 // do several checks on input parameters
4325 // we do not allow calls without album string
4326 if ($album == null) {
4327 throw new BadRequestException("no albumname specified");
4329 // if photo_id == null --> we are uploading a new photo
4330 if ($photo_id == null) {
4333 // error if no media posted in create-mode
4334 if (empty($_FILES['media'])) {
4336 throw new BadRequestException("no media data submitted");
4339 // album_new will be ignored in create-mode
4344 // check if photo is existing in databasei
4345 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4346 throw new BadRequestException("photo not available");
4350 // checks on acl strings provided by clients
4351 $acl_input_error = false;
4352 $acl_input_error |= check_acl_input($allow_cid);
4353 $acl_input_error |= check_acl_input($deny_cid);
4354 $acl_input_error |= check_acl_input($allow_gid);
4355 $acl_input_error |= check_acl_input($deny_gid);
4356 if ($acl_input_error) {
4357 throw new BadRequestException("acl data invalid");
4359 // now let's upload the new media in create-mode
4360 if ($mode == "create") {
4361 $media = $_FILES['media'];
4362 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4364 // return success of updating or error message
4365 if (!is_null($data)) {
4366 return api_format_data("photo_create", $type, $data);
4368 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4372 // now let's do the changes in update-mode
4373 if ($mode == "update") {
4374 $updated_fields = [];
4376 if (!is_null($desc)) {
4377 $updated_fields['desc'] = $desc;
4380 if (!is_null($album_new)) {
4381 $updated_fields['album'] = $album_new;
4384 if (!is_null($allow_cid)) {
4385 $allow_cid = trim($allow_cid);
4386 $updated_fields['allow_cid'] = $allow_cid;
4389 if (!is_null($deny_cid)) {
4390 $deny_cid = trim($deny_cid);
4391 $updated_fields['deny_cid'] = $deny_cid;
4394 if (!is_null($allow_gid)) {
4395 $allow_gid = trim($allow_gid);
4396 $updated_fields['allow_gid'] = $allow_gid;
4399 if (!is_null($deny_gid)) {
4400 $deny_gid = trim($deny_gid);
4401 $updated_fields['deny_gid'] = $deny_gid;
4405 if (count($updated_fields) > 0) {
4406 $nothingtodo = false;
4407 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4409 $nothingtodo = true;
4412 if (!empty($_FILES['media'])) {
4413 $nothingtodo = false;
4414 $media = $_FILES['media'];
4415 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4416 if (!is_null($data)) {
4417 return api_format_data("photo_update", $type, $data);
4421 // return success of updating or error message
4423 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4424 return api_format_data("photo_update", $type, ['$result' => $answer]);
4427 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4428 return api_format_data("photo_update", $type, ['$result' => $answer]);
4430 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4433 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4437 * delete a single photo from the database through api
4439 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4440 * @return string|array
4441 * @throws BadRequestException
4442 * @throws ForbiddenException
4443 * @throws InternalServerErrorException
4445 function api_fr_photo_delete($type)
4447 if (api_user() === false) {
4448 throw new ForbiddenException();
4452 $photo_id = $_REQUEST['photo_id'] ?? null;
4454 // do several checks on input parameters
4455 // we do not allow calls without photo id
4456 if ($photo_id == null) {
4457 throw new BadRequestException("no photo_id specified");
4460 // check if photo is existing in database
4461 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4462 throw new BadRequestException("photo not available");
4465 // now we can perform on the deletion of the photo
4466 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4468 // return success of deletion or error message
4470 // retrieve the id of the parent element (the photo element)
4471 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4472 $photo_item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4474 if (!DBA::isResult($photo_item)) {
4475 throw new InternalServerErrorException("problem with deleting items occured");
4477 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4478 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4479 Item::deleteForUser(['id' => $photo_item['id']], api_user());
4481 $answer = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4482 return api_format_data("photo_delete", $type, ['$result' => $answer]);
4484 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4490 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4492 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4493 * @return string|array
4494 * @throws BadRequestException
4495 * @throws ForbiddenException
4496 * @throws InternalServerErrorException
4497 * @throws NotFoundException
4499 function api_fr_photo_detail($type)
4501 if (api_user() === false) {
4502 throw new ForbiddenException();
4504 if (empty($_REQUEST['photo_id'])) {
4505 throw new BadRequestException("No photo id.");
4508 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4509 $photo_id = $_REQUEST['photo_id'];
4511 // prepare json/xml output with data from database for the requested photo
4512 $data = prepare_photo_data($type, $scale, $photo_id);
4514 return api_format_data("photo_detail", $type, $data);
4519 * updates the profile image for the user (either a specified profile or the default profile)
4521 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4523 * @return string|array
4524 * @throws BadRequestException
4525 * @throws ForbiddenException
4526 * @throws ImagickException
4527 * @throws InternalServerErrorException
4528 * @throws NotFoundException
4529 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4531 function api_account_update_profile_image($type)
4533 if (api_user() === false) {
4534 throw new ForbiddenException();
4537 $profile_id = $_REQUEST['profile_id'] ?? 0;
4539 // error if image data is missing
4540 if (empty($_FILES['image'])) {
4541 throw new BadRequestException("no media data submitted");
4544 // check if specified profile id is valid
4545 if ($profile_id != 0) {
4546 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4547 // error message if specified profile id is not in database
4548 if (!DBA::isResult($profile)) {
4549 throw new BadRequestException("profile_id not available");
4551 $is_default_profile = $profile['is-default'];
4553 $is_default_profile = 1;
4556 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4558 if (!empty($_FILES['image'])) {
4559 $media = $_FILES['image'];
4560 } elseif (!empty($_FILES['media'])) {
4561 $media = $_FILES['media'];
4563 // save new profile image
4564 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4567 if (is_array($media['type'])) {
4568 $filetype = $media['type'][0];
4570 $filetype = $media['type'];
4572 if ($filetype == "image/jpeg") {
4574 } elseif ($filetype == "image/png") {
4577 throw new InternalServerErrorException('Unsupported filetype');
4580 // change specified profile or all profiles to the new resource-id
4581 if ($is_default_profile) {
4582 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4583 Photo::update(['profile' => false], $condition);
4585 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4586 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4587 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4590 Contact::updateSelfFromUserID(api_user(), true);
4592 // Update global directory in background
4593 $url = DI::baseUrl() . '/profile/' . DI::app()->user['nickname'];
4594 if ($url && strlen(DI::config()->get('system', 'directory'))) {
4595 Worker::add(PRIORITY_LOW, "Directory", $url);
4598 Worker::add(PRIORITY_LOW, 'ProfileUpdate', api_user());
4600 // output for client
4602 return api_account_verify_credentials($type);
4604 // SaveMediaToDatabase failed for some reason
4605 throw new InternalServerErrorException("image upload failed");
4609 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4610 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4611 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4612 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4613 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4614 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4615 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4616 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4617 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4620 * Update user profile
4622 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4624 * @return array|string
4625 * @throws BadRequestException
4626 * @throws ForbiddenException
4627 * @throws ImagickException
4628 * @throws InternalServerErrorException
4629 * @throws UnauthorizedException
4631 function api_account_update_profile($type)
4633 $local_user = api_user();
4634 $api_user = api_get_user(DI::app());
4636 if (!empty($_POST['name'])) {
4637 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4638 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4639 DBA::update('contact', ['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4640 DBA::update('contact', ['name' => $_POST['name']], ['id' => $api_user['id']]);
4643 if (isset($_POST['description'])) {
4644 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4645 DBA::update('contact', ['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4646 DBA::update('contact', ['about' => $_POST['description']], ['id' => $api_user['id']]);
4649 Worker::add(PRIORITY_LOW, 'ProfileUpdate', $local_user);
4650 // Update global directory in background
4651 if ($api_user['url'] && strlen(DI::config()->get('system', 'directory'))) {
4652 Worker::add(PRIORITY_LOW, "Directory", $api_user['url']);
4655 return api_account_verify_credentials($type);
4658 /// @TODO move to top of file or somewhere better
4659 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4663 * @param string $acl_string
4667 function check_acl_input($acl_string)
4669 if (empty($acl_string)) {
4673 $contact_not_found = false;
4675 // split <x><y><z> into array of cid's
4676 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4678 // check for each cid if it is available on server
4679 $cid_array = $array[0];
4680 foreach ($cid_array as $cid) {
4681 $cid = str_replace("<", "", $cid);
4682 $cid = str_replace(">", "", $cid);
4683 $condition = ['id' => $cid, 'uid' => api_user()];
4684 $contact_not_found |= !DBA::exists('contact', $condition);
4686 return $contact_not_found;
4690 * @param string $mediatype
4691 * @param array $media
4692 * @param string $type
4693 * @param string $album
4694 * @param string $allow_cid
4695 * @param string $deny_cid
4696 * @param string $allow_gid
4697 * @param string $deny_gid
4698 * @param string $desc
4699 * @param integer $profile
4700 * @param boolean $visibility
4701 * @param string $photo_id
4703 * @throws BadRequestException
4704 * @throws ForbiddenException
4705 * @throws ImagickException
4706 * @throws InternalServerErrorException
4707 * @throws NotFoundException
4708 * @throws UnauthorizedException
4710 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)
4718 if (is_array($media)) {
4719 if (is_array($media['tmp_name'])) {
4720 $src = $media['tmp_name'][0];
4722 $src = $media['tmp_name'];
4724 if (is_array($media['name'])) {
4725 $filename = basename($media['name'][0]);
4727 $filename = basename($media['name']);
4729 if (is_array($media['size'])) {
4730 $filesize = intval($media['size'][0]);
4732 $filesize = intval($media['size']);
4734 if (is_array($media['type'])) {
4735 $filetype = $media['type'][0];
4737 $filetype = $media['type'];
4741 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4744 "File upload src: " . $src . " - filename: " . $filename .
4745 " - size: " . $filesize . " - type: " . $filetype,
4749 // check if there was a php upload error
4750 if ($filesize == 0 && $media['error'] == 1) {
4751 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4753 // check against max upload size within Friendica instance
4754 $maximagesize = DI::config()->get('system', 'maximagesize');
4755 if ($maximagesize && ($filesize > $maximagesize)) {
4756 $formattedBytes = Strings::formatBytes($maximagesize);
4757 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4760 // create Photo instance with the data of the image
4761 $imagedata = @file_get_contents($src);
4762 $Image = new Image($imagedata, $filetype);
4763 if (!$Image->isValid()) {
4764 throw new InternalServerErrorException("unable to process image data");
4767 // check orientation of image
4768 $Image->orient($src);
4771 // check max length of images on server
4772 $max_length = DI::config()->get('system', 'max_image_length');
4774 $max_length = MAX_IMAGE_LENGTH;
4776 if ($max_length > 0) {
4777 $Image->scaleDown($max_length);
4778 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4780 $width = $Image->getWidth();
4781 $height = $Image->getHeight();
4783 // create a new resource-id if not already provided
4784 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4786 if ($mediatype == "photo") {
4787 // upload normal image (scales 0, 1, 2)
4788 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4790 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4792 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4794 if ($width > 640 || $height > 640) {
4795 $Image->scaleDown(640);
4796 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4798 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4802 if ($width > 320 || $height > 320) {
4803 $Image->scaleDown(320);
4804 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4806 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4809 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4810 } elseif ($mediatype == "profileimage") {
4811 // upload profile image (scales 4, 5, 6)
4812 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4814 if ($width > 300 || $height > 300) {
4815 $Image->scaleDown(300);
4816 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4818 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4822 if ($width > 80 || $height > 80) {
4823 $Image->scaleDown(80);
4824 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4826 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4830 if ($width > 48 || $height > 48) {
4831 $Image->scaleDown(48);
4832 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4834 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4837 $Image->__destruct();
4838 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4841 if (isset($r) && $r) {
4842 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4843 if ($photo_id == null && $mediatype == "photo") {
4844 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4846 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4847 return prepare_photo_data($type, false, $resource_id);
4849 throw new InternalServerErrorException("image upload failed");
4855 * @param string $hash
4856 * @param string $allow_cid
4857 * @param string $deny_cid
4858 * @param string $allow_gid
4859 * @param string $deny_gid
4860 * @param string $filetype
4861 * @param boolean $visibility
4862 * @throws InternalServerErrorException
4864 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4866 // get data about the api authenticated user
4867 $uri = Item::newURI(intval(api_user()));
4868 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4871 $arr['guid'] = System::createUUID();
4872 $arr['uid'] = intval(api_user());
4874 $arr['parent-uri'] = $uri;
4875 $arr['type'] = 'photo';
4877 $arr['resource-id'] = $hash;
4878 $arr['contact-id'] = $owner_record['id'];
4879 $arr['owner-name'] = $owner_record['name'];
4880 $arr['owner-link'] = $owner_record['url'];
4881 $arr['owner-avatar'] = $owner_record['thumb'];
4882 $arr['author-name'] = $owner_record['name'];
4883 $arr['author-link'] = $owner_record['url'];
4884 $arr['author-avatar'] = $owner_record['thumb'];
4886 $arr['allow_cid'] = $allow_cid;
4887 $arr['allow_gid'] = $allow_gid;
4888 $arr['deny_cid'] = $deny_cid;
4889 $arr['deny_gid'] = $deny_gid;
4890 $arr['visible'] = $visibility;
4894 'image/jpeg' => 'jpg',
4895 'image/png' => 'png',
4896 'image/gif' => 'gif'
4899 // adds link to the thumbnail scale photo
4900 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4901 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4904 // do the magic for storing the item in the database and trigger the federation to other contacts
4910 * @param string $type
4912 * @param string $photo_id
4915 * @throws BadRequestException
4916 * @throws ForbiddenException
4917 * @throws ImagickException
4918 * @throws InternalServerErrorException
4919 * @throws NotFoundException
4920 * @throws UnauthorizedException
4922 function prepare_photo_data($type, $scale, $photo_id)
4925 $user_info = api_get_user($a);
4927 if ($user_info === false) {
4928 throw new ForbiddenException();
4931 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4932 $data_sql = ($scale === false ? "" : "data, ");
4934 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4935 // clients needs to convert this in their way for further processing
4937 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4938 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4939 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4940 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4941 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4942 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4944 intval(local_user()),
4945 DBA::escape($photo_id),
4950 'image/jpeg' => 'jpg',
4951 'image/png' => 'png',
4952 'image/gif' => 'gif'
4955 // prepare output data for photo
4956 if (DBA::isResult($r)) {
4957 $data = ['photo' => $r[0]];
4958 $data['photo']['id'] = $data['photo']['resource-id'];
4959 if ($scale !== false) {
4960 $data['photo']['data'] = base64_encode($data['photo']['data']);
4962 unset($data['photo']['datasize']); //needed only with scale param
4964 if ($type == "xml") {
4965 $data['photo']['links'] = [];
4966 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4967 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4969 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4972 $data['photo']['link'] = [];
4973 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4975 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4976 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4980 unset($data['photo']['resource-id']);
4981 unset($data['photo']['minscale']);
4982 unset($data['photo']['maxscale']);
4984 throw new NotFoundException();
4987 // retrieve item element for getting activities (like, dislike etc.) related to photo
4988 $condition = ['uid' => local_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4989 $item = Item::selectFirstForUser(local_user(), ['id'], $condition);
4990 if (!DBA::isResult($item)) {
4991 throw new NotFoundException('Photo-related item not found.');
4994 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4996 // retrieve comments on photo
4997 $condition = ["`parent` = ? AND `uid` = ? AND (`gravity` IN (?, ?) OR `type`='photo')",
4998 $item[0]['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
5000 $statuses = Item::selectForUser(api_user(), [], $condition);
5002 // prepare output of comments
5003 $commentData = api_format_items(Item::inArray($statuses), $user_info, false, $type);
5005 if ($type == "xml") {
5007 foreach ($commentData as $comment) {
5008 $comments[$k++ . ":comment"] = $comment;
5011 foreach ($commentData as $comment) {
5012 $comments[] = $comment;
5015 $data['photo']['friendica_comments'] = $comments;
5017 // include info if rights on photo and rights on item are mismatching
5018 $rights_mismatch = $data['photo']['allow_cid'] != $item[0]['allow_cid'] ||
5019 $data['photo']['deny_cid'] != $item[0]['deny_cid'] ||
5020 $data['photo']['allow_gid'] != $item[0]['allow_gid'] ||
5021 $data['photo']['deny_cid'] != $item[0]['deny_cid'];
5022 $data['photo']['rights_mismatch'] = $rights_mismatch;
5029 * Similar as /mod/redir.php
5030 * redirect to 'url' after dfrn auth
5032 * Why this when there is mod/redir.php already?
5033 * This use api_user() and api_login()
5036 * c_url: url of remote contact to auth to
5037 * url: string, url to redirect after auth
5039 function api_friendica_remoteauth()
5041 $url = $_GET['url'] ?? '';
5042 $c_url = $_GET['c_url'] ?? '';
5044 if ($url === '' || $c_url === '') {
5045 throw new BadRequestException("Wrong parameters.");
5048 $c_url = Strings::normaliseLink($c_url);
5052 $contact = DBA::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]);
5053 if (!DBA::isResult($contact)) {
5054 throw new BadRequestException("Unknown contact");
5057 $cid = $contact['id'];
5059 $dfrn_id = $contact['issued-id'] ?: $contact['dfrn-id'];
5061 if (($contact['network'] !== Protocol::DFRN) || empty($dfrn_id)) {
5062 System::externalRedirect($url ?: $c_url);
5065 if ($contact['duplex'] && $contact['issued-id']) {
5066 $orig_id = $contact['issued-id'];
5067 $dfrn_id = '1:' . $orig_id;
5069 if ($contact['duplex'] && $contact['dfrn-id']) {
5070 $orig_id = $contact['dfrn-id'];
5071 $dfrn_id = '0:' . $orig_id;
5074 $sec = Strings::getRandomHex();
5076 $fields = ['uid' => api_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id,
5077 'sec' => $sec, 'expire' => time() + 45];
5078 DBA::insert('profile_check', $fields);
5080 Logger::info(API_LOG_PREFIX . 'for contact {contact}', ['module' => 'api', 'action' => 'friendica_remoteauth', 'contact' => $contact['name'], 'hey' => $sec]);
5081 $dest = ($url ? '&destination_url=' . $url : '');
5083 System::externalRedirect(
5084 $contact['poll'] . '?dfrn_id=' . $dfrn_id
5085 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
5086 . '&type=profile&sec=' . $sec . $dest
5089 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
5092 * Return an item with announcer data if it had been announced
5094 * @param array $item Item array
5095 * @return array Item array with announce data
5097 function api_get_announce($item)
5099 // Quit if the item already has got a different owner and author
5100 if ($item['owner-id'] != $item['author-id']) {
5104 // Don't change original or Diaspora posts
5105 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
5109 // Quit if we do now the original author and it had been a post from a native network
5110 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
5114 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
5115 $activity = Item::activityToIndex(Activity::ANNOUNCE);
5116 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity];
5117 $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
5118 if (!DBA::isResult($announce)) {
5122 return array_merge($item, $announce);
5126 * Return the item shared, if the item contains only the [share] tag
5128 * @param array $item Sharer item
5129 * @return array|false Shared item or false if not a reshare
5130 * @throws ImagickException
5131 * @throws InternalServerErrorException
5133 function api_share_as_retweet(&$item)
5135 $body = trim($item["body"]);
5137 if (Diaspora::isReshare($body, false) === false) {
5138 if ($item['author-id'] == $item['owner-id']) {
5141 // Reshares from OStatus, ActivityPub and Twitter
5142 $reshared_item = $item;
5143 $reshared_item['owner-id'] = $reshared_item['author-id'];
5144 $reshared_item['owner-link'] = $reshared_item['author-link'];
5145 $reshared_item['owner-name'] = $reshared_item['author-name'];
5146 $reshared_item['owner-avatar'] = $reshared_item['author-avatar'];
5147 return $reshared_item;
5151 $reshared = Item::getShareArray($item);
5152 if (empty($reshared)) {
5156 $reshared_item = $item;
5158 if (empty($reshared['shared']) || empty($reshared['profile']) || empty($reshared['author']) || empty($reshared['avatar']) || empty($reshared['posted'])) {
5162 if (!empty($reshared['comment'])) {
5163 $item['body'] = $reshared['comment'];
5166 $reshared_item["share-pre-body"] = $reshared['comment'];
5167 $reshared_item["body"] = $reshared['shared'];
5168 $reshared_item["author-id"] = Contact::getIdForURL($reshared['profile'], 0, true);
5169 $reshared_item["author-name"] = $reshared['author'];
5170 $reshared_item["author-link"] = $reshared['profile'];
5171 $reshared_item["author-avatar"] = $reshared['avatar'];
5172 $reshared_item["plink"] = $reshared['link'] ?? '';
5173 $reshared_item["created"] = $reshared['posted'];
5174 $reshared_item["edited"] = $reshared['posted'];
5176 // Try to fetch the original item
5177 if (!empty($reshared['guid'])) {
5178 $condition = ['guid' => $reshared['guid'], 'uid' => [0, $item['uid']]];
5179 } elseif (!empty($reshared_item['plink']) && ($original_id = Item::searchByLink($reshared_item['plink']))) {
5180 $condition = ['id' => $original_id];
5185 if (!empty($condition)) {
5186 $original_item = Item::selectFirst([], $condition);
5187 if (DBA::isResult($original_item)) {
5188 $reshared_item = array_merge($reshared_item, $original_item);
5192 return $reshared_item;
5197 * @param array $item
5202 function api_in_reply_to($item)
5206 $in_reply_to['status_id'] = null;
5207 $in_reply_to['user_id'] = null;
5208 $in_reply_to['status_id_str'] = null;
5209 $in_reply_to['user_id_str'] = null;
5210 $in_reply_to['screen_name'] = null;
5212 if (($item['thr-parent'] != $item['uri']) && (intval($item['parent']) != intval($item['id']))) {
5213 $parent = Item::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
5214 if (DBA::isResult($parent)) {
5215 $in_reply_to['status_id'] = intval($parent['id']);
5217 $in_reply_to['status_id'] = intval($item['parent']);
5220 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
5222 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
5223 $parent = Item::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
5225 if (DBA::isResult($parent)) {
5226 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
5227 $in_reply_to['user_id'] = intval($parent['author-id']);
5228 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
5231 // There seems to be situation, where both fields are identical:
5232 // https://github.com/friendica/friendica/issues/1010
5233 // This is a bugfix for that.
5234 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
5235 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']]);
5236 $in_reply_to['status_id'] = null;
5237 $in_reply_to['user_id'] = null;
5238 $in_reply_to['status_id_str'] = null;
5239 $in_reply_to['user_id_str'] = null;
5240 $in_reply_to['screen_name'] = null;
5244 return $in_reply_to;
5249 * @param string $text
5252 * @throws InternalServerErrorException
5254 function api_clean_plain_items($text)
5256 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
5258 $text = BBCode::cleanPictureLinks($text);
5259 $URLSearchString = "^\[\]";
5261 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
5263 if ($include_entities == "true") {
5264 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
5267 // Simplify "attachment" element
5268 $text = BBCode::removeAttachment($text);
5275 * @param array $contacts
5279 function api_best_nickname(&$contacts)
5283 if (count($contacts) == 0) {
5287 foreach ($contacts as $contact) {
5288 if ($contact["network"] == "") {
5289 $contact["network"] = "dfrn";
5290 $best_contact = [$contact];
5294 if (sizeof($best_contact) == 0) {
5295 foreach ($contacts as $contact) {
5296 if ($contact["network"] == "dfrn") {
5297 $best_contact = [$contact];
5302 if (sizeof($best_contact) == 0) {
5303 foreach ($contacts as $contact) {
5304 if ($contact["network"] == "dspr") {
5305 $best_contact = [$contact];
5310 if (sizeof($best_contact) == 0) {
5311 foreach ($contacts as $contact) {
5312 if ($contact["network"] == "stat") {
5313 $best_contact = [$contact];
5318 if (sizeof($best_contact) == 0) {
5319 foreach ($contacts as $contact) {
5320 if ($contact["network"] == "pump") {
5321 $best_contact = [$contact];
5326 if (sizeof($best_contact) == 0) {
5327 foreach ($contacts as $contact) {
5328 if ($contact["network"] == "twit") {
5329 $best_contact = [$contact];
5334 if (sizeof($best_contact) == 1) {
5335 $contacts = $best_contact;
5337 $contacts = [$contacts[0]];
5342 * Return all or a specified group of the user with the containing contacts.
5344 * @param string $type Return type (atom, rss, xml, json)
5346 * @return array|string
5347 * @throws BadRequestException
5348 * @throws ForbiddenException
5349 * @throws ImagickException
5350 * @throws InternalServerErrorException
5351 * @throws UnauthorizedException
5353 function api_friendica_group_show($type)
5357 if (api_user() === false) {
5358 throw new ForbiddenException();
5362 $user_info = api_get_user($a);
5363 $gid = $_REQUEST['gid'] ?? 0;
5364 $uid = $user_info['uid'];
5366 // get data of the specified group id or all groups if not specified
5369 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5373 // error message if specified gid is not in database
5374 if (!DBA::isResult($r)) {
5375 throw new BadRequestException("gid not available");
5379 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5384 // loop through all groups and retrieve all members for adding data in the user array
5386 foreach ($r as $rr) {
5387 $members = Contact::getByGroupId($rr['id']);
5390 if ($type == "xml") {
5391 $user_element = "users";
5393 foreach ($members as $member) {
5394 $user = api_get_user($a, $member['nurl']);
5395 $users[$k++.":user"] = $user;
5398 $user_element = "user";
5399 foreach ($members as $member) {
5400 $user = api_get_user($a, $member['nurl']);
5404 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5406 return api_format_data("groups", $type, ['group' => $grps]);
5408 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5412 * Delete the specified group of the user.
5414 * @param string $type Return type (atom, rss, xml, json)
5416 * @return array|string
5417 * @throws BadRequestException
5418 * @throws ForbiddenException
5419 * @throws ImagickException
5420 * @throws InternalServerErrorException
5421 * @throws UnauthorizedException
5423 function api_friendica_group_delete($type)
5427 if (api_user() === false) {
5428 throw new ForbiddenException();
5432 $user_info = api_get_user($a);
5433 $gid = $_REQUEST['gid'] ?? 0;
5434 $name = $_REQUEST['name'] ?? '';
5435 $uid = $user_info['uid'];
5437 // error if no gid specified
5438 if ($gid == 0 || $name == "") {
5439 throw new BadRequestException('gid or name not specified');
5442 // get data of the specified group id
5444 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5448 // error message if specified gid is not in database
5449 if (!DBA::isResult($r)) {
5450 throw new BadRequestException('gid not available');
5453 // get data of the specified group id and group name
5455 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5460 // error message if specified gid is not in database
5461 if (!DBA::isResult($rname)) {
5462 throw new BadRequestException('wrong group name');
5466 $ret = Group::removeByName($uid, $name);
5469 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5470 return api_format_data("group_delete", $type, ['result' => $success]);
5472 throw new BadRequestException('other API error');
5475 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5480 * @param string $type Return type (atom, rss, xml, json)
5482 * @return array|string
5483 * @throws BadRequestException
5484 * @throws ForbiddenException
5485 * @throws ImagickException
5486 * @throws InternalServerErrorException
5487 * @throws UnauthorizedException
5488 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5490 function api_lists_destroy($type)
5494 if (api_user() === false) {
5495 throw new ForbiddenException();
5499 $user_info = api_get_user($a);
5500 $gid = $_REQUEST['list_id'] ?? 0;
5501 $uid = $user_info['uid'];
5503 // error if no gid specified
5505 throw new BadRequestException('gid not specified');
5508 // get data of the specified group id
5509 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5510 // error message if specified gid is not in database
5512 throw new BadRequestException('gid not available');
5515 if (Group::remove($gid)) {
5517 'name' => $group['name'],
5518 'id' => intval($gid),
5519 'id_str' => (string) $gid,
5520 'user' => $user_info
5523 return api_format_data("lists", $type, ['lists' => $list]);
5526 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5529 * Add a new group to the database.
5531 * @param string $name Group name
5532 * @param int $uid User ID
5533 * @param array $users List of users to add to the group
5536 * @throws BadRequestException
5538 function group_create($name, $uid, $users = [])
5540 // error if no name specified
5542 throw new BadRequestException('group name not specified');
5545 // get data of the specified group name
5547 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5551 // error message if specified group name already exists
5552 if (DBA::isResult($rname)) {
5553 throw new BadRequestException('group name already exists');
5556 // check if specified group name is a deleted group
5558 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5562 // error message if specified group name already exists
5563 if (DBA::isResult($rname)) {
5564 $reactivate_group = true;
5568 $ret = Group::create($uid, $name);
5570 $gid = Group::getIdByName($uid, $name);
5572 throw new BadRequestException('other API error');
5576 $erroraddinguser = false;
5578 foreach ($users as $user) {
5579 $cid = $user['cid'];
5580 // check if user really exists as contact
5582 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5586 if (count($contact)) {
5587 Group::addMember($gid, $cid);
5589 $erroraddinguser = true;
5590 $errorusers[] = $cid;
5594 // return success message incl. missing users in array
5595 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5597 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5601 * Create the specified group with the posted array of contacts.
5603 * @param string $type Return type (atom, rss, xml, json)
5605 * @return array|string
5606 * @throws BadRequestException
5607 * @throws ForbiddenException
5608 * @throws ImagickException
5609 * @throws InternalServerErrorException
5610 * @throws UnauthorizedException
5612 function api_friendica_group_create($type)
5616 if (api_user() === false) {
5617 throw new ForbiddenException();
5621 $user_info = api_get_user($a);
5622 $name = $_REQUEST['name'] ?? '';
5623 $uid = $user_info['uid'];
5624 $json = json_decode($_POST['json'], true);
5625 $users = $json['user'];
5627 $success = group_create($name, $uid, $users);
5629 return api_format_data("group_create", $type, ['result' => $success]);
5631 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5634 * Create a new group.
5636 * @param string $type Return type (atom, rss, xml, json)
5638 * @return array|string
5639 * @throws BadRequestException
5640 * @throws ForbiddenException
5641 * @throws ImagickException
5642 * @throws InternalServerErrorException
5643 * @throws UnauthorizedException
5644 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5646 function api_lists_create($type)
5650 if (api_user() === false) {
5651 throw new ForbiddenException();
5655 $user_info = api_get_user($a);
5656 $name = $_REQUEST['name'] ?? '';
5657 $uid = $user_info['uid'];
5659 $success = group_create($name, $uid);
5660 if ($success['success']) {
5662 'name' => $success['name'],
5663 'id' => intval($success['gid']),
5664 'id_str' => (string) $success['gid'],
5665 'user' => $user_info
5668 return api_format_data("lists", $type, ['lists'=>$grp]);
5671 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5674 * Update the specified group with the posted array of contacts.
5676 * @param string $type Return type (atom, rss, xml, json)
5678 * @return array|string
5679 * @throws BadRequestException
5680 * @throws ForbiddenException
5681 * @throws ImagickException
5682 * @throws InternalServerErrorException
5683 * @throws UnauthorizedException
5685 function api_friendica_group_update($type)
5689 if (api_user() === false) {
5690 throw new ForbiddenException();
5694 $user_info = api_get_user($a);
5695 $uid = $user_info['uid'];
5696 $gid = $_REQUEST['gid'] ?? 0;
5697 $name = $_REQUEST['name'] ?? '';
5698 $json = json_decode($_POST['json'], true);
5699 $users = $json['user'];
5701 // error if no name specified
5703 throw new BadRequestException('group name not specified');
5706 // error if no gid specified
5708 throw new BadRequestException('gid not specified');
5712 $members = Contact::getByGroupId($gid);
5713 foreach ($members as $member) {
5714 $cid = $member['id'];
5715 foreach ($users as $user) {
5716 $found = ($user['cid'] == $cid ? true : false);
5718 if (!isset($found) || !$found) {
5719 Group::removeMemberByName($uid, $name, $cid);
5724 $erroraddinguser = false;
5726 foreach ($users as $user) {
5727 $cid = $user['cid'];
5728 // check if user really exists as contact
5730 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5735 if (count($contact)) {
5736 Group::addMember($gid, $cid);
5738 $erroraddinguser = true;
5739 $errorusers[] = $cid;
5743 // return success message incl. missing users in array
5744 $status = ($erroraddinguser ? "missing user" : "ok");
5745 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5746 return api_format_data("group_update", $type, ['result' => $success]);
5749 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5752 * Update information about a group.
5754 * @param string $type Return type (atom, rss, xml, json)
5756 * @return array|string
5757 * @throws BadRequestException
5758 * @throws ForbiddenException
5759 * @throws ImagickException
5760 * @throws InternalServerErrorException
5761 * @throws UnauthorizedException
5762 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5764 function api_lists_update($type)
5768 if (api_user() === false) {
5769 throw new ForbiddenException();
5773 $user_info = api_get_user($a);
5774 $gid = $_REQUEST['list_id'] ?? 0;
5775 $name = $_REQUEST['name'] ?? '';
5776 $uid = $user_info['uid'];
5778 // error if no gid specified
5780 throw new BadRequestException('gid not specified');
5783 // get data of the specified group id
5784 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5785 // error message if specified gid is not in database
5787 throw new BadRequestException('gid not available');
5790 if (Group::update($gid, $name)) {
5793 'id' => intval($gid),
5794 'id_str' => (string) $gid,
5795 'user' => $user_info
5798 return api_format_data("lists", $type, ['lists' => $list]);
5802 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5806 * @param string $type Return type (atom, rss, xml, json)
5808 * @return array|string
5809 * @throws BadRequestException
5810 * @throws ForbiddenException
5811 * @throws ImagickException
5812 * @throws InternalServerErrorException
5814 function api_friendica_activity($type)
5818 if (api_user() === false) {
5819 throw new ForbiddenException();
5821 $verb = strtolower($a->argv[3]);
5822 $verb = preg_replace("|\..*$|", "", $verb);
5824 $id = $_REQUEST['id'] ?? 0;
5826 $res = Item::performActivity($id, $verb);
5829 if ($type == "xml") {
5834 return api_format_data('ok', $type, ['ok' => $ok]);
5836 throw new BadRequestException('Error adding activity');
5840 /// @TODO move to top of file or somewhere better
5841 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5842 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5843 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5844 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5845 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5846 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5847 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5848 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5849 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5850 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5853 * Returns notifications
5855 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5857 * @return string|array
5858 * @throws ForbiddenException
5859 * @throws BadRequestException
5862 function api_friendica_notification($type)
5866 if (api_user() === false) {
5867 throw new ForbiddenException();
5870 throw new BadRequestException("Invalid argument count");
5873 $notifications = DI::notification()->getApiList(local_user());
5875 if ($type == "xml") {
5877 if (!empty($notifications)) {
5878 foreach ($notifications as $notification) {
5879 $xmlnotes[] = ["@attributes" => $notification->toArray()];
5883 $result = $xmlnotes;
5884 } elseif (count($notifications) > 0) {
5885 $result = $notifications->getArrayCopy();
5890 return api_format_data("notes", $type, ['note' => $result]);
5894 * Set notification as seen and returns associated item (if possible)
5896 * POST request with 'id' param as notification id
5898 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5899 * @return string|array
5900 * @throws BadRequestException
5901 * @throws ForbiddenException
5902 * @throws ImagickException
5903 * @throws InternalServerErrorException
5904 * @throws UnauthorizedException
5906 function api_friendica_notification_seen($type)
5909 $user_info = api_get_user($a);
5911 if (api_user() === false || $user_info === false) {
5912 throw new ForbiddenException();
5914 if ($a->argc !== 4) {
5915 throw new BadRequestException("Invalid argument count");
5918 $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0);
5921 $notify = DI::notify()->getByID($id, api_user());
5922 DI::notify()->setSeen(true, $notify);
5924 if ($notify->otype === Notify\ObjectType::ITEM) {
5925 $item = Item::selectFirstForUser(api_user(), [], ['id' => $notify->iid, 'uid' => api_user()]);
5926 if (DBA::isResult($item)) {
5927 // we found the item, return it to the user
5928 $ret = api_format_items([$item], $user_info, false, $type);
5929 $data = ['status' => $ret];
5930 return api_format_data("status", $type, $data);
5932 // the item can't be found, but we set the notification as seen, so we count this as a success
5934 return api_format_data('result', $type, ['result' => "success"]);
5935 } catch (NotFoundException $e) {
5936 throw new BadRequestException('Invalid argument', $e);
5937 } catch (Exception $e) {
5938 throw new InternalServerErrorException('Internal Server exception', $e);
5942 /// @TODO move to top of file or somewhere better
5943 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5944 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5947 * update a direct_message to seen state
5949 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5950 * @return string|array (success result=ok, error result=error with error message)
5951 * @throws BadRequestException
5952 * @throws ForbiddenException
5953 * @throws ImagickException
5954 * @throws InternalServerErrorException
5955 * @throws UnauthorizedException
5957 function api_friendica_direct_messages_setseen($type)
5960 if (api_user() === false) {
5961 throw new ForbiddenException();
5965 $user_info = api_get_user($a);
5966 $uid = $user_info['uid'];
5967 $id = $_REQUEST['id'] ?? 0;
5969 // return error if id is zero
5971 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5972 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5975 // error message if specified id is not in database
5976 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5977 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5978 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5981 // update seen indicator
5982 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5986 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5987 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5989 $answer = ['result' => 'error', 'message' => 'unknown error'];
5990 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5994 /// @TODO move to top of file or somewhere better
5995 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5998 * search for direct_messages containing a searchstring through api
6000 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
6001 * @param string $box
6002 * @return string|array (success: success=true if found and search_result contains found messages,
6003 * success=false if nothing was found, search_result='nothing found',
6004 * error: result=error with error message)
6005 * @throws BadRequestException
6006 * @throws ForbiddenException
6007 * @throws ImagickException
6008 * @throws InternalServerErrorException
6009 * @throws UnauthorizedException
6011 function api_friendica_direct_messages_search($type, $box = "")
6015 if (api_user() === false) {
6016 throw new ForbiddenException();
6020 $user_info = api_get_user($a);
6021 $searchstring = $_REQUEST['searchstring'] ?? '';
6022 $uid = $user_info['uid'];
6024 // error if no searchstring specified
6025 if ($searchstring == "") {
6026 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
6027 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
6030 // get data for the specified searchstring
6032 "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",
6034 DBA::escape('%'.$searchstring.'%')
6037 $profile_url = $user_info["url"];
6039 // message if nothing was found
6040 if (!DBA::isResult($r)) {
6041 $success = ['success' => false, 'search_results' => 'problem with query'];
6042 } elseif (count($r) == 0) {
6043 $success = ['success' => false, 'search_results' => 'nothing found'];
6046 foreach ($r as $item) {
6047 if ($box == "inbox" || $item['from-url'] != $profile_url) {
6048 $recipient = $user_info;
6049 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6050 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
6051 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
6052 $sender = $user_info;
6055 if (isset($recipient) && isset($sender)) {
6056 $ret[] = api_format_messages($item, $recipient, $sender);
6059 $success = ['success' => true, 'search_results' => $ret];
6062 return api_format_data("direct_message_search", $type, ['$result' => $success]);
6065 /// @TODO move to top of file or somewhere better
6066 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
6069 * Returns a list of saved searches.
6071 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
6073 * @param string $type Return format: json or xml
6075 * @return string|array
6078 function api_saved_searches_list($type)
6080 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
6083 while ($term = DBA::fetch($terms)) {
6085 'created_at' => api_date(time()),
6086 'id' => intval($term['id']),
6087 'id_str' => $term['id'],
6088 'name' => $term['term'],
6090 'query' => $term['term']
6096 return api_format_data("terms", $type, ['terms' => $result]);
6099 /// @TODO move to top of file or somewhere better
6100 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
6103 * Number of comments
6105 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
6107 * @param object $data [Status, Status]
6111 function bindComments(&$data)
6113 if (count($data) == 0) {
6119 foreach ($data as $item) {
6120 $ids[] = $item['id'];
6123 $idStr = DBA::escape(implode(', ', $ids));
6124 $sql = "SELECT `parent`, COUNT(*) as comments FROM `item` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
6125 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
6126 $itemsData = DBA::toArray($items);
6128 foreach ($itemsData as $item) {
6129 $comments[$item['parent']] = $item['comments'];
6132 foreach ($data as $idx => $item) {
6134 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
6139 @TODO Maybe open to implement?
6141 [pagename] => api/1.1/statuses/lookup.json
6142 [id] => 605138389168451584
6143 [include_cards] => true
6144 [cards_platform] => Android-12
6145 [include_entities] => true
6146 [include_my_retweet] => 1
6148 [include_reply_count] => true
6149 [include_descendent_reply_count] => true
6153 Not implemented by now:
6154 statuses/retweets_of_me
6159 account/update_location
6160 account/update_profile_background_image
6163 friendica/profile/update
6164 friendica/profile/create
6165 friendica/profile/delete
6167 Not implemented in status.net:
6168 statuses/retweeted_to_me
6169 statuses/retweeted_by_me
6170 direct_messages/destroy
6172 account/update_delivery_device
6173 notifications/follow