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 = DBA::escape(Strings::normaliseLink($contact_id));
497 $extra_query = "AND `contact`.`nurl` = '%s' ";
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 = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
508 throw new BadRequestException("User ID ".$contact_id." not found.");
512 $extra_query = "AND `contact`.`nurl` = '%s' ";
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 = DBA::escape(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` = '%s' ";
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 = DBA::escape($_GET['screen_name']);
533 $extra_query = "AND `contact`.`nick` = '%s' ";
534 if (api_user() !== false) {
535 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
539 if (is_null($user) && !empty($_GET['profileurl'])) {
540 $user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
541 $extra_query = "AND `contact`.`nurl` = '%s' ";
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 = DBA::escape(api_unique_id_to_nurl(intval($user)));
561 $extra_query = "AND `contact`.`nurl` = '%s' ";
562 if (api_user() !== false) {
563 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
567 $user = DBA::escape($user);
568 $extra_query = "AND `contact`.`nick` = '%s' ";
569 if (api_user() !== false) {
570 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
575 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
578 if (api_user() === false) {
583 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
587 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
591 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
597 // Selecting the id by priority, friendica first
598 if (is_array($uinfo)) {
599 api_best_nickname($uinfo);
602 // if the contact wasn't found, fetch it from the contacts with uid = 0
603 if (!DBA::isResult($uinfo)) {
605 throw new BadRequestException("User not found.");
608 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
610 if (DBA::isResult($contact)) {
612 'id' => $contact["id"],
613 'id_str' => (string) $contact["id"],
614 'name' => $contact["name"],
615 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
616 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
617 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
618 'profile_image_url' => $contact["micro"],
619 'profile_image_url_https' => $contact["micro"],
620 'profile_image_url_profile_size' => $contact["thumb"],
621 'profile_image_url_large' => $contact["photo"],
622 'url' => $contact["url"],
623 'protected' => false,
624 'followers_count' => 0,
625 'friends_count' => 0,
627 'created_at' => api_date($contact["created"]),
628 'favourites_count' => 0,
630 'time_zone' => 'UTC',
631 'geo_enabled' => false,
633 'statuses_count' => 0,
635 'contributors_enabled' => false,
636 'is_translator' => false,
637 'is_translation_enabled' => false,
638 'following' => false,
639 'follow_request_sent' => false,
640 'statusnet_blocking' => false,
641 'notifications' => false,
642 'statusnet_profile_url' => $contact["url"],
644 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
645 'pid' => Contact::getIdForURL($contact["url"], 0, false),
647 'network' => $contact["network"],
652 throw new BadRequestException("User ".$url." not found.");
656 if ($uinfo[0]['self']) {
657 if ($uinfo[0]['network'] == "") {
658 $uinfo[0]['network'] = Protocol::DFRN;
661 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
662 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
669 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
671 if (!empty($profile['about'])) {
672 $description = $profile['about'];
674 $description = $uinfo[0]["about"];
677 if (!empty($usr['default-location'])) {
678 $location = $usr['default-location'];
679 } elseif (!empty($uinfo[0]["location"])) {
680 $location = $uinfo[0]["location"];
682 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
686 'id' => intval($pcontact_id),
687 'id_str' => (string) intval($pcontact_id),
688 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
689 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
690 'location' => $location,
691 'description' => BBCode::toPlaintext($description ?? ''),
692 'profile_image_url' => $uinfo[0]['micro'],
693 'profile_image_url_https' => $uinfo[0]['micro'],
694 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
695 'profile_image_url_large' => $uinfo[0]["photo"],
696 'url' => $uinfo[0]['url'],
697 'protected' => false,
698 'followers_count' => intval($countfollowers),
699 'friends_count' => intval($countfriends),
701 'created_at' => api_date($uinfo[0]['created']),
702 'favourites_count' => intval($starred),
704 'time_zone' => 'UTC',
705 'geo_enabled' => false,
707 'statuses_count' => intval($countitems),
709 'contributors_enabled' => false,
710 'is_translator' => false,
711 'is_translation_enabled' => false,
712 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
713 'follow_request_sent' => false,
714 'statusnet_blocking' => false,
715 'notifications' => false,
717 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
718 'statusnet_profile_url' => $uinfo[0]['url'],
719 'uid' => intval($uinfo[0]['uid']),
720 'cid' => intval($uinfo[0]['cid']),
721 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
722 'self' => $uinfo[0]['self'],
723 'network' => $uinfo[0]['network'],
726 // If this is a local user and it uses Frio, we can get its color preferences.
728 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
729 if ($theme_info['theme'] === 'frio') {
730 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
732 if ($schema && ($schema != '---')) {
733 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
734 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
735 require_once $schemefile;
738 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
739 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
740 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
742 if (empty($nav_bg)) {
745 if (empty($link_color)) {
746 $link_color = "#6fdbe8";
748 if (empty($bgcolor)) {
749 $bgcolor = "#ededed";
752 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
753 $ret['profile_link_color'] = str_replace('#', '', $link_color);
754 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
762 * return api-formatted array for item's author and owner
765 * @param array $item item from db
766 * @return array(array:author, array:owner)
767 * @throws BadRequestException
768 * @throws ImagickException
769 * @throws InternalServerErrorException
770 * @throws UnauthorizedException
772 function api_item_get_user(App $a, $item)
774 $status_user = api_get_user($a, $item['author-id'] ?? null);
776 $author_user = $status_user;
778 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
780 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
781 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
783 $owner_user = $author_user;
786 return ([$status_user, $author_user, $owner_user]);
790 * walks recursively through an array with the possibility to change value and key
792 * @param array $array The array to walk through
793 * @param callable $callback The callback function
795 * @return array the transformed array
797 function api_walk_recursive(array &$array, callable $callback)
801 foreach ($array as $k => $v) {
803 if ($callback($v, $k)) {
804 $new_array[$k] = api_walk_recursive($v, $callback);
807 if ($callback($v, $k)) {
818 * Callback function to transform the array in an array that can be transformed in a XML file
820 * @param mixed $item Array item value
821 * @param string $key Array key
823 * @return boolean Should the array item be deleted?
825 function api_reformat_xml(&$item, &$key)
827 if (is_bool($item)) {
828 $item = ($item ? "true" : "false");
831 if (substr($key, 0, 10) == "statusnet_") {
832 $key = "statusnet:".substr($key, 10);
833 } elseif (substr($key, 0, 10) == "friendica_") {
834 $key = "friendica:".substr($key, 10);
836 /// @TODO old-lost code?
838 // $key = "default:".$key;
844 * Creates the XML from a JSON style array
846 * @param array $data JSON style array
847 * @param string $root_element Name of the root element
849 * @return string The XML data
851 function api_create_xml(array $data, $root_element)
853 $childname = key($data);
854 $data2 = array_pop($data);
856 $namespaces = ["" => "http://api.twitter.com",
857 "statusnet" => "http://status.net/schema/api/1/",
858 "friendica" => "http://friendi.ca/schema/api/1/",
859 "georss" => "http://www.georss.org/georss"];
861 /// @todo Auto detection of needed namespaces
862 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
866 if (is_array($data2)) {
868 api_walk_recursive($data2, "api_reformat_xml");
874 foreach ($data2 as $item) {
875 $data4[$i++ . ":" . $childname] = $item;
882 $data3 = [$root_element => $data2];
884 $ret = XML::fromArray($data3, $xml, false, $namespaces);
889 * Formats the data according to the data type
891 * @param string $root_element Name of the root element
892 * @param string $type Return type (atom, rss, xml, json)
893 * @param array $data JSON style array
895 * @return array|string (string|array) XML data or JSON data
897 function api_format_data($root_element, $type, $data)
903 $ret = api_create_xml($data, $root_element);
918 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
919 * returns a 401 status code and an error message if not.
921 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
923 * @param string $type Return type (atom, rss, xml, json)
924 * @return array|string
925 * @throws BadRequestException
926 * @throws ForbiddenException
927 * @throws ImagickException
928 * @throws InternalServerErrorException
929 * @throws UnauthorizedException
931 function api_account_verify_credentials($type)
935 if (api_user() === false) {
936 throw new ForbiddenException();
939 unset($_REQUEST["user_id"]);
940 unset($_GET["user_id"]);
942 unset($_REQUEST["screen_name"]);
943 unset($_GET["screen_name"]);
945 $skip_status = $_REQUEST['skip_status'] ?? false;
947 $user_info = api_get_user($a);
949 // "verified" isn't used here in the standard
950 unset($user_info["verified"]);
952 // - Adding last status
954 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
956 $user_info['status'] = api_format_item($item, $type);
960 // "uid" and "self" are only needed for some internal stuff, so remove it from here
961 unset($user_info["uid"]);
962 unset($user_info["self"]);
964 return api_format_data("user", $type, ['user' => $user_info]);
967 /// @TODO move to top of file or somewhere better
968 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
971 * Get data from $_POST or $_GET
976 function requestdata($k)
978 if (!empty($_POST[$k])) {
981 if (!empty($_GET[$k])) {
988 * Deprecated function to upload media.
990 * @param string $type Return type (atom, rss, xml, json)
992 * @return array|string
993 * @throws BadRequestException
994 * @throws ForbiddenException
995 * @throws ImagickException
996 * @throws InternalServerErrorException
997 * @throws UnauthorizedException
999 function api_statuses_mediap($type)
1003 if (api_user() === false) {
1004 Logger::log('api_statuses_update: no user');
1005 throw new ForbiddenException();
1007 $user_info = api_get_user($a);
1009 $_REQUEST['profile_uid'] = api_user();
1010 $_REQUEST['api_source'] = true;
1011 $txt = requestdata('status') ?? '';
1012 /// @TODO old-lost code?
1013 //$txt = urldecode(requestdata('status'));
1015 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1016 $txt = HTML::toBBCodeVideo($txt);
1017 $config = HTMLPurifier_Config::createDefault();
1018 $config->set('Cache.DefinitionImpl', null);
1019 $purifier = new HTMLPurifier($config);
1020 $txt = $purifier->purify($txt);
1022 $txt = HTML::toBBCode($txt);
1024 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
1026 $picture = wall_upload_post($a, false);
1028 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1029 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1030 $item_id = item_post($a);
1032 // output the post that we just posted.
1033 return api_status_show($type, $item_id);
1036 /// @TODO move this to top of file or somewhere better!
1037 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1040 * Updates the user’s current status.
1042 * @param string $type Return type (atom, rss, xml, json)
1044 * @return array|string
1045 * @throws BadRequestException
1046 * @throws ForbiddenException
1047 * @throws ImagickException
1048 * @throws InternalServerErrorException
1049 * @throws TooManyRequestsException
1050 * @throws UnauthorizedException
1051 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1053 function api_statuses_update($type)
1057 if (api_user() === false) {
1058 Logger::log('api_statuses_update: no user');
1059 throw new ForbiddenException();
1064 // convert $_POST array items to the form we use for web posts.
1065 if (requestdata('htmlstatus')) {
1066 $txt = requestdata('htmlstatus') ?? '';
1067 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1068 $txt = HTML::toBBCodeVideo($txt);
1070 $config = HTMLPurifier_Config::createDefault();
1071 $config->set('Cache.DefinitionImpl', null);
1073 $purifier = new HTMLPurifier($config);
1074 $txt = $purifier->purify($txt);
1076 $_REQUEST['body'] = HTML::toBBCode($txt);
1079 $_REQUEST['body'] = requestdata('status');
1082 $_REQUEST['title'] = requestdata('title');
1084 $parent = requestdata('in_reply_to_status_id');
1086 // Twidere sends "-1" if it is no reply ...
1087 if ($parent == -1) {
1091 if (ctype_digit($parent)) {
1092 $_REQUEST['parent'] = $parent;
1094 $_REQUEST['parent_uri'] = $parent;
1097 if (requestdata('lat') && requestdata('long')) {
1098 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1100 $_REQUEST['profile_uid'] = api_user();
1103 // Check for throttling (maximum posts per day, week and month)
1104 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1105 if ($throttle_day > 0) {
1106 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1108 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1109 $posts_day = Post::count($condition);
1111 if ($posts_day > $throttle_day) {
1112 Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
1113 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1114 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));
1118 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1119 if ($throttle_week > 0) {
1120 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1122 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1123 $posts_week = Post::count($condition);
1125 if ($posts_week > $throttle_week) {
1126 Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
1127 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1128 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));
1132 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1133 if ($throttle_month > 0) {
1134 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1136 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1137 $posts_month = Post::count($condition);
1139 if ($posts_month > $throttle_month) {
1140 Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
1141 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1142 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));
1147 if (requestdata('media_ids')) {
1148 $ids = explode(',', requestdata('media_ids') ?? '');
1149 } elseif (!empty($_FILES['media'])) {
1150 // upload the image if we have one
1151 $picture = wall_upload_post($a, false);
1152 if (is_array($picture)) {
1153 $ids[] = $picture['id'];
1161 foreach ($ids as $id) {
1162 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1163 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1164 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1165 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1167 if (!empty($media)) {
1168 $ressources[] = $media[0]['resource-id'];
1169 $phototypes = Images::supportedTypes();
1170 $ext = $phototypes[$media[0]['type']];
1172 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1173 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1174 'size' => $media[0]['datasize'],
1175 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1176 'description' => $media[0]['desc'] ?? '',
1177 'width' => $media[0]['width'],
1178 'height' => $media[0]['height']];
1180 if (count($media) > 1) {
1181 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1182 $attachment['preview-width'] = $media[1]['width'];
1183 $attachment['preview-height'] = $media[1]['height'];
1185 $attachments[] = $attachment;
1189 // We have to avoid that the post is rejected because of an empty body
1190 if (empty($_REQUEST['body'])) {
1191 $_REQUEST['body'] = '[hr]';
1195 if (!empty($attachments)) {
1196 $_REQUEST['attachments'] = $attachments;
1199 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1201 $_REQUEST['api_source'] = true;
1203 if (empty($_REQUEST['source'])) {
1204 $_REQUEST["source"] = api_source();
1207 // call out normal post function
1208 $item_id = item_post($a);
1210 if (!empty($ressources) && !empty($item_id)) {
1211 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1212 foreach ($ressources as $ressource) {
1213 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1217 // output the post that we just posted.
1218 return api_status_show($type, $item_id);
1221 /// @TODO move to top of file or somewhere better
1222 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1223 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1226 * Uploads an image to Friendica.
1229 * @throws BadRequestException
1230 * @throws ForbiddenException
1231 * @throws ImagickException
1232 * @throws InternalServerErrorException
1233 * @throws UnauthorizedException
1234 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1236 function api_media_upload()
1240 if (api_user() === false) {
1241 Logger::log('no user');
1242 throw new ForbiddenException();
1247 if (empty($_FILES['media'])) {
1249 throw new BadRequestException("No media.");
1252 $media = wall_upload_post($a, false);
1255 throw new InternalServerErrorException();
1259 $returndata["media_id"] = $media["id"];
1260 $returndata["media_id_string"] = (string)$media["id"];
1261 $returndata["size"] = $media["size"];
1262 $returndata["image"] = ["w" => $media["width"],
1263 "h" => $media["height"],
1264 "image_type" => $media["type"],
1265 "friendica_preview_url" => $media["preview"]];
1267 Logger::info('Media uploaded', ['return' => $returndata]);
1269 return ["media" => $returndata];
1272 /// @TODO move to top of file or somewhere better
1273 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1276 * Updates media meta data (picture descriptions)
1278 * @param string $type Return type (atom, rss, xml, json)
1280 * @return array|string
1281 * @throws BadRequestException
1282 * @throws ForbiddenException
1283 * @throws ImagickException
1284 * @throws InternalServerErrorException
1285 * @throws TooManyRequestsException
1286 * @throws UnauthorizedException
1287 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1289 * @todo Compare the corresponding Twitter function for correct return values
1291 function api_media_metadata_create($type)
1295 if (api_user() === false) {
1296 Logger::info('no user');
1297 throw new ForbiddenException();
1302 $postdata = Network::postdata();
1304 if (empty($postdata)) {
1305 throw new BadRequestException("No post data");
1308 $data = json_decode($postdata, true);
1310 throw new BadRequestException("Invalid post data");
1313 if (empty($data['media_id']) || empty($data['alt_text'])) {
1314 throw new BadRequestException("Missing post data values");
1317 if (empty($data['alt_text']['text'])) {
1318 throw new BadRequestException("No alt text.");
1321 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1323 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1324 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1325 if (!DBA::isResult($photo)) {
1326 throw new BadRequestException("Metadata not found.");
1329 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1332 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1335 * @param string $type Return format (atom, rss, xml, json)
1336 * @param int $item_id
1337 * @return array|string
1340 function api_status_show($type, $item_id)
1342 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1346 $item = api_get_item(['id' => $item_id]);
1347 if (!empty($item)) {
1348 $status_info = api_format_item($item, $type);
1351 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1353 return api_format_data('statuses', $type, ['status' => $status_info]);
1357 * Retrieves the last public status of the provided user info
1359 * @param int $ownerId Public contact Id
1360 * @param int $uid User Id
1364 function api_get_last_status($ownerId, $uid)
1367 'author-id'=> $ownerId,
1369 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1370 'private' => [Item::PUBLIC, Item::UNLISTED]
1373 $item = api_get_item($condition);
1379 * Retrieves a single item record based on the provided condition and converts it for API use.
1381 * @param array $condition Item table condition array
1385 function api_get_item(array $condition)
1387 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1393 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1394 * The author's most recent status will be returned inline.
1396 * @param string $type Return type (atom, rss, xml, json)
1397 * @return array|string
1398 * @throws BadRequestException
1399 * @throws ImagickException
1400 * @throws InternalServerErrorException
1401 * @throws UnauthorizedException
1402 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1404 function api_users_show($type)
1406 $a = Friendica\DI::app();
1408 $user_info = api_get_user($a);
1410 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1411 if (!empty($item)) {
1412 $user_info['status'] = api_format_item($item, $type);
1415 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1416 unset($user_info['uid']);
1417 unset($user_info['self']);
1419 return api_format_data('user', $type, ['user' => $user_info]);
1422 /// @TODO move to top of file or somewhere better
1423 api_register_func('api/users/show', 'api_users_show');
1424 api_register_func('api/externalprofile/show', 'api_users_show');
1427 * Search a public user account.
1429 * @param string $type Return type (atom, rss, xml, json)
1431 * @return array|string
1432 * @throws BadRequestException
1433 * @throws ImagickException
1434 * @throws InternalServerErrorException
1435 * @throws UnauthorizedException
1436 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1438 function api_users_search($type)
1444 if (!empty($_GET['q'])) {
1445 $contacts = Contact::selectToArray(
1448 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1456 if (DBA::isResult($contacts)) {
1458 foreach ($contacts as $contact) {
1459 $user_info = api_get_user($a, $contact['id']);
1461 if ($type == 'xml') {
1462 $userlist[$k++ . ':user'] = $user_info;
1464 $userlist[] = $user_info;
1467 $userlist = ['users' => $userlist];
1469 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1472 throw new BadRequestException('No search term specified.');
1475 return api_format_data('users', $type, $userlist);
1478 /// @TODO move to top of file or somewhere better
1479 api_register_func('api/users/search', 'api_users_search');
1482 * Return user objects
1484 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1486 * @param string $type Return format: json or xml
1488 * @return array|string
1489 * @throws BadRequestException
1490 * @throws ImagickException
1491 * @throws InternalServerErrorException
1492 * @throws NotFoundException if the results are empty.
1493 * @throws UnauthorizedException
1495 function api_users_lookup($type)
1499 if (!empty($_REQUEST['user_id'])) {
1500 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1502 $users[] = api_get_user(DI::app(), $id);
1507 if (empty($users)) {
1508 throw new NotFoundException;
1511 return api_format_data("users", $type, ['users' => $users]);
1514 /// @TODO move to top of file or somewhere better
1515 api_register_func('api/users/lookup', 'api_users_lookup', true);
1518 * Returns statuses that match a specified query.
1520 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1522 * @param string $type Return format: json, xml, atom, rss
1524 * @return array|string
1525 * @throws BadRequestException if the "q" parameter is missing.
1526 * @throws ForbiddenException
1527 * @throws ImagickException
1528 * @throws InternalServerErrorException
1529 * @throws UnauthorizedException
1531 function api_search($type)
1534 $user_info = api_get_user($a);
1536 if (api_user() === false || $user_info === false) {
1537 throw new ForbiddenException();
1540 if (empty($_REQUEST['q'])) {
1541 throw new BadRequestException('q parameter is required.');
1544 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1547 $data['status'] = [];
1549 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1550 if (!empty($_REQUEST['rpp'])) {
1551 $count = $_REQUEST['rpp'];
1552 } elseif (!empty($_REQUEST['count'])) {
1553 $count = $_REQUEST['count'];
1556 $since_id = $_REQUEST['since_id'] ?? 0;
1557 $max_id = $_REQUEST['max_id'] ?? 0;
1558 $page = $_REQUEST['page'] ?? 1;
1560 $start = max(0, ($page - 1) * $count);
1562 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1563 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1564 $searchTerm = $matches[1];
1565 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1566 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1568 while ($tag = DBA::fetch($tags)) {
1569 $uriids[] = $tag['uri-id'];
1573 if (empty($uriids)) {
1574 return api_format_data('statuses', $type, $data);
1577 $condition = ['uri-id' => $uriids];
1578 if ($exclude_replies) {
1579 $condition['gravity'] = GRAVITY_PARENT;
1582 $params['group_by'] = ['uri-id'];
1584 $condition = ["`id` > ?
1585 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1586 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1587 AND `body` LIKE CONCAT('%',?,'%')",
1588 $since_id, api_user(), $_REQUEST['q']];
1590 $condition[0] .= ' AND `id` <= ?';
1591 $condition[] = $max_id;
1597 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1598 $id = Item::fetchByLink($searchTerm, api_user());
1601 $id = Item::fetchByLink($searchTerm);
1605 $statuses = Post::select([], ['id' => $id]);
1609 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1611 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1613 bindComments($data['status']);
1615 return api_format_data('statuses', $type, $data);
1618 /// @TODO move to top of file or somewhere better
1619 api_register_func('api/search/tweets', 'api_search', true);
1620 api_register_func('api/search', 'api_search', true);
1623 * Returns the most recent statuses posted by the user and the users they follow.
1625 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1627 * @param string $type Return type (atom, rss, xml, json)
1629 * @return array|string
1630 * @throws BadRequestException
1631 * @throws ForbiddenException
1632 * @throws ImagickException
1633 * @throws InternalServerErrorException
1634 * @throws UnauthorizedException
1635 * @todo Optional parameters
1636 * @todo Add reply info
1638 function api_statuses_home_timeline($type)
1641 $user_info = api_get_user($a);
1643 if (api_user() === false || $user_info === false) {
1644 throw new ForbiddenException();
1647 unset($_REQUEST["user_id"]);
1648 unset($_GET["user_id"]);
1650 unset($_REQUEST["screen_name"]);
1651 unset($_GET["screen_name"]);
1653 // get last network messages
1656 $count = $_REQUEST['count'] ?? 20;
1657 $page = $_REQUEST['page']?? 0;
1658 $since_id = $_REQUEST['since_id'] ?? 0;
1659 $max_id = $_REQUEST['max_id'] ?? 0;
1660 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1661 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1663 $start = max(0, ($page - 1) * $count);
1665 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1666 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1669 $condition[0] .= " AND `id` <= ?";
1670 $condition[] = $max_id;
1672 if ($exclude_replies) {
1673 $condition[0] .= ' AND `gravity` = ?';
1674 $condition[] = GRAVITY_PARENT;
1676 if ($conversation_id > 0) {
1677 $condition[0] .= " AND `parent` = ?";
1678 $condition[] = $conversation_id;
1681 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1682 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1684 $items = Post::toArray($statuses);
1686 $ret = api_format_items($items, $user_info, false, $type);
1688 // Set all posts from the query above to seen
1690 foreach ($items as $item) {
1691 $idarray[] = intval($item["id"]);
1694 if (!empty($idarray)) {
1695 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1697 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1703 $data = ['status' => $ret];
1708 $data = api_rss_extra($a, $data, $user_info);
1712 return api_format_data("statuses", $type, $data);
1716 /// @TODO move to top of file or somewhere better
1717 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1718 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1721 * Returns the most recent statuses from public users.
1723 * @param string $type Return type (atom, rss, xml, json)
1725 * @return array|string
1726 * @throws BadRequestException
1727 * @throws ForbiddenException
1728 * @throws ImagickException
1729 * @throws InternalServerErrorException
1730 * @throws UnauthorizedException
1732 function api_statuses_public_timeline($type)
1735 $user_info = api_get_user($a);
1737 if (api_user() === false || $user_info === false) {
1738 throw new ForbiddenException();
1741 // get last network messages
1744 $count = $_REQUEST['count'] ?? 20;
1745 $page = $_REQUEST['page'] ?? 1;
1746 $since_id = $_REQUEST['since_id'] ?? 0;
1747 $max_id = $_REQUEST['max_id'] ?? 0;
1748 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1749 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1751 $start = max(0, ($page - 1) * $count);
1753 if ($exclude_replies && !$conversation_id) {
1754 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1755 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1758 $condition[0] .= " AND `id` <= ?";
1759 $condition[] = $max_id;
1762 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1763 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1765 $r = Post::toArray($statuses);
1767 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1768 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1771 $condition[0] .= " AND `id` <= ?";
1772 $condition[] = $max_id;
1774 if ($conversation_id > 0) {
1775 $condition[0] .= " AND `parent` = ?";
1776 $condition[] = $conversation_id;
1779 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1780 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1782 $r = Post::toArray($statuses);
1785 $ret = api_format_items($r, $user_info, false, $type);
1789 $data = ['status' => $ret];
1794 $data = api_rss_extra($a, $data, $user_info);
1798 return api_format_data("statuses", $type, $data);
1801 /// @TODO move to top of file or somewhere better
1802 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1805 * Returns the most recent statuses posted by users this node knows about.
1807 * @param string $type Return format: json, xml, atom, rss
1808 * @return array|string
1809 * @throws BadRequestException
1810 * @throws ForbiddenException
1811 * @throws ImagickException
1812 * @throws InternalServerErrorException
1813 * @throws UnauthorizedException
1815 function api_statuses_networkpublic_timeline($type)
1818 $user_info = api_get_user($a);
1820 if (api_user() === false || $user_info === false) {
1821 throw new ForbiddenException();
1824 $since_id = $_REQUEST['since_id'] ?? 0;
1825 $max_id = $_REQUEST['max_id'] ?? 0;
1828 $count = $_REQUEST['count'] ?? 20;
1829 $page = $_REQUEST['page'] ?? 1;
1831 $start = max(0, ($page - 1) * $count);
1833 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1834 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1837 $condition[0] .= " AND `id` <= ?";
1838 $condition[] = $max_id;
1841 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1842 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1844 $ret = api_format_items($statuses, $user_info, false, $type);
1848 $data = ['status' => $ret];
1853 $data = api_rss_extra($a, $data, $user_info);
1857 return api_format_data("statuses", $type, $data);
1860 /// @TODO move to top of file or somewhere better
1861 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1864 * Returns a single status.
1866 * @param string $type Return type (atom, rss, xml, json)
1868 * @return array|string
1869 * @throws BadRequestException
1870 * @throws ForbiddenException
1871 * @throws ImagickException
1872 * @throws InternalServerErrorException
1873 * @throws UnauthorizedException
1874 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1876 function api_statuses_show($type)
1879 $user_info = api_get_user($a);
1881 if (api_user() === false || $user_info === false) {
1882 throw new ForbiddenException();
1886 $id = intval(DI::args()->getArgv()[3] ?? 0);
1889 $id = intval($_REQUEST['id'] ?? 0);
1894 $id = intval(DI::args()->getArgv()[4] ?? 0);
1897 Logger::log('API: api_statuses_show: ' . $id);
1899 $conversation = !empty($_REQUEST['conversation']);
1901 // try to fetch the item for the local user - or the public item, if there is no local one
1902 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1903 if (!DBA::isResult($uri_item)) {
1904 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1907 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1908 if (!DBA::isResult($item)) {
1909 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1914 if ($conversation) {
1915 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1916 $params = ['order' => ['id' => true]];
1918 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1922 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1924 /// @TODO How about copying this to above methods which don't check $r ?
1925 if (!DBA::isResult($statuses)) {
1926 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1929 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1931 if ($conversation) {
1932 $data = ['status' => $ret];
1933 return api_format_data("statuses", $type, $data);
1935 $data = ['status' => $ret[0]];
1936 return api_format_data("status", $type, $data);
1940 /// @TODO move to top of file or somewhere better
1941 api_register_func('api/statuses/show', 'api_statuses_show', true);
1945 * @param string $type Return type (atom, rss, xml, json)
1947 * @return array|string
1948 * @throws BadRequestException
1949 * @throws ForbiddenException
1950 * @throws ImagickException
1951 * @throws InternalServerErrorException
1952 * @throws UnauthorizedException
1953 * @todo nothing to say?
1955 function api_conversation_show($type)
1958 $user_info = api_get_user($a);
1960 if (api_user() === false || $user_info === false) {
1961 throw new ForbiddenException();
1965 $id = intval(DI::args()->getArgv()[3] ?? 0);
1966 $since_id = intval($_REQUEST['since_id'] ?? 0);
1967 $max_id = intval($_REQUEST['max_id'] ?? 0);
1968 $count = intval($_REQUEST['count'] ?? 20);
1969 $page = intval($_REQUEST['page'] ?? 1);
1971 $start = max(0, ($page - 1) * $count);
1974 $id = intval($_REQUEST['id'] ?? 0);
1979 $id = intval(DI::args()->getArgv()[4] ?? 0);
1982 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1984 // try to fetch the item for the local user - or the public item, if there is no local one
1985 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1986 if (!DBA::isResult($item)) {
1987 throw new BadRequestException("There is no status with this id.");
1990 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1991 if (!DBA::isResult($parent)) {
1992 throw new BadRequestException("There is no status with this id.");
1995 $id = $parent['id'];
1997 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1998 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2001 $condition[0] .= " AND `id` <= ?";
2002 $condition[] = $max_id;
2005 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2006 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2008 if (!DBA::isResult($statuses)) {
2009 throw new BadRequestException("There is no status with id $id.");
2012 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2014 $data = ['status' => $ret];
2015 return api_format_data("statuses", $type, $data);
2018 /// @TODO move to top of file or somewhere better
2019 api_register_func('api/conversation/show', 'api_conversation_show', true);
2020 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2025 * @param string $type Return type (atom, rss, xml, json)
2027 * @return array|string
2028 * @throws BadRequestException
2029 * @throws ForbiddenException
2030 * @throws ImagickException
2031 * @throws InternalServerErrorException
2032 * @throws UnauthorizedException
2033 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2035 function api_statuses_repeat($type)
2041 if (api_user() === false) {
2042 throw new ForbiddenException();
2048 $id = intval(DI::args()->getArgv()[3] ?? 0);
2051 $id = intval($_REQUEST['id'] ?? 0);
2056 $id = intval(DI::args()->getArgv()[4] ?? 0);
2059 Logger::log('API: api_statuses_repeat: '.$id);
2061 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2062 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2064 if (DBA::isResult($item) && !empty($item['body'])) {
2065 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2066 if (!Item::performActivity($id, 'announce', local_user())) {
2067 throw new InternalServerErrorException();
2072 if (strpos($item['body'], "[/share]") !== false) {
2073 $pos = strpos($item['body'], "[share");
2074 $post = substr($item['body'], $pos);
2076 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2078 if (!empty($item['title'])) {
2079 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2082 $post .= $item['body'];
2083 $post .= "[/share]";
2085 $_REQUEST['body'] = $post;
2086 $_REQUEST['profile_uid'] = api_user();
2087 $_REQUEST['api_source'] = true;
2089 if (empty($_REQUEST['source'])) {
2090 $_REQUEST["source"] = api_source();
2093 $item_id = item_post($a);
2096 throw new ForbiddenException();
2099 // output the post that we just posted.
2101 return api_status_show($type, $item_id);
2104 /// @TODO move to top of file or somewhere better
2105 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2108 * Destroys a specific status.
2110 * @param string $type Return type (atom, rss, xml, json)
2112 * @return array|string
2113 * @throws BadRequestException
2114 * @throws ForbiddenException
2115 * @throws ImagickException
2116 * @throws InternalServerErrorException
2117 * @throws UnauthorizedException
2118 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2120 function api_statuses_destroy($type)
2124 if (api_user() === false) {
2125 throw new ForbiddenException();
2131 $id = intval(DI::args()->getArgv()[3] ?? 0);
2134 $id = intval($_REQUEST['id'] ?? 0);
2139 $id = intval(DI::args()->getArgv()[4] ?? 0);
2142 Logger::log('API: api_statuses_destroy: '.$id);
2144 $ret = api_statuses_show($type);
2146 Item::deleteForUser(['id' => $id], api_user());
2151 /// @TODO move to top of file or somewhere better
2152 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2155 * Returns the most recent mentions.
2157 * @param string $type Return type (atom, rss, xml, json)
2159 * @return array|string
2160 * @throws BadRequestException
2161 * @throws ForbiddenException
2162 * @throws ImagickException
2163 * @throws InternalServerErrorException
2164 * @throws UnauthorizedException
2165 * @see http://developer.twitter.com/doc/get/statuses/mentions
2167 function api_statuses_mentions($type)
2170 $user_info = api_get_user($a);
2172 if (api_user() === false || $user_info === false) {
2173 throw new ForbiddenException();
2176 unset($_REQUEST["user_id"]);
2177 unset($_GET["user_id"]);
2179 unset($_REQUEST["screen_name"]);
2180 unset($_GET["screen_name"]);
2182 // get last network messages
2185 $since_id = intval($_REQUEST['since_id'] ?? 0);
2186 $max_id = intval($_REQUEST['max_id'] ?? 0);
2187 $count = intval($_REQUEST['count'] ?? 20);
2188 $page = intval($_REQUEST['page'] ?? 1);
2190 $start = max(0, ($page - 1) * $count);
2192 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2193 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2194 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2197 GRAVITY_PARENT, GRAVITY_COMMENT,
2199 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
2200 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
2201 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
2202 api_user(), $since_id,
2206 $query .= " AND `id` <= ?";
2207 $condition[] = $max_id;
2210 array_unshift($condition, $query);
2212 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2213 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2215 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2217 $data = ['status' => $ret];
2222 $data = api_rss_extra($a, $data, $user_info);
2226 return api_format_data("statuses", $type, $data);
2229 /// @TODO move to top of file or somewhere better
2230 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2231 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2234 * Returns the most recent statuses posted by the user.
2236 * @param string $type Either "json" or "xml"
2237 * @return string|array
2238 * @throws BadRequestException
2239 * @throws ForbiddenException
2240 * @throws ImagickException
2241 * @throws InternalServerErrorException
2242 * @throws UnauthorizedException
2243 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2245 function api_statuses_user_timeline($type)
2248 $user_info = api_get_user($a);
2250 if (api_user() === false || $user_info === false) {
2251 throw new ForbiddenException();
2254 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2256 $since_id = $_REQUEST['since_id'] ?? 0;
2257 $max_id = $_REQUEST['max_id'] ?? 0;
2258 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2259 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2262 $count = $_REQUEST['count'] ?? 20;
2263 $page = $_REQUEST['page'] ?? 1;
2265 $start = max(0, ($page - 1) * $count);
2267 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2268 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2270 if ($user_info['self'] == 1) {
2271 $condition[0] .= ' AND `wall` ';
2274 if ($exclude_replies) {
2275 $condition[0] .= ' AND `gravity` = ?';
2276 $condition[] = GRAVITY_PARENT;
2279 if ($conversation_id > 0) {
2280 $condition[0] .= " AND `parent` = ?";
2281 $condition[] = $conversation_id;
2285 $condition[0] .= " AND `id` <= ?";
2286 $condition[] = $max_id;
2288 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2289 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2291 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2295 $data = ['status' => $ret];
2300 $data = api_rss_extra($a, $data, $user_info);
2304 return api_format_data("statuses", $type, $data);
2307 /// @TODO move to top of file or somewhere better
2308 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2311 * Star/unstar an item.
2312 * param: id : id of the item
2314 * @param string $type Return type (atom, rss, xml, json)
2316 * @return array|string
2317 * @throws BadRequestException
2318 * @throws ForbiddenException
2319 * @throws ImagickException
2320 * @throws InternalServerErrorException
2321 * @throws UnauthorizedException
2322 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2324 function api_favorites_create_destroy($type)
2328 if (api_user() === false) {
2329 throw new ForbiddenException();
2332 // for versioned api.
2333 /// @TODO We need a better global soluton
2334 $action_argv_id = 2;
2335 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2336 $action_argv_id = 3;
2339 if (DI::args()->getArgc() <= $action_argv_id) {
2340 throw new BadRequestException("Invalid request.");
2342 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2343 if (DI::args()->getArgc() == $action_argv_id + 2) {
2344 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2346 $itemid = intval($_REQUEST['id'] ?? 0);
2349 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2351 if (!DBA::isResult($item)) {
2352 throw new BadRequestException("Invalid item.");
2357 $item['starred'] = 1;
2360 $item['starred'] = 0;
2363 throw new BadRequestException("Invalid action ".$action);
2366 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2369 throw new InternalServerErrorException("DB error");
2373 $user_info = api_get_user($a);
2374 $rets = api_format_items([$item], $user_info, false, $type);
2377 $data = ['status' => $ret];
2382 $data = api_rss_extra($a, $data, $user_info);
2386 return api_format_data("status", $type, $data);
2389 /// @TODO move to top of file or somewhere better
2390 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2391 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2394 * Returns the most recent favorite statuses.
2396 * @param string $type Return type (atom, rss, xml, json)
2398 * @return string|array
2399 * @throws BadRequestException
2400 * @throws ForbiddenException
2401 * @throws ImagickException
2402 * @throws InternalServerErrorException
2403 * @throws UnauthorizedException
2405 function api_favorites($type)
2410 $user_info = api_get_user($a);
2412 if (api_user() === false || $user_info === false) {
2413 throw new ForbiddenException();
2418 // in friendica starred item are private
2419 // return favorites only for self
2420 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2422 if ($user_info['self'] == 0) {
2426 $since_id = $_REQUEST['since_id'] ?? 0;
2427 $max_id = $_REQUEST['max_id'] ?? 0;
2428 $count = $_GET['count'] ?? 20;
2429 $page = $_REQUEST['page'] ?? 1;
2431 $start = max(0, ($page - 1) * $count);
2433 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2434 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2436 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2439 $condition[0] .= " AND `id` <= ?";
2440 $condition[] = $max_id;
2443 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2445 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2450 $data = ['status' => $ret];
2455 $data = api_rss_extra($a, $data, $user_info);
2459 return api_format_data("statuses", $type, $data);
2462 /// @TODO move to top of file or somewhere better
2463 api_register_func('api/favorites', 'api_favorites', true);
2467 * @param array $item
2468 * @param array $recipient
2469 * @param array $sender
2472 * @throws InternalServerErrorException
2474 function api_format_messages($item, $recipient, $sender)
2476 // standard meta information
2478 'id' => $item['id'],
2479 'sender_id' => $sender['id'],
2481 'recipient_id' => $recipient['id'],
2482 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2483 'sender_screen_name' => $sender['screen_name'],
2484 'recipient_screen_name' => $recipient['screen_name'],
2485 'sender' => $sender,
2486 'recipient' => $recipient,
2488 'friendica_seen' => $item['seen'] ?? 0,
2489 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2492 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2493 if (isset($ret['sender']['uid'])) {
2494 unset($ret['sender']['uid']);
2496 if (isset($ret['sender']['self'])) {
2497 unset($ret['sender']['self']);
2499 if (isset($ret['recipient']['uid'])) {
2500 unset($ret['recipient']['uid']);
2502 if (isset($ret['recipient']['self'])) {
2503 unset($ret['recipient']['self']);
2506 //don't send title to regular StatusNET requests to avoid confusing these apps
2507 if (!empty($_GET['getText'])) {
2508 $ret['title'] = $item['title'];
2509 if ($_GET['getText'] == 'html') {
2510 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2511 } elseif ($_GET['getText'] == 'plain') {
2512 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2515 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2517 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2518 unset($ret['sender']);
2519 unset($ret['recipient']);
2527 * @param array $item
2530 * @throws InternalServerErrorException
2532 function api_convert_item($item)
2534 $body = api_add_attachments_to_body($item);
2536 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2538 // Add pictures to the attachment array and remove them from the body
2539 $attachments = api_get_attachments($body, $item['uri-id']);
2541 // Workaround for ostatus messages where the title is identically to the body
2542 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2543 $statusbody = trim(HTML::toPlaintext($html, 0));
2545 // handle data: images
2546 $statusbody = api_format_items_embeded_images($item, $statusbody);
2548 $statustitle = trim($item['title']);
2550 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2551 $statustext = trim($statusbody);
2553 $statustext = trim($statustitle."\n\n".$statusbody);
2556 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2557 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2560 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2562 // Workaround for clients with limited HTML parser functionality
2563 $search = ["<br>", "<blockquote>", "</blockquote>",
2564 "<h1>", "</h1>", "<h2>", "</h2>",
2565 "<h3>", "</h3>", "<h4>", "</h4>",
2566 "<h5>", "</h5>", "<h6>", "</h6>"];
2567 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2568 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2569 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2570 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2571 $statushtml = str_replace($search, $replace, $statushtml);
2573 if ($item['title'] != "") {
2574 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2578 $oldtext = $statushtml;
2579 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2580 } while ($oldtext != $statushtml);
2582 if (substr($statushtml, 0, 4) == '<br>') {
2583 $statushtml = substr($statushtml, 4);
2586 if (substr($statushtml, 0, -4) == '<br>') {
2587 $statushtml = substr($statushtml, -4);
2590 // feeds without body should contain the link
2591 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2592 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2596 "text" => $statustext,
2597 "html" => $statushtml,
2598 "attachments" => $attachments,
2599 "entities" => $entities
2604 * Add media attachments to the body
2606 * @param array $item
2607 * @return string body with added media
2609 function api_add_attachments_to_body(array $item)
2611 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2613 if (strpos($body, '[/img]') !== false) {
2617 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2618 if (!empty($media['preview'])) {
2619 $description = $media['description'] ?: $media['name'];
2620 if (!empty($description)) {
2621 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2623 $body .= "\n[img]" . $media['preview'] .'[/img]';
2633 * @param string $body
2637 * @throws InternalServerErrorException
2639 function api_get_attachments(&$body, $uriid)
2641 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2642 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2644 $URLSearchString = "^\[\]";
2645 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2649 // Remove all embedded pictures, since they are added as attachments
2650 foreach ($images[0] as $orig) {
2651 $body = str_replace($orig, '', $body);
2656 foreach ($images[1] as $image) {
2657 $imagedata = Images::getInfoFromURLCached($image);
2660 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2664 return $attachments;
2669 * @param string $text
2670 * @param string $bbcode
2673 * @throws InternalServerErrorException
2674 * @todo Links at the first character of the post
2676 function api_get_entitities(&$text, $bbcode, $uriid)
2678 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2680 if ($include_entities != "true") {
2681 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2683 foreach ($images[1] as $image) {
2684 $replace = Post\Link::getByLink($uriid, $image);
2685 $text = str_replace($image, $replace, $text);
2690 $bbcode = BBCode::cleanPictureLinks($bbcode);
2692 // Change pure links in text to bbcode uris
2693 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2696 $entities["hashtags"] = [];
2697 $entities["symbols"] = [];
2698 $entities["urls"] = [];
2699 $entities["user_mentions"] = [];
2701 $URLSearchString = "^\[\]";
2703 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2705 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2706 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2708 $bbcode = preg_replace(
2709 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2710 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2713 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2715 $bbcode = preg_replace(
2716 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2717 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2720 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2722 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2724 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2727 foreach ($urls[1] as $id => $url) {
2728 $start = iconv_strpos($text, $url, 0, "UTF-8");
2729 if (!($start === false)) {
2730 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2734 ksort($ordered_urls);
2738 foreach ($ordered_urls as $url) {
2739 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2740 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2742 $display_url = $url["title"];
2744 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2745 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2747 if (strlen($display_url) > 26) {
2748 $display_url = substr($display_url, 0, 25)."…";
2752 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2753 if (!($start === false)) {
2754 $entities["urls"][] = ["url" => $url["url"],
2755 "expanded_url" => $url["url"],
2756 "display_url" => $display_url,
2757 "indices" => [$start, $start+strlen($url["url"])]];
2758 $offset = $start + 1;
2762 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2763 $ordered_images = [];
2764 foreach ($images as $image) {
2765 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2766 if (!($start === false)) {
2767 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2771 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2772 foreach ($images[1] as $image) {
2773 $start = iconv_strpos($text, $image, 0, "UTF-8");
2774 if (!($start === false)) {
2775 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2781 foreach ($ordered_images as $image) {
2782 $url = $image['url'];
2783 $ext_alt_text = $image['alt'];
2785 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2786 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2788 if (strlen($display_url) > 26) {
2789 $display_url = substr($display_url, 0, 25)."…";
2792 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2793 if (!($start === false)) {
2794 $image = Images::getInfoFromURLCached($url);
2796 $media_url = Post\Link::getByLink($uriid, $url);
2797 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2799 $entities["media"][] = [
2801 "id_str" => (string) ($start + 1),
2802 "indices" => [$start, $start+strlen($url)],
2803 "media_url" => Strings::normaliseLink($media_url),
2804 "media_url_https" => $media_url,
2806 "display_url" => $display_url,
2807 "expanded_url" => $url,
2808 "ext_alt_text" => $ext_alt_text,
2812 $offset = $start + 1;
2821 * @param array $item
2822 * @param string $text
2826 function api_format_items_embeded_images($item, $text)
2828 $text = preg_replace_callback(
2829 '|data:image/([^;]+)[^=]+=*|m',
2830 function () use ($item) {
2831 return DI::baseUrl() . '/display/' . $item['guid'];
2839 * return <a href='url'>name</a> as array
2841 * @param string $txt text
2846 function api_contactlink_to_array($txt)
2849 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2850 if ($r && count($match)==3) {
2852 'name' => $match[2],
2866 * return likes, dislikes and attend status for item
2868 * @param array $item array
2869 * @param string $type Return type (atom, rss, xml, json)
2872 * likes => int count,
2873 * dislikes => int count
2874 * @throws BadRequestException
2875 * @throws ImagickException
2876 * @throws InternalServerErrorException
2877 * @throws UnauthorizedException
2879 function api_format_items_activities($item, $type = "json")
2888 'attendmaybe' => [],
2892 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2893 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2895 while ($parent_item = Post::fetch($ret)) {
2896 // not used as result should be structured like other user data
2897 //builtin_activity_puller($i, $activities);
2899 // get user data and add it to the array of the activity
2900 $user = api_get_user($a, $parent_item['author-id']);
2901 switch ($parent_item['verb']) {
2902 case Activity::LIKE:
2903 $activities['like'][] = $user;
2905 case Activity::DISLIKE:
2906 $activities['dislike'][] = $user;
2908 case Activity::ATTEND:
2909 $activities['attendyes'][] = $user;
2911 case Activity::ATTENDNO:
2912 $activities['attendno'][] = $user;
2914 case Activity::ATTENDMAYBE:
2915 $activities['attendmaybe'][] = $user;
2917 case Activity::ANNOUNCE:
2918 $activities['announce'][] = $user;
2927 if ($type == "xml") {
2928 $xml_activities = [];
2929 foreach ($activities as $k => $v) {
2930 // change xml element from "like" to "friendica:like"
2931 $xml_activities["friendica:".$k] = $v;
2932 // add user data into xml output
2934 foreach ($v as $user) {
2935 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2938 $activities = $xml_activities;
2945 * format items to be returned by api
2947 * @param array $items array of items
2948 * @param array $user_info
2949 * @param bool $filter_user filter items by $user_info
2950 * @param string $type Return type (atom, rss, xml, json)
2952 * @throws BadRequestException
2953 * @throws ImagickException
2954 * @throws InternalServerErrorException
2955 * @throws UnauthorizedException
2957 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2959 $a = Friendica\DI::app();
2963 if (empty($items)) {
2967 foreach ((array)$items as $item) {
2968 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2970 // Look if the posts are matching if they should be filtered by user id
2971 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2975 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2984 * @param array $item Item record
2985 * @param string $type Return format (atom, rss, xml, json)
2986 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2987 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2988 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2989 * @return array API-formatted status
2990 * @throws BadRequestException
2991 * @throws ImagickException
2992 * @throws InternalServerErrorException
2993 * @throws UnauthorizedException
2995 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2997 $a = Friendica\DI::app();
2999 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3000 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3003 DI::contentItem()->localize($item);
3005 $in_reply_to = api_in_reply_to($item);
3007 $converted = api_convert_item($item);
3009 if ($type == "xml") {
3010 $geo = "georss:point";
3016 'text' => $converted["text"],
3017 'truncated' => false,
3018 'created_at'=> api_date($item['created']),
3019 'in_reply_to_status_id' => $in_reply_to['status_id'],
3020 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3021 'source' => (($item['app']) ? $item['app'] : 'web'),
3022 'id' => intval($item['id']),
3023 'id_str' => (string) intval($item['id']),
3024 'in_reply_to_user_id' => $in_reply_to['user_id'],
3025 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3026 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3028 'favorited' => $item['starred'] ? true : false,
3029 'user' => $status_user,
3030 'friendica_author' => $author_user,
3031 'friendica_owner' => $owner_user,
3032 'friendica_private' => $item['private'] == Item::PRIVATE,
3033 //'entities' => NULL,
3034 'statusnet_html' => $converted["html"],
3035 'statusnet_conversation_id' => $item['parent'],
3036 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3037 'friendica_activities' => api_format_items_activities($item, $type),
3038 'friendica_title' => $item['title'],
3039 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
3042 if (count($converted["attachments"]) > 0) {
3043 $status["attachments"] = $converted["attachments"];
3046 if (count($converted["entities"]) > 0) {
3047 $status["entities"] = $converted["entities"];
3050 if ($status["source"] == 'web') {
3051 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3052 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3053 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3056 $retweeted_item = [];
3059 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3060 $announce = api_get_announce($item);
3061 if (!empty($announce)) {
3062 $retweeted_item = $item;
3064 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3068 if (!empty($quoted_item)) {
3069 if ($quoted_item['id'] != $item['id']) {
3070 $quoted_status = api_format_item($quoted_item);
3071 /// @todo Only remove the attachments that are also contained in the quotes status
3072 unset($status['attachments']);
3073 unset($status['entities']);
3075 $conv_quoted = api_convert_item($quoted_item);
3076 $quoted_status = $status;
3077 unset($quoted_status['attachments']);
3078 unset($quoted_status['entities']);
3079 unset($quoted_status['statusnet_conversation_id']);
3080 $quoted_status['text'] = $conv_quoted['text'];
3081 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3083 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3084 } catch (BadRequestException $e) {
3085 // user not found. should be found?
3086 /// @todo check if the user should be always found
3087 $quoted_status["user"] = [];
3090 unset($quoted_status['friendica_author']);
3091 unset($quoted_status['friendica_owner']);
3092 unset($quoted_status['friendica_activities']);
3093 unset($quoted_status['friendica_private']);
3096 if (!empty($retweeted_item)) {
3097 $retweeted_status = $status;
3098 unset($retweeted_status['friendica_author']);
3099 unset($retweeted_status['friendica_owner']);
3100 unset($retweeted_status['friendica_activities']);
3101 unset($retweeted_status['friendica_private']);
3102 unset($retweeted_status['statusnet_conversation_id']);
3103 $status['user'] = $status['friendica_owner'];
3105 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3106 } catch (BadRequestException $e) {
3107 // user not found. should be found?
3108 /// @todo check if the user should be always found
3109 $retweeted_status["user"] = [];
3112 $rt_converted = api_convert_item($retweeted_item);
3114 $retweeted_status['text'] = $rt_converted["text"];
3115 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3116 $retweeted_status['friendica_html'] = $rt_converted["html"];
3117 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3119 if (!empty($quoted_status)) {
3120 $retweeted_status['quoted_status'] = $quoted_status;
3123 $status['friendica_author'] = $retweeted_status['user'];
3124 $status['retweeted_status'] = $retweeted_status;
3125 } elseif (!empty($quoted_status)) {
3126 $root_status = api_convert_item($item);
3128 $status['text'] = $root_status["text"];
3129 $status['statusnet_html'] = $root_status["html"];
3130 $status['quoted_status'] = $quoted_status;
3133 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3134 unset($status["user"]["uid"]);
3135 unset($status["user"]["self"]);
3137 if ($item["coord"] != "") {
3138 $coords = explode(' ', $item["coord"]);
3139 if (count($coords) == 2) {
3140 if ($type == "json") {
3141 $status["geo"] = ['type' => 'Point',
3142 'coordinates' => [(float) $coords[0],
3143 (float) $coords[1]]];
3144 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3145 $status["georss:point"] = $item["coord"];
3154 * Returns the remaining number of API requests available to the user before the API limit is reached.
3156 * @param string $type Return type (atom, rss, xml, json)
3158 * @return array|string
3161 function api_account_rate_limit_status($type)
3163 if ($type == "xml") {
3165 'remaining-hits' => '150',
3166 '@attributes' => ["type" => "integer"],
3167 'hourly-limit' => '150',
3168 '@attributes2' => ["type" => "integer"],
3169 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3170 '@attributes3' => ["type" => "datetime"],
3171 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3172 '@attributes4' => ["type" => "integer"],
3176 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3177 'remaining_hits' => '150',
3178 'hourly_limit' => '150',
3179 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3183 return api_format_data('hash', $type, ['hash' => $hash]);
3186 /// @TODO move to top of file or somewhere better
3187 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3190 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3192 * @param string $type Return type (atom, rss, xml, json)
3194 * @return array|string
3196 function api_help_test($type)
3198 if ($type == 'xml') {
3204 return api_format_data('ok', $type, ["ok" => $ok]);
3207 /// @TODO move to top of file or somewhere better
3208 api_register_func('api/help/test', 'api_help_test', false);
3211 * Returns all lists the user subscribes to.
3213 * @param string $type Return type (atom, rss, xml, json)
3215 * @return array|string
3216 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3218 function api_lists_list($type)
3221 /// @TODO $ret is not filled here?
3222 return api_format_data('lists', $type, ["lists_list" => $ret]);
3225 /// @TODO move to top of file or somewhere better
3226 api_register_func('api/lists/list', 'api_lists_list', true);
3227 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3230 * Returns all groups the user owns.
3232 * @param string $type Return type (atom, rss, xml, json)
3234 * @return array|string
3235 * @throws BadRequestException
3236 * @throws ForbiddenException
3237 * @throws ImagickException
3238 * @throws InternalServerErrorException
3239 * @throws UnauthorizedException
3240 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3242 function api_lists_ownerships($type)
3246 if (api_user() === false) {
3247 throw new ForbiddenException();
3251 $user_info = api_get_user($a);
3252 $uid = $user_info['uid'];
3254 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3256 // loop through all groups
3258 foreach ($groups as $group) {
3259 if ($group['visible']) {
3265 'name' => $group['name'],
3266 'id' => intval($group['id']),
3267 'id_str' => (string) $group['id'],
3268 'user' => $user_info,
3272 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3275 /// @TODO move to top of file or somewhere better
3276 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3279 * Returns recent statuses from users in the specified group.
3281 * @param string $type Return type (atom, rss, xml, json)
3283 * @return array|string
3284 * @throws BadRequestException
3285 * @throws ForbiddenException
3286 * @throws ImagickException
3287 * @throws InternalServerErrorException
3288 * @throws UnauthorizedException
3289 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3291 function api_lists_statuses($type)
3295 $user_info = api_get_user($a);
3296 if (api_user() === false || $user_info === false) {
3297 throw new ForbiddenException();
3300 unset($_REQUEST["user_id"]);
3301 unset($_GET["user_id"]);
3303 unset($_REQUEST["screen_name"]);
3304 unset($_GET["screen_name"]);
3306 if (empty($_REQUEST['list_id'])) {
3307 throw new BadRequestException('list_id not specified');
3311 $count = $_REQUEST['count'] ?? 20;
3312 $page = $_REQUEST['page'] ?? 1;
3313 $since_id = $_REQUEST['since_id'] ?? 0;
3314 $max_id = $_REQUEST['max_id'] ?? 0;
3315 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3316 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3318 $start = max(0, ($page - 1) * $count);
3320 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3321 $gids = array_column($groups, 'contact-id');
3322 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3323 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3326 $condition[0] .= " AND `id` <= ?";
3327 $condition[] = $max_id;
3329 if ($exclude_replies > 0) {
3330 $condition[0] .= ' AND `gravity` = ?';
3331 $condition[] = GRAVITY_PARENT;
3333 if ($conversation_id > 0) {
3334 $condition[0] .= " AND `parent` = ?";
3335 $condition[] = $conversation_id;
3338 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3339 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3341 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3343 $data = ['status' => $items];
3348 $data = api_rss_extra($a, $data, $user_info);
3352 return api_format_data("statuses", $type, $data);
3355 /// @TODO move to top of file or somewhere better
3356 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3359 * Returns either the friends of the follower list
3361 * Considers friends and followers lists to be private and won't return
3362 * anything if any user_id parameter is passed.
3364 * @param string $qtype Either "friends" or "followers"
3365 * @return boolean|array
3366 * @throws BadRequestException
3367 * @throws ForbiddenException
3368 * @throws ImagickException
3369 * @throws InternalServerErrorException
3370 * @throws UnauthorizedException
3372 function api_statuses_f($qtype)
3376 if (api_user() === false) {
3377 throw new ForbiddenException();
3381 $count = $_GET['count'] ?? 20;
3382 $page = $_GET['page'] ?? 1;
3384 $start = max(0, ($page - 1) * $count);
3386 $user_info = api_get_user($a);
3388 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3389 /* this is to stop Hotot to load friends multiple times
3390 * I'm not sure if I'm missing return something or
3391 * is a bug in hotot. Workaround, meantime
3395 return array('$users' => $ret);*/
3400 if ($qtype == 'friends') {
3401 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3402 } elseif ($qtype == 'followers') {
3403 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3406 // friends and followers only for self
3407 if ($user_info['self'] == 0) {
3408 $sql_extra = " AND false ";
3411 if ($qtype == 'blocks') {
3412 $sql_filter = 'AND `blocked` AND NOT `pending`';
3413 } elseif ($qtype == 'incoming') {
3414 $sql_filter = 'AND `pending`';
3416 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
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'])) {
3634 "SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
3636 DBA::escape($_POST['screen_name'])
3639 if (DBA::isResult($r)) {
3640 // Selecting the id by priority, friendica first
3641 api_best_nickname($r);
3643 $recipient = api_get_user($a, $r[0]['nurl']);
3646 $recipient = api_get_user($a, $_POST['user_id']);
3649 if (empty($recipient)) {
3650 throw new NotFoundException('Recipient not found');
3654 if (!empty($_REQUEST['replyto'])) {
3656 'SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
3658 intval($_REQUEST['replyto'])
3660 $replyto = $r[0]['parent-uri'];
3661 $sub = $r[0]['title'];
3663 if (!empty($_REQUEST['title'])) {
3664 $sub = $_REQUEST['title'];
3666 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3670 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3673 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
3674 $ret = api_format_messages($r[0], $recipient, $sender);
3676 $ret = ["error"=>$id];
3679 $data = ['direct_message'=>$ret];
3685 $data = api_rss_extra($a, $data, $sender);
3689 return api_format_data("direct-messages", $type, $data);
3692 /// @TODO move to top of file or somewhere better
3693 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3696 * delete a direct_message from mail table through api
3698 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3699 * @return string|array
3700 * @throws BadRequestException
3701 * @throws ForbiddenException
3702 * @throws ImagickException
3703 * @throws InternalServerErrorException
3704 * @throws UnauthorizedException
3705 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3707 function api_direct_messages_destroy($type)
3711 if (api_user() === false) {
3712 throw new ForbiddenException();
3716 $user_info = api_get_user($a);
3718 $id = $_REQUEST['id'] ?? 0;
3720 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3721 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3722 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3724 $uid = $user_info['uid'];
3725 // error if no id or parenturi specified (for clients posting parent-uri as well)
3726 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3727 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3728 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3731 // BadRequestException if no id specified (for clients using Twitter API)
3733 throw new BadRequestException('Message id not specified');
3736 // add parent-uri to sql command if specified by calling app
3737 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3739 // get data of the specified message id
3741 "SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3746 // error message if specified id is not in database
3747 if (!DBA::isResult($r)) {
3748 if ($verbose == "true") {
3749 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3750 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3752 /// @todo BadRequestException ok for Twitter API clients?
3753 throw new BadRequestException('message id not in database');
3758 "DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
3763 if ($verbose == "true") {
3766 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3767 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3769 $answer = ['result' => 'error', 'message' => 'unknown error'];
3770 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3773 /// @todo return JSON data like Twitter API not yet implemented
3776 /// @TODO move to top of file or somewhere better
3777 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3783 * @return string|array
3784 * @throws HTTPException\BadRequestException
3785 * @throws HTTPException\ExpectationFailedException
3786 * @throws HTTPException\ForbiddenException
3787 * @throws HTTPException\InternalServerErrorException
3788 * @throws HTTPException\NotFoundException
3789 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3791 function api_friendships_destroy($type)
3795 if ($uid === false) {
3796 throw new HTTPException\ForbiddenException();
3799 $owner = User::getOwnerDataById($uid);
3801 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3802 throw new HTTPException\NotFoundException('Error Processing Request');
3805 $contact_id = $_REQUEST['user_id'] ?? 0;
3807 if (empty($contact_id)) {
3808 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3809 throw new HTTPException\BadRequestException('no user_id specified');
3812 // Get Contact by given id
3813 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3815 if(!DBA::isResult($contact)) {
3816 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3817 throw new HTTPException\NotFoundException('no contact found to given ID');
3820 $url = $contact['url'];
3822 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3823 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3824 Strings::normaliseLink($url), $url];
3825 $contact = DBA::selectFirst('contact', [], $condition);
3827 if (!DBA::isResult($contact)) {
3828 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3829 throw new HTTPException\NotFoundException('Not following Contact');
3833 $result = Contact::terminateFriendship($owner, $contact);
3835 if ($result === null) {
3836 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3837 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3840 if ($result === false) {
3841 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3843 } catch (Exception $e) {
3844 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3845 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3848 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3849 unset($contact['uid']);
3850 unset($contact['self']);
3852 // Set screen_name since Twidere requests it
3853 $contact['screen_name'] = $contact['nick'];
3855 return api_format_data('friendships-destroy', $type, ['user' => $contact]);
3857 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3861 * @param string $type Return type (atom, rss, xml, json)
3862 * @param string $box
3863 * @param string $verbose
3865 * @return array|string
3866 * @throws BadRequestException
3867 * @throws ForbiddenException
3868 * @throws ImagickException
3869 * @throws InternalServerErrorException
3870 * @throws UnauthorizedException
3872 function api_direct_messages_box($type, $box, $verbose)
3875 if (api_user() === false) {
3876 throw new ForbiddenException();
3879 $count = $_GET['count'] ?? 20;
3880 $page = $_REQUEST['page'] ?? 1;
3882 $since_id = $_REQUEST['since_id'] ?? 0;
3883 $max_id = $_REQUEST['max_id'] ?? 0;
3885 $user_id = $_REQUEST['user_id'] ?? '';
3886 $screen_name = $_REQUEST['screen_name'] ?? '';
3889 unset($_REQUEST["user_id"]);
3890 unset($_GET["user_id"]);
3892 unset($_REQUEST["screen_name"]);
3893 unset($_GET["screen_name"]);
3895 $user_info = api_get_user($a);
3896 if ($user_info === false) {
3897 throw new ForbiddenException();
3899 $profile_url = $user_info["url"];
3902 $start = max(0, ($page - 1) * $count);
3907 if ($box=="sentbox") {
3908 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3909 } elseif ($box == "conversation") {
3910 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3911 } elseif ($box == "all") {
3912 $sql_extra = "true";
3913 } elseif ($box == "inbox") {
3914 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3918 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3921 if ($user_id != "") {
3922 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3923 } elseif ($screen_name !="") {
3924 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3928 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
3934 if ($verbose == "true" && !DBA::isResult($r)) {
3935 $answer = ['result' => 'error', 'message' => 'no mails available'];
3936 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3940 foreach ($r as $item) {
3941 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3942 $recipient = $user_info;
3943 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3944 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3945 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3946 $sender = $user_info;
3949 if (isset($recipient) && isset($sender)) {
3950 $ret[] = api_format_messages($item, $recipient, $sender);
3955 $data = ['direct_message' => $ret];
3960 $data = api_rss_extra($a, $data, $user_info);
3964 return api_format_data("direct-messages", $type, $data);
3968 * Returns the most recent direct messages sent by the user.
3970 * @param string $type Return type (atom, rss, xml, json)
3972 * @return array|string
3973 * @throws BadRequestException
3974 * @throws ForbiddenException
3975 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3977 function api_direct_messages_sentbox($type)
3979 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3980 return api_direct_messages_box($type, "sentbox", $verbose);
3984 * Returns the most recent direct messages sent to the user.
3986 * @param string $type Return type (atom, rss, xml, json)
3988 * @return array|string
3989 * @throws BadRequestException
3990 * @throws ForbiddenException
3991 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3993 function api_direct_messages_inbox($type)
3995 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3996 return api_direct_messages_box($type, "inbox", $verbose);
4001 * @param string $type Return type (atom, rss, xml, json)
4003 * @return array|string
4004 * @throws BadRequestException
4005 * @throws ForbiddenException
4007 function api_direct_messages_all($type)
4009 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4010 return api_direct_messages_box($type, "all", $verbose);
4015 * @param string $type Return type (atom, rss, xml, json)
4017 * @return array|string
4018 * @throws BadRequestException
4019 * @throws ForbiddenException
4021 function api_direct_messages_conversation($type)
4023 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4024 return api_direct_messages_box($type, "conversation", $verbose);
4027 /// @TODO move to top of file or somewhere better
4028 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4029 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4030 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4031 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4034 * delete a complete photoalbum with all containing photos from database through api
4036 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4037 * @return string|array
4038 * @throws BadRequestException
4039 * @throws ForbiddenException
4040 * @throws InternalServerErrorException
4042 function api_fr_photoalbum_delete($type)
4044 if (api_user() === false) {
4045 throw new ForbiddenException();
4048 $album = $_REQUEST['album'] ?? '';
4050 // we do not allow calls without album string
4052 throw new BadRequestException("no albumname specified");
4054 // check if album is existing
4056 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4057 if (!DBA::isResult($photos)) {
4058 throw new BadRequestException("album not available");
4061 $resourceIds = array_column($photos, 'resource-id');
4063 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4064 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4065 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4066 Item::deleteForUser($condition, api_user());
4068 // now let's delete all photos from the album
4069 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4071 // return success of deletion or error message
4073 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4074 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4076 throw new InternalServerErrorException("unknown error - deleting from database failed");
4081 * update the name of the album for all photos of an album
4083 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4084 * @return string|array
4085 * @throws BadRequestException
4086 * @throws ForbiddenException
4087 * @throws InternalServerErrorException
4089 function api_fr_photoalbum_update($type)
4091 if (api_user() === false) {
4092 throw new ForbiddenException();
4095 $album = $_REQUEST['album'] ?? '';
4096 $album_new = $_REQUEST['album_new'] ?? '';
4098 // we do not allow calls without album string
4100 throw new BadRequestException("no albumname specified");
4102 if ($album_new == "") {
4103 throw new BadRequestException("no new albumname specified");
4105 // check if album is existing
4106 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4107 throw new BadRequestException("album not available");
4109 // now let's update all photos to the albumname
4110 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4112 // return success of updating or error message
4114 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4115 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4117 throw new InternalServerErrorException("unknown error - updating in database failed");
4123 * list all photos of the authenticated user
4125 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4126 * @return string|array
4127 * @throws ForbiddenException
4128 * @throws InternalServerErrorException
4130 function api_fr_photos_list($type)
4132 if (api_user() === false) {
4133 throw new ForbiddenException();
4136 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4137 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4138 WHERE `uid` = %d AND `album` != 'Contact Photos' GROUP BY `resource-id`, `album`, `filename`, `type`",
4139 intval(local_user())
4142 'image/jpeg' => 'jpg',
4143 'image/png' => 'png',
4144 'image/gif' => 'gif'
4146 $data = ['photo'=>[]];
4147 if (DBA::isResult($r)) {
4148 foreach ($r as $rr) {
4150 $photo['id'] = $rr['resource-id'];
4151 $photo['album'] = $rr['album'];
4152 $photo['filename'] = $rr['filename'];
4153 $photo['type'] = $rr['type'];
4154 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4155 $photo['created'] = $rr['created'];
4156 $photo['edited'] = $rr['edited'];
4157 $photo['desc'] = $rr['desc'];
4159 if ($type == "xml") {
4160 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4162 $photo['thumb'] = $thumb;
4163 $data['photo'][] = $photo;
4167 return api_format_data("photos", $type, $data);
4171 * upload a new photo or change an existing photo
4173 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4174 * @return string|array
4175 * @throws BadRequestException
4176 * @throws ForbiddenException
4177 * @throws ImagickException
4178 * @throws InternalServerErrorException
4179 * @throws NotFoundException
4181 function api_fr_photo_create_update($type)
4183 if (api_user() === false) {
4184 throw new ForbiddenException();
4187 $photo_id = $_REQUEST['photo_id'] ?? null;
4188 $desc = $_REQUEST['desc'] ?? null;
4189 $album = $_REQUEST['album'] ?? null;
4190 $album_new = $_REQUEST['album_new'] ?? null;
4191 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4192 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4193 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4194 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4195 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4197 // do several checks on input parameters
4198 // we do not allow calls without album string
4199 if ($album == null) {
4200 throw new BadRequestException("no albumname specified");
4202 // if photo_id == null --> we are uploading a new photo
4203 if ($photo_id == null) {
4206 // error if no media posted in create-mode
4207 if (empty($_FILES['media'])) {
4209 throw new BadRequestException("no media data submitted");
4212 // album_new will be ignored in create-mode
4217 // check if photo is existing in databasei
4218 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4219 throw new BadRequestException("photo not available");
4223 // checks on acl strings provided by clients
4224 $acl_input_error = false;
4225 $acl_input_error |= check_acl_input($allow_cid);
4226 $acl_input_error |= check_acl_input($deny_cid);
4227 $acl_input_error |= check_acl_input($allow_gid);
4228 $acl_input_error |= check_acl_input($deny_gid);
4229 if ($acl_input_error) {
4230 throw new BadRequestException("acl data invalid");
4232 // now let's upload the new media in create-mode
4233 if ($mode == "create") {
4234 $media = $_FILES['media'];
4235 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, $visibility);
4237 // return success of updating or error message
4238 if (!is_null($data)) {
4239 return api_format_data("photo_create", $type, $data);
4241 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4245 // now let's do the changes in update-mode
4246 if ($mode == "update") {
4247 $updated_fields = [];
4249 if (!is_null($desc)) {
4250 $updated_fields['desc'] = $desc;
4253 if (!is_null($album_new)) {
4254 $updated_fields['album'] = $album_new;
4257 if (!is_null($allow_cid)) {
4258 $allow_cid = trim($allow_cid);
4259 $updated_fields['allow_cid'] = $allow_cid;
4262 if (!is_null($deny_cid)) {
4263 $deny_cid = trim($deny_cid);
4264 $updated_fields['deny_cid'] = $deny_cid;
4267 if (!is_null($allow_gid)) {
4268 $allow_gid = trim($allow_gid);
4269 $updated_fields['allow_gid'] = $allow_gid;
4272 if (!is_null($deny_gid)) {
4273 $deny_gid = trim($deny_gid);
4274 $updated_fields['deny_gid'] = $deny_gid;
4278 if (count($updated_fields) > 0) {
4279 $nothingtodo = false;
4280 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4282 $nothingtodo = true;
4285 if (!empty($_FILES['media'])) {
4286 $nothingtodo = false;
4287 $media = $_FILES['media'];
4288 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, 0, $visibility, $photo_id);
4289 if (!is_null($data)) {
4290 return api_format_data("photo_update", $type, $data);
4294 // return success of updating or error message
4296 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4297 return api_format_data("photo_update", $type, ['$result' => $answer]);
4300 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4301 return api_format_data("photo_update", $type, ['$result' => $answer]);
4303 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4306 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4310 * delete a single photo from the database through api
4312 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4313 * @return string|array
4314 * @throws BadRequestException
4315 * @throws ForbiddenException
4316 * @throws InternalServerErrorException
4318 function api_fr_photo_delete($type)
4320 if (api_user() === false) {
4321 throw new ForbiddenException();
4325 $photo_id = $_REQUEST['photo_id'] ?? null;
4327 // do several checks on input parameters
4328 // we do not allow calls without photo id
4329 if ($photo_id == null) {
4330 throw new BadRequestException("no photo_id specified");
4333 // check if photo is existing in database
4334 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4335 throw new BadRequestException("photo not available");
4338 // now we can perform on the deletion of the photo
4339 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4341 // return success of deletion or error message
4343 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4344 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4345 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4346 Item::deleteForUser($condition, api_user());
4348 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4349 return api_format_data("photo_delete", $type, ['$result' => $result]);
4351 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4357 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4359 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4360 * @return string|array
4361 * @throws BadRequestException
4362 * @throws ForbiddenException
4363 * @throws InternalServerErrorException
4364 * @throws NotFoundException
4366 function api_fr_photo_detail($type)
4368 if (api_user() === false) {
4369 throw new ForbiddenException();
4371 if (empty($_REQUEST['photo_id'])) {
4372 throw new BadRequestException("No photo id.");
4375 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4376 $photo_id = $_REQUEST['photo_id'];
4378 // prepare json/xml output with data from database for the requested photo
4379 $data = prepare_photo_data($type, $scale, $photo_id);
4381 return api_format_data("photo_detail", $type, $data);
4386 * updates the profile image for the user (either a specified profile or the default profile)
4388 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4390 * @return string|array
4391 * @throws BadRequestException
4392 * @throws ForbiddenException
4393 * @throws ImagickException
4394 * @throws InternalServerErrorException
4395 * @throws NotFoundException
4396 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4398 function api_account_update_profile_image($type)
4400 if (api_user() === false) {
4401 throw new ForbiddenException();
4404 $profile_id = $_REQUEST['profile_id'] ?? 0;
4406 // error if image data is missing
4407 if (empty($_FILES['image'])) {
4408 throw new BadRequestException("no media data submitted");
4411 // check if specified profile id is valid
4412 if ($profile_id != 0) {
4413 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4414 // error message if specified profile id is not in database
4415 if (!DBA::isResult($profile)) {
4416 throw new BadRequestException("profile_id not available");
4418 $is_default_profile = $profile['is-default'];
4420 $is_default_profile = 1;
4423 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4425 if (!empty($_FILES['image'])) {
4426 $media = $_FILES['image'];
4427 } elseif (!empty($_FILES['media'])) {
4428 $media = $_FILES['media'];
4430 // save new profile image
4431 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t('Profile Photos'), "", "", "", "", "", $is_default_profile);
4434 if (is_array($media['type'])) {
4435 $filetype = $media['type'][0];
4437 $filetype = $media['type'];
4439 if ($filetype == "image/jpeg") {
4441 } elseif ($filetype == "image/png") {
4444 throw new InternalServerErrorException('Unsupported filetype');
4447 // change specified profile or all profiles to the new resource-id
4448 if ($is_default_profile) {
4449 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4450 Photo::update(['profile' => false], $condition);
4452 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4453 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4454 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4457 Contact::updateSelfFromUserID(api_user(), true);
4459 // Update global directory in background
4460 Profile::publishUpdate(api_user());
4462 // output for client
4464 return api_account_verify_credentials($type);
4466 // SaveMediaToDatabase failed for some reason
4467 throw new InternalServerErrorException("image upload failed");
4471 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4472 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4473 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4474 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4475 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4476 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4477 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4478 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4479 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4482 * Update user profile
4484 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4486 * @return array|string
4487 * @throws BadRequestException
4488 * @throws ForbiddenException
4489 * @throws ImagickException
4490 * @throws InternalServerErrorException
4491 * @throws UnauthorizedException
4493 function api_account_update_profile($type)
4495 $local_user = api_user();
4496 $api_user = api_get_user(DI::app());
4498 if (!empty($_POST['name'])) {
4499 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4500 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4501 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4502 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
4505 if (isset($_POST['description'])) {
4506 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4507 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4508 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
4511 Profile::publishUpdate($local_user);
4513 return api_account_verify_credentials($type);
4516 /// @TODO move to top of file or somewhere better
4517 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4521 * @param string $acl_string
4525 function check_acl_input($acl_string)
4527 if (empty($acl_string)) {
4531 $contact_not_found = false;
4533 // split <x><y><z> into array of cid's
4534 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4536 // check for each cid if it is available on server
4537 $cid_array = $array[0];
4538 foreach ($cid_array as $cid) {
4539 $cid = str_replace("<", "", $cid);
4540 $cid = str_replace(">", "", $cid);
4541 $condition = ['id' => $cid, 'uid' => api_user()];
4542 $contact_not_found |= !DBA::exists('contact', $condition);
4544 return $contact_not_found;
4548 * @param string $mediatype
4549 * @param array $media
4550 * @param string $type
4551 * @param string $album
4552 * @param string $allow_cid
4553 * @param string $deny_cid
4554 * @param string $allow_gid
4555 * @param string $deny_gid
4556 * @param string $desc
4557 * @param integer $profile
4558 * @param boolean $visibility
4559 * @param string $photo_id
4561 * @throws BadRequestException
4562 * @throws ForbiddenException
4563 * @throws ImagickException
4564 * @throws InternalServerErrorException
4565 * @throws NotFoundException
4566 * @throws UnauthorizedException
4568 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $profile = 0, $visibility = false, $photo_id = null)
4576 if (is_array($media)) {
4577 if (is_array($media['tmp_name'])) {
4578 $src = $media['tmp_name'][0];
4580 $src = $media['tmp_name'];
4582 if (is_array($media['name'])) {
4583 $filename = basename($media['name'][0]);
4585 $filename = basename($media['name']);
4587 if (is_array($media['size'])) {
4588 $filesize = intval($media['size'][0]);
4590 $filesize = intval($media['size']);
4592 if (is_array($media['type'])) {
4593 $filetype = $media['type'][0];
4595 $filetype = $media['type'];
4599 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4602 "File upload src: " . $src . " - filename: " . $filename .
4603 " - size: " . $filesize . " - type: " . $filetype,
4607 // check if there was a php upload error
4608 if ($filesize == 0 && $media['error'] == 1) {
4609 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4611 // check against max upload size within Friendica instance
4612 $maximagesize = DI::config()->get('system', 'maximagesize');
4613 if ($maximagesize && ($filesize > $maximagesize)) {
4614 $formattedBytes = Strings::formatBytes($maximagesize);
4615 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4618 // create Photo instance with the data of the image
4619 $imagedata = @file_get_contents($src);
4620 $Image = new Image($imagedata, $filetype);
4621 if (!$Image->isValid()) {
4622 throw new InternalServerErrorException("unable to process image data");
4625 // check orientation of image
4626 $Image->orient($src);
4629 // check max length of images on server
4630 $max_length = DI::config()->get('system', 'max_image_length');
4632 $max_length = MAX_IMAGE_LENGTH;
4634 if ($max_length > 0) {
4635 $Image->scaleDown($max_length);
4636 Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
4638 $width = $Image->getWidth();
4639 $height = $Image->getHeight();
4641 // create a new resource-id if not already provided
4642 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4644 if ($mediatype == "photo") {
4645 // upload normal image (scales 0, 1, 2)
4646 Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
4648 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4650 Logger::log("photo upload: image upload with scale 0 (original size) failed");
4652 if ($width > 640 || $height > 640) {
4653 $Image->scaleDown(640);
4654 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4656 Logger::log("photo upload: image upload with scale 1 (640x640) failed");
4660 if ($width > 320 || $height > 320) {
4661 $Image->scaleDown(320);
4662 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4664 Logger::log("photo upload: image upload with scale 2 (320x320) failed");
4667 Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
4668 } elseif ($mediatype == "profileimage") {
4669 // upload profile image (scales 4, 5, 6)
4670 Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
4672 if ($width > 300 || $height > 300) {
4673 $Image->scaleDown(300);
4674 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4676 Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
4680 if ($width > 80 || $height > 80) {
4681 $Image->scaleDown(80);
4682 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4684 Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
4688 if ($width > 48 || $height > 48) {
4689 $Image->scaleDown(48);
4690 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4692 Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
4695 $Image->__destruct();
4696 Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
4700 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4701 if ($photo_id == null && $mediatype == "photo") {
4702 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4704 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4705 return prepare_photo_data($type, false, $resource_id);
4707 throw new InternalServerErrorException("image upload failed");
4713 * @param string $hash
4714 * @param string $allow_cid
4715 * @param string $deny_cid
4716 * @param string $allow_gid
4717 * @param string $deny_gid
4718 * @param string $filetype
4719 * @param boolean $visibility
4720 * @throws InternalServerErrorException
4722 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4724 // get data about the api authenticated user
4725 $uri = Item::newURI(intval(api_user()));
4726 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4729 $arr['guid'] = System::createUUID();
4730 $arr['uid'] = intval(api_user());
4732 $arr['type'] = 'photo';
4734 $arr['resource-id'] = $hash;
4735 $arr['contact-id'] = $owner_record['id'];
4736 $arr['owner-name'] = $owner_record['name'];
4737 $arr['owner-link'] = $owner_record['url'];
4738 $arr['owner-avatar'] = $owner_record['thumb'];
4739 $arr['author-name'] = $owner_record['name'];
4740 $arr['author-link'] = $owner_record['url'];
4741 $arr['author-avatar'] = $owner_record['thumb'];
4743 $arr['allow_cid'] = $allow_cid;
4744 $arr['allow_gid'] = $allow_gid;
4745 $arr['deny_cid'] = $deny_cid;
4746 $arr['deny_gid'] = $deny_gid;
4747 $arr['visible'] = $visibility;
4751 'image/jpeg' => 'jpg',
4752 'image/png' => 'png',
4753 'image/gif' => 'gif'
4756 // adds link to the thumbnail scale photo
4757 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4758 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4761 // do the magic for storing the item in the database and trigger the federation to other contacts
4767 * @param string $type
4769 * @param string $photo_id
4772 * @throws BadRequestException
4773 * @throws ForbiddenException
4774 * @throws ImagickException
4775 * @throws InternalServerErrorException
4776 * @throws NotFoundException
4777 * @throws UnauthorizedException
4779 function prepare_photo_data($type, $scale, $photo_id)
4782 $user_info = api_get_user($a);
4784 if ($user_info === false) {
4785 throw new ForbiddenException();
4788 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4789 $data_sql = ($scale === false ? "" : "data, ");
4791 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4792 // clients needs to convert this in their way for further processing
4794 "SELECT %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4795 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4796 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4797 FROM `photo` WHERE `uid` = %d AND `resource-id` = '%s' %s GROUP BY
4798 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4799 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4801 intval(local_user()),
4802 DBA::escape($photo_id),
4807 'image/jpeg' => 'jpg',
4808 'image/png' => 'png',
4809 'image/gif' => 'gif'
4812 // prepare output data for photo
4813 if (DBA::isResult($r)) {
4814 $data = ['photo' => $r[0]];
4815 $data['photo']['id'] = $data['photo']['resource-id'];
4816 if ($scale !== false) {
4817 $data['photo']['data'] = base64_encode($data['photo']['data']);
4819 unset($data['photo']['datasize']); //needed only with scale param
4821 if ($type == "xml") {
4822 $data['photo']['links'] = [];
4823 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4824 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4826 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4829 $data['photo']['link'] = [];
4830 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4832 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4833 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4837 unset($data['photo']['resource-id']);
4838 unset($data['photo']['minscale']);
4839 unset($data['photo']['maxscale']);
4841 throw new NotFoundException();
4844 // retrieve item element for getting activities (like, dislike etc.) related to photo
4845 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4846 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4847 if (!DBA::isResult($item)) {
4848 throw new NotFoundException('Photo-related item not found.');
4851 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4853 // retrieve comments on photo
4854 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4855 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4857 $statuses = Post::selectForUser(api_user(), [], $condition);
4859 // prepare output of comments
4860 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4862 if ($type == "xml") {
4864 foreach ($commentData as $comment) {
4865 $comments[$k++ . ":comment"] = $comment;
4868 foreach ($commentData as $comment) {
4869 $comments[] = $comment;
4872 $data['photo']['friendica_comments'] = $comments;
4874 // include info if rights on photo and rights on item are mismatching
4875 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4876 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4877 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4878 $data['photo']['deny_gid'] != $item['deny_gid'];
4879 $data['photo']['rights_mismatch'] = $rights_mismatch;
4885 * Return an item with announcer data if it had been announced
4887 * @param array $item Item array
4888 * @return array Item array with announce data
4890 function api_get_announce($item)
4892 // Quit if the item already has got a different owner and author
4893 if ($item['owner-id'] != $item['author-id']) {
4897 // Don't change original or Diaspora posts
4898 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4902 // Quit if we do now the original author and it had been a post from a native network
4903 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4907 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4908 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4909 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4910 if (!DBA::isResult($announce)) {
4914 return array_merge($item, $announce);
4919 * @param array $item
4924 function api_in_reply_to($item)
4928 $in_reply_to['status_id'] = null;
4929 $in_reply_to['user_id'] = null;
4930 $in_reply_to['status_id_str'] = null;
4931 $in_reply_to['user_id_str'] = null;
4932 $in_reply_to['screen_name'] = null;
4934 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4935 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4936 if (DBA::isResult($parent)) {
4937 $in_reply_to['status_id'] = intval($parent['id']);
4939 $in_reply_to['status_id'] = intval($item['parent']);
4942 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4944 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4945 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4947 if (DBA::isResult($parent)) {
4948 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4949 $in_reply_to['user_id'] = intval($parent['author-id']);
4950 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4953 // There seems to be situation, where both fields are identical:
4954 // https://github.com/friendica/friendica/issues/1010
4955 // This is a bugfix for that.
4956 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4957 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']]);
4958 $in_reply_to['status_id'] = null;
4959 $in_reply_to['user_id'] = null;
4960 $in_reply_to['status_id_str'] = null;
4961 $in_reply_to['user_id_str'] = null;
4962 $in_reply_to['screen_name'] = null;
4966 return $in_reply_to;
4971 * @param string $text
4974 * @throws InternalServerErrorException
4976 function api_clean_plain_items($text)
4978 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4980 $text = BBCode::cleanPictureLinks($text);
4981 $URLSearchString = "^\[\]";
4983 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4985 if ($include_entities == "true") {
4986 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4989 // Simplify "attachment" element
4990 $text = BBCode::removeAttachment($text);
4997 * @param array $contacts
5001 function api_best_nickname(&$contacts)
5005 if (count($contacts) == 0) {
5009 foreach ($contacts as $contact) {
5010 if ($contact["network"] == "") {
5011 $contact["network"] = "dfrn";
5012 $best_contact = [$contact];
5016 if (sizeof($best_contact) == 0) {
5017 foreach ($contacts as $contact) {
5018 if ($contact["network"] == "dfrn") {
5019 $best_contact = [$contact];
5024 if (sizeof($best_contact) == 0) {
5025 foreach ($contacts as $contact) {
5026 if ($contact["network"] == "dspr") {
5027 $best_contact = [$contact];
5032 if (sizeof($best_contact) == 0) {
5033 foreach ($contacts as $contact) {
5034 if ($contact["network"] == "stat") {
5035 $best_contact = [$contact];
5040 if (sizeof($best_contact) == 0) {
5041 foreach ($contacts as $contact) {
5042 if ($contact["network"] == "pump") {
5043 $best_contact = [$contact];
5048 if (sizeof($best_contact) == 0) {
5049 foreach ($contacts as $contact) {
5050 if ($contact["network"] == "twit") {
5051 $best_contact = [$contact];
5056 if (sizeof($best_contact) == 1) {
5057 $contacts = $best_contact;
5059 $contacts = [$contacts[0]];
5064 * Return all or a specified group of the user with the containing contacts.
5066 * @param string $type Return type (atom, rss, xml, json)
5068 * @return array|string
5069 * @throws BadRequestException
5070 * @throws ForbiddenException
5071 * @throws ImagickException
5072 * @throws InternalServerErrorException
5073 * @throws UnauthorizedException
5075 function api_friendica_group_show($type)
5079 if (api_user() === false) {
5080 throw new ForbiddenException();
5084 $user_info = api_get_user($a);
5085 $gid = $_REQUEST['gid'] ?? 0;
5086 $uid = $user_info['uid'];
5088 // get data of the specified group id or all groups if not specified
5091 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
5095 // error message if specified gid is not in database
5096 if (!DBA::isResult($r)) {
5097 throw new BadRequestException("gid not available");
5101 "SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
5106 // loop through all groups and retrieve all members for adding data in the user array
5108 foreach ($r as $rr) {
5109 $members = Contact\Group::getById($rr['id']);
5112 if ($type == "xml") {
5113 $user_element = "users";
5115 foreach ($members as $member) {
5116 $user = api_get_user($a, $member['nurl']);
5117 $users[$k++.":user"] = $user;
5120 $user_element = "user";
5121 foreach ($members as $member) {
5122 $user = api_get_user($a, $member['nurl']);
5126 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5128 return api_format_data("groups", $type, ['group' => $grps]);
5130 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5134 * Delete the specified group of the user.
5136 * @param string $type Return type (atom, rss, xml, json)
5138 * @return array|string
5139 * @throws BadRequestException
5140 * @throws ForbiddenException
5141 * @throws ImagickException
5142 * @throws InternalServerErrorException
5143 * @throws UnauthorizedException
5145 function api_friendica_group_delete($type)
5149 if (api_user() === false) {
5150 throw new ForbiddenException();
5154 $user_info = api_get_user($a);
5155 $gid = $_REQUEST['gid'] ?? 0;
5156 $name = $_REQUEST['name'] ?? '';
5157 $uid = $user_info['uid'];
5159 // error if no gid specified
5160 if ($gid == 0 || $name == "") {
5161 throw new BadRequestException('gid or name not specified');
5164 // get data of the specified group id
5166 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
5170 // error message if specified gid is not in database
5171 if (!DBA::isResult($r)) {
5172 throw new BadRequestException('gid not available');
5175 // get data of the specified group id and group name
5177 "SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
5182 // error message if specified gid is not in database
5183 if (!DBA::isResult($rname)) {
5184 throw new BadRequestException('wrong group name');
5188 $ret = Group::removeByName($uid, $name);
5191 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5192 return api_format_data("group_delete", $type, ['result' => $success]);
5194 throw new BadRequestException('other API error');
5197 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5202 * @param string $type Return type (atom, rss, xml, json)
5204 * @return array|string
5205 * @throws BadRequestException
5206 * @throws ForbiddenException
5207 * @throws ImagickException
5208 * @throws InternalServerErrorException
5209 * @throws UnauthorizedException
5210 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5212 function api_lists_destroy($type)
5216 if (api_user() === false) {
5217 throw new ForbiddenException();
5221 $user_info = api_get_user($a);
5222 $gid = $_REQUEST['list_id'] ?? 0;
5223 $uid = $user_info['uid'];
5225 // error if no gid specified
5227 throw new BadRequestException('gid not specified');
5230 // get data of the specified group id
5231 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5232 // error message if specified gid is not in database
5234 throw new BadRequestException('gid not available');
5237 if (Group::remove($gid)) {
5239 'name' => $group['name'],
5240 'id' => intval($gid),
5241 'id_str' => (string) $gid,
5242 'user' => $user_info
5245 return api_format_data("lists", $type, ['lists' => $list]);
5248 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5251 * Add a new group to the database.
5253 * @param string $name Group name
5254 * @param int $uid User ID
5255 * @param array $users List of users to add to the group
5258 * @throws BadRequestException
5260 function group_create($name, $uid, $users = [])
5262 // error if no name specified
5264 throw new BadRequestException('group name not specified');
5267 // get data of the specified group name
5269 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
5273 // error message if specified group name already exists
5274 if (DBA::isResult($rname)) {
5275 throw new BadRequestException('group name already exists');
5278 // check if specified group name is a deleted group
5280 "SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
5284 // error message if specified group name already exists
5285 if (DBA::isResult($rname)) {
5286 $reactivate_group = true;
5290 $ret = Group::create($uid, $name);
5292 $gid = Group::getIdByName($uid, $name);
5294 throw new BadRequestException('other API error');
5298 $erroraddinguser = false;
5300 foreach ($users as $user) {
5301 $cid = $user['cid'];
5302 // check if user really exists as contact
5304 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5308 if (count($contact)) {
5309 Group::addMember($gid, $cid);
5311 $erroraddinguser = true;
5312 $errorusers[] = $cid;
5316 // return success message incl. missing users in array
5317 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5319 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5323 * Create the specified group with the posted array of contacts.
5325 * @param string $type Return type (atom, rss, xml, json)
5327 * @return array|string
5328 * @throws BadRequestException
5329 * @throws ForbiddenException
5330 * @throws ImagickException
5331 * @throws InternalServerErrorException
5332 * @throws UnauthorizedException
5334 function api_friendica_group_create($type)
5338 if (api_user() === false) {
5339 throw new ForbiddenException();
5343 $user_info = api_get_user($a);
5344 $name = $_REQUEST['name'] ?? '';
5345 $uid = $user_info['uid'];
5346 $json = json_decode($_POST['json'], true);
5347 $users = $json['user'];
5349 $success = group_create($name, $uid, $users);
5351 return api_format_data("group_create", $type, ['result' => $success]);
5353 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5356 * Create a new group.
5358 * @param string $type Return type (atom, rss, xml, json)
5360 * @return array|string
5361 * @throws BadRequestException
5362 * @throws ForbiddenException
5363 * @throws ImagickException
5364 * @throws InternalServerErrorException
5365 * @throws UnauthorizedException
5366 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5368 function api_lists_create($type)
5372 if (api_user() === false) {
5373 throw new ForbiddenException();
5377 $user_info = api_get_user($a);
5378 $name = $_REQUEST['name'] ?? '';
5379 $uid = $user_info['uid'];
5381 $success = group_create($name, $uid);
5382 if ($success['success']) {
5384 'name' => $success['name'],
5385 'id' => intval($success['gid']),
5386 'id_str' => (string) $success['gid'],
5387 'user' => $user_info
5390 return api_format_data("lists", $type, ['lists'=>$grp]);
5393 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5396 * Update the specified group with the posted array of contacts.
5398 * @param string $type Return type (atom, rss, xml, json)
5400 * @return array|string
5401 * @throws BadRequestException
5402 * @throws ForbiddenException
5403 * @throws ImagickException
5404 * @throws InternalServerErrorException
5405 * @throws UnauthorizedException
5407 function api_friendica_group_update($type)
5411 if (api_user() === false) {
5412 throw new ForbiddenException();
5416 $user_info = api_get_user($a);
5417 $uid = $user_info['uid'];
5418 $gid = $_REQUEST['gid'] ?? 0;
5419 $name = $_REQUEST['name'] ?? '';
5420 $json = json_decode($_POST['json'], true);
5421 $users = $json['user'];
5423 // error if no name specified
5425 throw new BadRequestException('group name not specified');
5428 // error if no gid specified
5430 throw new BadRequestException('gid not specified');
5434 $members = Contact\Group::getById($gid);
5435 foreach ($members as $member) {
5436 $cid = $member['id'];
5437 foreach ($users as $user) {
5438 $found = ($user['cid'] == $cid ? true : false);
5440 if (!isset($found) || !$found) {
5441 Group::removeMemberByName($uid, $name, $cid);
5446 $erroraddinguser = false;
5448 foreach ($users as $user) {
5449 $cid = $user['cid'];
5450 // check if user really exists as contact
5452 "SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
5457 if (count($contact)) {
5458 Group::addMember($gid, $cid);
5460 $erroraddinguser = true;
5461 $errorusers[] = $cid;
5465 // return success message incl. missing users in array
5466 $status = ($erroraddinguser ? "missing user" : "ok");
5467 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5468 return api_format_data("group_update", $type, ['result' => $success]);
5471 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5474 * Update information about a group.
5476 * @param string $type Return type (atom, rss, xml, json)
5478 * @return array|string
5479 * @throws BadRequestException
5480 * @throws ForbiddenException
5481 * @throws ImagickException
5482 * @throws InternalServerErrorException
5483 * @throws UnauthorizedException
5484 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5486 function api_lists_update($type)
5490 if (api_user() === false) {
5491 throw new ForbiddenException();
5495 $user_info = api_get_user($a);
5496 $gid = $_REQUEST['list_id'] ?? 0;
5497 $name = $_REQUEST['name'] ?? '';
5498 $uid = $user_info['uid'];
5500 // error if no gid specified
5502 throw new BadRequestException('gid not specified');
5505 // get data of the specified group id
5506 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5507 // error message if specified gid is not in database
5509 throw new BadRequestException('gid not available');
5512 if (Group::update($gid, $name)) {
5515 'id' => intval($gid),
5516 'id_str' => (string) $gid,
5517 'user' => $user_info
5520 return api_format_data("lists", $type, ['lists' => $list]);
5524 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5528 * @param string $type Return type (atom, rss, xml, json)
5530 * @return array|string
5531 * @throws BadRequestException
5532 * @throws ForbiddenException
5533 * @throws ImagickException
5534 * @throws InternalServerErrorException
5536 function api_friendica_activity($type)
5540 if (api_user() === false) {
5541 throw new ForbiddenException();
5543 $verb = strtolower(DI::args()->getArgv()[3]);
5544 $verb = preg_replace("|\..*$|", "", $verb);
5546 $id = $_REQUEST['id'] ?? 0;
5548 $res = Item::performActivity($id, $verb, api_user());
5551 if ($type == "xml") {
5556 return api_format_data('ok', $type, ['ok' => $ok]);
5558 throw new BadRequestException('Error adding activity');
5562 /// @TODO move to top of file or somewhere better
5563 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5564 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5565 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5566 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5567 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5568 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5569 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5570 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5571 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5572 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5575 * Returns notifications
5577 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5579 * @return string|array
5580 * @throws ForbiddenException
5581 * @throws BadRequestException
5584 function api_friendica_notification($type)
5586 if (api_user() === false) {
5587 throw new ForbiddenException();
5589 if (DI::args()->getArgc()!==3) {
5590 throw new BadRequestException('Invalid argument count');
5593 $Notifies = DI::notify()->selectAllForUser(local_user(), ['order' => ['seen' => 'ASC', 'date' => 'DESC'], 'limit' => 50]);
5595 $notifications = new ApiNotifications();
5596 foreach ($Notifies as $Notify) {
5597 $notifications[] = new ApiNotification($Notify);
5600 if ($type == 'xml') {
5602 foreach ($notifications as $notification) {
5603 $xmlnotes[] = ['@attributes' => $notification->toArray()];
5606 $result = $xmlnotes;
5607 } elseif (count($notifications) > 0) {
5608 $result = $notifications->getArrayCopy();
5613 return api_format_data('notes', $type, ['note' => $result]);
5617 * Set notification as seen and returns associated item (if possible)
5619 * POST request with 'id' param as notification id
5621 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5622 * @return string|array
5623 * @throws BadRequestException
5624 * @throws ForbiddenException
5625 * @throws ImagickException
5626 * @throws InternalServerErrorException
5627 * @throws UnauthorizedException
5629 function api_friendica_notification_seen($type)
5632 $user_info = api_get_user($a);
5634 if (api_user() === false || $user_info === false) {
5635 throw new ForbiddenException();
5637 if (DI::args()->getArgc() !== 4) {
5638 throw new BadRequestException('Invalid argument count');
5641 $id = intval($_REQUEST['id'] ?? 0);
5644 $Notify = DI::notify()->selectOneById($id);
5645 if ($Notify->uid !== api_user()) {
5646 throw new NotFoundException();
5649 if ($Notify->uriId) {
5650 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
5654 DI::notify()->save($Notify);
5656 if ($Notify->otype === Notification\ObjectType::ITEM) {
5657 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
5658 if (DBA::isResult($item)) {
5659 // we found the item, return it to the user
5660 $ret = api_format_items([$item], $user_info, false, $type);
5661 $data = ['status' => $ret];
5662 return api_format_data('status', $type, $data);
5664 // the item can't be found, but we set the notification as seen, so we count this as a success
5667 return api_format_data('result', $type, ['result' => 'success']);
5668 } catch (NotFoundException $e) {
5669 throw new BadRequestException('Invalid argument', $e);
5670 } catch (Exception $e) {
5671 throw new InternalServerErrorException('Internal Server exception', $e);
5675 /// @TODO move to top of file or somewhere better
5676 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5677 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5680 * update a direct_message to seen state
5682 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5683 * @return string|array (success result=ok, error result=error with error message)
5684 * @throws BadRequestException
5685 * @throws ForbiddenException
5686 * @throws ImagickException
5687 * @throws InternalServerErrorException
5688 * @throws UnauthorizedException
5690 function api_friendica_direct_messages_setseen($type)
5693 if (api_user() === false) {
5694 throw new ForbiddenException();
5698 $user_info = api_get_user($a);
5699 $uid = $user_info['uid'];
5700 $id = $_REQUEST['id'] ?? 0;
5702 // return error if id is zero
5704 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5705 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5708 // error message if specified id is not in database
5709 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5710 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5711 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5714 // update seen indicator
5715 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5719 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5720 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5722 $answer = ['result' => 'error', 'message' => 'unknown error'];
5723 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5727 /// @TODO move to top of file or somewhere better
5728 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5731 * search for direct_messages containing a searchstring through api
5733 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5734 * @param string $box
5735 * @return string|array (success: success=true if found and search_result contains found messages,
5736 * success=false if nothing was found, search_result='nothing found',
5737 * error: result=error with error message)
5738 * @throws BadRequestException
5739 * @throws ForbiddenException
5740 * @throws ImagickException
5741 * @throws InternalServerErrorException
5742 * @throws UnauthorizedException
5744 function api_friendica_direct_messages_search($type, $box = "")
5748 if (api_user() === false) {
5749 throw new ForbiddenException();
5753 $user_info = api_get_user($a);
5754 $searchstring = $_REQUEST['searchstring'] ?? '';
5755 $uid = $user_info['uid'];
5757 // error if no searchstring specified
5758 if ($searchstring == "") {
5759 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5760 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5763 // get data for the specified searchstring
5765 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND `body` LIKE '%s' ORDER BY `mail`.`id` DESC",
5767 DBA::escape('%'.$searchstring.'%')
5770 $profile_url = $user_info["url"];
5772 // message if nothing was found
5773 if (!DBA::isResult($r)) {
5774 $success = ['success' => false, 'search_results' => 'problem with query'];
5775 } elseif (count($r) == 0) {
5776 $success = ['success' => false, 'search_results' => 'nothing found'];
5779 foreach ($r as $item) {
5780 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5781 $recipient = $user_info;
5782 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5783 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5784 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5785 $sender = $user_info;
5788 if (isset($recipient) && isset($sender)) {
5789 $ret[] = api_format_messages($item, $recipient, $sender);
5792 $success = ['success' => true, 'search_results' => $ret];
5795 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5798 /// @TODO move to top of file or somewhere better
5799 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5802 * Returns a list of saved searches.
5804 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5806 * @param string $type Return format: json or xml
5808 * @return string|array
5811 function api_saved_searches_list($type)
5813 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5816 while ($term = DBA::fetch($terms)) {
5818 'created_at' => api_date(time()),
5819 'id' => intval($term['id']),
5820 'id_str' => $term['id'],
5821 'name' => $term['term'],
5823 'query' => $term['term']
5829 return api_format_data("terms", $type, ['terms' => $result]);
5832 /// @TODO move to top of file or somewhere better
5833 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5836 * Number of comments
5838 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5840 * @param object $data [Status, Status]
5844 function bindComments(&$data)
5846 if (count($data) == 0) {
5852 foreach ($data as $item) {
5853 $ids[] = $item['id'];
5856 $idStr = DBA::escape(implode(', ', $ids));
5857 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5858 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5859 $itemsData = DBA::toArray($items);
5861 foreach ($itemsData as $item) {
5862 $comments[$item['parent']] = $item['comments'];
5865 foreach ($data as $idx => $item) {
5867 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5872 @TODO Maybe open to implement?
5874 [pagename] => api/1.1/statuses/lookup.json
5875 [id] => 605138389168451584
5876 [include_cards] => true
5877 [cards_platform] => Android-12
5878 [include_entities] => true
5879 [include_my_retweet] => 1
5881 [include_reply_count] => true
5882 [include_descendent_reply_count] => true
5886 Not implemented by now:
5887 statuses/retweets_of_me
5892 account/update_location
5893 account/update_profile_background_image
5896 friendica/profile/update
5897 friendica/profile/create
5898 friendica/profile/delete
5900 Not implemented in status.net:
5901 statuses/retweeted_to_me
5902 statuses/retweeted_by_me
5903 direct_messages/destroy
5905 account/update_delivery_device
5906 notifications/follow