3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Collection\Api\Notifications as ApiNotifications;
28 use Friendica\Content\ContactSelector;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Content\Text\HTML;
31 use Friendica\Core\Hook;
32 use Friendica\Core\Logger;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\System;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Contact;
38 use Friendica\Model\Group;
39 use Friendica\Model\Item;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Notification;
42 use Friendica\Model\Photo;
43 use Friendica\Model\Post;
44 use Friendica\Model\Profile;
45 use Friendica\Model\User;
46 use Friendica\Model\Verb;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ExpectationFailedException;
50 use Friendica\Network\HTTPException\ForbiddenException;
51 use Friendica\Network\HTTPException\InternalServerErrorException;
52 use Friendica\Network\HTTPException\MethodNotAllowedException;
53 use Friendica\Network\HTTPException\NotFoundException;
54 use Friendica\Network\HTTPException\TooManyRequestsException;
55 use Friendica\Network\HTTPException\UnauthorizedException;
56 use Friendica\Object\Api\Friendica\Notification as ApiNotification;
57 use Friendica\Object\Image;
58 use Friendica\Protocol\Activity;
59 use Friendica\Protocol\Diaspora;
60 use Friendica\Security\OAuth;
61 use Friendica\Util\DateTimeFormat;
62 use Friendica\Util\Images;
63 use Friendica\Util\Network;
64 use Friendica\Util\Strings;
65 use Friendica\Util\XML;
67 require_once __DIR__ . '/../mod/item.php';
68 require_once __DIR__ . '/../mod/wall_upload.php';
70 define('API_METHOD_ANY', '*');
71 define('API_METHOD_GET', 'GET');
72 define('API_METHOD_POST', 'POST,PUT');
73 define('API_METHOD_DELETE', 'POST,DELETE');
75 define('API_LOG_PREFIX', 'API {action} - ');
83 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
84 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
85 * into a page, and visitors will post something without noticing it).
89 $user = OAuth::getCurrentUserID();
94 if (!empty($_SESSION['allow_api'])) {
102 * Get source name from API client
104 * Clients can send 'source' parameter to be show in post metadata
105 * as "sent via <source>".
106 * Some clients doesn't send a source param, we support ones we know
107 * (only Twidere, atm)
110 * Client source name, default to "api" if unset/unknown
113 function api_source()
115 if (requestdata('source')) {
116 return requestdata('source');
119 // Support for known clients that doesn't send a source name
120 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
121 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
125 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
127 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
134 * Format date for API
136 * @param string $str Source date, as UTC
137 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
140 function api_date($str)
142 // Wed May 23 06:01:13 +0000 2007
143 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
147 * Register a function to be the endpoint for defined API path.
149 * @param string $path API URL path, relative to DI::baseUrl()
150 * @param string $func Function name to call on path request
151 * @param bool $auth API need logged user
152 * @param string $method HTTP method reqiured to call this endpoint.
153 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
154 * Default to API_METHOD_ANY
156 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
166 // Workaround for hotot
167 $path = str_replace("api/", "api/1.1/", $path);
177 * Log in user via Simple HTTP Auth.
178 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
181 * @throws ForbiddenException
182 * @throws InternalServerErrorException
183 * @throws UnauthorizedException
184 * @hook 'authenticate'
186 * 'username' => username from login form
187 * 'password' => password from login form
188 * 'authenticated' => return status,
189 * 'user_record' => return authenticated user record
191 function api_login(App $a)
193 $_SESSION["allow_api"] = false;
195 // workaround for HTTP-auth in CGI mode
196 if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
197 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
198 if (strlen($userpass)) {
199 list($name, $password) = explode(':', $userpass);
200 $_SERVER['PHP_AUTH_USER'] = $name;
201 $_SERVER['PHP_AUTH_PW'] = $password;
205 if (empty($_SERVER['PHP_AUTH_USER'])) {
206 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
207 header('WWW-Authenticate: Basic realm="Friendica"');
208 throw new UnauthorizedException("This API requires login");
211 $user = $_SERVER['PHP_AUTH_USER'] ?? '';
212 $password = $_SERVER['PHP_AUTH_PW'] ?? '';
214 // allow "user@server" login (but ignore 'server' part)
215 $at = strstr($user, "@", true);
220 // next code from mod/auth.php. needs better solution
224 'username' => trim($user),
225 'password' => trim($password),
226 'authenticated' => 0,
227 'user_record' => null,
231 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
232 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
233 * and later addons should not interfere with an earlier one that succeeded.
235 Hook::callAll('authenticate', $addon_auth);
237 if ($addon_auth['authenticated'] && !empty($addon_auth['user_record'])) {
238 $record = $addon_auth['user_record'];
240 $user_id = User::authenticate(trim($user), trim($password), true);
241 if ($user_id !== false) {
242 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
246 if (!DBA::isResult($record)) {
247 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
248 header('WWW-Authenticate: Basic realm="Friendica"');
249 //header('HTTP/1.0 401 Unauthorized');
250 //die('This api requires login');
251 throw new UnauthorizedException("This API requires login");
254 // Don't refresh the login date more often than twice a day to spare database writes
255 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
257 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
259 $_SESSION["allow_api"] = true;
261 Hook::callAll('logged_in', $record);
265 * Check HTTP method of called API
267 * API endpoints can define which HTTP method to accept when called.
268 * This function check the current HTTP method agains endpoint
271 * @param string $method Required methods, uppercase, separated by comma
274 function api_check_method($method)
276 if ($method == "*") {
279 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
283 * Main API entry point
285 * Authenticate user, call registered API function, set HTTP headers
288 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
289 * @return string|array API call result
292 function api_call(App $a, App\Arguments $args = null)
294 global $API, $called_api;
301 if (strpos($args->getCommand(), ".xml") > 0) {
304 if (strpos($args->getCommand(), ".json") > 0) {
307 if (strpos($args->getCommand(), ".rss") > 0) {
310 if (strpos($args->getCommand(), ".atom") > 0) {
315 foreach ($API as $p => $info) {
316 if (strpos($args->getCommand(), $p) === 0) {
317 if (!api_check_method($info['method'])) {
318 throw new MethodNotAllowedException();
321 $called_api = explode("/", $p);
323 if (!empty($info['auth']) && api_user() === false) {
325 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
328 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
330 $stamp = microtime(true);
331 $return = call_user_func($info['func'], $type);
332 $duration = floatval(microtime(true) - $stamp);
334 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
336 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
338 if (false === $return) {
340 * api function returned false withour throw an
341 * exception. This should not happend, throw a 500
343 throw new InternalServerErrorException();
348 header("Content-Type: text/xml");
351 header("Content-Type: application/json");
352 if (!empty($return)) {
353 $json = json_encode(end($return));
354 if (!empty($_GET['callback'])) {
355 $json = $_GET['callback'] . "(" . $json . ")";
361 header("Content-Type: application/rss+xml");
362 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
365 header("Content-Type: application/atom+xml");
366 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
373 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
374 throw new NotFoundException();
375 } catch (HTTPException $e) {
376 header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
377 return api_error($type, $e, $args);
382 * Format API error string
384 * @param string $type Return type (xml, json, rss, as)
385 * @param object $e HTTPException Error object
386 * @param App\Arguments $args The App arguments
387 * @return string|array error message formatted as $type
389 function api_error($type, $e, App\Arguments $args)
391 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
392 /// @TODO: https://dev.twitter.com/overview/api/response-codes
394 $error = ["error" => $error,
395 "code" => $e->getCode() . " " . $e->httpdesc,
396 "request" => $args->getQueryString()];
398 $return = api_format_data('status', $type, ['status' => $error]);
402 header("Content-Type: text/xml");
405 header("Content-Type: application/json");
406 $return = json_encode($return);
409 header("Content-Type: application/rss+xml");
412 header("Content-Type: application/atom+xml");
420 * Set values for RSS template
423 * @param array $arr Array to be passed to template
424 * @param array $user_info User info
426 * @throws BadRequestException
427 * @throws ImagickException
428 * @throws InternalServerErrorException
429 * @throws UnauthorizedException
430 * @todo find proper type-hints
432 function api_rss_extra(App $a, $arr, $user_info)
434 if (is_null($user_info)) {
435 $user_info = api_get_user($a);
438 $arr['$user'] = $user_info;
440 'alternate' => $user_info['url'],
441 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
442 'base' => DI::baseUrl(),
443 'updated' => api_date(null),
444 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
445 'language' => $user_info['lang'],
446 'logo' => DI::baseUrl() . "/images/friendica-32.png",
454 * Unique contact to contact url.
456 * @param int $id Contact id
457 * @return bool|string
458 * Contact url or False if contact id is unknown
461 function api_unique_id_to_nurl($id)
463 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
465 if (DBA::isResult($r)) {
473 * Get user info array.
476 * @param int|string $contact_id Contact ID or URL
478 * @throws BadRequestException
479 * @throws ImagickException
480 * @throws InternalServerErrorException
481 * @throws UnauthorizedException
483 function api_get_user(App $a, $contact_id = null)
491 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
493 // Searching for contact URL
494 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
495 $user = Strings::normaliseLink($contact_id);
497 $extra_query = "AND `contact`.`nurl` = ? ";
498 if (api_user() !== false) {
499 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
503 // Searching for contact id with uid = 0
504 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
505 $user = api_unique_id_to_nurl(intval($contact_id));
508 throw new BadRequestException("User ID ".$contact_id." not found.");
512 $extra_query = "AND `contact`.`nurl` = ? ";
513 if (api_user() !== false) {
514 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
518 if (is_null($user) && !empty($_GET['user_id'])) {
519 $user = api_unique_id_to_nurl($_GET['user_id']);
522 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
526 $extra_query = "AND `contact`.`nurl` = ? ";
527 if (api_user() !== false) {
528 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
531 if (is_null($user) && !empty($_GET['screen_name'])) {
532 $user = $_GET['screen_name'];
533 $extra_query = "AND `contact`.`nick` = ? ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 if (is_null($user) && !empty($_GET['profileurl'])) {
540 $user = Strings::normaliseLink($_GET['profileurl']);
541 $extra_query = "AND `contact`.`nurl` = ? ";
542 if (api_user() !== false) {
543 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
547 // $called_api is the API path exploded on / and is expected to have at least 2 elements
548 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
549 $argid = count($called_api);
550 if (!empty(DI::args()->getArgv()[$argid])) {
551 $data = explode(".", DI::args()->getArgv()[$argid]);
552 if (count($data) > 1) {
553 list($user, $null) = $data;
556 if (is_numeric($user)) {
557 $user = api_unique_id_to_nurl(intval($user));
561 $extra_query = "AND `contact`.`nurl` = ? ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 $extra_query = "AND `contact`.`nick` = ? ";
568 if (api_user() !== false) {
569 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
574 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
577 if (api_user() === false) {
582 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
586 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
589 $uinfo = DBA::toArray(DBA::p(
590 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
596 // Selecting the id by priority, friendica first
597 if (is_array($uinfo)) {
598 api_best_nickname($uinfo);
601 // if the contact wasn't found, fetch it from the contacts with uid = 0
602 if (!DBA::isResult($uinfo)) {
604 throw new BadRequestException("User not found.");
607 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
609 if (DBA::isResult($contact)) {
611 'id' => $contact["id"],
612 'id_str' => (string) $contact["id"],
613 'name' => $contact["name"],
614 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
615 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
616 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
617 'profile_image_url' => $contact["micro"],
618 'profile_image_url_https' => $contact["micro"],
619 'profile_image_url_profile_size' => $contact["thumb"],
620 'profile_image_url_large' => $contact["photo"],
621 'url' => $contact["url"],
622 'protected' => false,
623 'followers_count' => 0,
624 'friends_count' => 0,
626 'created_at' => api_date($contact["created"]),
627 'favourites_count' => 0,
629 'time_zone' => 'UTC',
630 'geo_enabled' => false,
632 'statuses_count' => 0,
634 'contributors_enabled' => false,
635 'is_translator' => false,
636 'is_translation_enabled' => false,
637 'following' => false,
638 'follow_request_sent' => false,
639 'statusnet_blocking' => false,
640 'notifications' => false,
641 'statusnet_profile_url' => $contact["url"],
643 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
644 'pid' => Contact::getIdForURL($contact["url"], 0, false),
646 'network' => $contact["network"],
651 throw new BadRequestException("User ".$url." not found.");
655 if ($uinfo[0]['self']) {
656 if ($uinfo[0]['network'] == "") {
657 $uinfo[0]['network'] = Protocol::DFRN;
660 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
661 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
668 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
670 if (!empty($profile['about'])) {
671 $description = $profile['about'];
673 $description = $uinfo[0]["about"];
676 if (!empty($usr['default-location'])) {
677 $location = $usr['default-location'];
678 } elseif (!empty($uinfo[0]["location"])) {
679 $location = $uinfo[0]["location"];
681 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
685 'id' => intval($pcontact_id),
686 'id_str' => (string) intval($pcontact_id),
687 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
688 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
689 'location' => $location,
690 'description' => BBCode::toPlaintext($description ?? ''),
691 'profile_image_url' => $uinfo[0]['micro'],
692 'profile_image_url_https' => $uinfo[0]['micro'],
693 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
694 'profile_image_url_large' => $uinfo[0]["photo"],
695 'url' => $uinfo[0]['url'],
696 'protected' => false,
697 'followers_count' => intval($countfollowers),
698 'friends_count' => intval($countfriends),
700 'created_at' => api_date($uinfo[0]['created']),
701 'favourites_count' => intval($starred),
703 'time_zone' => 'UTC',
704 'geo_enabled' => false,
706 'statuses_count' => intval($countitems),
708 'contributors_enabled' => false,
709 'is_translator' => false,
710 'is_translation_enabled' => false,
711 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
712 'follow_request_sent' => false,
713 'statusnet_blocking' => false,
714 'notifications' => false,
716 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
717 'statusnet_profile_url' => $uinfo[0]['url'],
718 'uid' => intval($uinfo[0]['uid']),
719 'cid' => intval($uinfo[0]['cid']),
720 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
721 'self' => $uinfo[0]['self'],
722 'network' => $uinfo[0]['network'],
725 // If this is a local user and it uses Frio, we can get its color preferences.
727 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
728 if ($theme_info['theme'] === 'frio') {
729 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
731 if ($schema && ($schema != '---')) {
732 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
733 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
734 require_once $schemefile;
737 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
738 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
739 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
741 if (empty($nav_bg)) {
744 if (empty($link_color)) {
745 $link_color = "#6fdbe8";
747 if (empty($bgcolor)) {
748 $bgcolor = "#ededed";
751 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
752 $ret['profile_link_color'] = str_replace('#', '', $link_color);
753 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
761 * return api-formatted array for item's author and owner
764 * @param array $item item from db
765 * @return array(array:author, array:owner)
766 * @throws BadRequestException
767 * @throws ImagickException
768 * @throws InternalServerErrorException
769 * @throws UnauthorizedException
771 function api_item_get_user(App $a, $item)
773 $status_user = api_get_user($a, $item['author-id'] ?? null);
775 $author_user = $status_user;
777 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
779 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
780 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
782 $owner_user = $author_user;
785 return ([$status_user, $author_user, $owner_user]);
789 * walks recursively through an array with the possibility to change value and key
791 * @param array $array The array to walk through
792 * @param callable $callback The callback function
794 * @return array the transformed array
796 function api_walk_recursive(array &$array, callable $callback)
800 foreach ($array as $k => $v) {
802 if ($callback($v, $k)) {
803 $new_array[$k] = api_walk_recursive($v, $callback);
806 if ($callback($v, $k)) {
817 * Callback function to transform the array in an array that can be transformed in a XML file
819 * @param mixed $item Array item value
820 * @param string $key Array key
822 * @return boolean Should the array item be deleted?
824 function api_reformat_xml(&$item, &$key)
826 if (is_bool($item)) {
827 $item = ($item ? "true" : "false");
830 if (substr($key, 0, 10) == "statusnet_") {
831 $key = "statusnet:".substr($key, 10);
832 } elseif (substr($key, 0, 10) == "friendica_") {
833 $key = "friendica:".substr($key, 10);
835 /// @TODO old-lost code?
837 // $key = "default:".$key;
843 * Creates the XML from a JSON style array
845 * @param array $data JSON style array
846 * @param string $root_element Name of the root element
848 * @return string The XML data
850 function api_create_xml(array $data, $root_element)
852 $childname = key($data);
853 $data2 = array_pop($data);
855 $namespaces = ["" => "http://api.twitter.com",
856 "statusnet" => "http://status.net/schema/api/1/",
857 "friendica" => "http://friendi.ca/schema/api/1/",
858 "georss" => "http://www.georss.org/georss"];
860 /// @todo Auto detection of needed namespaces
861 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
865 if (is_array($data2)) {
867 api_walk_recursive($data2, "api_reformat_xml");
873 foreach ($data2 as $item) {
874 $data4[$i++ . ":" . $childname] = $item;
881 $data3 = [$root_element => $data2];
883 $ret = XML::fromArray($data3, $xml, false, $namespaces);
888 * Formats the data according to the data type
890 * @param string $root_element Name of the root element
891 * @param string $type Return type (atom, rss, xml, json)
892 * @param array $data JSON style array
894 * @return array|string (string|array) XML data or JSON data
896 function api_format_data($root_element, $type, $data)
902 $ret = api_create_xml($data, $root_element);
917 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
918 * returns a 401 status code and an error message if not.
920 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
922 * @param string $type Return type (atom, rss, xml, json)
923 * @return array|string
924 * @throws BadRequestException
925 * @throws ForbiddenException
926 * @throws ImagickException
927 * @throws InternalServerErrorException
928 * @throws UnauthorizedException
930 function api_account_verify_credentials($type)
934 if (api_user() === false) {
935 throw new ForbiddenException();
938 unset($_REQUEST["user_id"]);
939 unset($_GET["user_id"]);
941 unset($_REQUEST["screen_name"]);
942 unset($_GET["screen_name"]);
944 $skip_status = $_REQUEST['skip_status'] ?? false;
946 $user_info = api_get_user($a);
948 // "verified" isn't used here in the standard
949 unset($user_info["verified"]);
951 // - Adding last status
953 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
955 $user_info['status'] = api_format_item($item, $type);
959 // "uid" and "self" are only needed for some internal stuff, so remove it from here
960 unset($user_info["uid"]);
961 unset($user_info["self"]);
963 return api_format_data("user", $type, ['user' => $user_info]);
966 /// @TODO move to top of file or somewhere better
967 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
970 * Get data from $_POST or $_GET
975 function requestdata($k)
977 if (!empty($_POST[$k])) {
980 if (!empty($_GET[$k])) {
987 * Deprecated function to upload media.
989 * @param string $type Return type (atom, rss, xml, json)
991 * @return array|string
992 * @throws BadRequestException
993 * @throws ForbiddenException
994 * @throws ImagickException
995 * @throws InternalServerErrorException
996 * @throws UnauthorizedException
998 function api_statuses_mediap($type)
1002 if (api_user() === false) {
1003 logger::notice('api_statuses_update: no user');
1004 throw new ForbiddenException();
1006 $user_info = api_get_user($a);
1008 $_REQUEST['profile_uid'] = api_user();
1009 $_REQUEST['api_source'] = true;
1010 $txt = requestdata('status') ?? '';
1011 /// @TODO old-lost code?
1012 //$txt = urldecode(requestdata('status'));
1014 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1015 $txt = HTML::toBBCodeVideo($txt);
1016 $config = HTMLPurifier_Config::createDefault();
1017 $config->set('Cache.DefinitionImpl', null);
1018 $purifier = new HTMLPurifier($config);
1019 $txt = $purifier->purify($txt);
1021 $txt = HTML::toBBCode($txt);
1023 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
1025 $picture = wall_upload_post($a, false);
1027 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1028 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1029 $item_id = item_post($a);
1031 // output the post that we just posted.
1032 return api_status_show($type, $item_id);
1035 /// @TODO move this to top of file or somewhere better!
1036 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1039 * Updates the user’s current status.
1041 * @param string $type Return type (atom, rss, xml, json)
1043 * @return array|string
1044 * @throws BadRequestException
1045 * @throws ForbiddenException
1046 * @throws ImagickException
1047 * @throws InternalServerErrorException
1048 * @throws TooManyRequestsException
1049 * @throws UnauthorizedException
1050 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1052 function api_statuses_update($type)
1056 if (api_user() === false) {
1057 logger::notice('api_statuses_update: no user');
1058 throw new ForbiddenException();
1063 // convert $_POST array items to the form we use for web posts.
1064 if (requestdata('htmlstatus')) {
1065 $txt = requestdata('htmlstatus') ?? '';
1066 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1067 $txt = HTML::toBBCodeVideo($txt);
1069 $config = HTMLPurifier_Config::createDefault();
1070 $config->set('Cache.DefinitionImpl', null);
1072 $purifier = new HTMLPurifier($config);
1073 $txt = $purifier->purify($txt);
1075 $_REQUEST['body'] = HTML::toBBCode($txt);
1078 $_REQUEST['body'] = requestdata('status');
1081 $_REQUEST['title'] = requestdata('title');
1083 $parent = requestdata('in_reply_to_status_id');
1085 // Twidere sends "-1" if it is no reply ...
1086 if ($parent == -1) {
1090 if (ctype_digit($parent)) {
1091 $_REQUEST['parent'] = $parent;
1093 $_REQUEST['parent_uri'] = $parent;
1096 if (requestdata('lat') && requestdata('long')) {
1097 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1099 $_REQUEST['profile_uid'] = api_user();
1102 // Check for throttling (maximum posts per day, week and month)
1103 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1104 if ($throttle_day > 0) {
1105 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1107 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1108 $posts_day = Post::count($condition);
1110 if ($posts_day > $throttle_day) {
1111 logger::info('Daily posting limit reached for user '.api_user());
1112 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1113 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));
1117 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1118 if ($throttle_week > 0) {
1119 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1121 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1122 $posts_week = Post::count($condition);
1124 if ($posts_week > $throttle_week) {
1125 logger::info('Weekly posting limit reached for user '.api_user());
1126 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1127 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));
1131 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1132 if ($throttle_month > 0) {
1133 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1135 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1136 $posts_month = Post::count($condition);
1138 if ($posts_month > $throttle_month) {
1139 logger::info('Monthly posting limit reached for user '.api_user());
1140 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1141 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));
1146 if (requestdata('media_ids')) {
1147 $ids = explode(',', requestdata('media_ids') ?? '');
1148 } elseif (!empty($_FILES['media'])) {
1149 // upload the image if we have one
1150 $picture = wall_upload_post($a, false);
1151 if (is_array($picture)) {
1152 $ids[] = $picture['id'];
1160 foreach ($ids as $id) {
1161 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1162 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1163 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1164 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1166 if (!empty($media)) {
1167 $ressources[] = $media[0]['resource-id'];
1168 $phototypes = Images::supportedTypes();
1169 $ext = $phototypes[$media[0]['type']];
1171 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1172 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1173 'size' => $media[0]['datasize'],
1174 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1175 'description' => $media[0]['desc'] ?? '',
1176 'width' => $media[0]['width'],
1177 'height' => $media[0]['height']];
1179 if (count($media) > 1) {
1180 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1181 $attachment['preview-width'] = $media[1]['width'];
1182 $attachment['preview-height'] = $media[1]['height'];
1184 $attachments[] = $attachment;
1188 // We have to avoid that the post is rejected because of an empty body
1189 if (empty($_REQUEST['body'])) {
1190 $_REQUEST['body'] = '[hr]';
1194 if (!empty($attachments)) {
1195 $_REQUEST['attachments'] = $attachments;
1198 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1200 $_REQUEST['api_source'] = true;
1202 if (empty($_REQUEST['source'])) {
1203 $_REQUEST["source"] = api_source();
1206 // call out normal post function
1207 $item_id = item_post($a);
1209 if (!empty($ressources) && !empty($item_id)) {
1210 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1211 foreach ($ressources as $ressource) {
1212 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1216 // output the post that we just posted.
1217 return api_status_show($type, $item_id);
1220 /// @TODO move to top of file or somewhere better
1221 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1222 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1225 * Uploads an image to Friendica.
1228 * @throws BadRequestException
1229 * @throws ForbiddenException
1230 * @throws ImagickException
1231 * @throws InternalServerErrorException
1232 * @throws UnauthorizedException
1233 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1235 function api_media_upload()
1239 if (api_user() === false) {
1240 logger::notice('no user');
1241 throw new ForbiddenException();
1246 if (empty($_FILES['media'])) {
1248 throw new BadRequestException("No media.");
1251 $media = wall_upload_post($a, false);
1254 throw new InternalServerErrorException();
1258 $returndata["media_id"] = $media["id"];
1259 $returndata["media_id_string"] = (string)$media["id"];
1260 $returndata["size"] = $media["size"];
1261 $returndata["image"] = ["w" => $media["width"],
1262 "h" => $media["height"],
1263 "image_type" => $media["type"],
1264 "friendica_preview_url" => $media["preview"]];
1266 Logger::info('Media uploaded', ['return' => $returndata]);
1268 return ["media" => $returndata];
1271 /// @TODO move to top of file or somewhere better
1272 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1275 * Updates media meta data (picture descriptions)
1277 * @param string $type Return type (atom, rss, xml, json)
1279 * @return array|string
1280 * @throws BadRequestException
1281 * @throws ForbiddenException
1282 * @throws ImagickException
1283 * @throws InternalServerErrorException
1284 * @throws TooManyRequestsException
1285 * @throws UnauthorizedException
1286 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1288 * @todo Compare the corresponding Twitter function for correct return values
1290 function api_media_metadata_create($type)
1294 if (api_user() === false) {
1295 Logger::info('no user');
1296 throw new ForbiddenException();
1301 $postdata = Network::postdata();
1303 if (empty($postdata)) {
1304 throw new BadRequestException("No post data");
1307 $data = json_decode($postdata, true);
1309 throw new BadRequestException("Invalid post data");
1312 if (empty($data['media_id']) || empty($data['alt_text'])) {
1313 throw new BadRequestException("Missing post data values");
1316 if (empty($data['alt_text']['text'])) {
1317 throw new BadRequestException("No alt text.");
1320 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1322 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1323 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1324 if (!DBA::isResult($photo)) {
1325 throw new BadRequestException("Metadata not found.");
1328 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1331 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1334 * @param string $type Return format (atom, rss, xml, json)
1335 * @param int $item_id
1336 * @return array|string
1339 function api_status_show($type, $item_id)
1341 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1345 $item = api_get_item(['id' => $item_id]);
1346 if (!empty($item)) {
1347 $status_info = api_format_item($item, $type);
1350 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1352 return api_format_data('statuses', $type, ['status' => $status_info]);
1356 * Retrieves the last public status of the provided user info
1358 * @param int $ownerId Public contact Id
1359 * @param int $uid User Id
1363 function api_get_last_status($ownerId, $uid)
1366 'author-id'=> $ownerId,
1368 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1369 'private' => [Item::PUBLIC, Item::UNLISTED]
1372 $item = api_get_item($condition);
1378 * Retrieves a single item record based on the provided condition and converts it for API use.
1380 * @param array $condition Item table condition array
1384 function api_get_item(array $condition)
1386 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1392 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1393 * The author's most recent status will be returned inline.
1395 * @param string $type Return type (atom, rss, xml, json)
1396 * @return array|string
1397 * @throws BadRequestException
1398 * @throws ImagickException
1399 * @throws InternalServerErrorException
1400 * @throws UnauthorizedException
1401 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1403 function api_users_show($type)
1405 $a = Friendica\DI::app();
1407 $user_info = api_get_user($a);
1409 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1410 if (!empty($item)) {
1411 $user_info['status'] = api_format_item($item, $type);
1414 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1415 unset($user_info['uid']);
1416 unset($user_info['self']);
1418 return api_format_data('user', $type, ['user' => $user_info]);
1421 /// @TODO move to top of file or somewhere better
1422 api_register_func('api/users/show', 'api_users_show');
1423 api_register_func('api/externalprofile/show', 'api_users_show');
1426 * Search a public user account.
1428 * @param string $type Return type (atom, rss, xml, json)
1430 * @return array|string
1431 * @throws BadRequestException
1432 * @throws ImagickException
1433 * @throws InternalServerErrorException
1434 * @throws UnauthorizedException
1435 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1437 function api_users_search($type)
1443 if (!empty($_GET['q'])) {
1444 $contacts = Contact::selectToArray(
1447 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1455 if (DBA::isResult($contacts)) {
1457 foreach ($contacts as $contact) {
1458 $user_info = api_get_user($a, $contact['id']);
1460 if ($type == 'xml') {
1461 $userlist[$k++ . ':user'] = $user_info;
1463 $userlist[] = $user_info;
1466 $userlist = ['users' => $userlist];
1468 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1471 throw new BadRequestException('No search term specified.');
1474 return api_format_data('users', $type, $userlist);
1477 /// @TODO move to top of file or somewhere better
1478 api_register_func('api/users/search', 'api_users_search');
1481 * Return user objects
1483 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1485 * @param string $type Return format: json or xml
1487 * @return array|string
1488 * @throws BadRequestException
1489 * @throws ImagickException
1490 * @throws InternalServerErrorException
1491 * @throws NotFoundException if the results are empty.
1492 * @throws UnauthorizedException
1494 function api_users_lookup($type)
1498 if (!empty($_REQUEST['user_id'])) {
1499 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1501 $users[] = api_get_user(DI::app(), $id);
1506 if (empty($users)) {
1507 throw new NotFoundException;
1510 return api_format_data("users", $type, ['users' => $users]);
1513 /// @TODO move to top of file or somewhere better
1514 api_register_func('api/users/lookup', 'api_users_lookup', true);
1517 * Returns statuses that match a specified query.
1519 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1521 * @param string $type Return format: json, xml, atom, rss
1523 * @return array|string
1524 * @throws BadRequestException if the "q" parameter is missing.
1525 * @throws ForbiddenException
1526 * @throws ImagickException
1527 * @throws InternalServerErrorException
1528 * @throws UnauthorizedException
1530 function api_search($type)
1533 $user_info = api_get_user($a);
1535 if (api_user() === false || $user_info === false) {
1536 throw new ForbiddenException();
1539 if (empty($_REQUEST['q'])) {
1540 throw new BadRequestException('q parameter is required.');
1543 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1546 $data['status'] = [];
1548 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1549 if (!empty($_REQUEST['rpp'])) {
1550 $count = $_REQUEST['rpp'];
1551 } elseif (!empty($_REQUEST['count'])) {
1552 $count = $_REQUEST['count'];
1555 $since_id = $_REQUEST['since_id'] ?? 0;
1556 $max_id = $_REQUEST['max_id'] ?? 0;
1557 $page = $_REQUEST['page'] ?? 1;
1559 $start = max(0, ($page - 1) * $count);
1561 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1562 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1563 $searchTerm = $matches[1];
1564 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1565 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1567 while ($tag = DBA::fetch($tags)) {
1568 $uriids[] = $tag['uri-id'];
1572 if (empty($uriids)) {
1573 return api_format_data('statuses', $type, $data);
1576 $condition = ['uri-id' => $uriids];
1577 if ($exclude_replies) {
1578 $condition['gravity'] = GRAVITY_PARENT;
1581 $params['group_by'] = ['uri-id'];
1583 $condition = ["`id` > ?
1584 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1585 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1586 AND `body` LIKE CONCAT('%',?,'%')",
1587 $since_id, api_user(), $_REQUEST['q']];
1589 $condition[0] .= ' AND `id` <= ?';
1590 $condition[] = $max_id;
1596 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1597 $id = Item::fetchByLink($searchTerm, api_user());
1600 $id = Item::fetchByLink($searchTerm);
1604 $statuses = Post::select([], ['id' => $id]);
1608 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1610 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1612 bindComments($data['status']);
1614 return api_format_data('statuses', $type, $data);
1617 /// @TODO move to top of file or somewhere better
1618 api_register_func('api/search/tweets', 'api_search', true);
1619 api_register_func('api/search', 'api_search', true);
1622 * Returns the most recent statuses posted by the user and the users they follow.
1624 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1626 * @param string $type Return type (atom, rss, xml, json)
1628 * @return array|string
1629 * @throws BadRequestException
1630 * @throws ForbiddenException
1631 * @throws ImagickException
1632 * @throws InternalServerErrorException
1633 * @throws UnauthorizedException
1634 * @todo Optional parameters
1635 * @todo Add reply info
1637 function api_statuses_home_timeline($type)
1640 $user_info = api_get_user($a);
1642 if (api_user() === false || $user_info === false) {
1643 throw new ForbiddenException();
1646 unset($_REQUEST["user_id"]);
1647 unset($_GET["user_id"]);
1649 unset($_REQUEST["screen_name"]);
1650 unset($_GET["screen_name"]);
1652 // get last network messages
1655 $count = $_REQUEST['count'] ?? 20;
1656 $page = $_REQUEST['page']?? 0;
1657 $since_id = $_REQUEST['since_id'] ?? 0;
1658 $max_id = $_REQUEST['max_id'] ?? 0;
1659 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1660 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1662 $start = max(0, ($page - 1) * $count);
1664 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1665 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1668 $condition[0] .= " AND `id` <= ?";
1669 $condition[] = $max_id;
1671 if ($exclude_replies) {
1672 $condition[0] .= ' AND `gravity` = ?';
1673 $condition[] = GRAVITY_PARENT;
1675 if ($conversation_id > 0) {
1676 $condition[0] .= " AND `parent` = ?";
1677 $condition[] = $conversation_id;
1680 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1681 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1683 $items = Post::toArray($statuses);
1685 $ret = api_format_items($items, $user_info, false, $type);
1687 // Set all posts from the query above to seen
1689 foreach ($items as $item) {
1690 $idarray[] = intval($item["id"]);
1693 if (!empty($idarray)) {
1694 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1696 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1702 $data = ['status' => $ret];
1707 $data = api_rss_extra($a, $data, $user_info);
1711 return api_format_data("statuses", $type, $data);
1715 /// @TODO move to top of file or somewhere better
1716 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1717 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1720 * Returns the most recent statuses from public users.
1722 * @param string $type Return type (atom, rss, xml, json)
1724 * @return array|string
1725 * @throws BadRequestException
1726 * @throws ForbiddenException
1727 * @throws ImagickException
1728 * @throws InternalServerErrorException
1729 * @throws UnauthorizedException
1731 function api_statuses_public_timeline($type)
1734 $user_info = api_get_user($a);
1736 if (api_user() === false || $user_info === false) {
1737 throw new ForbiddenException();
1740 // get last network messages
1743 $count = $_REQUEST['count'] ?? 20;
1744 $page = $_REQUEST['page'] ?? 1;
1745 $since_id = $_REQUEST['since_id'] ?? 0;
1746 $max_id = $_REQUEST['max_id'] ?? 0;
1747 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1748 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1750 $start = max(0, ($page - 1) * $count);
1752 if ($exclude_replies && !$conversation_id) {
1753 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1754 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1757 $condition[0] .= " AND `id` <= ?";
1758 $condition[] = $max_id;
1761 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1762 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1764 $r = Post::toArray($statuses);
1766 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1767 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1770 $condition[0] .= " AND `id` <= ?";
1771 $condition[] = $max_id;
1773 if ($conversation_id > 0) {
1774 $condition[0] .= " AND `parent` = ?";
1775 $condition[] = $conversation_id;
1778 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1779 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1781 $r = Post::toArray($statuses);
1784 $ret = api_format_items($r, $user_info, false, $type);
1788 $data = ['status' => $ret];
1793 $data = api_rss_extra($a, $data, $user_info);
1797 return api_format_data("statuses", $type, $data);
1800 /// @TODO move to top of file or somewhere better
1801 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1804 * Returns the most recent statuses posted by users this node knows about.
1806 * @param string $type Return format: json, xml, atom, rss
1807 * @return array|string
1808 * @throws BadRequestException
1809 * @throws ForbiddenException
1810 * @throws ImagickException
1811 * @throws InternalServerErrorException
1812 * @throws UnauthorizedException
1814 function api_statuses_networkpublic_timeline($type)
1817 $user_info = api_get_user($a);
1819 if (api_user() === false || $user_info === false) {
1820 throw new ForbiddenException();
1823 $since_id = $_REQUEST['since_id'] ?? 0;
1824 $max_id = $_REQUEST['max_id'] ?? 0;
1827 $count = $_REQUEST['count'] ?? 20;
1828 $page = $_REQUEST['page'] ?? 1;
1830 $start = max(0, ($page - 1) * $count);
1832 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1833 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1836 $condition[0] .= " AND `id` <= ?";
1837 $condition[] = $max_id;
1840 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1841 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1843 $ret = api_format_items($statuses, $user_info, false, $type);
1847 $data = ['status' => $ret];
1852 $data = api_rss_extra($a, $data, $user_info);
1856 return api_format_data("statuses", $type, $data);
1859 /// @TODO move to top of file or somewhere better
1860 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1863 * Returns a single status.
1865 * @param string $type Return type (atom, rss, xml, json)
1867 * @return array|string
1868 * @throws BadRequestException
1869 * @throws ForbiddenException
1870 * @throws ImagickException
1871 * @throws InternalServerErrorException
1872 * @throws UnauthorizedException
1873 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1875 function api_statuses_show($type)
1878 $user_info = api_get_user($a);
1880 if (api_user() === false || $user_info === false) {
1881 throw new ForbiddenException();
1885 $id = intval(DI::args()->getArgv()[3] ?? 0);
1888 $id = intval($_REQUEST['id'] ?? 0);
1893 $id = intval(DI::args()->getArgv()[4] ?? 0);
1896 logger::notice('API: api_statuses_show: ' . $id);
1898 $conversation = !empty($_REQUEST['conversation']);
1900 // try to fetch the item for the local user - or the public item, if there is no local one
1901 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1902 if (!DBA::isResult($uri_item)) {
1903 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1906 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1907 if (!DBA::isResult($item)) {
1908 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1913 if ($conversation) {
1914 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1915 $params = ['order' => ['id' => true]];
1917 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1921 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1923 /// @TODO How about copying this to above methods which don't check $r ?
1924 if (!DBA::isResult($statuses)) {
1925 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1928 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1930 if ($conversation) {
1931 $data = ['status' => $ret];
1932 return api_format_data("statuses", $type, $data);
1934 $data = ['status' => $ret[0]];
1935 return api_format_data("status", $type, $data);
1939 /// @TODO move to top of file or somewhere better
1940 api_register_func('api/statuses/show', 'api_statuses_show', true);
1944 * @param string $type Return type (atom, rss, xml, json)
1946 * @return array|string
1947 * @throws BadRequestException
1948 * @throws ForbiddenException
1949 * @throws ImagickException
1950 * @throws InternalServerErrorException
1951 * @throws UnauthorizedException
1952 * @todo nothing to say?
1954 function api_conversation_show($type)
1957 $user_info = api_get_user($a);
1959 if (api_user() === false || $user_info === false) {
1960 throw new ForbiddenException();
1964 $id = intval(DI::args()->getArgv()[3] ?? 0);
1965 $since_id = intval($_REQUEST['since_id'] ?? 0);
1966 $max_id = intval($_REQUEST['max_id'] ?? 0);
1967 $count = intval($_REQUEST['count'] ?? 20);
1968 $page = intval($_REQUEST['page'] ?? 1);
1970 $start = max(0, ($page - 1) * $count);
1973 $id = intval($_REQUEST['id'] ?? 0);
1978 $id = intval(DI::args()->getArgv()[4] ?? 0);
1981 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1983 // try to fetch the item for the local user - or the public item, if there is no local one
1984 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1985 if (!DBA::isResult($item)) {
1986 throw new BadRequestException("There is no status with this id.");
1989 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1990 if (!DBA::isResult($parent)) {
1991 throw new BadRequestException("There is no status with this id.");
1994 $id = $parent['id'];
1996 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1997 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2000 $condition[0] .= " AND `id` <= ?";
2001 $condition[] = $max_id;
2004 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2005 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2007 if (!DBA::isResult($statuses)) {
2008 throw new BadRequestException("There is no status with id $id.");
2011 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2013 $data = ['status' => $ret];
2014 return api_format_data("statuses", $type, $data);
2017 /// @TODO move to top of file or somewhere better
2018 api_register_func('api/conversation/show', 'api_conversation_show', true);
2019 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2024 * @param string $type Return type (atom, rss, xml, json)
2026 * @return array|string
2027 * @throws BadRequestException
2028 * @throws ForbiddenException
2029 * @throws ImagickException
2030 * @throws InternalServerErrorException
2031 * @throws UnauthorizedException
2032 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2034 function api_statuses_repeat($type)
2040 if (api_user() === false) {
2041 throw new ForbiddenException();
2047 $id = intval(DI::args()->getArgv()[3] ?? 0);
2050 $id = intval($_REQUEST['id'] ?? 0);
2055 $id = intval(DI::args()->getArgv()[4] ?? 0);
2058 logger::notice('API: api_statuses_repeat: ' . $id);
2060 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2061 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2063 if (DBA::isResult($item) && !empty($item['body'])) {
2064 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2065 if (!Item::performActivity($id, 'announce', local_user())) {
2066 throw new InternalServerErrorException();
2071 if (strpos($item['body'], "[/share]") !== false) {
2072 $pos = strpos($item['body'], "[share");
2073 $post = substr($item['body'], $pos);
2075 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2077 if (!empty($item['title'])) {
2078 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2081 $post .= $item['body'];
2082 $post .= "[/share]";
2084 $_REQUEST['body'] = $post;
2085 $_REQUEST['profile_uid'] = api_user();
2086 $_REQUEST['api_source'] = true;
2088 if (empty($_REQUEST['source'])) {
2089 $_REQUEST["source"] = api_source();
2092 $item_id = item_post($a);
2095 throw new ForbiddenException();
2098 // output the post that we just posted.
2100 return api_status_show($type, $item_id);
2103 /// @TODO move to top of file or somewhere better
2104 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2107 * Destroys a specific status.
2109 * @param string $type Return type (atom, rss, xml, json)
2111 * @return array|string
2112 * @throws BadRequestException
2113 * @throws ForbiddenException
2114 * @throws ImagickException
2115 * @throws InternalServerErrorException
2116 * @throws UnauthorizedException
2117 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2119 function api_statuses_destroy($type)
2123 if (api_user() === false) {
2124 throw new ForbiddenException();
2130 $id = intval(DI::args()->getArgv()[3] ?? 0);
2133 $id = intval($_REQUEST['id'] ?? 0);
2138 $id = intval(DI::args()->getArgv()[4] ?? 0);
2141 logger::notice('API: api_statuses_destroy: ' . $id);
2143 $ret = api_statuses_show($type);
2145 Item::deleteForUser(['id' => $id], api_user());
2150 /// @TODO move to top of file or somewhere better
2151 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2154 * Returns the most recent mentions.
2156 * @param string $type Return type (atom, rss, xml, json)
2158 * @return array|string
2159 * @throws BadRequestException
2160 * @throws ForbiddenException
2161 * @throws ImagickException
2162 * @throws InternalServerErrorException
2163 * @throws UnauthorizedException
2164 * @see http://developer.twitter.com/doc/get/statuses/mentions
2166 function api_statuses_mentions($type)
2169 $user_info = api_get_user($a);
2171 if (api_user() === false || $user_info === false) {
2172 throw new ForbiddenException();
2175 unset($_REQUEST["user_id"]);
2176 unset($_GET["user_id"]);
2178 unset($_REQUEST["screen_name"]);
2179 unset($_GET["screen_name"]);
2181 // get last network messages
2184 $since_id = intval($_REQUEST['since_id'] ?? 0);
2185 $max_id = intval($_REQUEST['max_id'] ?? 0);
2186 $count = intval($_REQUEST['count'] ?? 20);
2187 $page = intval($_REQUEST['page'] ?? 1);
2189 $start = max(0, ($page - 1) * $count);
2191 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2192 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2193 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2196 GRAVITY_PARENT, GRAVITY_COMMENT,
2198 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
2199 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
2200 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
2201 api_user(), $since_id,
2205 $query .= " AND `id` <= ?";
2206 $condition[] = $max_id;
2209 array_unshift($condition, $query);
2211 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2212 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2214 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2216 $data = ['status' => $ret];
2221 $data = api_rss_extra($a, $data, $user_info);
2225 return api_format_data("statuses", $type, $data);
2228 /// @TODO move to top of file or somewhere better
2229 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2230 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2233 * Returns the most recent statuses posted by the user.
2235 * @param string $type Either "json" or "xml"
2236 * @return string|array
2237 * @throws BadRequestException
2238 * @throws ForbiddenException
2239 * @throws ImagickException
2240 * @throws InternalServerErrorException
2241 * @throws UnauthorizedException
2242 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2244 function api_statuses_user_timeline($type)
2247 $user_info = api_get_user($a);
2249 if (api_user() === false || $user_info === false) {
2250 throw new ForbiddenException();
2253 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2255 $since_id = $_REQUEST['since_id'] ?? 0;
2256 $max_id = $_REQUEST['max_id'] ?? 0;
2257 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2258 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2261 $count = $_REQUEST['count'] ?? 20;
2262 $page = $_REQUEST['page'] ?? 1;
2264 $start = max(0, ($page - 1) * $count);
2266 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2267 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2269 if ($user_info['self'] == 1) {
2270 $condition[0] .= ' AND `wall` ';
2273 if ($exclude_replies) {
2274 $condition[0] .= ' AND `gravity` = ?';
2275 $condition[] = GRAVITY_PARENT;
2278 if ($conversation_id > 0) {
2279 $condition[0] .= " AND `parent` = ?";
2280 $condition[] = $conversation_id;
2284 $condition[0] .= " AND `id` <= ?";
2285 $condition[] = $max_id;
2287 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2288 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2290 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2294 $data = ['status' => $ret];
2299 $data = api_rss_extra($a, $data, $user_info);
2303 return api_format_data("statuses", $type, $data);
2306 /// @TODO move to top of file or somewhere better
2307 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2310 * Star/unstar an item.
2311 * param: id : id of the item
2313 * @param string $type Return type (atom, rss, xml, json)
2315 * @return array|string
2316 * @throws BadRequestException
2317 * @throws ForbiddenException
2318 * @throws ImagickException
2319 * @throws InternalServerErrorException
2320 * @throws UnauthorizedException
2321 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2323 function api_favorites_create_destroy($type)
2327 if (api_user() === false) {
2328 throw new ForbiddenException();
2331 // for versioned api.
2332 /// @TODO We need a better global soluton
2333 $action_argv_id = 2;
2334 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2335 $action_argv_id = 3;
2338 if (DI::args()->getArgc() <= $action_argv_id) {
2339 throw new BadRequestException("Invalid request.");
2341 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2342 if (DI::args()->getArgc() == $action_argv_id + 2) {
2343 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2345 $itemid = intval($_REQUEST['id'] ?? 0);
2348 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2350 if (!DBA::isResult($item)) {
2351 throw new BadRequestException("Invalid item.");
2356 $item['starred'] = 1;
2359 $item['starred'] = 0;
2362 throw new BadRequestException("Invalid action ".$action);
2365 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2368 throw new InternalServerErrorException("DB error");
2372 $user_info = api_get_user($a);
2373 $rets = api_format_items([$item], $user_info, false, $type);
2376 $data = ['status' => $ret];
2381 $data = api_rss_extra($a, $data, $user_info);
2385 return api_format_data("status", $type, $data);
2388 /// @TODO move to top of file or somewhere better
2389 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2390 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2393 * Returns the most recent favorite statuses.
2395 * @param string $type Return type (atom, rss, xml, json)
2397 * @return string|array
2398 * @throws BadRequestException
2399 * @throws ForbiddenException
2400 * @throws ImagickException
2401 * @throws InternalServerErrorException
2402 * @throws UnauthorizedException
2404 function api_favorites($type)
2409 $user_info = api_get_user($a);
2411 if (api_user() === false || $user_info === false) {
2412 throw new ForbiddenException();
2417 // in friendica starred item are private
2418 // return favorites only for self
2419 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2421 if ($user_info['self'] == 0) {
2425 $since_id = $_REQUEST['since_id'] ?? 0;
2426 $max_id = $_REQUEST['max_id'] ?? 0;
2427 $count = $_GET['count'] ?? 20;
2428 $page = $_REQUEST['page'] ?? 1;
2430 $start = max(0, ($page - 1) * $count);
2432 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2433 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2435 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2438 $condition[0] .= " AND `id` <= ?";
2439 $condition[] = $max_id;
2442 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2444 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2449 $data = ['status' => $ret];
2454 $data = api_rss_extra($a, $data, $user_info);
2458 return api_format_data("statuses", $type, $data);
2461 /// @TODO move to top of file or somewhere better
2462 api_register_func('api/favorites', 'api_favorites', true);
2466 * @param array $item
2467 * @param array $recipient
2468 * @param array $sender
2471 * @throws InternalServerErrorException
2473 function api_format_messages($item, $recipient, $sender)
2475 // standard meta information
2477 'id' => $item['id'],
2478 'sender_id' => $sender['id'],
2480 'recipient_id' => $recipient['id'],
2481 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2482 'sender_screen_name' => $sender['screen_name'],
2483 'recipient_screen_name' => $recipient['screen_name'],
2484 'sender' => $sender,
2485 'recipient' => $recipient,
2487 'friendica_seen' => $item['seen'] ?? 0,
2488 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2491 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2492 if (isset($ret['sender']['uid'])) {
2493 unset($ret['sender']['uid']);
2495 if (isset($ret['sender']['self'])) {
2496 unset($ret['sender']['self']);
2498 if (isset($ret['recipient']['uid'])) {
2499 unset($ret['recipient']['uid']);
2501 if (isset($ret['recipient']['self'])) {
2502 unset($ret['recipient']['self']);
2505 //don't send title to regular StatusNET requests to avoid confusing these apps
2506 if (!empty($_GET['getText'])) {
2507 $ret['title'] = $item['title'];
2508 if ($_GET['getText'] == 'html') {
2509 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2510 } elseif ($_GET['getText'] == 'plain') {
2511 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2514 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2516 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2517 unset($ret['sender']);
2518 unset($ret['recipient']);
2526 * @param array $item
2529 * @throws InternalServerErrorException
2531 function api_convert_item($item)
2533 $body = api_add_attachments_to_body($item);
2535 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2537 // Add pictures to the attachment array and remove them from the body
2538 $attachments = api_get_attachments($body, $item['uri-id']);
2540 // Workaround for ostatus messages where the title is identically to the body
2541 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2542 $statusbody = trim(HTML::toPlaintext($html, 0));
2544 // handle data: images
2545 $statusbody = api_format_items_embeded_images($item, $statusbody);
2547 $statustitle = trim($item['title']);
2549 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2550 $statustext = trim($statusbody);
2552 $statustext = trim($statustitle."\n\n".$statusbody);
2555 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2556 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2559 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2561 // Workaround for clients with limited HTML parser functionality
2562 $search = ["<br>", "<blockquote>", "</blockquote>",
2563 "<h1>", "</h1>", "<h2>", "</h2>",
2564 "<h3>", "</h3>", "<h4>", "</h4>",
2565 "<h5>", "</h5>", "<h6>", "</h6>"];
2566 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2567 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2568 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2569 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2570 $statushtml = str_replace($search, $replace, $statushtml);
2572 if ($item['title'] != "") {
2573 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2577 $oldtext = $statushtml;
2578 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2579 } while ($oldtext != $statushtml);
2581 if (substr($statushtml, 0, 4) == '<br>') {
2582 $statushtml = substr($statushtml, 4);
2585 if (substr($statushtml, 0, -4) == '<br>') {
2586 $statushtml = substr($statushtml, -4);
2589 // feeds without body should contain the link
2590 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2591 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2595 "text" => $statustext,
2596 "html" => $statushtml,
2597 "attachments" => $attachments,
2598 "entities" => $entities
2603 * Add media attachments to the body
2605 * @param array $item
2606 * @return string body with added media
2608 function api_add_attachments_to_body(array $item)
2610 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2612 if (strpos($body, '[/img]') !== false) {
2616 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2617 if (!empty($media['preview'])) {
2618 $description = $media['description'] ?: $media['name'];
2619 if (!empty($description)) {
2620 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2622 $body .= "\n[img]" . $media['preview'] .'[/img]';
2632 * @param string $body
2636 * @throws InternalServerErrorException
2638 function api_get_attachments(&$body, $uriid)
2640 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2641 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2643 $URLSearchString = "^\[\]";
2644 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2648 // Remove all embedded pictures, since they are added as attachments
2649 foreach ($images[0] as $orig) {
2650 $body = str_replace($orig, '', $body);
2655 foreach ($images[1] as $image) {
2656 $imagedata = Images::getInfoFromURLCached($image);
2659 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2663 return $attachments;
2668 * @param string $text
2669 * @param string $bbcode
2672 * @throws InternalServerErrorException
2673 * @todo Links at the first character of the post
2675 function api_get_entitities(&$text, $bbcode, $uriid)
2677 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2679 if ($include_entities != "true") {
2680 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2682 foreach ($images[1] as $image) {
2683 $replace = Post\Link::getByLink($uriid, $image);
2684 $text = str_replace($image, $replace, $text);
2689 $bbcode = BBCode::cleanPictureLinks($bbcode);
2691 // Change pure links in text to bbcode uris
2692 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2695 $entities["hashtags"] = [];
2696 $entities["symbols"] = [];
2697 $entities["urls"] = [];
2698 $entities["user_mentions"] = [];
2700 $URLSearchString = "^\[\]";
2702 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2704 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2705 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2707 $bbcode = preg_replace(
2708 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2709 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2712 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2714 $bbcode = preg_replace(
2715 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2716 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2719 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2721 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2723 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2726 foreach ($urls[1] as $id => $url) {
2727 $start = iconv_strpos($text, $url, 0, "UTF-8");
2728 if (!($start === false)) {
2729 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2733 ksort($ordered_urls);
2737 foreach ($ordered_urls as $url) {
2738 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2739 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2741 $display_url = $url["title"];
2743 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2744 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2746 if (strlen($display_url) > 26) {
2747 $display_url = substr($display_url, 0, 25)."…";
2751 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2752 if (!($start === false)) {
2753 $entities["urls"][] = ["url" => $url["url"],
2754 "expanded_url" => $url["url"],
2755 "display_url" => $display_url,
2756 "indices" => [$start, $start+strlen($url["url"])]];
2757 $offset = $start + 1;
2761 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2762 $ordered_images = [];
2763 foreach ($images as $image) {
2764 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2765 if (!($start === false)) {
2766 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2770 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2771 foreach ($images[1] as $image) {
2772 $start = iconv_strpos($text, $image, 0, "UTF-8");
2773 if (!($start === false)) {
2774 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2780 foreach ($ordered_images as $image) {
2781 $url = $image['url'];
2782 $ext_alt_text = $image['alt'];
2784 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2785 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2787 if (strlen($display_url) > 26) {
2788 $display_url = substr($display_url, 0, 25)."…";
2791 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2792 if (!($start === false)) {
2793 $image = Images::getInfoFromURLCached($url);
2795 $media_url = Post\Link::getByLink($uriid, $url);
2796 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2798 $entities["media"][] = [
2800 "id_str" => (string) ($start + 1),
2801 "indices" => [$start, $start+strlen($url)],
2802 "media_url" => Strings::normaliseLink($media_url),
2803 "media_url_https" => $media_url,
2805 "display_url" => $display_url,
2806 "expanded_url" => $url,
2807 "ext_alt_text" => $ext_alt_text,
2811 $offset = $start + 1;
2820 * @param array $item
2821 * @param string $text
2825 function api_format_items_embeded_images($item, $text)
2827 $text = preg_replace_callback(
2828 '|data:image/([^;]+)[^=]+=*|m',
2829 function () use ($item) {
2830 return DI::baseUrl() . '/display/' . $item['guid'];
2838 * return <a href='url'>name</a> as array
2840 * @param string $txt text
2845 function api_contactlink_to_array($txt)
2848 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2849 if ($r && count($match)==3) {
2851 'name' => $match[2],
2865 * return likes, dislikes and attend status for item
2867 * @param array $item array
2868 * @param string $type Return type (atom, rss, xml, json)
2871 * likes => int count,
2872 * dislikes => int count
2873 * @throws BadRequestException
2874 * @throws ImagickException
2875 * @throws InternalServerErrorException
2876 * @throws UnauthorizedException
2878 function api_format_items_activities($item, $type = "json")
2887 'attendmaybe' => [],
2891 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2892 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2894 while ($parent_item = Post::fetch($ret)) {
2895 // not used as result should be structured like other user data
2896 //builtin_activity_puller($i, $activities);
2898 // get user data and add it to the array of the activity
2899 $user = api_get_user($a, $parent_item['author-id']);
2900 switch ($parent_item['verb']) {
2901 case Activity::LIKE:
2902 $activities['like'][] = $user;
2904 case Activity::DISLIKE:
2905 $activities['dislike'][] = $user;
2907 case Activity::ATTEND:
2908 $activities['attendyes'][] = $user;
2910 case Activity::ATTENDNO:
2911 $activities['attendno'][] = $user;
2913 case Activity::ATTENDMAYBE:
2914 $activities['attendmaybe'][] = $user;
2916 case Activity::ANNOUNCE:
2917 $activities['announce'][] = $user;
2926 if ($type == "xml") {
2927 $xml_activities = [];
2928 foreach ($activities as $k => $v) {
2929 // change xml element from "like" to "friendica:like"
2930 $xml_activities["friendica:".$k] = $v;
2931 // add user data into xml output
2933 foreach ($v as $user) {
2934 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2937 $activities = $xml_activities;
2944 * format items to be returned by api
2946 * @param array $items array of items
2947 * @param array $user_info
2948 * @param bool $filter_user filter items by $user_info
2949 * @param string $type Return type (atom, rss, xml, json)
2951 * @throws BadRequestException
2952 * @throws ImagickException
2953 * @throws InternalServerErrorException
2954 * @throws UnauthorizedException
2956 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2958 $a = Friendica\DI::app();
2962 if (empty($items)) {
2966 foreach ((array)$items as $item) {
2967 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2969 // Look if the posts are matching if they should be filtered by user id
2970 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2974 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2983 * @param array $item Item record
2984 * @param string $type Return format (atom, rss, xml, json)
2985 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2986 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2987 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2988 * @return array API-formatted status
2989 * @throws BadRequestException
2990 * @throws ImagickException
2991 * @throws InternalServerErrorException
2992 * @throws UnauthorizedException
2994 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2996 $a = Friendica\DI::app();
2998 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2999 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3002 DI::contentItem()->localize($item);
3004 $in_reply_to = api_in_reply_to($item);
3006 $converted = api_convert_item($item);
3008 if ($type == "xml") {
3009 $geo = "georss:point";
3015 'text' => $converted["text"],
3016 'truncated' => false,
3017 'created_at'=> api_date($item['created']),
3018 'in_reply_to_status_id' => $in_reply_to['status_id'],
3019 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3020 'source' => (($item['app']) ? $item['app'] : 'web'),
3021 'id' => intval($item['id']),
3022 'id_str' => (string) intval($item['id']),
3023 'in_reply_to_user_id' => $in_reply_to['user_id'],
3024 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3025 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3027 'favorited' => $item['starred'] ? true : false,
3028 'user' => $status_user,
3029 'friendica_author' => $author_user,
3030 'friendica_owner' => $owner_user,
3031 'friendica_private' => $item['private'] == Item::PRIVATE,
3032 //'entities' => NULL,
3033 'statusnet_html' => $converted["html"],
3034 'statusnet_conversation_id' => $item['parent'],
3035 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3036 'friendica_activities' => api_format_items_activities($item, $type),
3037 'friendica_title' => $item['title'],
3038 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
3041 if (count($converted["attachments"]) > 0) {
3042 $status["attachments"] = $converted["attachments"];
3045 if (count($converted["entities"]) > 0) {
3046 $status["entities"] = $converted["entities"];
3049 if ($status["source"] == 'web') {
3050 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3051 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3052 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3055 $retweeted_item = [];
3058 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3059 $announce = api_get_announce($item);
3060 if (!empty($announce)) {
3061 $retweeted_item = $item;
3063 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3067 if (!empty($quoted_item)) {
3068 if ($quoted_item['id'] != $item['id']) {
3069 $quoted_status = api_format_item($quoted_item);
3070 /// @todo Only remove the attachments that are also contained in the quotes status
3071 unset($status['attachments']);
3072 unset($status['entities']);
3074 $conv_quoted = api_convert_item($quoted_item);
3075 $quoted_status = $status;
3076 unset($quoted_status['attachments']);
3077 unset($quoted_status['entities']);
3078 unset($quoted_status['statusnet_conversation_id']);
3079 $quoted_status['text'] = $conv_quoted['text'];
3080 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3082 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3083 } catch (BadRequestException $e) {
3084 // user not found. should be found?
3085 /// @todo check if the user should be always found
3086 $quoted_status["user"] = [];
3089 unset($quoted_status['friendica_author']);
3090 unset($quoted_status['friendica_owner']);
3091 unset($quoted_status['friendica_activities']);
3092 unset($quoted_status['friendica_private']);
3095 if (!empty($retweeted_item)) {
3096 $retweeted_status = $status;
3097 unset($retweeted_status['friendica_author']);
3098 unset($retweeted_status['friendica_owner']);
3099 unset($retweeted_status['friendica_activities']);
3100 unset($retweeted_status['friendica_private']);
3101 unset($retweeted_status['statusnet_conversation_id']);
3102 $status['user'] = $status['friendica_owner'];
3104 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3105 } catch (BadRequestException $e) {
3106 // user not found. should be found?
3107 /// @todo check if the user should be always found
3108 $retweeted_status["user"] = [];
3111 $rt_converted = api_convert_item($retweeted_item);
3113 $retweeted_status['text'] = $rt_converted["text"];
3114 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3115 $retweeted_status['friendica_html'] = $rt_converted["html"];
3116 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3118 if (!empty($quoted_status)) {
3119 $retweeted_status['quoted_status'] = $quoted_status;
3122 $status['friendica_author'] = $retweeted_status['user'];
3123 $status['retweeted_status'] = $retweeted_status;
3124 } elseif (!empty($quoted_status)) {
3125 $root_status = api_convert_item($item);
3127 $status['text'] = $root_status["text"];
3128 $status['statusnet_html'] = $root_status["html"];
3129 $status['quoted_status'] = $quoted_status;
3132 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3133 unset($status["user"]["uid"]);
3134 unset($status["user"]["self"]);
3136 if ($item["coord"] != "") {
3137 $coords = explode(' ', $item["coord"]);
3138 if (count($coords) == 2) {
3139 if ($type == "json") {
3140 $status["geo"] = ['type' => 'Point',
3141 'coordinates' => [(float) $coords[0],
3142 (float) $coords[1]]];
3143 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3144 $status["georss:point"] = $item["coord"];
3153 * Returns the remaining number of API requests available to the user before the API limit is reached.
3155 * @param string $type Return type (atom, rss, xml, json)
3157 * @return array|string
3160 function api_account_rate_limit_status($type)
3162 if ($type == "xml") {
3164 'remaining-hits' => '150',
3165 '@attributes' => ["type" => "integer"],
3166 'hourly-limit' => '150',
3167 '@attributes2' => ["type" => "integer"],
3168 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3169 '@attributes3' => ["type" => "datetime"],
3170 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3171 '@attributes4' => ["type" => "integer"],
3175 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3176 'remaining_hits' => '150',
3177 'hourly_limit' => '150',
3178 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3182 return api_format_data('hash', $type, ['hash' => $hash]);
3185 /// @TODO move to top of file or somewhere better
3186 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3189 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3191 * @param string $type Return type (atom, rss, xml, json)
3193 * @return array|string
3195 function api_help_test($type)
3197 if ($type == 'xml') {
3203 return api_format_data('ok', $type, ["ok" => $ok]);
3206 /// @TODO move to top of file or somewhere better
3207 api_register_func('api/help/test', 'api_help_test', false);
3210 * Returns all lists the user subscribes to.
3212 * @param string $type Return type (atom, rss, xml, json)
3214 * @return array|string
3215 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3217 function api_lists_list($type)
3220 /// @TODO $ret is not filled here?
3221 return api_format_data('lists', $type, ["lists_list" => $ret]);
3224 /// @TODO move to top of file or somewhere better
3225 api_register_func('api/lists/list', 'api_lists_list', true);
3226 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3229 * Returns all groups the user owns.
3231 * @param string $type Return type (atom, rss, xml, json)
3233 * @return array|string
3234 * @throws BadRequestException
3235 * @throws ForbiddenException
3236 * @throws ImagickException
3237 * @throws InternalServerErrorException
3238 * @throws UnauthorizedException
3239 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3241 function api_lists_ownerships($type)
3245 if (api_user() === false) {
3246 throw new ForbiddenException();
3250 $user_info = api_get_user($a);
3251 $uid = $user_info['uid'];
3253 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3255 // loop through all groups
3257 foreach ($groups as $group) {
3258 if ($group['visible']) {
3264 'name' => $group['name'],
3265 'id' => intval($group['id']),
3266 'id_str' => (string) $group['id'],
3267 'user' => $user_info,
3271 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3274 /// @TODO move to top of file or somewhere better
3275 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3278 * Returns recent statuses from users in the specified group.
3280 * @param string $type Return type (atom, rss, xml, json)
3282 * @return array|string
3283 * @throws BadRequestException
3284 * @throws ForbiddenException
3285 * @throws ImagickException
3286 * @throws InternalServerErrorException
3287 * @throws UnauthorizedException
3288 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3290 function api_lists_statuses($type)
3294 $user_info = api_get_user($a);
3295 if (api_user() === false || $user_info === false) {
3296 throw new ForbiddenException();
3299 unset($_REQUEST["user_id"]);
3300 unset($_GET["user_id"]);
3302 unset($_REQUEST["screen_name"]);
3303 unset($_GET["screen_name"]);
3305 if (empty($_REQUEST['list_id'])) {
3306 throw new BadRequestException('list_id not specified');
3310 $count = $_REQUEST['count'] ?? 20;
3311 $page = $_REQUEST['page'] ?? 1;
3312 $since_id = $_REQUEST['since_id'] ?? 0;
3313 $max_id = $_REQUEST['max_id'] ?? 0;
3314 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3315 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3317 $start = max(0, ($page - 1) * $count);
3319 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3320 $gids = array_column($groups, 'contact-id');
3321 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3322 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3325 $condition[0] .= " AND `id` <= ?";
3326 $condition[] = $max_id;
3328 if ($exclude_replies > 0) {
3329 $condition[0] .= ' AND `gravity` = ?';
3330 $condition[] = GRAVITY_PARENT;
3332 if ($conversation_id > 0) {
3333 $condition[0] .= " AND `parent` = ?";
3334 $condition[] = $conversation_id;
3337 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3338 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3340 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3342 $data = ['status' => $items];
3347 $data = api_rss_extra($a, $data, $user_info);
3351 return api_format_data("statuses", $type, $data);
3354 /// @TODO move to top of file or somewhere better
3355 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3358 * Returns either the friends of the follower list
3360 * Considers friends and followers lists to be private and won't return
3361 * anything if any user_id parameter is passed.
3363 * @param string $qtype Either "friends" or "followers"
3364 * @return boolean|array
3365 * @throws BadRequestException
3366 * @throws ForbiddenException
3367 * @throws ImagickException
3368 * @throws InternalServerErrorException
3369 * @throws UnauthorizedException
3371 function api_statuses_f($qtype)
3375 if (api_user() === false) {
3376 throw new ForbiddenException();
3380 $count = $_GET['count'] ?? 20;
3381 $page = $_GET['page'] ?? 1;
3383 $start = max(0, ($page - 1) * $count);
3385 $user_info = api_get_user($a);
3387 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3388 /* this is to stop Hotot to load friends multiple times
3389 * I'm not sure if I'm missing return something or
3390 * is a bug in hotot. Workaround, meantime
3394 return array('$users' => $ret);*/
3399 if ($qtype == 'friends') {
3400 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3401 } elseif ($qtype == 'followers') {
3402 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3405 // friends and followers only for self
3406 if ($user_info['self'] == 0) {
3407 $sql_extra = " AND false ";
3410 if ($qtype == 'blocks') {
3411 $sql_filter = 'AND `blocked` AND NOT `pending`';
3412 } elseif ($qtype == 'incoming') {
3413 $sql_filter = 'AND `pending`';
3415 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3418 // @todo This query most likely can be replaced with a Contact::select...
3419 $r = DBA::toArray(DBA::p(
3434 foreach ($r as $cid) {
3435 $user = api_get_user($a, $cid['nurl']);
3436 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3437 unset($user["uid"]);
3438 unset($user["self"]);
3445 return ['user' => $ret];
3450 * Returns the list of friends of the provided user
3452 * @deprecated By Twitter API in favor of friends/list
3454 * @param string $type Either "json" or "xml"
3455 * @return boolean|string|array
3456 * @throws BadRequestException
3457 * @throws ForbiddenException
3459 function api_statuses_friends($type)
3461 $data = api_statuses_f("friends");
3462 if ($data === false) {
3465 return api_format_data("users", $type, $data);
3469 * Returns the list of followers of the provided user
3471 * @deprecated By Twitter API in favor of friends/list
3473 * @param string $type Either "json" or "xml"
3474 * @return boolean|string|array
3475 * @throws BadRequestException
3476 * @throws ForbiddenException
3478 function api_statuses_followers($type)
3480 $data = api_statuses_f("followers");
3481 if ($data === false) {
3484 return api_format_data("users", $type, $data);
3487 /// @TODO move to top of file or somewhere better
3488 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3489 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3492 * Returns the list of blocked users
3494 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3496 * @param string $type Either "json" or "xml"
3498 * @return boolean|string|array
3499 * @throws BadRequestException
3500 * @throws ForbiddenException
3502 function api_blocks_list($type)
3504 $data = api_statuses_f('blocks');
3505 if ($data === false) {
3508 return api_format_data("users", $type, $data);
3511 /// @TODO move to top of file or somewhere better
3512 api_register_func('api/blocks/list', 'api_blocks_list', true);
3515 * Returns the list of pending users IDs
3517 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3519 * @param string $type Either "json" or "xml"
3521 * @return boolean|string|array
3522 * @throws BadRequestException
3523 * @throws ForbiddenException
3525 function api_friendships_incoming($type)
3527 $data = api_statuses_f('incoming');
3528 if ($data === false) {
3533 foreach ($data['user'] as $user) {
3534 $ids[] = $user['id'];
3537 return api_format_data("ids", $type, ['id' => $ids]);
3540 /// @TODO move to top of file or somewhere better
3541 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3544 * Returns the instance's configuration information.
3546 * @param string $type Return type (atom, rss, xml, json)
3548 * @return array|string
3549 * @throws InternalServerErrorException
3551 function api_statusnet_config($type)
3553 $name = DI::config()->get('config', 'sitename');
3554 $server = DI::baseUrl()->getHostname();
3555 $logo = DI::baseUrl() . '/images/friendica-64.png';
3556 $email = DI::config()->get('config', 'admin_email');
3557 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3558 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3559 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3560 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3561 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3564 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3565 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3566 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3567 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3568 'shorturllength' => '30',
3570 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3571 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3572 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3573 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3578 return api_format_data('config', $type, ['config' => $config]);
3581 /// @TODO move to top of file or somewhere better
3582 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3583 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3587 * @param string $type Return type (atom, rss, xml, json)
3589 * @return array|string
3591 function api_statusnet_version($type)
3594 $fake_statusnet_version = "0.9.7";
3596 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3599 /// @TODO move to top of file or somewhere better
3600 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3601 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3604 * Sends a new direct message.
3606 * @param string $type Return type (atom, rss, xml, json)
3608 * @return array|string
3609 * @throws BadRequestException
3610 * @throws ForbiddenException
3611 * @throws ImagickException
3612 * @throws InternalServerErrorException
3613 * @throws NotFoundException
3614 * @throws UnauthorizedException
3615 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3617 function api_direct_messages_new($type)
3621 if (api_user() === false) {
3622 throw new ForbiddenException();
3625 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3629 $sender = api_get_user($a);
3632 if (!empty($_POST['screen_name'])) {
3633 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3634 if (DBA::isResult($contacts)) {
3635 // Selecting the id by priority, friendica first
3636 api_best_nickname($contacts);
3638 $recipient = api_get_user($a, $contacts[0]['nurl']);
3641 $recipient = api_get_user($a, $_POST['user_id']);
3644 if (empty($recipient)) {
3645 throw new NotFoundException('Recipient not found');
3649 if (!empty($_REQUEST['replyto'])) {
3650 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3651 $replyto = $mail['parent-uri'];
3652 $sub = $mail['title'];
3654 if (!empty($_REQUEST['title'])) {
3655 $sub = $_REQUEST['title'];
3657 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3661 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3664 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3665 $ret = api_format_messages($mail, $recipient, $sender);
3667 $ret = ["error" => $id];
3670 $data = ['direct_message'=>$ret];
3676 $data = api_rss_extra($a, $data, $sender);
3680 return api_format_data("direct-messages", $type, $data);
3683 /// @TODO move to top of file or somewhere better
3684 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3687 * delete a direct_message from mail table through api
3689 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3690 * @return string|array
3691 * @throws BadRequestException
3692 * @throws ForbiddenException
3693 * @throws ImagickException
3694 * @throws InternalServerErrorException
3695 * @throws UnauthorizedException
3696 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3698 function api_direct_messages_destroy($type)
3702 if (api_user() === false) {
3703 throw new ForbiddenException();
3707 $user_info = api_get_user($a);
3709 $id = $_REQUEST['id'] ?? 0;
3711 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3712 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3713 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3715 $uid = $user_info['uid'];
3716 // error if no id or parenturi specified (for clients posting parent-uri as well)
3717 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3718 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3719 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3722 // BadRequestException if no id specified (for clients using Twitter API)
3724 throw new BadRequestException('Message id not specified');
3727 // add parent-uri to sql command if specified by calling app
3728 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3730 // error message if specified id is not in database
3731 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3732 if ($verbose == "true") {
3733 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3734 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3736 /// @todo BadRequestException ok for Twitter API clients?
3737 throw new BadRequestException('message id not in database');
3741 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3743 if ($verbose == "true") {
3746 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3747 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3749 $answer = ['result' => 'error', 'message' => 'unknown error'];
3750 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3753 /// @todo return JSON data like Twitter API not yet implemented
3756 /// @TODO move to top of file or somewhere better
3757 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3762 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3763 * @return string|array
3764 * @throws HTTPException\BadRequestException
3765 * @throws HTTPException\ExpectationFailedException
3766 * @throws HTTPException\ForbiddenException
3767 * @throws HTTPException\InternalServerErrorException
3768 * @throws HTTPException\NotFoundException
3769 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3771 function api_friendships_destroy($type)
3775 if ($uid === false) {
3776 throw new HTTPException\ForbiddenException();
3779 $owner = User::getOwnerDataById($uid);
3781 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3782 throw new HTTPException\NotFoundException('Error Processing Request');
3785 $contact_id = $_REQUEST['user_id'] ?? 0;
3787 if (empty($contact_id)) {
3788 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3789 throw new HTTPException\BadRequestException('no user_id specified');
3792 // Get Contact by given id
3793 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3795 if(!DBA::isResult($contact)) {
3796 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3797 throw new HTTPException\NotFoundException('no contact found to given ID');
3800 $url = $contact['url'];
3802 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3803 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3804 Strings::normaliseLink($url), $url];
3805 $contact = DBA::selectFirst('contact', [], $condition);
3807 if (!DBA::isResult($contact)) {
3808 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3809 throw new HTTPException\NotFoundException('Not following Contact');
3813 $result = Contact::terminateFriendship($owner, $contact);
3815 if ($result === null) {
3816 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3817 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3820 if ($result === false) {
3821 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3823 } catch (Exception $e) {
3824 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3825 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3828 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3829 unset($contact['uid']);
3830 unset($contact['self']);
3832 // Set screen_name since Twidere requests it
3833 $contact['screen_name'] = $contact['nick'];
3835 return api_format_data('friendships-destroy', $type, ['user' => $contact]);
3837 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3841 * @param string $type Return type (atom, rss, xml, json)
3842 * @param string $box
3843 * @param string $verbose
3845 * @return array|string
3846 * @throws BadRequestException
3847 * @throws ForbiddenException
3848 * @throws ImagickException
3849 * @throws InternalServerErrorException
3850 * @throws UnauthorizedException
3852 function api_direct_messages_box($type, $box, $verbose)
3855 if (api_user() === false) {
3856 throw new ForbiddenException();
3859 $count = $_GET['count'] ?? 20;
3860 $page = $_REQUEST['page'] ?? 1;
3862 $since_id = $_REQUEST['since_id'] ?? 0;
3863 $max_id = $_REQUEST['max_id'] ?? 0;
3865 $user_id = $_REQUEST['user_id'] ?? '';
3866 $screen_name = $_REQUEST['screen_name'] ?? '';
3869 unset($_REQUEST["user_id"]);
3870 unset($_GET["user_id"]);
3872 unset($_REQUEST["screen_name"]);
3873 unset($_GET["screen_name"]);
3875 $user_info = api_get_user($a);
3876 if ($user_info === false) {
3877 throw new ForbiddenException();
3879 $profile_url = $user_info["url"];
3882 $start = max(0, ($page - 1) * $count);
3887 if ($box=="sentbox") {
3888 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3889 } elseif ($box == "conversation") {
3890 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3891 } elseif ($box == "all") {
3892 $sql_extra = "true";
3893 } elseif ($box == "inbox") {
3894 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3898 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3901 if ($user_id != "") {
3902 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3903 } elseif ($screen_name !="") {
3904 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3907 $r = DBA::toArray(DBA::p(
3908 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
3914 if ($verbose == "true" && !DBA::isResult($r)) {
3915 $answer = ['result' => 'error', 'message' => 'no mails available'];
3916 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3920 foreach ($r as $item) {
3921 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3922 $recipient = $user_info;
3923 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3924 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3925 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3926 $sender = $user_info;
3929 if (isset($recipient) && isset($sender)) {
3930 $ret[] = api_format_messages($item, $recipient, $sender);
3935 $data = ['direct_message' => $ret];
3940 $data = api_rss_extra($a, $data, $user_info);
3944 return api_format_data("direct-messages", $type, $data);
3948 * Returns the most recent direct messages sent by the user.
3950 * @param string $type Return type (atom, rss, xml, json)
3952 * @return array|string
3953 * @throws BadRequestException
3954 * @throws ForbiddenException
3955 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3957 function api_direct_messages_sentbox($type)
3959 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3960 return api_direct_messages_box($type, "sentbox", $verbose);
3964 * Returns the most recent direct messages sent to the user.
3966 * @param string $type Return type (atom, rss, xml, json)
3968 * @return array|string
3969 * @throws BadRequestException
3970 * @throws ForbiddenException
3971 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3973 function api_direct_messages_inbox($type)
3975 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3976 return api_direct_messages_box($type, "inbox", $verbose);
3981 * @param string $type Return type (atom, rss, xml, json)
3983 * @return array|string
3984 * @throws BadRequestException
3985 * @throws ForbiddenException
3987 function api_direct_messages_all($type)
3989 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3990 return api_direct_messages_box($type, "all", $verbose);
3995 * @param string $type Return type (atom, rss, xml, json)
3997 * @return array|string
3998 * @throws BadRequestException
3999 * @throws ForbiddenException
4001 function api_direct_messages_conversation($type)
4003 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4004 return api_direct_messages_box($type, "conversation", $verbose);
4007 /// @TODO move to top of file or somewhere better
4008 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4009 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4010 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4011 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4014 * delete a complete photoalbum with all containing photos from database through api
4016 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4017 * @return string|array
4018 * @throws BadRequestException
4019 * @throws ForbiddenException
4020 * @throws InternalServerErrorException
4022 function api_fr_photoalbum_delete($type)
4024 if (api_user() === false) {
4025 throw new ForbiddenException();
4028 $album = $_REQUEST['album'] ?? '';
4030 // we do not allow calls without album string
4032 throw new BadRequestException("no albumname specified");
4034 // check if album is existing
4036 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4037 if (!DBA::isResult($photos)) {
4038 throw new BadRequestException("album not available");
4041 $resourceIds = array_column($photos, 'resource-id');
4043 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4044 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4045 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4046 Item::deleteForUser($condition, api_user());
4048 // now let's delete all photos from the album
4049 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4051 // return success of deletion or error message
4053 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4054 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4056 throw new InternalServerErrorException("unknown error - deleting from database failed");
4061 * update the name of the album for all photos of an album
4063 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4064 * @return string|array
4065 * @throws BadRequestException
4066 * @throws ForbiddenException
4067 * @throws InternalServerErrorException
4069 function api_fr_photoalbum_update($type)
4071 if (api_user() === false) {
4072 throw new ForbiddenException();
4075 $album = $_REQUEST['album'] ?? '';
4076 $album_new = $_REQUEST['album_new'] ?? '';
4078 // we do not allow calls without album string
4080 throw new BadRequestException("no albumname specified");
4082 if ($album_new == "") {
4083 throw new BadRequestException("no new albumname specified");
4085 // check if album is existing
4086 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4087 throw new BadRequestException("album not available");
4089 // now let's update all photos to the albumname
4090 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4092 // return success of updating or error message
4094 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4095 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4097 throw new InternalServerErrorException("unknown error - updating in database failed");
4103 * list all photos of the authenticated user
4105 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4106 * @return string|array
4107 * @throws ForbiddenException
4108 * @throws InternalServerErrorException
4110 function api_fr_photos_list($type)
4112 if (api_user() === false) {
4113 throw new ForbiddenException();
4115 $r = DBA::toArray(DBA::p(
4116 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4117 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4118 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
4119 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
4122 'image/jpeg' => 'jpg',
4123 'image/png' => 'png',
4124 'image/gif' => 'gif'
4126 $data = ['photo'=>[]];
4127 if (DBA::isResult($r)) {
4128 foreach ($r as $rr) {
4130 $photo['id'] = $rr['resource-id'];
4131 $photo['album'] = $rr['album'];
4132 $photo['filename'] = $rr['filename'];
4133 $photo['type'] = $rr['type'];
4134 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4135 $photo['created'] = $rr['created'];
4136 $photo['edited'] = $rr['edited'];
4137 $photo['desc'] = $rr['desc'];
4139 if ($type == "xml") {
4140 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4142 $photo['thumb'] = $thumb;
4143 $data['photo'][] = $photo;
4147 return api_format_data("photos", $type, $data);
4151 * upload a new photo or change an existing photo
4153 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4154 * @return string|array
4155 * @throws BadRequestException
4156 * @throws ForbiddenException
4157 * @throws ImagickException
4158 * @throws InternalServerErrorException
4159 * @throws NotFoundException
4161 function api_fr_photo_create_update($type)
4163 if (api_user() === false) {
4164 throw new ForbiddenException();
4167 $photo_id = $_REQUEST['photo_id'] ?? null;
4168 $desc = $_REQUEST['desc'] ?? null;
4169 $album = $_REQUEST['album'] ?? null;
4170 $album_new = $_REQUEST['album_new'] ?? null;
4171 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4172 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4173 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4174 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4175 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4177 // do several checks on input parameters
4178 // we do not allow calls without album string
4179 if ($album == null) {
4180 throw new BadRequestException("no albumname specified");
4182 // if photo_id == null --> we are uploading a new photo
4183 if ($photo_id == null) {
4186 // error if no media posted in create-mode
4187 if (empty($_FILES['media'])) {
4189 throw new BadRequestException("no media data submitted");
4192 // album_new will be ignored in create-mode
4197 // check if photo is existing in databasei
4198 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4199 throw new BadRequestException("photo not available");
4203 // checks on acl strings provided by clients
4204 $acl_input_error = false;
4205 $acl_input_error |= check_acl_input($allow_cid);
4206 $acl_input_error |= check_acl_input($deny_cid);
4207 $acl_input_error |= check_acl_input($allow_gid);
4208 $acl_input_error |= check_acl_input($deny_gid);
4209 if ($acl_input_error) {
4210 throw new BadRequestException("acl data invalid");
4212 // now let's upload the new media in create-mode
4213 if ($mode == "create") {
4214 $media = $_FILES['media'];
4215 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility);
4217 // return success of updating or error message
4218 if (!is_null($data)) {
4219 return api_format_data("photo_create", $type, $data);
4221 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4225 // now let's do the changes in update-mode
4226 if ($mode == "update") {
4227 $updated_fields = [];
4229 if (!is_null($desc)) {
4230 $updated_fields['desc'] = $desc;
4233 if (!is_null($album_new)) {
4234 $updated_fields['album'] = $album_new;
4237 if (!is_null($allow_cid)) {
4238 $allow_cid = trim($allow_cid);
4239 $updated_fields['allow_cid'] = $allow_cid;
4242 if (!is_null($deny_cid)) {
4243 $deny_cid = trim($deny_cid);
4244 $updated_fields['deny_cid'] = $deny_cid;
4247 if (!is_null($allow_gid)) {
4248 $allow_gid = trim($allow_gid);
4249 $updated_fields['allow_gid'] = $allow_gid;
4252 if (!is_null($deny_gid)) {
4253 $deny_gid = trim($deny_gid);
4254 $updated_fields['deny_gid'] = $deny_gid;
4258 if (count($updated_fields) > 0) {
4259 $nothingtodo = false;
4260 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4262 $nothingtodo = true;
4265 if (!empty($_FILES['media'])) {
4266 $nothingtodo = false;
4267 $media = $_FILES['media'];
4268 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
4269 if (!is_null($data)) {
4270 return api_format_data("photo_update", $type, $data);
4274 // return success of updating or error message
4276 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4277 return api_format_data("photo_update", $type, ['$result' => $answer]);
4280 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4281 return api_format_data("photo_update", $type, ['$result' => $answer]);
4283 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4286 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4290 * delete a single photo from the database through api
4292 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4293 * @return string|array
4294 * @throws BadRequestException
4295 * @throws ForbiddenException
4296 * @throws InternalServerErrorException
4298 function api_fr_photo_delete($type)
4300 if (api_user() === false) {
4301 throw new ForbiddenException();
4305 $photo_id = $_REQUEST['photo_id'] ?? null;
4307 // do several checks on input parameters
4308 // we do not allow calls without photo id
4309 if ($photo_id == null) {
4310 throw new BadRequestException("no photo_id specified");
4313 // check if photo is existing in database
4314 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4315 throw new BadRequestException("photo not available");
4318 // now we can perform on the deletion of the photo
4319 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4321 // return success of deletion or error message
4323 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4324 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4325 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4326 Item::deleteForUser($condition, api_user());
4328 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4329 return api_format_data("photo_delete", $type, ['$result' => $result]);
4331 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4337 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4339 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4340 * @return string|array
4341 * @throws BadRequestException
4342 * @throws ForbiddenException
4343 * @throws InternalServerErrorException
4344 * @throws NotFoundException
4346 function api_fr_photo_detail($type)
4348 if (api_user() === false) {
4349 throw new ForbiddenException();
4351 if (empty($_REQUEST['photo_id'])) {
4352 throw new BadRequestException("No photo id.");
4355 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4356 $photo_id = $_REQUEST['photo_id'];
4358 // prepare json/xml output with data from database for the requested photo
4359 $data = prepare_photo_data($type, $scale, $photo_id);
4361 return api_format_data("photo_detail", $type, $data);
4366 * updates the profile image for the user (either a specified profile or the default profile)
4368 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4370 * @return string|array
4371 * @throws BadRequestException
4372 * @throws ForbiddenException
4373 * @throws ImagickException
4374 * @throws InternalServerErrorException
4375 * @throws NotFoundException
4376 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4378 function api_account_update_profile_image($type)
4380 if (api_user() === false) {
4381 throw new ForbiddenException();
4384 $profile_id = $_REQUEST['profile_id'] ?? 0;
4386 // error if image data is missing
4387 if (empty($_FILES['image'])) {
4388 throw new BadRequestException("no media data submitted");
4391 // check if specified profile id is valid
4392 if ($profile_id != 0) {
4393 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4394 // error message if specified profile id is not in database
4395 if (!DBA::isResult($profile)) {
4396 throw new BadRequestException("profile_id not available");
4398 $is_default_profile = $profile['is-default'];
4400 $is_default_profile = 1;
4403 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4405 if (!empty($_FILES['image'])) {
4406 $media = $_FILES['image'];
4407 } elseif (!empty($_FILES['media'])) {
4408 $media = $_FILES['media'];
4410 // save new profile image
4411 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
4414 if (is_array($media['type'])) {
4415 $filetype = $media['type'][0];
4417 $filetype = $media['type'];
4419 if ($filetype == "image/jpeg") {
4421 } elseif ($filetype == "image/png") {
4424 throw new InternalServerErrorException('Unsupported filetype');
4427 // change specified profile or all profiles to the new resource-id
4428 if ($is_default_profile) {
4429 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4430 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
4432 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4433 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4434 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4437 Contact::updateSelfFromUserID(api_user(), true);
4439 // Update global directory in background
4440 Profile::publishUpdate(api_user());
4442 // output for client
4444 return api_account_verify_credentials($type);
4446 // SaveMediaToDatabase failed for some reason
4447 throw new InternalServerErrorException("image upload failed");
4451 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4452 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4453 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4454 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4455 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4456 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4457 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4458 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4459 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4462 * Update user profile
4464 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4466 * @return array|string
4467 * @throws BadRequestException
4468 * @throws ForbiddenException
4469 * @throws ImagickException
4470 * @throws InternalServerErrorException
4471 * @throws UnauthorizedException
4473 function api_account_update_profile($type)
4475 $local_user = api_user();
4476 $api_user = api_get_user(DI::app());
4478 if (!empty($_POST['name'])) {
4479 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4480 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4481 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4482 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
4485 if (isset($_POST['description'])) {
4486 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4487 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4488 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
4491 Profile::publishUpdate($local_user);
4493 return api_account_verify_credentials($type);
4496 /// @TODO move to top of file or somewhere better
4497 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4501 * @param string $acl_string
4505 function check_acl_input($acl_string)
4507 if (empty($acl_string)) {
4511 $contact_not_found = false;
4513 // split <x><y><z> into array of cid's
4514 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4516 // check for each cid if it is available on server
4517 $cid_array = $array[0];
4518 foreach ($cid_array as $cid) {
4519 $cid = str_replace("<", "", $cid);
4520 $cid = str_replace(">", "", $cid);
4521 $condition = ['id' => $cid, 'uid' => api_user()];
4522 $contact_not_found |= !DBA::exists('contact', $condition);
4524 return $contact_not_found;
4528 * @param string $mediatype
4529 * @param array $media
4530 * @param string $type
4531 * @param string $album
4532 * @param string $allow_cid
4533 * @param string $deny_cid
4534 * @param string $allow_gid
4535 * @param string $deny_gid
4536 * @param string $desc
4537 * @param integer $phototype
4538 * @param boolean $visibility
4539 * @param string $photo_id
4541 * @throws BadRequestException
4542 * @throws ForbiddenException
4543 * @throws ImagickException
4544 * @throws InternalServerErrorException
4545 * @throws NotFoundException
4546 * @throws UnauthorizedException
4548 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
4556 if (is_array($media)) {
4557 if (is_array($media['tmp_name'])) {
4558 $src = $media['tmp_name'][0];
4560 $src = $media['tmp_name'];
4562 if (is_array($media['name'])) {
4563 $filename = basename($media['name'][0]);
4565 $filename = basename($media['name']);
4567 if (is_array($media['size'])) {
4568 $filesize = intval($media['size'][0]);
4570 $filesize = intval($media['size']);
4572 if (is_array($media['type'])) {
4573 $filetype = $media['type'][0];
4575 $filetype = $media['type'];
4579 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4582 "File upload src: " . $src . " - filename: " . $filename .
4583 " - size: " . $filesize . " - type: " . $filetype);
4585 // check if there was a php upload error
4586 if ($filesize == 0 && $media['error'] == 1) {
4587 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4589 // check against max upload size within Friendica instance
4590 $maximagesize = DI::config()->get('system', 'maximagesize');
4591 if ($maximagesize && ($filesize > $maximagesize)) {
4592 $formattedBytes = Strings::formatBytes($maximagesize);
4593 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4596 // create Photo instance with the data of the image
4597 $imagedata = @file_get_contents($src);
4598 $Image = new Image($imagedata, $filetype);
4599 if (!$Image->isValid()) {
4600 throw new InternalServerErrorException("unable to process image data");
4603 // check orientation of image
4604 $Image->orient($src);
4607 // check max length of images on server
4608 $max_length = DI::config()->get('system', 'max_image_length');
4610 $max_length = MAX_IMAGE_LENGTH;
4612 if ($max_length > 0) {
4613 $Image->scaleDown($max_length);
4614 logger::info("File upload: Scaling picture to new size " . $max_length);
4616 $width = $Image->getWidth();
4617 $height = $Image->getHeight();
4619 // create a new resource-id if not already provided
4620 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4622 if ($mediatype == "photo") {
4623 // upload normal image (scales 0, 1, 2)
4624 logger::info("photo upload: starting new photo upload");
4626 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4628 logger::notice("photo upload: image upload with scale 0 (original size) failed");
4630 if ($width > 640 || $height > 640) {
4631 $Image->scaleDown(640);
4632 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4634 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
4638 if ($width > 320 || $height > 320) {
4639 $Image->scaleDown(320);
4640 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4642 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
4645 logger::info("photo upload: new photo upload ended");
4646 } elseif ($mediatype == "profileimage") {
4647 // upload profile image (scales 4, 5, 6)
4648 logger::info("photo upload: starting new profile image upload");
4650 if ($width > 300 || $height > 300) {
4651 $Image->scaleDown(300);
4652 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4654 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4658 if ($width > 80 || $height > 80) {
4659 $Image->scaleDown(80);
4660 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4662 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4666 if ($width > 48 || $height > 48) {
4667 $Image->scaleDown(48);
4668 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4670 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4673 $Image->__destruct();
4674 logger::info("photo upload: new profile image upload ended");
4678 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4679 if ($photo_id == null && $mediatype == "photo") {
4680 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4682 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4683 return prepare_photo_data($type, false, $resource_id);
4685 throw new InternalServerErrorException("image upload failed");
4691 * @param string $hash
4692 * @param string $allow_cid
4693 * @param string $deny_cid
4694 * @param string $allow_gid
4695 * @param string $deny_gid
4696 * @param string $filetype
4697 * @param boolean $visibility
4698 * @throws InternalServerErrorException
4700 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4702 // get data about the api authenticated user
4703 $uri = Item::newURI(intval(api_user()));
4704 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4707 $arr['guid'] = System::createUUID();
4708 $arr['uid'] = intval(api_user());
4710 $arr['type'] = 'photo';
4712 $arr['resource-id'] = $hash;
4713 $arr['contact-id'] = $owner_record['id'];
4714 $arr['owner-name'] = $owner_record['name'];
4715 $arr['owner-link'] = $owner_record['url'];
4716 $arr['owner-avatar'] = $owner_record['thumb'];
4717 $arr['author-name'] = $owner_record['name'];
4718 $arr['author-link'] = $owner_record['url'];
4719 $arr['author-avatar'] = $owner_record['thumb'];
4721 $arr['allow_cid'] = $allow_cid;
4722 $arr['allow_gid'] = $allow_gid;
4723 $arr['deny_cid'] = $deny_cid;
4724 $arr['deny_gid'] = $deny_gid;
4725 $arr['visible'] = $visibility;
4729 'image/jpeg' => 'jpg',
4730 'image/png' => 'png',
4731 'image/gif' => 'gif'
4734 // adds link to the thumbnail scale photo
4735 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4736 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4739 // do the magic for storing the item in the database and trigger the federation to other contacts
4745 * @param string $type
4747 * @param string $photo_id
4750 * @throws BadRequestException
4751 * @throws ForbiddenException
4752 * @throws ImagickException
4753 * @throws InternalServerErrorException
4754 * @throws NotFoundException
4755 * @throws UnauthorizedException
4757 function prepare_photo_data($type, $scale, $photo_id)
4760 $user_info = api_get_user($a);
4762 if ($user_info === false) {
4763 throw new ForbiddenException();
4766 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4767 $data_sql = ($scale === false ? "" : "data, ");
4769 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4770 // clients needs to convert this in their way for further processing
4771 $r = DBA::toArray(DBA::p(
4772 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4773 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4774 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4775 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4776 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4777 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4783 'image/jpeg' => 'jpg',
4784 'image/png' => 'png',
4785 'image/gif' => 'gif'
4788 // prepare output data for photo
4789 if (DBA::isResult($r)) {
4790 $data = ['photo' => $r[0]];
4791 $data['photo']['id'] = $data['photo']['resource-id'];
4792 if ($scale !== false) {
4793 $data['photo']['data'] = base64_encode($data['photo']['data']);
4795 unset($data['photo']['datasize']); //needed only with scale param
4797 if ($type == "xml") {
4798 $data['photo']['links'] = [];
4799 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4800 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4802 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4805 $data['photo']['link'] = [];
4806 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4808 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4809 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4813 unset($data['photo']['resource-id']);
4814 unset($data['photo']['minscale']);
4815 unset($data['photo']['maxscale']);
4817 throw new NotFoundException();
4820 // retrieve item element for getting activities (like, dislike etc.) related to photo
4821 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4822 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4823 if (!DBA::isResult($item)) {
4824 throw new NotFoundException('Photo-related item not found.');
4827 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4829 // retrieve comments on photo
4830 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4831 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4833 $statuses = Post::selectForUser(api_user(), [], $condition);
4835 // prepare output of comments
4836 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4838 if ($type == "xml") {
4840 foreach ($commentData as $comment) {
4841 $comments[$k++ . ":comment"] = $comment;
4844 foreach ($commentData as $comment) {
4845 $comments[] = $comment;
4848 $data['photo']['friendica_comments'] = $comments;
4850 // include info if rights on photo and rights on item are mismatching
4851 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4852 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4853 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4854 $data['photo']['deny_gid'] != $item['deny_gid'];
4855 $data['photo']['rights_mismatch'] = $rights_mismatch;
4861 * Return an item with announcer data if it had been announced
4863 * @param array $item Item array
4864 * @return array Item array with announce data
4866 function api_get_announce($item)
4868 // Quit if the item already has got a different owner and author
4869 if ($item['owner-id'] != $item['author-id']) {
4873 // Don't change original or Diaspora posts
4874 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4878 // Quit if we do now the original author and it had been a post from a native network
4879 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4883 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4884 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4885 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4886 if (!DBA::isResult($announce)) {
4890 return array_merge($item, $announce);
4895 * @param array $item
4900 function api_in_reply_to($item)
4904 $in_reply_to['status_id'] = null;
4905 $in_reply_to['user_id'] = null;
4906 $in_reply_to['status_id_str'] = null;
4907 $in_reply_to['user_id_str'] = null;
4908 $in_reply_to['screen_name'] = null;
4910 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4911 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4912 if (DBA::isResult($parent)) {
4913 $in_reply_to['status_id'] = intval($parent['id']);
4915 $in_reply_to['status_id'] = intval($item['parent']);
4918 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4920 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4921 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4923 if (DBA::isResult($parent)) {
4924 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4925 $in_reply_to['user_id'] = intval($parent['author-id']);
4926 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4929 // There seems to be situation, where both fields are identical:
4930 // https://github.com/friendica/friendica/issues/1010
4931 // This is a bugfix for that.
4932 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4933 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']]);
4934 $in_reply_to['status_id'] = null;
4935 $in_reply_to['user_id'] = null;
4936 $in_reply_to['status_id_str'] = null;
4937 $in_reply_to['user_id_str'] = null;
4938 $in_reply_to['screen_name'] = null;
4942 return $in_reply_to;
4947 * @param string $text
4950 * @throws InternalServerErrorException
4952 function api_clean_plain_items($text)
4954 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4956 $text = BBCode::cleanPictureLinks($text);
4957 $URLSearchString = "^\[\]";
4959 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4961 if ($include_entities == "true") {
4962 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4965 // Simplify "attachment" element
4966 $text = BBCode::removeAttachment($text);
4973 * @param array $contacts
4977 function api_best_nickname(&$contacts)
4981 if (count($contacts) == 0) {
4985 foreach ($contacts as $contact) {
4986 if ($contact["network"] == "") {
4987 $contact["network"] = "dfrn";
4988 $best_contact = [$contact];
4992 if (sizeof($best_contact) == 0) {
4993 foreach ($contacts as $contact) {
4994 if ($contact["network"] == "dfrn") {
4995 $best_contact = [$contact];
5000 if (sizeof($best_contact) == 0) {
5001 foreach ($contacts as $contact) {
5002 if ($contact["network"] == "dspr") {
5003 $best_contact = [$contact];
5008 if (sizeof($best_contact) == 0) {
5009 foreach ($contacts as $contact) {
5010 if ($contact["network"] == "stat") {
5011 $best_contact = [$contact];
5016 if (sizeof($best_contact) == 0) {
5017 foreach ($contacts as $contact) {
5018 if ($contact["network"] == "pump") {
5019 $best_contact = [$contact];
5024 if (sizeof($best_contact) == 0) {
5025 foreach ($contacts as $contact) {
5026 if ($contact["network"] == "twit") {
5027 $best_contact = [$contact];
5032 if (sizeof($best_contact) == 1) {
5033 $contacts = $best_contact;
5035 $contacts = [$contacts[0]];
5040 * Return all or a specified group of the user with the containing contacts.
5042 * @param string $type Return type (atom, rss, xml, json)
5044 * @return array|string
5045 * @throws BadRequestException
5046 * @throws ForbiddenException
5047 * @throws ImagickException
5048 * @throws InternalServerErrorException
5049 * @throws UnauthorizedException
5051 function api_friendica_group_show($type)
5055 if (api_user() === false) {
5056 throw new ForbiddenException();
5060 $user_info = api_get_user($a);
5061 $gid = $_REQUEST['gid'] ?? 0;
5062 $uid = $user_info['uid'];
5064 // get data of the specified group id or all groups if not specified
5066 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
5068 // error message if specified gid is not in database
5069 if (!DBA::isResult($groups)) {
5070 throw new BadRequestException("gid not available");
5073 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
5076 // loop through all groups and retrieve all members for adding data in the user array
5078 foreach ($groups as $rr) {
5079 $members = Contact\Group::getById($rr['id']);
5082 if ($type == "xml") {
5083 $user_element = "users";
5085 foreach ($members as $member) {
5086 $user = api_get_user($a, $member['nurl']);
5087 $users[$k++.":user"] = $user;
5090 $user_element = "user";
5091 foreach ($members as $member) {
5092 $user = api_get_user($a, $member['nurl']);
5096 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5098 return api_format_data("groups", $type, ['group' => $grps]);
5100 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5104 * Delete the specified group of the user.
5106 * @param string $type Return type (atom, rss, xml, json)
5108 * @return array|string
5109 * @throws BadRequestException
5110 * @throws ForbiddenException
5111 * @throws ImagickException
5112 * @throws InternalServerErrorException
5113 * @throws UnauthorizedException
5115 function api_friendica_group_delete($type)
5119 if (api_user() === false) {
5120 throw new ForbiddenException();
5124 $user_info = api_get_user($a);
5125 $gid = $_REQUEST['gid'] ?? 0;
5126 $name = $_REQUEST['name'] ?? '';
5127 $uid = $user_info['uid'];
5129 // error if no gid specified
5130 if ($gid == 0 || $name == "") {
5131 throw new BadRequestException('gid or name not specified');
5134 // error message if specified gid is not in database
5135 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) {
5136 throw new BadRequestException('gid not available');
5139 // error message if specified gid is not in database
5140 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) {
5141 throw new BadRequestException('wrong group name');
5145 $ret = Group::removeByName($uid, $name);
5148 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5149 return api_format_data("group_delete", $type, ['result' => $success]);
5151 throw new BadRequestException('other API error');
5154 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5159 * @param string $type Return type (atom, rss, xml, json)
5161 * @return array|string
5162 * @throws BadRequestException
5163 * @throws ForbiddenException
5164 * @throws ImagickException
5165 * @throws InternalServerErrorException
5166 * @throws UnauthorizedException
5167 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5169 function api_lists_destroy($type)
5173 if (api_user() === false) {
5174 throw new ForbiddenException();
5178 $user_info = api_get_user($a);
5179 $gid = $_REQUEST['list_id'] ?? 0;
5180 $uid = $user_info['uid'];
5182 // error if no gid specified
5184 throw new BadRequestException('gid not specified');
5187 // get data of the specified group id
5188 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5189 // error message if specified gid is not in database
5191 throw new BadRequestException('gid not available');
5194 if (Group::remove($gid)) {
5196 'name' => $group['name'],
5197 'id' => intval($gid),
5198 'id_str' => (string) $gid,
5199 'user' => $user_info
5202 return api_format_data("lists", $type, ['lists' => $list]);
5205 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5208 * Add a new group to the database.
5210 * @param string $name Group name
5211 * @param int $uid User ID
5212 * @param array $users List of users to add to the group
5215 * @throws BadRequestException
5217 function group_create($name, $uid, $users = [])
5219 // error if no name specified
5221 throw new BadRequestException('group name not specified');
5224 // error message if specified group name already exists
5225 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
5226 throw new BadRequestException('group name already exists');
5229 // Check if the group needs to be reactivated
5230 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
5231 $reactivate_group = true;
5235 $ret = Group::create($uid, $name);
5237 $gid = Group::getIdByName($uid, $name);
5239 throw new BadRequestException('other API error');
5243 $erroraddinguser = false;
5245 foreach ($users as $user) {
5246 $cid = $user['cid'];
5247 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
5248 Group::addMember($gid, $cid);
5250 $erroraddinguser = true;
5251 $errorusers[] = $cid;
5255 // return success message incl. missing users in array
5256 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5258 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5262 * Create the specified group with the posted array of contacts.
5264 * @param string $type Return type (atom, rss, xml, json)
5266 * @return array|string
5267 * @throws BadRequestException
5268 * @throws ForbiddenException
5269 * @throws ImagickException
5270 * @throws InternalServerErrorException
5271 * @throws UnauthorizedException
5273 function api_friendica_group_create($type)
5277 if (api_user() === false) {
5278 throw new ForbiddenException();
5282 $user_info = api_get_user($a);
5283 $name = $_REQUEST['name'] ?? '';
5284 $uid = $user_info['uid'];
5285 $json = json_decode($_POST['json'], true);
5286 $users = $json['user'];
5288 $success = group_create($name, $uid, $users);
5290 return api_format_data("group_create", $type, ['result' => $success]);
5292 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5295 * Create a new group.
5297 * @param string $type Return type (atom, rss, xml, json)
5299 * @return array|string
5300 * @throws BadRequestException
5301 * @throws ForbiddenException
5302 * @throws ImagickException
5303 * @throws InternalServerErrorException
5304 * @throws UnauthorizedException
5305 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5307 function api_lists_create($type)
5311 if (api_user() === false) {
5312 throw new ForbiddenException();
5316 $user_info = api_get_user($a);
5317 $name = $_REQUEST['name'] ?? '';
5318 $uid = $user_info['uid'];
5320 $success = group_create($name, $uid);
5321 if ($success['success']) {
5323 'name' => $success['name'],
5324 'id' => intval($success['gid']),
5325 'id_str' => (string) $success['gid'],
5326 'user' => $user_info
5329 return api_format_data("lists", $type, ['lists'=>$grp]);
5332 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5335 * Update the specified group with the posted array of contacts.
5337 * @param string $type Return type (atom, rss, xml, json)
5339 * @return array|string
5340 * @throws BadRequestException
5341 * @throws ForbiddenException
5342 * @throws ImagickException
5343 * @throws InternalServerErrorException
5344 * @throws UnauthorizedException
5346 function api_friendica_group_update($type)
5350 if (api_user() === false) {
5351 throw new ForbiddenException();
5355 $user_info = api_get_user($a);
5356 $uid = $user_info['uid'];
5357 $gid = $_REQUEST['gid'] ?? 0;
5358 $name = $_REQUEST['name'] ?? '';
5359 $json = json_decode($_POST['json'], true);
5360 $users = $json['user'];
5362 // error if no name specified
5364 throw new BadRequestException('group name not specified');
5367 // error if no gid specified
5369 throw new BadRequestException('gid not specified');
5373 $members = Contact\Group::getById($gid);
5374 foreach ($members as $member) {
5375 $cid = $member['id'];
5376 foreach ($users as $user) {
5377 $found = ($user['cid'] == $cid ? true : false);
5379 if (!isset($found) || !$found) {
5380 Group::removeMemberByName($uid, $name, $cid);
5385 $erroraddinguser = false;
5387 foreach ($users as $user) {
5388 $cid = $user['cid'];
5390 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
5391 Group::addMember($gid, $cid);
5393 $erroraddinguser = true;
5394 $errorusers[] = $cid;
5398 // return success message incl. missing users in array
5399 $status = ($erroraddinguser ? "missing user" : "ok");
5400 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5401 return api_format_data("group_update", $type, ['result' => $success]);
5404 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5407 * Update information about a group.
5409 * @param string $type Return type (atom, rss, xml, json)
5411 * @return array|string
5412 * @throws BadRequestException
5413 * @throws ForbiddenException
5414 * @throws ImagickException
5415 * @throws InternalServerErrorException
5416 * @throws UnauthorizedException
5417 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5419 function api_lists_update($type)
5423 if (api_user() === false) {
5424 throw new ForbiddenException();
5428 $user_info = api_get_user($a);
5429 $gid = $_REQUEST['list_id'] ?? 0;
5430 $name = $_REQUEST['name'] ?? '';
5431 $uid = $user_info['uid'];
5433 // error if no gid specified
5435 throw new BadRequestException('gid not specified');
5438 // get data of the specified group id
5439 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5440 // error message if specified gid is not in database
5442 throw new BadRequestException('gid not available');
5445 if (Group::update($gid, $name)) {
5448 'id' => intval($gid),
5449 'id_str' => (string) $gid,
5450 'user' => $user_info
5453 return api_format_data("lists", $type, ['lists' => $list]);
5457 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5461 * @param string $type Return type (atom, rss, xml, json)
5463 * @return array|string
5464 * @throws BadRequestException
5465 * @throws ForbiddenException
5466 * @throws ImagickException
5467 * @throws InternalServerErrorException
5469 function api_friendica_activity($type)
5473 if (api_user() === false) {
5474 throw new ForbiddenException();
5476 $verb = strtolower(DI::args()->getArgv()[3]);
5477 $verb = preg_replace("|\..*$|", "", $verb);
5479 $id = $_REQUEST['id'] ?? 0;
5481 $res = Item::performActivity($id, $verb, api_user());
5484 if ($type == "xml") {
5489 return api_format_data('ok', $type, ['ok' => $ok]);
5491 throw new BadRequestException('Error adding activity');
5495 /// @TODO move to top of file or somewhere better
5496 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5497 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5498 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5499 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5500 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5501 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5502 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5503 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5504 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5505 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5508 * Returns notifications
5510 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5512 * @return string|array
5513 * @throws ForbiddenException
5514 * @throws BadRequestException
5517 function api_friendica_notification($type)
5519 if (api_user() === false) {
5520 throw new ForbiddenException();
5522 if (DI::args()->getArgc()!==3) {
5523 throw new BadRequestException('Invalid argument count');
5526 $Notifies = DI::notify()->selectAllForUser(local_user(), 50);
5528 $notifications = new ApiNotifications();
5529 foreach ($Notifies as $Notify) {
5530 $notifications[] = new ApiNotification($Notify);
5533 if ($type == 'xml') {
5535 foreach ($notifications as $notification) {
5536 $xmlnotes[] = ['@attributes' => $notification->toArray()];
5539 $result = $xmlnotes;
5540 } elseif (count($notifications) > 0) {
5541 $result = $notifications->getArrayCopy();
5546 return api_format_data('notes', $type, ['note' => $result]);
5550 * Set notification as seen and returns associated item (if possible)
5552 * POST request with 'id' param as notification id
5554 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5555 * @return string|array
5556 * @throws BadRequestException
5557 * @throws ForbiddenException
5558 * @throws ImagickException
5559 * @throws InternalServerErrorException
5560 * @throws UnauthorizedException
5562 function api_friendica_notification_seen($type)
5565 $user_info = api_get_user($a);
5567 if (api_user() === false || $user_info === false) {
5568 throw new ForbiddenException();
5570 if (DI::args()->getArgc() !== 4) {
5571 throw new BadRequestException('Invalid argument count');
5574 $id = intval($_REQUEST['id'] ?? 0);
5577 $Notify = DI::notify()->selectOneById($id);
5578 if ($Notify->uid !== api_user()) {
5579 throw new NotFoundException();
5582 if ($Notify->uriId) {
5583 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
5587 DI::notify()->save($Notify);
5589 if ($Notify->otype === Notification\ObjectType::ITEM) {
5590 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
5591 if (DBA::isResult($item)) {
5592 // we found the item, return it to the user
5593 $ret = api_format_items([$item], $user_info, false, $type);
5594 $data = ['status' => $ret];
5595 return api_format_data('status', $type, $data);
5597 // the item can't be found, but we set the notification as seen, so we count this as a success
5600 return api_format_data('result', $type, ['result' => 'success']);
5601 } catch (NotFoundException $e) {
5602 throw new BadRequestException('Invalid argument', $e);
5603 } catch (Exception $e) {
5604 throw new InternalServerErrorException('Internal Server exception', $e);
5608 /// @TODO move to top of file or somewhere better
5609 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5610 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5613 * update a direct_message to seen state
5615 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5616 * @return string|array (success result=ok, error result=error with error message)
5617 * @throws BadRequestException
5618 * @throws ForbiddenException
5619 * @throws ImagickException
5620 * @throws InternalServerErrorException
5621 * @throws UnauthorizedException
5623 function api_friendica_direct_messages_setseen($type)
5626 if (api_user() === false) {
5627 throw new ForbiddenException();
5631 $user_info = api_get_user($a);
5632 $uid = $user_info['uid'];
5633 $id = $_REQUEST['id'] ?? 0;
5635 // return error if id is zero
5637 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5638 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5641 // error message if specified id is not in database
5642 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5643 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5644 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5647 // update seen indicator
5648 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5652 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5653 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5655 $answer = ['result' => 'error', 'message' => 'unknown error'];
5656 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5660 /// @TODO move to top of file or somewhere better
5661 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5664 * search for direct_messages containing a searchstring through api
5666 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5667 * @param string $box
5668 * @return string|array (success: success=true if found and search_result contains found messages,
5669 * success=false if nothing was found, search_result='nothing found',
5670 * error: result=error with error message)
5671 * @throws BadRequestException
5672 * @throws ForbiddenException
5673 * @throws ImagickException
5674 * @throws InternalServerErrorException
5675 * @throws UnauthorizedException
5677 function api_friendica_direct_messages_search($type, $box = "")
5681 if (api_user() === false) {
5682 throw new ForbiddenException();
5686 $user_info = api_get_user($a);
5687 $searchstring = $_REQUEST['searchstring'] ?? '';
5688 $uid = $user_info['uid'];
5690 // error if no searchstring specified
5691 if ($searchstring == "") {
5692 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5693 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5696 // get data for the specified searchstring
5697 $r = DBA::toArray(DBA::p(
5698 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
5700 '%'.$searchstring.'%'
5703 $profile_url = $user_info["url"];
5705 // message if nothing was found
5706 if (!DBA::isResult($r)) {
5707 $success = ['success' => false, 'search_results' => 'problem with query'];
5708 } elseif (count($r) == 0) {
5709 $success = ['success' => false, 'search_results' => 'nothing found'];
5712 foreach ($r as $item) {
5713 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5714 $recipient = $user_info;
5715 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5716 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5717 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5718 $sender = $user_info;
5721 if (isset($recipient) && isset($sender)) {
5722 $ret[] = api_format_messages($item, $recipient, $sender);
5725 $success = ['success' => true, 'search_results' => $ret];
5728 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5731 /// @TODO move to top of file or somewhere better
5732 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5735 * Returns a list of saved searches.
5737 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5739 * @param string $type Return format: json or xml
5741 * @return string|array
5744 function api_saved_searches_list($type)
5746 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5749 while ($term = DBA::fetch($terms)) {
5751 'created_at' => api_date(time()),
5752 'id' => intval($term['id']),
5753 'id_str' => $term['id'],
5754 'name' => $term['term'],
5756 'query' => $term['term']
5762 return api_format_data("terms", $type, ['terms' => $result]);
5765 /// @TODO move to top of file or somewhere better
5766 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5769 * Number of comments
5771 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5773 * @param object $data [Status, Status]
5777 function bindComments(&$data)
5779 if (count($data) == 0) {
5785 foreach ($data as $item) {
5786 $ids[] = $item['id'];
5789 $idStr = DBA::escape(implode(', ', $ids));
5790 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5791 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5792 $itemsData = DBA::toArray($items);
5794 foreach ($itemsData as $item) {
5795 $comments[$item['parent']] = $item['comments'];
5798 foreach ($data as $idx => $item) {
5800 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5805 @TODO Maybe open to implement?
5807 [pagename] => api/1.1/statuses/lookup.json
5808 [id] => 605138389168451584
5809 [include_cards] => true
5810 [cards_platform] => Android-12
5811 [include_entities] => true
5812 [include_my_retweet] => 1
5814 [include_reply_count] => true
5815 [include_descendent_reply_count] => true
5819 Not implemented by now:
5820 statuses/retweets_of_me
5825 account/update_location
5826 account/update_profile_background_image
5829 friendica/profile/update
5830 friendica/profile/create
5831 friendica/profile/delete
5833 Not implemented in status.net:
5834 statuses/retweeted_to_me
5835 statuses/retweeted_by_me
5836 direct_messages/destroy
5838 account/update_delivery_device
5839 notifications/follow