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'];
241 $user_id = User::getIdFromPasswordAuthentication(trim($user), trim($password), true);
242 if ($user_id !== false) {
243 $record = DBA::selectFirst('user', [], ['uid' => $user_id]);
245 } catch (Exception $ex) {
250 if (!DBA::isResult($record)) {
251 Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
252 header('WWW-Authenticate: Basic realm="Friendica"');
253 throw new UnauthorizedException("This API requires login");
256 // Don't refresh the login date more often than twice a day to spare database writes
257 $login_refresh = strcmp(DateTimeFormat::utc('now - 12 hours'), $record['login_date']) > 0;
259 DI::auth()->setForUser($a, $record, false, false, $login_refresh);
261 $_SESSION["allow_api"] = true;
263 Hook::callAll('logged_in', $record);
267 * Check HTTP method of called API
269 * API endpoints can define which HTTP method to accept when called.
270 * This function check the current HTTP method agains endpoint
273 * @param string $method Required methods, uppercase, separated by comma
276 function api_check_method($method)
278 if ($method == "*") {
281 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
285 * Main API entry point
287 * Authenticate user, call registered API function, set HTTP headers
290 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
291 * @return string|array API call result
294 function api_call(App $a, App\Arguments $args = null)
296 global $API, $called_api;
303 if (strpos($args->getCommand(), ".xml") > 0) {
306 if (strpos($args->getCommand(), ".json") > 0) {
309 if (strpos($args->getCommand(), ".rss") > 0) {
312 if (strpos($args->getCommand(), ".atom") > 0) {
317 foreach ($API as $p => $info) {
318 if (strpos($args->getCommand(), $p) === 0) {
319 if (!api_check_method($info['method'])) {
320 throw new MethodNotAllowedException();
323 $called_api = explode("/", $p);
325 if (!empty($info['auth']) && api_user() === false) {
327 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
330 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
332 $stamp = microtime(true);
333 $return = call_user_func($info['func'], $type);
334 $duration = floatval(microtime(true) - $stamp);
336 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
338 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
340 if (false === $return) {
342 * api function returned false withour throw an
343 * exception. This should not happend, throw a 500
345 throw new InternalServerErrorException();
350 header("Content-Type: text/xml");
353 header("Content-Type: application/json");
354 if (!empty($return)) {
355 $json = json_encode(end($return));
356 if (!empty($_GET['callback'])) {
357 $json = $_GET['callback'] . "(" . $json . ")";
363 header("Content-Type: application/rss+xml");
364 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
367 header("Content-Type: application/atom+xml");
368 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
375 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
376 throw new NotFoundException();
377 } catch (HTTPException $e) {
378 header("HTTP/1.1 {$e->getCode()} {$e->getDescription()}");
379 return api_error($type, $e, $args);
384 * Format API error string
386 * @param string $type Return type (xml, json, rss, as)
387 * @param object $e HTTPException Error object
388 * @param App\Arguments $args The App arguments
389 * @return string|array error message formatted as $type
391 function api_error($type, $e, App\Arguments $args)
393 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->getDescription());
394 /// @TODO: https://dev.twitter.com/overview/api/response-codes
396 $error = ["error" => $error,
397 "code" => $e->getCode() . " " . $e->getDescription(),
398 "request" => $args->getQueryString()];
400 $return = api_format_data('status', $type, ['status' => $error]);
404 header("Content-Type: text/xml");
407 header("Content-Type: application/json");
408 $return = json_encode($return);
411 header("Content-Type: application/rss+xml");
414 header("Content-Type: application/atom+xml");
422 * Set values for RSS template
425 * @param array $arr Array to be passed to template
426 * @param array $user_info User info
428 * @throws BadRequestException
429 * @throws ImagickException
430 * @throws InternalServerErrorException
431 * @throws UnauthorizedException
432 * @todo find proper type-hints
434 function api_rss_extra(App $a, $arr, $user_info)
436 if (is_null($user_info)) {
437 $user_info = api_get_user($a);
440 $arr['$user'] = $user_info;
442 'alternate' => $user_info['url'],
443 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
444 'base' => DI::baseUrl(),
445 'updated' => api_date(null),
446 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
447 'language' => $user_info['lang'],
448 'logo' => DI::baseUrl() . "/images/friendica-32.png",
456 * Unique contact to contact url.
458 * @param int $id Contact id
459 * @return bool|string
460 * Contact url or False if contact id is unknown
463 function api_unique_id_to_nurl($id)
465 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
467 if (DBA::isResult($r)) {
475 * Get user info array.
478 * @param int|string $contact_id Contact ID or URL
480 * @throws BadRequestException
481 * @throws ImagickException
482 * @throws InternalServerErrorException
483 * @throws UnauthorizedException
485 function api_get_user(App $a, $contact_id = null)
493 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
495 // Searching for contact URL
496 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
497 $user = Strings::normaliseLink($contact_id);
499 $extra_query = "AND `contact`.`nurl` = ? ";
500 if (api_user() !== false) {
501 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
505 // Searching for contact id with uid = 0
506 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
507 $user = api_unique_id_to_nurl(intval($contact_id));
510 throw new BadRequestException("User ID ".$contact_id." not found.");
514 $extra_query = "AND `contact`.`nurl` = ? ";
515 if (api_user() !== false) {
516 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
520 if (is_null($user) && !empty($_GET['user_id'])) {
521 $user = api_unique_id_to_nurl($_GET['user_id']);
524 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
528 $extra_query = "AND `contact`.`nurl` = ? ";
529 if (api_user() !== false) {
530 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
533 if (is_null($user) && !empty($_GET['screen_name'])) {
534 $user = $_GET['screen_name'];
535 $extra_query = "AND `contact`.`nick` = ? ";
536 if (api_user() !== false) {
537 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
541 if (is_null($user) && !empty($_GET['profileurl'])) {
542 $user = Strings::normaliseLink($_GET['profileurl']);
543 $extra_query = "AND `contact`.`nurl` = ? ";
544 if (api_user() !== false) {
545 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
549 // $called_api is the API path exploded on / and is expected to have at least 2 elements
550 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
551 $argid = count($called_api);
552 if (!empty(DI::args()->getArgv()[$argid])) {
553 $data = explode(".", DI::args()->getArgv()[$argid]);
554 if (count($data) > 1) {
555 list($user, $null) = $data;
558 if (is_numeric($user)) {
559 $user = api_unique_id_to_nurl(intval($user));
563 $extra_query = "AND `contact`.`nurl` = ? ";
564 if (api_user() !== false) {
565 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
569 $extra_query = "AND `contact`.`nick` = ? ";
570 if (api_user() !== false) {
571 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
576 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
579 if (api_user() === false) {
584 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
588 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
591 $uinfo = DBA::toArray(DBA::p(
592 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
598 // Selecting the id by priority, friendica first
599 if (is_array($uinfo)) {
600 api_best_nickname($uinfo);
603 // if the contact wasn't found, fetch it from the contacts with uid = 0
604 if (!DBA::isResult($uinfo)) {
606 throw new BadRequestException("User not found.");
609 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
611 if (DBA::isResult($contact)) {
613 'id' => $contact["id"],
614 'id_str' => (string) $contact["id"],
615 'name' => $contact["name"],
616 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
617 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
618 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
619 'profile_image_url' => $contact["micro"],
620 'profile_image_url_https' => $contact["micro"],
621 'profile_image_url_profile_size' => $contact["thumb"],
622 'profile_image_url_large' => $contact["photo"],
623 'url' => $contact["url"],
624 'protected' => false,
625 'followers_count' => 0,
626 'friends_count' => 0,
628 'created_at' => api_date($contact["created"]),
629 'favourites_count' => 0,
631 'time_zone' => 'UTC',
632 'geo_enabled' => false,
634 'statuses_count' => 0,
636 'contributors_enabled' => false,
637 'is_translator' => false,
638 'is_translation_enabled' => false,
639 'following' => false,
640 'follow_request_sent' => false,
641 'statusnet_blocking' => false,
642 'notifications' => false,
643 'statusnet_profile_url' => $contact["url"],
645 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
646 'pid' => Contact::getIdForURL($contact["url"], 0, false),
648 'network' => $contact["network"],
653 throw new BadRequestException("User ".$url." not found.");
657 if ($uinfo[0]['self']) {
658 if ($uinfo[0]['network'] == "") {
659 $uinfo[0]['network'] = Protocol::DFRN;
662 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
663 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
670 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
672 if (!empty($profile['about'])) {
673 $description = $profile['about'];
675 $description = $uinfo[0]["about"];
678 if (!empty($usr['default-location'])) {
679 $location = $usr['default-location'];
680 } elseif (!empty($uinfo[0]["location"])) {
681 $location = $uinfo[0]["location"];
683 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
687 'id' => intval($pcontact_id),
688 'id_str' => (string) intval($pcontact_id),
689 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
690 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
691 'location' => $location,
692 'description' => BBCode::toPlaintext($description ?? ''),
693 'profile_image_url' => $uinfo[0]['micro'],
694 'profile_image_url_https' => $uinfo[0]['micro'],
695 'profile_image_url_profile_size' => $uinfo[0]["thumb"],
696 'profile_image_url_large' => $uinfo[0]["photo"],
697 'url' => $uinfo[0]['url'],
698 'protected' => false,
699 'followers_count' => intval($countfollowers),
700 'friends_count' => intval($countfriends),
702 'created_at' => api_date($uinfo[0]['created']),
703 'favourites_count' => intval($starred),
705 'time_zone' => 'UTC',
706 'geo_enabled' => false,
708 'statuses_count' => intval($countitems),
710 'contributors_enabled' => false,
711 'is_translator' => false,
712 'is_translation_enabled' => false,
713 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
714 'follow_request_sent' => false,
715 'statusnet_blocking' => false,
716 'notifications' => false,
718 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
719 'statusnet_profile_url' => $uinfo[0]['url'],
720 'uid' => intval($uinfo[0]['uid']),
721 'cid' => intval($uinfo[0]['cid']),
722 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
723 'self' => $uinfo[0]['self'],
724 'network' => $uinfo[0]['network'],
727 // If this is a local user and it uses Frio, we can get its color preferences.
729 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
730 if ($theme_info['theme'] === 'frio') {
731 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
733 if ($schema && ($schema != '---')) {
734 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
735 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
736 require_once $schemefile;
739 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
740 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
741 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
743 if (empty($nav_bg)) {
746 if (empty($link_color)) {
747 $link_color = "#6fdbe8";
749 if (empty($bgcolor)) {
750 $bgcolor = "#ededed";
753 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
754 $ret['profile_link_color'] = str_replace('#', '', $link_color);
755 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
763 * return api-formatted array for item's author and owner
766 * @param array $item item from db
767 * @return array(array:author, array:owner)
768 * @throws BadRequestException
769 * @throws ImagickException
770 * @throws InternalServerErrorException
771 * @throws UnauthorizedException
773 function api_item_get_user(App $a, $item)
775 $status_user = api_get_user($a, $item['author-id'] ?? null);
777 $author_user = $status_user;
779 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
781 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
782 $owner_user = api_get_user($a, $item['owner-id'] ?? null);
784 $owner_user = $author_user;
787 return ([$status_user, $author_user, $owner_user]);
791 * walks recursively through an array with the possibility to change value and key
793 * @param array $array The array to walk through
794 * @param callable $callback The callback function
796 * @return array the transformed array
798 function api_walk_recursive(array &$array, callable $callback)
802 foreach ($array as $k => $v) {
804 if ($callback($v, $k)) {
805 $new_array[$k] = api_walk_recursive($v, $callback);
808 if ($callback($v, $k)) {
819 * Callback function to transform the array in an array that can be transformed in a XML file
821 * @param mixed $item Array item value
822 * @param string $key Array key
824 * @return boolean Should the array item be deleted?
826 function api_reformat_xml(&$item, &$key)
828 if (is_bool($item)) {
829 $item = ($item ? "true" : "false");
832 if (substr($key, 0, 10) == "statusnet_") {
833 $key = "statusnet:".substr($key, 10);
834 } elseif (substr($key, 0, 10) == "friendica_") {
835 $key = "friendica:".substr($key, 10);
837 /// @TODO old-lost code?
839 // $key = "default:".$key;
845 * Creates the XML from a JSON style array
847 * @param array $data JSON style array
848 * @param string $root_element Name of the root element
850 * @return string The XML data
852 function api_create_xml(array $data, $root_element)
854 $childname = key($data);
855 $data2 = array_pop($data);
857 $namespaces = ["" => "http://api.twitter.com",
858 "statusnet" => "http://status.net/schema/api/1/",
859 "friendica" => "http://friendi.ca/schema/api/1/",
860 "georss" => "http://www.georss.org/georss"];
862 /// @todo Auto detection of needed namespaces
863 if (in_array($root_element, ["ok", "hash", "config", "version", "ids", "notes", "photos"])) {
867 if (is_array($data2)) {
869 api_walk_recursive($data2, "api_reformat_xml");
875 foreach ($data2 as $item) {
876 $data4[$i++ . ":" . $childname] = $item;
883 $data3 = [$root_element => $data2];
885 $ret = XML::fromArray($data3, $xml, false, $namespaces);
890 * Formats the data according to the data type
892 * @param string $root_element Name of the root element
893 * @param string $type Return type (atom, rss, xml, json)
894 * @param array $data JSON style array
896 * @return array|string (string|array) XML data or JSON data
898 function api_format_data($root_element, $type, $data)
904 $ret = api_create_xml($data, $root_element);
919 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
920 * returns a 401 status code and an error message if not.
922 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
924 * @param string $type Return type (atom, rss, xml, json)
925 * @return array|string
926 * @throws BadRequestException
927 * @throws ForbiddenException
928 * @throws ImagickException
929 * @throws InternalServerErrorException
930 * @throws UnauthorizedException
932 function api_account_verify_credentials($type)
936 if (api_user() === false) {
937 throw new ForbiddenException();
940 unset($_REQUEST["user_id"]);
941 unset($_GET["user_id"]);
943 unset($_REQUEST["screen_name"]);
944 unset($_GET["screen_name"]);
946 $skip_status = $_REQUEST['skip_status'] ?? false;
948 $user_info = api_get_user($a);
950 // "verified" isn't used here in the standard
951 unset($user_info["verified"]);
953 // - Adding last status
955 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
957 $user_info['status'] = api_format_item($item, $type);
961 // "uid" and "self" are only needed for some internal stuff, so remove it from here
962 unset($user_info["uid"]);
963 unset($user_info["self"]);
965 return api_format_data("user", $type, ['user' => $user_info]);
968 /// @TODO move to top of file or somewhere better
969 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
972 * Get data from $_POST or $_GET
977 function requestdata($k)
979 if (!empty($_POST[$k])) {
982 if (!empty($_GET[$k])) {
989 * Deprecated function to upload media.
991 * @param string $type Return type (atom, rss, xml, json)
993 * @return array|string
994 * @throws BadRequestException
995 * @throws ForbiddenException
996 * @throws ImagickException
997 * @throws InternalServerErrorException
998 * @throws UnauthorizedException
1000 function api_statuses_mediap($type)
1004 if (api_user() === false) {
1005 logger::notice('api_statuses_update: no user');
1006 throw new ForbiddenException();
1008 $user_info = api_get_user($a);
1010 $_REQUEST['profile_uid'] = api_user();
1011 $_REQUEST['api_source'] = true;
1012 $txt = requestdata('status') ?? '';
1013 /// @TODO old-lost code?
1014 //$txt = urldecode(requestdata('status'));
1016 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1017 $txt = HTML::toBBCodeVideo($txt);
1018 $config = HTMLPurifier_Config::createDefault();
1019 $config->set('Cache.DefinitionImpl', null);
1020 $purifier = new HTMLPurifier($config);
1021 $txt = $purifier->purify($txt);
1023 $txt = HTML::toBBCode($txt);
1025 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
1027 $picture = wall_upload_post($a, false);
1029 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
1030 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
1031 $item_id = item_post($a);
1033 // output the post that we just posted.
1034 return api_status_show($type, $item_id);
1037 /// @TODO move this to top of file or somewhere better!
1038 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
1041 * Updates the user’s current status.
1043 * @param string $type Return type (atom, rss, xml, json)
1045 * @return array|string
1046 * @throws BadRequestException
1047 * @throws ForbiddenException
1048 * @throws ImagickException
1049 * @throws InternalServerErrorException
1050 * @throws TooManyRequestsException
1051 * @throws UnauthorizedException
1052 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1054 function api_statuses_update($type)
1058 if (api_user() === false) {
1059 logger::notice('api_statuses_update: no user');
1060 throw new ForbiddenException();
1065 // convert $_POST array items to the form we use for web posts.
1066 if (requestdata('htmlstatus')) {
1067 $txt = requestdata('htmlstatus') ?? '';
1068 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
1069 $txt = HTML::toBBCodeVideo($txt);
1071 $config = HTMLPurifier_Config::createDefault();
1072 $config->set('Cache.DefinitionImpl', null);
1074 $purifier = new HTMLPurifier($config);
1075 $txt = $purifier->purify($txt);
1077 $_REQUEST['body'] = HTML::toBBCode($txt);
1080 $_REQUEST['body'] = requestdata('status');
1083 $_REQUEST['title'] = requestdata('title');
1085 $parent = requestdata('in_reply_to_status_id');
1087 // Twidere sends "-1" if it is no reply ...
1088 if ($parent == -1) {
1092 if (ctype_digit($parent)) {
1093 $_REQUEST['parent'] = $parent;
1095 $_REQUEST['parent_uri'] = $parent;
1098 if (requestdata('lat') && requestdata('long')) {
1099 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
1101 $_REQUEST['profile_uid'] = api_user();
1104 // Check for throttling (maximum posts per day, week and month)
1105 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
1106 if ($throttle_day > 0) {
1107 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
1109 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1110 $posts_day = Post::count($condition);
1112 if ($posts_day > $throttle_day) {
1113 logger::info('Daily posting limit reached for user '.api_user());
1114 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
1115 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));
1119 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
1120 if ($throttle_week > 0) {
1121 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
1123 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1124 $posts_week = Post::count($condition);
1126 if ($posts_week > $throttle_week) {
1127 logger::info('Weekly posting limit reached for user '.api_user());
1128 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
1129 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));
1133 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
1134 if ($throttle_month > 0) {
1135 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
1137 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
1138 $posts_month = Post::count($condition);
1140 if ($posts_month > $throttle_month) {
1141 logger::info('Monthly posting limit reached for user '.api_user());
1142 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
1143 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));
1148 if (requestdata('media_ids')) {
1149 $ids = explode(',', requestdata('media_ids') ?? '');
1150 } elseif (!empty($_FILES['media'])) {
1151 // upload the image if we have one
1152 $picture = wall_upload_post($a, false);
1153 if (is_array($picture)) {
1154 $ids[] = $picture['id'];
1162 foreach ($ids as $id) {
1163 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
1164 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
1165 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
1166 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
1168 if (!empty($media)) {
1169 $ressources[] = $media[0]['resource-id'];
1170 $phototypes = Images::supportedTypes();
1171 $ext = $phototypes[$media[0]['type']];
1173 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
1174 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
1175 'size' => $media[0]['datasize'],
1176 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
1177 'description' => $media[0]['desc'] ?? '',
1178 'width' => $media[0]['width'],
1179 'height' => $media[0]['height']];
1181 if (count($media) > 1) {
1182 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
1183 $attachment['preview-width'] = $media[1]['width'];
1184 $attachment['preview-height'] = $media[1]['height'];
1186 $attachments[] = $attachment;
1190 // We have to avoid that the post is rejected because of an empty body
1191 if (empty($_REQUEST['body'])) {
1192 $_REQUEST['body'] = '[hr]';
1196 if (!empty($attachments)) {
1197 $_REQUEST['attachments'] = $attachments;
1200 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1202 $_REQUEST['api_source'] = true;
1204 if (empty($_REQUEST['source'])) {
1205 $_REQUEST["source"] = api_source();
1208 // call out normal post function
1209 $item_id = item_post($a);
1211 if (!empty($ressources) && !empty($item_id)) {
1212 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
1213 foreach ($ressources as $ressource) {
1214 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
1218 // output the post that we just posted.
1219 return api_status_show($type, $item_id);
1222 /// @TODO move to top of file or somewhere better
1223 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
1224 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
1227 * Uploads an image to Friendica.
1230 * @throws BadRequestException
1231 * @throws ForbiddenException
1232 * @throws ImagickException
1233 * @throws InternalServerErrorException
1234 * @throws UnauthorizedException
1235 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
1237 function api_media_upload()
1241 if (api_user() === false) {
1242 logger::notice('no user');
1243 throw new ForbiddenException();
1248 if (empty($_FILES['media'])) {
1250 throw new BadRequestException("No media.");
1253 $media = wall_upload_post($a, false);
1256 throw new InternalServerErrorException();
1260 $returndata["media_id"] = $media["id"];
1261 $returndata["media_id_string"] = (string)$media["id"];
1262 $returndata["size"] = $media["size"];
1263 $returndata["image"] = ["w" => $media["width"],
1264 "h" => $media["height"],
1265 "image_type" => $media["type"],
1266 "friendica_preview_url" => $media["preview"]];
1268 Logger::info('Media uploaded', ['return' => $returndata]);
1270 return ["media" => $returndata];
1273 /// @TODO move to top of file or somewhere better
1274 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1277 * Updates media meta data (picture descriptions)
1279 * @param string $type Return type (atom, rss, xml, json)
1281 * @return array|string
1282 * @throws BadRequestException
1283 * @throws ForbiddenException
1284 * @throws ImagickException
1285 * @throws InternalServerErrorException
1286 * @throws TooManyRequestsException
1287 * @throws UnauthorizedException
1288 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1290 * @todo Compare the corresponding Twitter function for correct return values
1292 function api_media_metadata_create($type)
1296 if (api_user() === false) {
1297 Logger::info('no user');
1298 throw new ForbiddenException();
1303 $postdata = Network::postdata();
1305 if (empty($postdata)) {
1306 throw new BadRequestException("No post data");
1309 $data = json_decode($postdata, true);
1311 throw new BadRequestException("Invalid post data");
1314 if (empty($data['media_id']) || empty($data['alt_text'])) {
1315 throw new BadRequestException("Missing post data values");
1318 if (empty($data['alt_text']['text'])) {
1319 throw new BadRequestException("No alt text.");
1322 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1324 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1325 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1326 if (!DBA::isResult($photo)) {
1327 throw new BadRequestException("Metadata not found.");
1330 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1333 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1336 * @param string $type Return format (atom, rss, xml, json)
1337 * @param int $item_id
1338 * @return array|string
1341 function api_status_show($type, $item_id)
1343 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1347 $item = api_get_item(['id' => $item_id]);
1348 if (!empty($item)) {
1349 $status_info = api_format_item($item, $type);
1352 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1354 return api_format_data('statuses', $type, ['status' => $status_info]);
1358 * Retrieves the last public status of the provided user info
1360 * @param int $ownerId Public contact Id
1361 * @param int $uid User Id
1365 function api_get_last_status($ownerId, $uid)
1368 'author-id'=> $ownerId,
1370 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1371 'private' => [Item::PUBLIC, Item::UNLISTED]
1374 $item = api_get_item($condition);
1380 * Retrieves a single item record based on the provided condition and converts it for API use.
1382 * @param array $condition Item table condition array
1386 function api_get_item(array $condition)
1388 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1394 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1395 * The author's most recent status will be returned inline.
1397 * @param string $type Return type (atom, rss, xml, json)
1398 * @return array|string
1399 * @throws BadRequestException
1400 * @throws ImagickException
1401 * @throws InternalServerErrorException
1402 * @throws UnauthorizedException
1403 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1405 function api_users_show($type)
1407 $a = Friendica\DI::app();
1409 $user_info = api_get_user($a);
1411 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1412 if (!empty($item)) {
1413 $user_info['status'] = api_format_item($item, $type);
1416 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1417 unset($user_info['uid']);
1418 unset($user_info['self']);
1420 return api_format_data('user', $type, ['user' => $user_info]);
1423 /// @TODO move to top of file or somewhere better
1424 api_register_func('api/users/show', 'api_users_show');
1425 api_register_func('api/externalprofile/show', 'api_users_show');
1428 * Search a public user account.
1430 * @param string $type Return type (atom, rss, xml, json)
1432 * @return array|string
1433 * @throws BadRequestException
1434 * @throws ImagickException
1435 * @throws InternalServerErrorException
1436 * @throws UnauthorizedException
1437 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1439 function api_users_search($type)
1445 if (!empty($_GET['q'])) {
1446 $contacts = Contact::selectToArray(
1449 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1457 if (DBA::isResult($contacts)) {
1459 foreach ($contacts as $contact) {
1460 $user_info = api_get_user($a, $contact['id']);
1462 if ($type == 'xml') {
1463 $userlist[$k++ . ':user'] = $user_info;
1465 $userlist[] = $user_info;
1468 $userlist = ['users' => $userlist];
1470 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1473 throw new BadRequestException('No search term specified.');
1476 return api_format_data('users', $type, $userlist);
1479 /// @TODO move to top of file or somewhere better
1480 api_register_func('api/users/search', 'api_users_search');
1483 * Return user objects
1485 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1487 * @param string $type Return format: json or xml
1489 * @return array|string
1490 * @throws BadRequestException
1491 * @throws ImagickException
1492 * @throws InternalServerErrorException
1493 * @throws NotFoundException if the results are empty.
1494 * @throws UnauthorizedException
1496 function api_users_lookup($type)
1500 if (!empty($_REQUEST['user_id'])) {
1501 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1503 $users[] = api_get_user(DI::app(), $id);
1508 if (empty($users)) {
1509 throw new NotFoundException;
1512 return api_format_data("users", $type, ['users' => $users]);
1515 /// @TODO move to top of file or somewhere better
1516 api_register_func('api/users/lookup', 'api_users_lookup', true);
1519 * Returns statuses that match a specified query.
1521 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1523 * @param string $type Return format: json, xml, atom, rss
1525 * @return array|string
1526 * @throws BadRequestException if the "q" parameter is missing.
1527 * @throws ForbiddenException
1528 * @throws ImagickException
1529 * @throws InternalServerErrorException
1530 * @throws UnauthorizedException
1532 function api_search($type)
1535 $user_info = api_get_user($a);
1537 if (api_user() === false || $user_info === false) {
1538 throw new ForbiddenException();
1541 if (empty($_REQUEST['q'])) {
1542 throw new BadRequestException('q parameter is required.');
1545 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1548 $data['status'] = [];
1550 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1551 if (!empty($_REQUEST['rpp'])) {
1552 $count = $_REQUEST['rpp'];
1553 } elseif (!empty($_REQUEST['count'])) {
1554 $count = $_REQUEST['count'];
1557 $since_id = $_REQUEST['since_id'] ?? 0;
1558 $max_id = $_REQUEST['max_id'] ?? 0;
1559 $page = $_REQUEST['page'] ?? 1;
1561 $start = max(0, ($page - 1) * $count);
1563 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1564 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1565 $searchTerm = $matches[1];
1566 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1567 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1569 while ($tag = DBA::fetch($tags)) {
1570 $uriids[] = $tag['uri-id'];
1574 if (empty($uriids)) {
1575 return api_format_data('statuses', $type, $data);
1578 $condition = ['uri-id' => $uriids];
1579 if ($exclude_replies) {
1580 $condition['gravity'] = GRAVITY_PARENT;
1583 $params['group_by'] = ['uri-id'];
1585 $condition = ["`id` > ?
1586 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1587 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1588 AND `body` LIKE CONCAT('%',?,'%')",
1589 $since_id, api_user(), $_REQUEST['q']];
1591 $condition[0] .= ' AND `id` <= ?';
1592 $condition[] = $max_id;
1598 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1599 $id = Item::fetchByLink($searchTerm, api_user());
1602 $id = Item::fetchByLink($searchTerm);
1606 $statuses = Post::select([], ['id' => $id]);
1610 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1612 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1614 bindComments($data['status']);
1616 return api_format_data('statuses', $type, $data);
1619 /// @TODO move to top of file or somewhere better
1620 api_register_func('api/search/tweets', 'api_search', true);
1621 api_register_func('api/search', 'api_search', true);
1624 * Returns the most recent statuses posted by the user and the users they follow.
1626 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1628 * @param string $type Return type (atom, rss, xml, json)
1630 * @return array|string
1631 * @throws BadRequestException
1632 * @throws ForbiddenException
1633 * @throws ImagickException
1634 * @throws InternalServerErrorException
1635 * @throws UnauthorizedException
1636 * @todo Optional parameters
1637 * @todo Add reply info
1639 function api_statuses_home_timeline($type)
1642 $user_info = api_get_user($a);
1644 if (api_user() === false || $user_info === false) {
1645 throw new ForbiddenException();
1648 unset($_REQUEST["user_id"]);
1649 unset($_GET["user_id"]);
1651 unset($_REQUEST["screen_name"]);
1652 unset($_GET["screen_name"]);
1654 // get last network messages
1657 $count = $_REQUEST['count'] ?? 20;
1658 $page = $_REQUEST['page']?? 0;
1659 $since_id = $_REQUEST['since_id'] ?? 0;
1660 $max_id = $_REQUEST['max_id'] ?? 0;
1661 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1662 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1664 $start = max(0, ($page - 1) * $count);
1666 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1667 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1670 $condition[0] .= " AND `id` <= ?";
1671 $condition[] = $max_id;
1673 if ($exclude_replies) {
1674 $condition[0] .= ' AND `gravity` = ?';
1675 $condition[] = GRAVITY_PARENT;
1677 if ($conversation_id > 0) {
1678 $condition[0] .= " AND `parent` = ?";
1679 $condition[] = $conversation_id;
1682 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1683 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1685 $items = Post::toArray($statuses);
1687 $ret = api_format_items($items, $user_info, false, $type);
1689 // Set all posts from the query above to seen
1691 foreach ($items as $item) {
1692 $idarray[] = intval($item["id"]);
1695 if (!empty($idarray)) {
1696 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1698 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1704 $data = ['status' => $ret];
1709 $data = api_rss_extra($a, $data, $user_info);
1713 return api_format_data("statuses", $type, $data);
1717 /// @TODO move to top of file or somewhere better
1718 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1719 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1722 * Returns the most recent statuses from public users.
1724 * @param string $type Return type (atom, rss, xml, json)
1726 * @return array|string
1727 * @throws BadRequestException
1728 * @throws ForbiddenException
1729 * @throws ImagickException
1730 * @throws InternalServerErrorException
1731 * @throws UnauthorizedException
1733 function api_statuses_public_timeline($type)
1736 $user_info = api_get_user($a);
1738 if (api_user() === false || $user_info === false) {
1739 throw new ForbiddenException();
1742 // get last network messages
1745 $count = $_REQUEST['count'] ?? 20;
1746 $page = $_REQUEST['page'] ?? 1;
1747 $since_id = $_REQUEST['since_id'] ?? 0;
1748 $max_id = $_REQUEST['max_id'] ?? 0;
1749 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1750 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1752 $start = max(0, ($page - 1) * $count);
1754 if ($exclude_replies && !$conversation_id) {
1755 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1756 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1759 $condition[0] .= " AND `id` <= ?";
1760 $condition[] = $max_id;
1763 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1764 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1766 $r = Post::toArray($statuses);
1768 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1769 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1772 $condition[0] .= " AND `id` <= ?";
1773 $condition[] = $max_id;
1775 if ($conversation_id > 0) {
1776 $condition[0] .= " AND `parent` = ?";
1777 $condition[] = $conversation_id;
1780 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1781 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1783 $r = Post::toArray($statuses);
1786 $ret = api_format_items($r, $user_info, false, $type);
1790 $data = ['status' => $ret];
1795 $data = api_rss_extra($a, $data, $user_info);
1799 return api_format_data("statuses", $type, $data);
1802 /// @TODO move to top of file or somewhere better
1803 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1806 * Returns the most recent statuses posted by users this node knows about.
1808 * @param string $type Return format: json, xml, atom, rss
1809 * @return array|string
1810 * @throws BadRequestException
1811 * @throws ForbiddenException
1812 * @throws ImagickException
1813 * @throws InternalServerErrorException
1814 * @throws UnauthorizedException
1816 function api_statuses_networkpublic_timeline($type)
1819 $user_info = api_get_user($a);
1821 if (api_user() === false || $user_info === false) {
1822 throw new ForbiddenException();
1825 $since_id = $_REQUEST['since_id'] ?? 0;
1826 $max_id = $_REQUEST['max_id'] ?? 0;
1829 $count = $_REQUEST['count'] ?? 20;
1830 $page = $_REQUEST['page'] ?? 1;
1832 $start = max(0, ($page - 1) * $count);
1834 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1835 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1838 $condition[0] .= " AND `id` <= ?";
1839 $condition[] = $max_id;
1842 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1843 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1845 $ret = api_format_items($statuses, $user_info, false, $type);
1849 $data = ['status' => $ret];
1854 $data = api_rss_extra($a, $data, $user_info);
1858 return api_format_data("statuses", $type, $data);
1861 /// @TODO move to top of file or somewhere better
1862 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1865 * Returns a single status.
1867 * @param string $type Return type (atom, rss, xml, json)
1869 * @return array|string
1870 * @throws BadRequestException
1871 * @throws ForbiddenException
1872 * @throws ImagickException
1873 * @throws InternalServerErrorException
1874 * @throws UnauthorizedException
1875 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1877 function api_statuses_show($type)
1880 $user_info = api_get_user($a);
1882 if (api_user() === false || $user_info === false) {
1883 throw new ForbiddenException();
1887 $id = intval(DI::args()->getArgv()[3] ?? 0);
1890 $id = intval($_REQUEST['id'] ?? 0);
1895 $id = intval(DI::args()->getArgv()[4] ?? 0);
1898 logger::notice('API: api_statuses_show: ' . $id);
1900 $conversation = !empty($_REQUEST['conversation']);
1902 // try to fetch the item for the local user - or the public item, if there is no local one
1903 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1904 if (!DBA::isResult($uri_item)) {
1905 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1908 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1909 if (!DBA::isResult($item)) {
1910 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1915 if ($conversation) {
1916 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1917 $params = ['order' => ['id' => true]];
1919 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1923 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1925 /// @TODO How about copying this to above methods which don't check $r ?
1926 if (!DBA::isResult($statuses)) {
1927 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1930 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1932 if ($conversation) {
1933 $data = ['status' => $ret];
1934 return api_format_data("statuses", $type, $data);
1936 $data = ['status' => $ret[0]];
1937 return api_format_data("status", $type, $data);
1941 /// @TODO move to top of file or somewhere better
1942 api_register_func('api/statuses/show', 'api_statuses_show', true);
1946 * @param string $type Return type (atom, rss, xml, json)
1948 * @return array|string
1949 * @throws BadRequestException
1950 * @throws ForbiddenException
1951 * @throws ImagickException
1952 * @throws InternalServerErrorException
1953 * @throws UnauthorizedException
1954 * @todo nothing to say?
1956 function api_conversation_show($type)
1959 $user_info = api_get_user($a);
1961 if (api_user() === false || $user_info === false) {
1962 throw new ForbiddenException();
1966 $id = intval(DI::args()->getArgv()[3] ?? 0);
1967 $since_id = intval($_REQUEST['since_id'] ?? 0);
1968 $max_id = intval($_REQUEST['max_id'] ?? 0);
1969 $count = intval($_REQUEST['count'] ?? 20);
1970 $page = intval($_REQUEST['page'] ?? 1);
1972 $start = max(0, ($page - 1) * $count);
1975 $id = intval($_REQUEST['id'] ?? 0);
1980 $id = intval(DI::args()->getArgv()[4] ?? 0);
1983 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1985 // try to fetch the item for the local user - or the public item, if there is no local one
1986 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1987 if (!DBA::isResult($item)) {
1988 throw new BadRequestException("There is no status with this id.");
1991 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1992 if (!DBA::isResult($parent)) {
1993 throw new BadRequestException("There is no status with this id.");
1996 $id = $parent['id'];
1998 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1999 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2002 $condition[0] .= " AND `id` <= ?";
2003 $condition[] = $max_id;
2006 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2007 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2009 if (!DBA::isResult($statuses)) {
2010 throw new BadRequestException("There is no status with id $id.");
2013 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2015 $data = ['status' => $ret];
2016 return api_format_data("statuses", $type, $data);
2019 /// @TODO move to top of file or somewhere better
2020 api_register_func('api/conversation/show', 'api_conversation_show', true);
2021 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
2026 * @param string $type Return type (atom, rss, xml, json)
2028 * @return array|string
2029 * @throws BadRequestException
2030 * @throws ForbiddenException
2031 * @throws ImagickException
2032 * @throws InternalServerErrorException
2033 * @throws UnauthorizedException
2034 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
2036 function api_statuses_repeat($type)
2042 if (api_user() === false) {
2043 throw new ForbiddenException();
2049 $id = intval(DI::args()->getArgv()[3] ?? 0);
2052 $id = intval($_REQUEST['id'] ?? 0);
2057 $id = intval(DI::args()->getArgv()[4] ?? 0);
2060 logger::notice('API: api_statuses_repeat: ' . $id);
2062 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
2063 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
2065 if (DBA::isResult($item) && !empty($item['body'])) {
2066 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
2067 if (!Item::performActivity($id, 'announce', local_user())) {
2068 throw new InternalServerErrorException();
2073 if (strpos($item['body'], "[/share]") !== false) {
2074 $pos = strpos($item['body'], "[share");
2075 $post = substr($item['body'], $pos);
2077 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
2079 if (!empty($item['title'])) {
2080 $post .= '[h3]' . $item['title'] . "[/h3]\n";
2083 $post .= $item['body'];
2084 $post .= "[/share]";
2086 $_REQUEST['body'] = $post;
2087 $_REQUEST['profile_uid'] = api_user();
2088 $_REQUEST['api_source'] = true;
2090 if (empty($_REQUEST['source'])) {
2091 $_REQUEST["source"] = api_source();
2094 $item_id = item_post($a);
2097 throw new ForbiddenException();
2100 // output the post that we just posted.
2102 return api_status_show($type, $item_id);
2105 /// @TODO move to top of file or somewhere better
2106 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
2109 * Destroys a specific status.
2111 * @param string $type Return type (atom, rss, xml, json)
2113 * @return array|string
2114 * @throws BadRequestException
2115 * @throws ForbiddenException
2116 * @throws ImagickException
2117 * @throws InternalServerErrorException
2118 * @throws UnauthorizedException
2119 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
2121 function api_statuses_destroy($type)
2125 if (api_user() === false) {
2126 throw new ForbiddenException();
2132 $id = intval(DI::args()->getArgv()[3] ?? 0);
2135 $id = intval($_REQUEST['id'] ?? 0);
2140 $id = intval(DI::args()->getArgv()[4] ?? 0);
2143 logger::notice('API: api_statuses_destroy: ' . $id);
2145 $ret = api_statuses_show($type);
2147 Item::deleteForUser(['id' => $id], api_user());
2152 /// @TODO move to top of file or somewhere better
2153 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
2156 * Returns the most recent mentions.
2158 * @param string $type Return type (atom, rss, xml, json)
2160 * @return array|string
2161 * @throws BadRequestException
2162 * @throws ForbiddenException
2163 * @throws ImagickException
2164 * @throws InternalServerErrorException
2165 * @throws UnauthorizedException
2166 * @see http://developer.twitter.com/doc/get/statuses/mentions
2168 function api_statuses_mentions($type)
2171 $user_info = api_get_user($a);
2173 if (api_user() === false || $user_info === false) {
2174 throw new ForbiddenException();
2177 unset($_REQUEST["user_id"]);
2178 unset($_GET["user_id"]);
2180 unset($_REQUEST["screen_name"]);
2181 unset($_GET["screen_name"]);
2183 // get last network messages
2186 $since_id = intval($_REQUEST['since_id'] ?? 0);
2187 $max_id = intval($_REQUEST['max_id'] ?? 0);
2188 $count = intval($_REQUEST['count'] ?? 20);
2189 $page = intval($_REQUEST['page'] ?? 1);
2191 $start = max(0, ($page - 1) * $count);
2193 $query = "`gravity` IN (?, ?) AND `uri-id` IN
2194 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
2195 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
2198 GRAVITY_PARENT, GRAVITY_COMMENT,
2200 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
2201 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
2202 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
2203 api_user(), $since_id,
2207 $query .= " AND `id` <= ?";
2208 $condition[] = $max_id;
2211 array_unshift($condition, $query);
2213 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2214 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2216 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2218 $data = ['status' => $ret];
2223 $data = api_rss_extra($a, $data, $user_info);
2227 return api_format_data("statuses", $type, $data);
2230 /// @TODO move to top of file or somewhere better
2231 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
2232 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
2235 * Returns the most recent statuses posted by the user.
2237 * @param string $type Either "json" or "xml"
2238 * @return string|array
2239 * @throws BadRequestException
2240 * @throws ForbiddenException
2241 * @throws ImagickException
2242 * @throws InternalServerErrorException
2243 * @throws UnauthorizedException
2244 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
2246 function api_statuses_user_timeline($type)
2249 $user_info = api_get_user($a);
2251 if (api_user() === false || $user_info === false) {
2252 throw new ForbiddenException();
2255 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2257 $since_id = $_REQUEST['since_id'] ?? 0;
2258 $max_id = $_REQUEST['max_id'] ?? 0;
2259 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2260 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2263 $count = $_REQUEST['count'] ?? 20;
2264 $page = $_REQUEST['page'] ?? 1;
2266 $start = max(0, ($page - 1) * $count);
2268 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2269 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2271 if ($user_info['self'] == 1) {
2272 $condition[0] .= ' AND `wall` ';
2275 if ($exclude_replies) {
2276 $condition[0] .= ' AND `gravity` = ?';
2277 $condition[] = GRAVITY_PARENT;
2280 if ($conversation_id > 0) {
2281 $condition[0] .= " AND `parent` = ?";
2282 $condition[] = $conversation_id;
2286 $condition[0] .= " AND `id` <= ?";
2287 $condition[] = $max_id;
2289 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2290 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2292 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2296 $data = ['status' => $ret];
2301 $data = api_rss_extra($a, $data, $user_info);
2305 return api_format_data("statuses", $type, $data);
2308 /// @TODO move to top of file or somewhere better
2309 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2312 * Star/unstar an item.
2313 * param: id : id of the item
2315 * @param string $type Return type (atom, rss, xml, json)
2317 * @return array|string
2318 * @throws BadRequestException
2319 * @throws ForbiddenException
2320 * @throws ImagickException
2321 * @throws InternalServerErrorException
2322 * @throws UnauthorizedException
2323 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2325 function api_favorites_create_destroy($type)
2329 if (api_user() === false) {
2330 throw new ForbiddenException();
2333 // for versioned api.
2334 /// @TODO We need a better global soluton
2335 $action_argv_id = 2;
2336 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2337 $action_argv_id = 3;
2340 if (DI::args()->getArgc() <= $action_argv_id) {
2341 throw new BadRequestException("Invalid request.");
2343 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2344 if (DI::args()->getArgc() == $action_argv_id + 2) {
2345 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2347 $itemid = intval($_REQUEST['id'] ?? 0);
2350 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2352 if (!DBA::isResult($item)) {
2353 throw new BadRequestException("Invalid item.");
2358 $item['starred'] = 1;
2361 $item['starred'] = 0;
2364 throw new BadRequestException("Invalid action ".$action);
2367 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2370 throw new InternalServerErrorException("DB error");
2374 $user_info = api_get_user($a);
2375 $rets = api_format_items([$item], $user_info, false, $type);
2378 $data = ['status' => $ret];
2383 $data = api_rss_extra($a, $data, $user_info);
2387 return api_format_data("status", $type, $data);
2390 /// @TODO move to top of file or somewhere better
2391 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2392 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2395 * Returns the most recent favorite statuses.
2397 * @param string $type Return type (atom, rss, xml, json)
2399 * @return string|array
2400 * @throws BadRequestException
2401 * @throws ForbiddenException
2402 * @throws ImagickException
2403 * @throws InternalServerErrorException
2404 * @throws UnauthorizedException
2406 function api_favorites($type)
2411 $user_info = api_get_user($a);
2413 if (api_user() === false || $user_info === false) {
2414 throw new ForbiddenException();
2419 // in friendica starred item are private
2420 // return favorites only for self
2421 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2423 if ($user_info['self'] == 0) {
2427 $since_id = $_REQUEST['since_id'] ?? 0;
2428 $max_id = $_REQUEST['max_id'] ?? 0;
2429 $count = $_GET['count'] ?? 20;
2430 $page = $_REQUEST['page'] ?? 1;
2432 $start = max(0, ($page - 1) * $count);
2434 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2435 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2437 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2440 $condition[0] .= " AND `id` <= ?";
2441 $condition[] = $max_id;
2444 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2446 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2451 $data = ['status' => $ret];
2456 $data = api_rss_extra($a, $data, $user_info);
2460 return api_format_data("statuses", $type, $data);
2463 /// @TODO move to top of file or somewhere better
2464 api_register_func('api/favorites', 'api_favorites', true);
2468 * @param array $item
2469 * @param array $recipient
2470 * @param array $sender
2473 * @throws InternalServerErrorException
2475 function api_format_messages($item, $recipient, $sender)
2477 // standard meta information
2479 'id' => $item['id'],
2480 'sender_id' => $sender['id'],
2482 'recipient_id' => $recipient['id'],
2483 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2484 'sender_screen_name' => $sender['screen_name'],
2485 'recipient_screen_name' => $recipient['screen_name'],
2486 'sender' => $sender,
2487 'recipient' => $recipient,
2489 'friendica_seen' => $item['seen'] ?? 0,
2490 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2493 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2494 if (isset($ret['sender']['uid'])) {
2495 unset($ret['sender']['uid']);
2497 if (isset($ret['sender']['self'])) {
2498 unset($ret['sender']['self']);
2500 if (isset($ret['recipient']['uid'])) {
2501 unset($ret['recipient']['uid']);
2503 if (isset($ret['recipient']['self'])) {
2504 unset($ret['recipient']['self']);
2507 //don't send title to regular StatusNET requests to avoid confusing these apps
2508 if (!empty($_GET['getText'])) {
2509 $ret['title'] = $item['title'];
2510 if ($_GET['getText'] == 'html') {
2511 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2512 } elseif ($_GET['getText'] == 'plain') {
2513 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2516 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2518 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2519 unset($ret['sender']);
2520 unset($ret['recipient']);
2528 * @param array $item
2531 * @throws InternalServerErrorException
2533 function api_convert_item($item)
2535 $body = api_add_attachments_to_body($item);
2537 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2539 // Add pictures to the attachment array and remove them from the body
2540 $attachments = api_get_attachments($body, $item['uri-id']);
2542 // Workaround for ostatus messages where the title is identically to the body
2543 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2544 $statusbody = trim(HTML::toPlaintext($html, 0));
2546 // handle data: images
2547 $statusbody = api_format_items_embeded_images($item, $statusbody);
2549 $statustitle = trim($item['title']);
2551 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2552 $statustext = trim($statusbody);
2554 $statustext = trim($statustitle."\n\n".$statusbody);
2557 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2558 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2561 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2563 // Workaround for clients with limited HTML parser functionality
2564 $search = ["<br>", "<blockquote>", "</blockquote>",
2565 "<h1>", "</h1>", "<h2>", "</h2>",
2566 "<h3>", "</h3>", "<h4>", "</h4>",
2567 "<h5>", "</h5>", "<h6>", "</h6>"];
2568 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2569 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2570 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2571 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2572 $statushtml = str_replace($search, $replace, $statushtml);
2574 if ($item['title'] != "") {
2575 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2579 $oldtext = $statushtml;
2580 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2581 } while ($oldtext != $statushtml);
2583 if (substr($statushtml, 0, 4) == '<br>') {
2584 $statushtml = substr($statushtml, 4);
2587 if (substr($statushtml, 0, -4) == '<br>') {
2588 $statushtml = substr($statushtml, -4);
2591 // feeds without body should contain the link
2592 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2593 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2597 "text" => $statustext,
2598 "html" => $statushtml,
2599 "attachments" => $attachments,
2600 "entities" => $entities
2605 * Add media attachments to the body
2607 * @param array $item
2608 * @return string body with added media
2610 function api_add_attachments_to_body(array $item)
2612 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2614 if (strpos($body, '[/img]') !== false) {
2618 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2619 if (!empty($media['preview'])) {
2620 $description = $media['description'] ?: $media['name'];
2621 if (!empty($description)) {
2622 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2624 $body .= "\n[img]" . $media['preview'] .'[/img]';
2634 * @param string $body
2638 * @throws InternalServerErrorException
2640 function api_get_attachments(&$body, $uriid)
2642 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2643 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2645 $URLSearchString = "^\[\]";
2646 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2650 // Remove all embedded pictures, since they are added as attachments
2651 foreach ($images[0] as $orig) {
2652 $body = str_replace($orig, '', $body);
2657 foreach ($images[1] as $image) {
2658 $imagedata = Images::getInfoFromURLCached($image);
2661 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2665 return $attachments;
2670 * @param string $text
2671 * @param string $bbcode
2674 * @throws InternalServerErrorException
2675 * @todo Links at the first character of the post
2677 function api_get_entitities(&$text, $bbcode, $uriid)
2679 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2681 if ($include_entities != "true") {
2682 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2684 foreach ($images[1] as $image) {
2685 $replace = Post\Link::getByLink($uriid, $image);
2686 $text = str_replace($image, $replace, $text);
2691 $bbcode = BBCode::cleanPictureLinks($bbcode);
2693 // Change pure links in text to bbcode uris
2694 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2697 $entities["hashtags"] = [];
2698 $entities["symbols"] = [];
2699 $entities["urls"] = [];
2700 $entities["user_mentions"] = [];
2702 $URLSearchString = "^\[\]";
2704 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2706 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2707 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2709 $bbcode = preg_replace(
2710 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2711 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2714 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2716 $bbcode = preg_replace(
2717 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2718 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2721 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2723 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2725 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2728 foreach ($urls[1] as $id => $url) {
2729 $start = iconv_strpos($text, $url, 0, "UTF-8");
2730 if (!($start === false)) {
2731 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2735 ksort($ordered_urls);
2739 foreach ($ordered_urls as $url) {
2740 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2741 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2743 $display_url = $url["title"];
2745 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2746 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2748 if (strlen($display_url) > 26) {
2749 $display_url = substr($display_url, 0, 25)."…";
2753 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2754 if (!($start === false)) {
2755 $entities["urls"][] = ["url" => $url["url"],
2756 "expanded_url" => $url["url"],
2757 "display_url" => $display_url,
2758 "indices" => [$start, $start+strlen($url["url"])]];
2759 $offset = $start + 1;
2763 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2764 $ordered_images = [];
2765 foreach ($images as $image) {
2766 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2767 if (!($start === false)) {
2768 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2772 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2773 foreach ($images[1] as $image) {
2774 $start = iconv_strpos($text, $image, 0, "UTF-8");
2775 if (!($start === false)) {
2776 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2782 foreach ($ordered_images as $image) {
2783 $url = $image['url'];
2784 $ext_alt_text = $image['alt'];
2786 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2787 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2789 if (strlen($display_url) > 26) {
2790 $display_url = substr($display_url, 0, 25)."…";
2793 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2794 if (!($start === false)) {
2795 $image = Images::getInfoFromURLCached($url);
2797 $media_url = Post\Link::getByLink($uriid, $url);
2798 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2800 $entities["media"][] = [
2802 "id_str" => (string) ($start + 1),
2803 "indices" => [$start, $start+strlen($url)],
2804 "media_url" => Strings::normaliseLink($media_url),
2805 "media_url_https" => $media_url,
2807 "display_url" => $display_url,
2808 "expanded_url" => $url,
2809 "ext_alt_text" => $ext_alt_text,
2813 $offset = $start + 1;
2822 * @param array $item
2823 * @param string $text
2827 function api_format_items_embeded_images($item, $text)
2829 $text = preg_replace_callback(
2830 '|data:image/([^;]+)[^=]+=*|m',
2831 function () use ($item) {
2832 return DI::baseUrl() . '/display/' . $item['guid'];
2840 * return <a href='url'>name</a> as array
2842 * @param string $txt text
2847 function api_contactlink_to_array($txt)
2850 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2851 if ($r && count($match)==3) {
2853 'name' => $match[2],
2867 * return likes, dislikes and attend status for item
2869 * @param array $item array
2870 * @param string $type Return type (atom, rss, xml, json)
2873 * likes => int count,
2874 * dislikes => int count
2875 * @throws BadRequestException
2876 * @throws ImagickException
2877 * @throws InternalServerErrorException
2878 * @throws UnauthorizedException
2880 function api_format_items_activities($item, $type = "json")
2889 'attendmaybe' => [],
2893 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2894 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2896 while ($parent_item = Post::fetch($ret)) {
2897 // not used as result should be structured like other user data
2898 //builtin_activity_puller($i, $activities);
2900 // get user data and add it to the array of the activity
2901 $user = api_get_user($a, $parent_item['author-id']);
2902 switch ($parent_item['verb']) {
2903 case Activity::LIKE:
2904 $activities['like'][] = $user;
2906 case Activity::DISLIKE:
2907 $activities['dislike'][] = $user;
2909 case Activity::ATTEND:
2910 $activities['attendyes'][] = $user;
2912 case Activity::ATTENDNO:
2913 $activities['attendno'][] = $user;
2915 case Activity::ATTENDMAYBE:
2916 $activities['attendmaybe'][] = $user;
2918 case Activity::ANNOUNCE:
2919 $activities['announce'][] = $user;
2928 if ($type == "xml") {
2929 $xml_activities = [];
2930 foreach ($activities as $k => $v) {
2931 // change xml element from "like" to "friendica:like"
2932 $xml_activities["friendica:".$k] = $v;
2933 // add user data into xml output
2935 foreach ($v as $user) {
2936 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2939 $activities = $xml_activities;
2946 * format items to be returned by api
2948 * @param array $items array of items
2949 * @param array $user_info
2950 * @param bool $filter_user filter items by $user_info
2951 * @param string $type Return type (atom, rss, xml, json)
2953 * @throws BadRequestException
2954 * @throws ImagickException
2955 * @throws InternalServerErrorException
2956 * @throws UnauthorizedException
2958 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2960 $a = Friendica\DI::app();
2964 if (empty($items)) {
2968 foreach ((array)$items as $item) {
2969 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2971 // Look if the posts are matching if they should be filtered by user id
2972 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2976 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2985 * @param array $item Item record
2986 * @param string $type Return format (atom, rss, xml, json)
2987 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2988 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2989 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2990 * @return array API-formatted status
2991 * @throws BadRequestException
2992 * @throws ImagickException
2993 * @throws InternalServerErrorException
2994 * @throws UnauthorizedException
2996 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2998 $a = Friendica\DI::app();
3000 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
3001 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
3004 DI::contentItem()->localize($item);
3006 $in_reply_to = api_in_reply_to($item);
3008 $converted = api_convert_item($item);
3010 if ($type == "xml") {
3011 $geo = "georss:point";
3017 'text' => $converted["text"],
3018 'truncated' => false,
3019 'created_at'=> api_date($item['created']),
3020 'in_reply_to_status_id' => $in_reply_to['status_id'],
3021 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
3022 'source' => (($item['app']) ? $item['app'] : 'web'),
3023 'id' => intval($item['id']),
3024 'id_str' => (string) intval($item['id']),
3025 'in_reply_to_user_id' => $in_reply_to['user_id'],
3026 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
3027 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
3029 'favorited' => $item['starred'] ? true : false,
3030 'user' => $status_user,
3031 'friendica_author' => $author_user,
3032 'friendica_owner' => $owner_user,
3033 'friendica_private' => $item['private'] == Item::PRIVATE,
3034 //'entities' => NULL,
3035 'statusnet_html' => $converted["html"],
3036 'statusnet_conversation_id' => $item['parent'],
3037 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
3038 'friendica_activities' => api_format_items_activities($item, $type),
3039 'friendica_title' => $item['title'],
3040 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
3043 if (count($converted["attachments"]) > 0) {
3044 $status["attachments"] = $converted["attachments"];
3047 if (count($converted["entities"]) > 0) {
3048 $status["entities"] = $converted["entities"];
3051 if ($status["source"] == 'web') {
3052 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
3053 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
3054 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
3057 $retweeted_item = [];
3060 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
3061 $announce = api_get_announce($item);
3062 if (!empty($announce)) {
3063 $retweeted_item = $item;
3065 $status['friendica_owner'] = api_get_user($a, $announce['author-id']);
3069 if (!empty($quoted_item)) {
3070 if ($quoted_item['id'] != $item['id']) {
3071 $quoted_status = api_format_item($quoted_item);
3072 /// @todo Only remove the attachments that are also contained in the quotes status
3073 unset($status['attachments']);
3074 unset($status['entities']);
3076 $conv_quoted = api_convert_item($quoted_item);
3077 $quoted_status = $status;
3078 unset($quoted_status['attachments']);
3079 unset($quoted_status['entities']);
3080 unset($quoted_status['statusnet_conversation_id']);
3081 $quoted_status['text'] = $conv_quoted['text'];
3082 $quoted_status['statusnet_html'] = $conv_quoted['html'];
3084 $quoted_status["user"] = api_get_user($a, $quoted_item["author-id"]);
3085 } catch (BadRequestException $e) {
3086 // user not found. should be found?
3087 /// @todo check if the user should be always found
3088 $quoted_status["user"] = [];
3091 unset($quoted_status['friendica_author']);
3092 unset($quoted_status['friendica_owner']);
3093 unset($quoted_status['friendica_activities']);
3094 unset($quoted_status['friendica_private']);
3097 if (!empty($retweeted_item)) {
3098 $retweeted_status = $status;
3099 unset($retweeted_status['friendica_author']);
3100 unset($retweeted_status['friendica_owner']);
3101 unset($retweeted_status['friendica_activities']);
3102 unset($retweeted_status['friendica_private']);
3103 unset($retweeted_status['statusnet_conversation_id']);
3104 $status['user'] = $status['friendica_owner'];
3106 $retweeted_status["user"] = api_get_user($a, $retweeted_item["author-id"]);
3107 } catch (BadRequestException $e) {
3108 // user not found. should be found?
3109 /// @todo check if the user should be always found
3110 $retweeted_status["user"] = [];
3113 $rt_converted = api_convert_item($retweeted_item);
3115 $retweeted_status['text'] = $rt_converted["text"];
3116 $retweeted_status['statusnet_html'] = $rt_converted["html"];
3117 $retweeted_status['friendica_html'] = $rt_converted["html"];
3118 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
3120 if (!empty($quoted_status)) {
3121 $retweeted_status['quoted_status'] = $quoted_status;
3124 $status['friendica_author'] = $retweeted_status['user'];
3125 $status['retweeted_status'] = $retweeted_status;
3126 } elseif (!empty($quoted_status)) {
3127 $root_status = api_convert_item($item);
3129 $status['text'] = $root_status["text"];
3130 $status['statusnet_html'] = $root_status["html"];
3131 $status['quoted_status'] = $quoted_status;
3134 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3135 unset($status["user"]["uid"]);
3136 unset($status["user"]["self"]);
3138 if ($item["coord"] != "") {
3139 $coords = explode(' ', $item["coord"]);
3140 if (count($coords) == 2) {
3141 if ($type == "json") {
3142 $status["geo"] = ['type' => 'Point',
3143 'coordinates' => [(float) $coords[0],
3144 (float) $coords[1]]];
3145 } else {// Not sure if this is the official format - if someone founds a documentation we can check
3146 $status["georss:point"] = $item["coord"];
3155 * Returns the remaining number of API requests available to the user before the API limit is reached.
3157 * @param string $type Return type (atom, rss, xml, json)
3159 * @return array|string
3162 function api_account_rate_limit_status($type)
3164 if ($type == "xml") {
3166 'remaining-hits' => '150',
3167 '@attributes' => ["type" => "integer"],
3168 'hourly-limit' => '150',
3169 '@attributes2' => ["type" => "integer"],
3170 'reset-time' => DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM),
3171 '@attributes3' => ["type" => "datetime"],
3172 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3173 '@attributes4' => ["type" => "integer"],
3177 'reset_time_in_seconds' => strtotime('now + 1 hour'),
3178 'remaining_hits' => '150',
3179 'hourly_limit' => '150',
3180 'reset_time' => api_date(DateTimeFormat::utc('now + 1 hour', DateTimeFormat::ATOM)),
3184 return api_format_data('hash', $type, ['hash' => $hash]);
3187 /// @TODO move to top of file or somewhere better
3188 api_register_func('api/account/rate_limit_status', 'api_account_rate_limit_status', true);
3191 * Returns the string "ok" in the requested format with a 200 OK HTTP status code.
3193 * @param string $type Return type (atom, rss, xml, json)
3195 * @return array|string
3197 function api_help_test($type)
3199 if ($type == 'xml') {
3205 return api_format_data('ok', $type, ["ok" => $ok]);
3208 /// @TODO move to top of file or somewhere better
3209 api_register_func('api/help/test', 'api_help_test', false);
3212 * Returns all lists the user subscribes to.
3214 * @param string $type Return type (atom, rss, xml, json)
3216 * @return array|string
3217 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
3219 function api_lists_list($type)
3222 /// @TODO $ret is not filled here?
3223 return api_format_data('lists', $type, ["lists_list" => $ret]);
3226 /// @TODO move to top of file or somewhere better
3227 api_register_func('api/lists/list', 'api_lists_list', true);
3228 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
3231 * Returns all groups the user owns.
3233 * @param string $type Return type (atom, rss, xml, json)
3235 * @return array|string
3236 * @throws BadRequestException
3237 * @throws ForbiddenException
3238 * @throws ImagickException
3239 * @throws InternalServerErrorException
3240 * @throws UnauthorizedException
3241 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3243 function api_lists_ownerships($type)
3247 if (api_user() === false) {
3248 throw new ForbiddenException();
3252 $user_info = api_get_user($a);
3253 $uid = $user_info['uid'];
3255 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
3257 // loop through all groups
3259 foreach ($groups as $group) {
3260 if ($group['visible']) {
3266 'name' => $group['name'],
3267 'id' => intval($group['id']),
3268 'id_str' => (string) $group['id'],
3269 'user' => $user_info,
3273 return api_format_data("lists", $type, ['lists' => ['lists' => $lists]]);
3276 /// @TODO move to top of file or somewhere better
3277 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
3280 * Returns recent statuses from users in the specified group.
3282 * @param string $type Return type (atom, rss, xml, json)
3284 * @return array|string
3285 * @throws BadRequestException
3286 * @throws ForbiddenException
3287 * @throws ImagickException
3288 * @throws InternalServerErrorException
3289 * @throws UnauthorizedException
3290 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
3292 function api_lists_statuses($type)
3296 $user_info = api_get_user($a);
3297 if (api_user() === false || $user_info === false) {
3298 throw new ForbiddenException();
3301 unset($_REQUEST["user_id"]);
3302 unset($_GET["user_id"]);
3304 unset($_REQUEST["screen_name"]);
3305 unset($_GET["screen_name"]);
3307 if (empty($_REQUEST['list_id'])) {
3308 throw new BadRequestException('list_id not specified');
3312 $count = $_REQUEST['count'] ?? 20;
3313 $page = $_REQUEST['page'] ?? 1;
3314 $since_id = $_REQUEST['since_id'] ?? 0;
3315 $max_id = $_REQUEST['max_id'] ?? 0;
3316 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3317 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3319 $start = max(0, ($page - 1) * $count);
3321 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3322 $gids = array_column($groups, 'contact-id');
3323 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3324 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3327 $condition[0] .= " AND `id` <= ?";
3328 $condition[] = $max_id;
3330 if ($exclude_replies > 0) {
3331 $condition[0] .= ' AND `gravity` = ?';
3332 $condition[] = GRAVITY_PARENT;
3334 if ($conversation_id > 0) {
3335 $condition[0] .= " AND `parent` = ?";
3336 $condition[] = $conversation_id;
3339 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3340 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3342 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3344 $data = ['status' => $items];
3349 $data = api_rss_extra($a, $data, $user_info);
3353 return api_format_data("statuses", $type, $data);
3356 /// @TODO move to top of file or somewhere better
3357 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3360 * Returns either the friends of the follower list
3362 * Considers friends and followers lists to be private and won't return
3363 * anything if any user_id parameter is passed.
3365 * @param string $qtype Either "friends" or "followers"
3366 * @return boolean|array
3367 * @throws BadRequestException
3368 * @throws ForbiddenException
3369 * @throws ImagickException
3370 * @throws InternalServerErrorException
3371 * @throws UnauthorizedException
3373 function api_statuses_f($qtype)
3377 if (api_user() === false) {
3378 throw new ForbiddenException();
3382 $count = $_GET['count'] ?? 20;
3383 $page = $_GET['page'] ?? 1;
3385 $start = max(0, ($page - 1) * $count);
3387 $user_info = api_get_user($a);
3389 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3390 /* this is to stop Hotot to load friends multiple times
3391 * I'm not sure if I'm missing return something or
3392 * is a bug in hotot. Workaround, meantime
3396 return array('$users' => $ret);*/
3401 if ($qtype == 'friends') {
3402 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3403 } elseif ($qtype == 'followers') {
3404 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3407 // friends and followers only for self
3408 if ($user_info['self'] == 0) {
3409 $sql_extra = " AND false ";
3412 if ($qtype == 'blocks') {
3413 $sql_filter = 'AND `blocked` AND NOT `pending`';
3414 } elseif ($qtype == 'incoming') {
3415 $sql_filter = 'AND `pending`';
3417 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3420 // @todo This query most likely can be replaced with a Contact::select...
3421 $r = DBA::toArray(DBA::p(
3436 foreach ($r as $cid) {
3437 $user = api_get_user($a, $cid['nurl']);
3438 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3439 unset($user["uid"]);
3440 unset($user["self"]);
3447 return ['user' => $ret];
3452 * Returns the list of friends of the provided user
3454 * @deprecated By Twitter API in favor of friends/list
3456 * @param string $type Either "json" or "xml"
3457 * @return boolean|string|array
3458 * @throws BadRequestException
3459 * @throws ForbiddenException
3461 function api_statuses_friends($type)
3463 $data = api_statuses_f("friends");
3464 if ($data === false) {
3467 return api_format_data("users", $type, $data);
3471 * Returns the list of followers of the provided user
3473 * @deprecated By Twitter API in favor of friends/list
3475 * @param string $type Either "json" or "xml"
3476 * @return boolean|string|array
3477 * @throws BadRequestException
3478 * @throws ForbiddenException
3480 function api_statuses_followers($type)
3482 $data = api_statuses_f("followers");
3483 if ($data === false) {
3486 return api_format_data("users", $type, $data);
3489 /// @TODO move to top of file or somewhere better
3490 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3491 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3494 * Returns the list of blocked users
3496 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3498 * @param string $type Either "json" or "xml"
3500 * @return boolean|string|array
3501 * @throws BadRequestException
3502 * @throws ForbiddenException
3504 function api_blocks_list($type)
3506 $data = api_statuses_f('blocks');
3507 if ($data === false) {
3510 return api_format_data("users", $type, $data);
3513 /// @TODO move to top of file or somewhere better
3514 api_register_func('api/blocks/list', 'api_blocks_list', true);
3517 * Returns the list of pending users IDs
3519 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3521 * @param string $type Either "json" or "xml"
3523 * @return boolean|string|array
3524 * @throws BadRequestException
3525 * @throws ForbiddenException
3527 function api_friendships_incoming($type)
3529 $data = api_statuses_f('incoming');
3530 if ($data === false) {
3535 foreach ($data['user'] as $user) {
3536 $ids[] = $user['id'];
3539 return api_format_data("ids", $type, ['id' => $ids]);
3542 /// @TODO move to top of file or somewhere better
3543 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3546 * Returns the instance's configuration information.
3548 * @param string $type Return type (atom, rss, xml, json)
3550 * @return array|string
3551 * @throws InternalServerErrorException
3553 function api_statusnet_config($type)
3555 $name = DI::config()->get('config', 'sitename');
3556 $server = DI::baseUrl()->getHostname();
3557 $logo = DI::baseUrl() . '/images/friendica-64.png';
3558 $email = DI::config()->get('config', 'admin_email');
3559 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3560 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3561 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3562 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3563 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3566 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3567 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3568 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3569 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3570 'shorturllength' => '30',
3572 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3573 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3574 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3575 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3580 return api_format_data('config', $type, ['config' => $config]);
3583 /// @TODO move to top of file or somewhere better
3584 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3585 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3589 * @param string $type Return type (atom, rss, xml, json)
3591 * @return array|string
3593 function api_statusnet_version($type)
3596 $fake_statusnet_version = "0.9.7";
3598 return api_format_data('version', $type, ['version' => $fake_statusnet_version]);
3601 /// @TODO move to top of file or somewhere better
3602 api_register_func('api/gnusocial/version', 'api_statusnet_version', false);
3603 api_register_func('api/statusnet/version', 'api_statusnet_version', false);
3606 * Sends a new direct message.
3608 * @param string $type Return type (atom, rss, xml, json)
3610 * @return array|string
3611 * @throws BadRequestException
3612 * @throws ForbiddenException
3613 * @throws ImagickException
3614 * @throws InternalServerErrorException
3615 * @throws NotFoundException
3616 * @throws UnauthorizedException
3617 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3619 function api_direct_messages_new($type)
3623 if (api_user() === false) {
3624 throw new ForbiddenException();
3627 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3631 $sender = api_get_user($a);
3634 if (!empty($_POST['screen_name'])) {
3635 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3636 if (DBA::isResult($contacts)) {
3637 // Selecting the id by priority, friendica first
3638 api_best_nickname($contacts);
3640 $recipient = api_get_user($a, $contacts[0]['nurl']);
3643 $recipient = api_get_user($a, $_POST['user_id']);
3646 if (empty($recipient)) {
3647 throw new NotFoundException('Recipient not found');
3651 if (!empty($_REQUEST['replyto'])) {
3652 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3653 $replyto = $mail['parent-uri'];
3654 $sub = $mail['title'];
3656 if (!empty($_REQUEST['title'])) {
3657 $sub = $_REQUEST['title'];
3659 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3663 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3666 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3667 $ret = api_format_messages($mail, $recipient, $sender);
3669 $ret = ["error" => $id];
3672 $data = ['direct_message'=>$ret];
3678 $data = api_rss_extra($a, $data, $sender);
3682 return api_format_data("direct-messages", $type, $data);
3685 /// @TODO move to top of file or somewhere better
3686 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3689 * delete a direct_message from mail table through api
3691 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3692 * @return string|array
3693 * @throws BadRequestException
3694 * @throws ForbiddenException
3695 * @throws ImagickException
3696 * @throws InternalServerErrorException
3697 * @throws UnauthorizedException
3698 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3700 function api_direct_messages_destroy($type)
3704 if (api_user() === false) {
3705 throw new ForbiddenException();
3709 $user_info = api_get_user($a);
3711 $id = $_REQUEST['id'] ?? 0;
3713 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3714 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3715 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3717 $uid = $user_info['uid'];
3718 // error if no id or parenturi specified (for clients posting parent-uri as well)
3719 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3720 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3721 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3724 // BadRequestException if no id specified (for clients using Twitter API)
3726 throw new BadRequestException('Message id not specified');
3729 // add parent-uri to sql command if specified by calling app
3730 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3732 // error message if specified id is not in database
3733 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3734 if ($verbose == "true") {
3735 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3736 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3738 /// @todo BadRequestException ok for Twitter API clients?
3739 throw new BadRequestException('message id not in database');
3743 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3745 if ($verbose == "true") {
3748 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3749 return api_format_data("direct_message_delete", $type, ['$result' => $answer]);
3751 $answer = ['result' => 'error', 'message' => 'unknown error'];
3752 return api_format_data("direct_messages_delete", $type, ['$result' => $answer]);
3755 /// @todo return JSON data like Twitter API not yet implemented
3758 /// @TODO move to top of file or somewhere better
3759 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3764 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3765 * @return string|array
3766 * @throws HTTPException\BadRequestException
3767 * @throws HTTPException\ExpectationFailedException
3768 * @throws HTTPException\ForbiddenException
3769 * @throws HTTPException\InternalServerErrorException
3770 * @throws HTTPException\NotFoundException
3771 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3773 function api_friendships_destroy($type)
3777 if ($uid === false) {
3778 throw new HTTPException\ForbiddenException();
3781 $owner = User::getOwnerDataById($uid);
3783 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3784 throw new HTTPException\NotFoundException('Error Processing Request');
3787 $contact_id = $_REQUEST['user_id'] ?? 0;
3789 if (empty($contact_id)) {
3790 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3791 throw new HTTPException\BadRequestException('no user_id specified');
3794 // Get Contact by given id
3795 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3797 if(!DBA::isResult($contact)) {
3798 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3799 throw new HTTPException\NotFoundException('no contact found to given ID');
3802 $url = $contact['url'];
3804 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3805 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3806 Strings::normaliseLink($url), $url];
3807 $contact = DBA::selectFirst('contact', [], $condition);
3809 if (!DBA::isResult($contact)) {
3810 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3811 throw new HTTPException\NotFoundException('Not following Contact');
3815 $result = Contact::terminateFriendship($owner, $contact);
3817 if ($result === null) {
3818 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3819 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3822 if ($result === false) {
3823 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3825 } catch (Exception $e) {
3826 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3827 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3830 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3831 unset($contact['uid']);
3832 unset($contact['self']);
3834 // Set screen_name since Twidere requests it
3835 $contact['screen_name'] = $contact['nick'];
3837 return api_format_data('friendships-destroy', $type, ['user' => $contact]);
3839 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3843 * @param string $type Return type (atom, rss, xml, json)
3844 * @param string $box
3845 * @param string $verbose
3847 * @return array|string
3848 * @throws BadRequestException
3849 * @throws ForbiddenException
3850 * @throws ImagickException
3851 * @throws InternalServerErrorException
3852 * @throws UnauthorizedException
3854 function api_direct_messages_box($type, $box, $verbose)
3857 if (api_user() === false) {
3858 throw new ForbiddenException();
3861 $count = $_GET['count'] ?? 20;
3862 $page = $_REQUEST['page'] ?? 1;
3864 $since_id = $_REQUEST['since_id'] ?? 0;
3865 $max_id = $_REQUEST['max_id'] ?? 0;
3867 $user_id = $_REQUEST['user_id'] ?? '';
3868 $screen_name = $_REQUEST['screen_name'] ?? '';
3871 unset($_REQUEST["user_id"]);
3872 unset($_GET["user_id"]);
3874 unset($_REQUEST["screen_name"]);
3875 unset($_GET["screen_name"]);
3877 $user_info = api_get_user($a);
3878 if ($user_info === false) {
3879 throw new ForbiddenException();
3881 $profile_url = $user_info["url"];
3884 $start = max(0, ($page - 1) * $count);
3889 if ($box=="sentbox") {
3890 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3891 } elseif ($box == "conversation") {
3892 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3893 } elseif ($box == "all") {
3894 $sql_extra = "true";
3895 } elseif ($box == "inbox") {
3896 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3900 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3903 if ($user_id != "") {
3904 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3905 } elseif ($screen_name !="") {
3906 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3909 $r = DBA::toArray(DBA::p(
3910 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND $sql_extra AND `mail`.`id` > ? ORDER BY `mail`.`id` DESC LIMIT ?,?",
3916 if ($verbose == "true" && !DBA::isResult($r)) {
3917 $answer = ['result' => 'error', 'message' => 'no mails available'];
3918 return api_format_data("direct_messages_all", $type, ['$result' => $answer]);
3922 foreach ($r as $item) {
3923 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3924 $recipient = $user_info;
3925 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3926 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3927 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
3928 $sender = $user_info;
3931 if (isset($recipient) && isset($sender)) {
3932 $ret[] = api_format_messages($item, $recipient, $sender);
3937 $data = ['direct_message' => $ret];
3942 $data = api_rss_extra($a, $data, $user_info);
3946 return api_format_data("direct-messages", $type, $data);
3950 * Returns the most recent direct messages sent by the user.
3952 * @param string $type Return type (atom, rss, xml, json)
3954 * @return array|string
3955 * @throws BadRequestException
3956 * @throws ForbiddenException
3957 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3959 function api_direct_messages_sentbox($type)
3961 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3962 return api_direct_messages_box($type, "sentbox", $verbose);
3966 * Returns the most recent direct messages sent to the user.
3968 * @param string $type Return type (atom, rss, xml, json)
3970 * @return array|string
3971 * @throws BadRequestException
3972 * @throws ForbiddenException
3973 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3975 function api_direct_messages_inbox($type)
3977 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3978 return api_direct_messages_box($type, "inbox", $verbose);
3983 * @param string $type Return type (atom, rss, xml, json)
3985 * @return array|string
3986 * @throws BadRequestException
3987 * @throws ForbiddenException
3989 function api_direct_messages_all($type)
3991 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3992 return api_direct_messages_box($type, "all", $verbose);
3997 * @param string $type Return type (atom, rss, xml, json)
3999 * @return array|string
4000 * @throws BadRequestException
4001 * @throws ForbiddenException
4003 function api_direct_messages_conversation($type)
4005 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
4006 return api_direct_messages_box($type, "conversation", $verbose);
4009 /// @TODO move to top of file or somewhere better
4010 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
4011 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
4012 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
4013 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
4016 * delete a complete photoalbum with all containing photos from database through api
4018 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4019 * @return string|array
4020 * @throws BadRequestException
4021 * @throws ForbiddenException
4022 * @throws InternalServerErrorException
4024 function api_fr_photoalbum_delete($type)
4026 if (api_user() === false) {
4027 throw new ForbiddenException();
4030 $album = $_REQUEST['album'] ?? '';
4032 // we do not allow calls without album string
4034 throw new BadRequestException("no albumname specified");
4036 // check if album is existing
4038 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
4039 if (!DBA::isResult($photos)) {
4040 throw new BadRequestException("album not available");
4043 $resourceIds = array_column($photos, 'resource-id');
4045 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4046 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
4047 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
4048 Item::deleteForUser($condition, api_user());
4050 // now let's delete all photos from the album
4051 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
4053 // return success of deletion or error message
4055 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
4056 return api_format_data("photoalbum_delete", $type, ['$result' => $answer]);
4058 throw new InternalServerErrorException("unknown error - deleting from database failed");
4063 * update the name of the album for all photos of an album
4065 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4066 * @return string|array
4067 * @throws BadRequestException
4068 * @throws ForbiddenException
4069 * @throws InternalServerErrorException
4071 function api_fr_photoalbum_update($type)
4073 if (api_user() === false) {
4074 throw new ForbiddenException();
4077 $album = $_REQUEST['album'] ?? '';
4078 $album_new = $_REQUEST['album_new'] ?? '';
4080 // we do not allow calls without album string
4082 throw new BadRequestException("no albumname specified");
4084 if ($album_new == "") {
4085 throw new BadRequestException("no new albumname specified");
4087 // check if album is existing
4088 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
4089 throw new BadRequestException("album not available");
4091 // now let's update all photos to the albumname
4092 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
4094 // return success of updating or error message
4096 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
4097 return api_format_data("photoalbum_update", $type, ['$result' => $answer]);
4099 throw new InternalServerErrorException("unknown error - updating in database failed");
4105 * list all photos of the authenticated user
4107 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4108 * @return string|array
4109 * @throws ForbiddenException
4110 * @throws InternalServerErrorException
4112 function api_fr_photos_list($type)
4114 if (api_user() === false) {
4115 throw new ForbiddenException();
4117 $r = DBA::toArray(DBA::p(
4118 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
4119 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
4120 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
4121 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
4124 'image/jpeg' => 'jpg',
4125 'image/png' => 'png',
4126 'image/gif' => 'gif'
4128 $data = ['photo'=>[]];
4129 if (DBA::isResult($r)) {
4130 foreach ($r as $rr) {
4132 $photo['id'] = $rr['resource-id'];
4133 $photo['album'] = $rr['album'];
4134 $photo['filename'] = $rr['filename'];
4135 $photo['type'] = $rr['type'];
4136 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
4137 $photo['created'] = $rr['created'];
4138 $photo['edited'] = $rr['edited'];
4139 $photo['desc'] = $rr['desc'];
4141 if ($type == "xml") {
4142 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
4144 $photo['thumb'] = $thumb;
4145 $data['photo'][] = $photo;
4149 return api_format_data("photos", $type, $data);
4153 * upload a new photo or change an existing photo
4155 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4156 * @return string|array
4157 * @throws BadRequestException
4158 * @throws ForbiddenException
4159 * @throws ImagickException
4160 * @throws InternalServerErrorException
4161 * @throws NotFoundException
4163 function api_fr_photo_create_update($type)
4165 if (api_user() === false) {
4166 throw new ForbiddenException();
4169 $photo_id = $_REQUEST['photo_id'] ?? null;
4170 $desc = $_REQUEST['desc'] ?? null;
4171 $album = $_REQUEST['album'] ?? null;
4172 $album_new = $_REQUEST['album_new'] ?? null;
4173 $allow_cid = $_REQUEST['allow_cid'] ?? null;
4174 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
4175 $allow_gid = $_REQUEST['allow_gid'] ?? null;
4176 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
4177 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
4179 // do several checks on input parameters
4180 // we do not allow calls without album string
4181 if ($album == null) {
4182 throw new BadRequestException("no albumname specified");
4184 // if photo_id == null --> we are uploading a new photo
4185 if ($photo_id == null) {
4188 // error if no media posted in create-mode
4189 if (empty($_FILES['media'])) {
4191 throw new BadRequestException("no media data submitted");
4194 // album_new will be ignored in create-mode
4199 // check if photo is existing in databasei
4200 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
4201 throw new BadRequestException("photo not available");
4205 // checks on acl strings provided by clients
4206 $acl_input_error = false;
4207 $acl_input_error |= check_acl_input($allow_cid);
4208 $acl_input_error |= check_acl_input($deny_cid);
4209 $acl_input_error |= check_acl_input($allow_gid);
4210 $acl_input_error |= check_acl_input($deny_gid);
4211 if ($acl_input_error) {
4212 throw new BadRequestException("acl data invalid");
4214 // now let's upload the new media in create-mode
4215 if ($mode == "create") {
4216 $media = $_FILES['media'];
4217 $data = save_media_to_database("photo", $media, $type, $album, trim($allow_cid), trim($deny_cid), trim($allow_gid), trim($deny_gid), $desc, Photo::DEFAULT, $visibility);
4219 // return success of updating or error message
4220 if (!is_null($data)) {
4221 return api_format_data("photo_create", $type, $data);
4223 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
4227 // now let's do the changes in update-mode
4228 if ($mode == "update") {
4229 $updated_fields = [];
4231 if (!is_null($desc)) {
4232 $updated_fields['desc'] = $desc;
4235 if (!is_null($album_new)) {
4236 $updated_fields['album'] = $album_new;
4239 if (!is_null($allow_cid)) {
4240 $allow_cid = trim($allow_cid);
4241 $updated_fields['allow_cid'] = $allow_cid;
4244 if (!is_null($deny_cid)) {
4245 $deny_cid = trim($deny_cid);
4246 $updated_fields['deny_cid'] = $deny_cid;
4249 if (!is_null($allow_gid)) {
4250 $allow_gid = trim($allow_gid);
4251 $updated_fields['allow_gid'] = $allow_gid;
4254 if (!is_null($deny_gid)) {
4255 $deny_gid = trim($deny_gid);
4256 $updated_fields['deny_gid'] = $deny_gid;
4260 if (count($updated_fields) > 0) {
4261 $nothingtodo = false;
4262 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
4264 $nothingtodo = true;
4267 if (!empty($_FILES['media'])) {
4268 $nothingtodo = false;
4269 $media = $_FILES['media'];
4270 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
4271 if (!is_null($data)) {
4272 return api_format_data("photo_update", $type, $data);
4276 // return success of updating or error message
4278 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
4279 return api_format_data("photo_update", $type, ['$result' => $answer]);
4282 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
4283 return api_format_data("photo_update", $type, ['$result' => $answer]);
4285 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
4288 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
4292 * delete a single photo from the database through api
4294 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4295 * @return string|array
4296 * @throws BadRequestException
4297 * @throws ForbiddenException
4298 * @throws InternalServerErrorException
4300 function api_fr_photo_delete($type)
4302 if (api_user() === false) {
4303 throw new ForbiddenException();
4307 $photo_id = $_REQUEST['photo_id'] ?? null;
4309 // do several checks on input parameters
4310 // we do not allow calls without photo id
4311 if ($photo_id == null) {
4312 throw new BadRequestException("no photo_id specified");
4315 // check if photo is existing in database
4316 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
4317 throw new BadRequestException("photo not available");
4320 // now we can perform on the deletion of the photo
4321 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
4323 // return success of deletion or error message
4325 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
4326 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
4327 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
4328 Item::deleteForUser($condition, api_user());
4330 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4331 return api_format_data("photo_delete", $type, ['$result' => $result]);
4333 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4339 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4341 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4342 * @return string|array
4343 * @throws BadRequestException
4344 * @throws ForbiddenException
4345 * @throws InternalServerErrorException
4346 * @throws NotFoundException
4348 function api_fr_photo_detail($type)
4350 if (api_user() === false) {
4351 throw new ForbiddenException();
4353 if (empty($_REQUEST['photo_id'])) {
4354 throw new BadRequestException("No photo id.");
4357 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4358 $photo_id = $_REQUEST['photo_id'];
4360 // prepare json/xml output with data from database for the requested photo
4361 $data = prepare_photo_data($type, $scale, $photo_id);
4363 return api_format_data("photo_detail", $type, $data);
4368 * updates the profile image for the user (either a specified profile or the default profile)
4370 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4372 * @return string|array
4373 * @throws BadRequestException
4374 * @throws ForbiddenException
4375 * @throws ImagickException
4376 * @throws InternalServerErrorException
4377 * @throws NotFoundException
4378 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4380 function api_account_update_profile_image($type)
4382 if (api_user() === false) {
4383 throw new ForbiddenException();
4386 $profile_id = $_REQUEST['profile_id'] ?? 0;
4388 // error if image data is missing
4389 if (empty($_FILES['image'])) {
4390 throw new BadRequestException("no media data submitted");
4393 // check if specified profile id is valid
4394 if ($profile_id != 0) {
4395 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4396 // error message if specified profile id is not in database
4397 if (!DBA::isResult($profile)) {
4398 throw new BadRequestException("profile_id not available");
4400 $is_default_profile = $profile['is-default'];
4402 $is_default_profile = 1;
4405 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4407 if (!empty($_FILES['image'])) {
4408 $media = $_FILES['image'];
4409 } elseif (!empty($_FILES['media'])) {
4410 $media = $_FILES['media'];
4412 // save new profile image
4413 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
4416 if (is_array($media['type'])) {
4417 $filetype = $media['type'][0];
4419 $filetype = $media['type'];
4421 if ($filetype == "image/jpeg") {
4423 } elseif ($filetype == "image/png") {
4426 throw new InternalServerErrorException('Unsupported filetype');
4429 // change specified profile or all profiles to the new resource-id
4430 if ($is_default_profile) {
4431 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4432 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
4434 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4435 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4436 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4439 Contact::updateSelfFromUserID(api_user(), true);
4441 // Update global directory in background
4442 Profile::publishUpdate(api_user());
4444 // output for client
4446 return api_account_verify_credentials($type);
4448 // SaveMediaToDatabase failed for some reason
4449 throw new InternalServerErrorException("image upload failed");
4453 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4454 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4455 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4456 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4457 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4458 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4459 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4460 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4461 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4464 * Update user profile
4466 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4468 * @return array|string
4469 * @throws BadRequestException
4470 * @throws ForbiddenException
4471 * @throws ImagickException
4472 * @throws InternalServerErrorException
4473 * @throws UnauthorizedException
4475 function api_account_update_profile($type)
4477 $local_user = api_user();
4478 $api_user = api_get_user(DI::app());
4480 if (!empty($_POST['name'])) {
4481 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4482 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4483 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4484 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
4487 if (isset($_POST['description'])) {
4488 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4489 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4490 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
4493 Profile::publishUpdate($local_user);
4495 return api_account_verify_credentials($type);
4498 /// @TODO move to top of file or somewhere better
4499 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4503 * @param string $acl_string
4507 function check_acl_input($acl_string)
4509 if (empty($acl_string)) {
4513 $contact_not_found = false;
4515 // split <x><y><z> into array of cid's
4516 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4518 // check for each cid if it is available on server
4519 $cid_array = $array[0];
4520 foreach ($cid_array as $cid) {
4521 $cid = str_replace("<", "", $cid);
4522 $cid = str_replace(">", "", $cid);
4523 $condition = ['id' => $cid, 'uid' => api_user()];
4524 $contact_not_found |= !DBA::exists('contact', $condition);
4526 return $contact_not_found;
4530 * @param string $mediatype
4531 * @param array $media
4532 * @param string $type
4533 * @param string $album
4534 * @param string $allow_cid
4535 * @param string $deny_cid
4536 * @param string $allow_gid
4537 * @param string $deny_gid
4538 * @param string $desc
4539 * @param integer $phototype
4540 * @param boolean $visibility
4541 * @param string $photo_id
4543 * @throws BadRequestException
4544 * @throws ForbiddenException
4545 * @throws ImagickException
4546 * @throws InternalServerErrorException
4547 * @throws NotFoundException
4548 * @throws UnauthorizedException
4550 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
4558 if (is_array($media)) {
4559 if (is_array($media['tmp_name'])) {
4560 $src = $media['tmp_name'][0];
4562 $src = $media['tmp_name'];
4564 if (is_array($media['name'])) {
4565 $filename = basename($media['name'][0]);
4567 $filename = basename($media['name']);
4569 if (is_array($media['size'])) {
4570 $filesize = intval($media['size'][0]);
4572 $filesize = intval($media['size']);
4574 if (is_array($media['type'])) {
4575 $filetype = $media['type'][0];
4577 $filetype = $media['type'];
4581 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4584 "File upload src: " . $src . " - filename: " . $filename .
4585 " - size: " . $filesize . " - type: " . $filetype);
4587 // check if there was a php upload error
4588 if ($filesize == 0 && $media['error'] == 1) {
4589 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4591 // check against max upload size within Friendica instance
4592 $maximagesize = DI::config()->get('system', 'maximagesize');
4593 if ($maximagesize && ($filesize > $maximagesize)) {
4594 $formattedBytes = Strings::formatBytes($maximagesize);
4595 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4598 // create Photo instance with the data of the image
4599 $imagedata = @file_get_contents($src);
4600 $Image = new Image($imagedata, $filetype);
4601 if (!$Image->isValid()) {
4602 throw new InternalServerErrorException("unable to process image data");
4605 // check orientation of image
4606 $Image->orient($src);
4609 // check max length of images on server
4610 $max_length = DI::config()->get('system', 'max_image_length');
4611 if ($max_length > 0) {
4612 $Image->scaleDown($max_length);
4613 logger::info("File upload: Scaling picture to new size " . $max_length);
4615 $width = $Image->getWidth();
4616 $height = $Image->getHeight();
4618 // create a new resource-id if not already provided
4619 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4621 if ($mediatype == "photo") {
4622 // upload normal image (scales 0, 1, 2)
4623 logger::info("photo upload: starting new photo upload");
4625 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4627 logger::notice("photo upload: image upload with scale 0 (original size) failed");
4629 if ($width > 640 || $height > 640) {
4630 $Image->scaleDown(640);
4631 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4633 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
4637 if ($width > 320 || $height > 320) {
4638 $Image->scaleDown(320);
4639 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4641 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
4644 logger::info("photo upload: new photo upload ended");
4645 } elseif ($mediatype == "profileimage") {
4646 // upload profile image (scales 4, 5, 6)
4647 logger::info("photo upload: starting new profile image upload");
4649 if ($width > 300 || $height > 300) {
4650 $Image->scaleDown(300);
4651 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4653 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4657 if ($width > 80 || $height > 80) {
4658 $Image->scaleDown(80);
4659 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4661 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4665 if ($width > 48 || $height > 48) {
4666 $Image->scaleDown(48);
4667 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4669 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4672 $Image->__destruct();
4673 logger::info("photo upload: new profile image upload ended");
4677 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4678 if ($photo_id == null && $mediatype == "photo") {
4679 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4681 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4682 return prepare_photo_data($type, false, $resource_id);
4684 throw new InternalServerErrorException("image upload failed");
4690 * @param string $hash
4691 * @param string $allow_cid
4692 * @param string $deny_cid
4693 * @param string $allow_gid
4694 * @param string $deny_gid
4695 * @param string $filetype
4696 * @param boolean $visibility
4697 * @throws InternalServerErrorException
4699 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4701 // get data about the api authenticated user
4702 $uri = Item::newURI(intval(api_user()));
4703 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4706 $arr['guid'] = System::createUUID();
4707 $arr['uid'] = intval(api_user());
4709 $arr['type'] = 'photo';
4711 $arr['resource-id'] = $hash;
4712 $arr['contact-id'] = $owner_record['id'];
4713 $arr['owner-name'] = $owner_record['name'];
4714 $arr['owner-link'] = $owner_record['url'];
4715 $arr['owner-avatar'] = $owner_record['thumb'];
4716 $arr['author-name'] = $owner_record['name'];
4717 $arr['author-link'] = $owner_record['url'];
4718 $arr['author-avatar'] = $owner_record['thumb'];
4720 $arr['allow_cid'] = $allow_cid;
4721 $arr['allow_gid'] = $allow_gid;
4722 $arr['deny_cid'] = $deny_cid;
4723 $arr['deny_gid'] = $deny_gid;
4724 $arr['visible'] = $visibility;
4728 'image/jpeg' => 'jpg',
4729 'image/png' => 'png',
4730 'image/gif' => 'gif'
4733 // adds link to the thumbnail scale photo
4734 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4735 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4738 // do the magic for storing the item in the database and trigger the federation to other contacts
4744 * @param string $type
4746 * @param string $photo_id
4749 * @throws BadRequestException
4750 * @throws ForbiddenException
4751 * @throws ImagickException
4752 * @throws InternalServerErrorException
4753 * @throws NotFoundException
4754 * @throws UnauthorizedException
4756 function prepare_photo_data($type, $scale, $photo_id)
4759 $user_info = api_get_user($a);
4761 if ($user_info === false) {
4762 throw new ForbiddenException();
4765 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4766 $data_sql = ($scale === false ? "" : "data, ");
4768 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4769 // clients needs to convert this in their way for further processing
4770 $r = DBA::toArray(DBA::p(
4771 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4772 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4773 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4774 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4775 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4776 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4782 'image/jpeg' => 'jpg',
4783 'image/png' => 'png',
4784 'image/gif' => 'gif'
4787 // prepare output data for photo
4788 if (DBA::isResult($r)) {
4789 $data = ['photo' => $r[0]];
4790 $data['photo']['id'] = $data['photo']['resource-id'];
4791 if ($scale !== false) {
4792 $data['photo']['data'] = base64_encode($data['photo']['data']);
4794 unset($data['photo']['datasize']); //needed only with scale param
4796 if ($type == "xml") {
4797 $data['photo']['links'] = [];
4798 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4799 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4801 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4804 $data['photo']['link'] = [];
4805 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4807 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4808 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4812 unset($data['photo']['resource-id']);
4813 unset($data['photo']['minscale']);
4814 unset($data['photo']['maxscale']);
4816 throw new NotFoundException();
4819 // retrieve item element for getting activities (like, dislike etc.) related to photo
4820 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4821 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4822 if (!DBA::isResult($item)) {
4823 throw new NotFoundException('Photo-related item not found.');
4826 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4828 // retrieve comments on photo
4829 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4830 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4832 $statuses = Post::selectForUser(api_user(), [], $condition);
4834 // prepare output of comments
4835 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4837 if ($type == "xml") {
4839 foreach ($commentData as $comment) {
4840 $comments[$k++ . ":comment"] = $comment;
4843 foreach ($commentData as $comment) {
4844 $comments[] = $comment;
4847 $data['photo']['friendica_comments'] = $comments;
4849 // include info if rights on photo and rights on item are mismatching
4850 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4851 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4852 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4853 $data['photo']['deny_gid'] != $item['deny_gid'];
4854 $data['photo']['rights_mismatch'] = $rights_mismatch;
4860 * Return an item with announcer data if it had been announced
4862 * @param array $item Item array
4863 * @return array Item array with announce data
4865 function api_get_announce($item)
4867 // Quit if the item already has got a different owner and author
4868 if ($item['owner-id'] != $item['author-id']) {
4872 // Don't change original or Diaspora posts
4873 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4877 // Quit if we do now the original author and it had been a post from a native network
4878 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4882 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4883 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4884 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4885 if (!DBA::isResult($announce)) {
4889 return array_merge($item, $announce);
4894 * @param array $item
4899 function api_in_reply_to($item)
4903 $in_reply_to['status_id'] = null;
4904 $in_reply_to['user_id'] = null;
4905 $in_reply_to['status_id_str'] = null;
4906 $in_reply_to['user_id_str'] = null;
4907 $in_reply_to['screen_name'] = null;
4909 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4910 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4911 if (DBA::isResult($parent)) {
4912 $in_reply_to['status_id'] = intval($parent['id']);
4914 $in_reply_to['status_id'] = intval($item['parent']);
4917 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4919 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4920 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4922 if (DBA::isResult($parent)) {
4923 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4924 $in_reply_to['user_id'] = intval($parent['author-id']);
4925 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4928 // There seems to be situation, where both fields are identical:
4929 // https://github.com/friendica/friendica/issues/1010
4930 // This is a bugfix for that.
4931 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4932 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']]);
4933 $in_reply_to['status_id'] = null;
4934 $in_reply_to['user_id'] = null;
4935 $in_reply_to['status_id_str'] = null;
4936 $in_reply_to['user_id_str'] = null;
4937 $in_reply_to['screen_name'] = null;
4941 return $in_reply_to;
4946 * @param string $text
4949 * @throws InternalServerErrorException
4951 function api_clean_plain_items($text)
4953 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4955 $text = BBCode::cleanPictureLinks($text);
4956 $URLSearchString = "^\[\]";
4958 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4960 if ($include_entities == "true") {
4961 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4964 // Simplify "attachment" element
4965 $text = BBCode::removeAttachment($text);
4972 * @param array $contacts
4976 function api_best_nickname(&$contacts)
4980 if (count($contacts) == 0) {
4984 foreach ($contacts as $contact) {
4985 if ($contact["network"] == "") {
4986 $contact["network"] = "dfrn";
4987 $best_contact = [$contact];
4991 if (sizeof($best_contact) == 0) {
4992 foreach ($contacts as $contact) {
4993 if ($contact["network"] == "dfrn") {
4994 $best_contact = [$contact];
4999 if (sizeof($best_contact) == 0) {
5000 foreach ($contacts as $contact) {
5001 if ($contact["network"] == "dspr") {
5002 $best_contact = [$contact];
5007 if (sizeof($best_contact) == 0) {
5008 foreach ($contacts as $contact) {
5009 if ($contact["network"] == "stat") {
5010 $best_contact = [$contact];
5015 if (sizeof($best_contact) == 0) {
5016 foreach ($contacts as $contact) {
5017 if ($contact["network"] == "pump") {
5018 $best_contact = [$contact];
5023 if (sizeof($best_contact) == 0) {
5024 foreach ($contacts as $contact) {
5025 if ($contact["network"] == "twit") {
5026 $best_contact = [$contact];
5031 if (sizeof($best_contact) == 1) {
5032 $contacts = $best_contact;
5034 $contacts = [$contacts[0]];
5039 * Return all or a specified group of the user with the containing contacts.
5041 * @param string $type Return type (atom, rss, xml, json)
5043 * @return array|string
5044 * @throws BadRequestException
5045 * @throws ForbiddenException
5046 * @throws ImagickException
5047 * @throws InternalServerErrorException
5048 * @throws UnauthorizedException
5050 function api_friendica_group_show($type)
5054 if (api_user() === false) {
5055 throw new ForbiddenException();
5059 $user_info = api_get_user($a);
5060 $gid = $_REQUEST['gid'] ?? 0;
5061 $uid = $user_info['uid'];
5063 // get data of the specified group id or all groups if not specified
5065 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
5067 // error message if specified gid is not in database
5068 if (!DBA::isResult($groups)) {
5069 throw new BadRequestException("gid not available");
5072 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
5075 // loop through all groups and retrieve all members for adding data in the user array
5077 foreach ($groups as $rr) {
5078 $members = Contact\Group::getById($rr['id']);
5081 if ($type == "xml") {
5082 $user_element = "users";
5084 foreach ($members as $member) {
5085 $user = api_get_user($a, $member['nurl']);
5086 $users[$k++.":user"] = $user;
5089 $user_element = "user";
5090 foreach ($members as $member) {
5091 $user = api_get_user($a, $member['nurl']);
5095 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
5097 return api_format_data("groups", $type, ['group' => $grps]);
5099 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
5103 * Delete the specified group of the user.
5105 * @param string $type Return type (atom, rss, xml, json)
5107 * @return array|string
5108 * @throws BadRequestException
5109 * @throws ForbiddenException
5110 * @throws ImagickException
5111 * @throws InternalServerErrorException
5112 * @throws UnauthorizedException
5114 function api_friendica_group_delete($type)
5118 if (api_user() === false) {
5119 throw new ForbiddenException();
5123 $user_info = api_get_user($a);
5124 $gid = $_REQUEST['gid'] ?? 0;
5125 $name = $_REQUEST['name'] ?? '';
5126 $uid = $user_info['uid'];
5128 // error if no gid specified
5129 if ($gid == 0 || $name == "") {
5130 throw new BadRequestException('gid or name not specified');
5133 // error message if specified gid is not in database
5134 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) {
5135 throw new BadRequestException('gid not available');
5138 // error message if specified gid is not in database
5139 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) {
5140 throw new BadRequestException('wrong group name');
5144 $gid = Group::getIdByName($uid, $name);
5146 throw new BadRequestException('other API error');
5149 $ret = Group::remove($gid);
5153 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
5154 return api_format_data("group_delete", $type, ['result' => $success]);
5156 throw new BadRequestException('other API error');
5159 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
5164 * @param string $type Return type (atom, rss, xml, json)
5166 * @return array|string
5167 * @throws BadRequestException
5168 * @throws ForbiddenException
5169 * @throws ImagickException
5170 * @throws InternalServerErrorException
5171 * @throws UnauthorizedException
5172 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
5174 function api_lists_destroy($type)
5178 if (api_user() === false) {
5179 throw new ForbiddenException();
5183 $user_info = api_get_user($a);
5184 $gid = $_REQUEST['list_id'] ?? 0;
5185 $uid = $user_info['uid'];
5187 // error if no gid specified
5189 throw new BadRequestException('gid not specified');
5192 // get data of the specified group id
5193 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5194 // error message if specified gid is not in database
5196 throw new BadRequestException('gid not available');
5199 if (Group::remove($gid)) {
5201 'name' => $group['name'],
5202 'id' => intval($gid),
5203 'id_str' => (string) $gid,
5204 'user' => $user_info
5207 return api_format_data("lists", $type, ['lists' => $list]);
5210 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
5213 * Add a new group to the database.
5215 * @param string $name Group name
5216 * @param int $uid User ID
5217 * @param array $users List of users to add to the group
5220 * @throws BadRequestException
5222 function group_create($name, $uid, $users = [])
5224 // error if no name specified
5226 throw new BadRequestException('group name not specified');
5229 // error message if specified group name already exists
5230 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
5231 throw new BadRequestException('group name already exists');
5234 // Check if the group needs to be reactivated
5235 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
5236 $reactivate_group = true;
5240 $ret = Group::create($uid, $name);
5242 $gid = Group::getIdByName($uid, $name);
5244 throw new BadRequestException('other API error');
5248 $erroraddinguser = false;
5250 foreach ($users as $user) {
5251 $cid = $user['cid'];
5252 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
5253 Group::addMember($gid, $cid);
5255 $erroraddinguser = true;
5256 $errorusers[] = $cid;
5260 // return success message incl. missing users in array
5261 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
5263 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5267 * Create the specified group with the posted array of contacts.
5269 * @param string $type Return type (atom, rss, xml, json)
5271 * @return array|string
5272 * @throws BadRequestException
5273 * @throws ForbiddenException
5274 * @throws ImagickException
5275 * @throws InternalServerErrorException
5276 * @throws UnauthorizedException
5278 function api_friendica_group_create($type)
5282 if (api_user() === false) {
5283 throw new ForbiddenException();
5287 $user_info = api_get_user($a);
5288 $name = $_REQUEST['name'] ?? '';
5289 $uid = $user_info['uid'];
5290 $json = json_decode($_POST['json'], true);
5291 $users = $json['user'];
5293 $success = group_create($name, $uid, $users);
5295 return api_format_data("group_create", $type, ['result' => $success]);
5297 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
5300 * Create a new group.
5302 * @param string $type Return type (atom, rss, xml, json)
5304 * @return array|string
5305 * @throws BadRequestException
5306 * @throws ForbiddenException
5307 * @throws ImagickException
5308 * @throws InternalServerErrorException
5309 * @throws UnauthorizedException
5310 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
5312 function api_lists_create($type)
5316 if (api_user() === false) {
5317 throw new ForbiddenException();
5321 $user_info = api_get_user($a);
5322 $name = $_REQUEST['name'] ?? '';
5323 $uid = $user_info['uid'];
5325 $success = group_create($name, $uid);
5326 if ($success['success']) {
5328 'name' => $success['name'],
5329 'id' => intval($success['gid']),
5330 'id_str' => (string) $success['gid'],
5331 'user' => $user_info
5334 return api_format_data("lists", $type, ['lists'=>$grp]);
5337 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5340 * Update the specified group with the posted array of contacts.
5342 * @param string $type Return type (atom, rss, xml, json)
5344 * @return array|string
5345 * @throws BadRequestException
5346 * @throws ForbiddenException
5347 * @throws ImagickException
5348 * @throws InternalServerErrorException
5349 * @throws UnauthorizedException
5351 function api_friendica_group_update($type)
5355 if (api_user() === false) {
5356 throw new ForbiddenException();
5360 $user_info = api_get_user($a);
5361 $uid = $user_info['uid'];
5362 $gid = $_REQUEST['gid'] ?? 0;
5363 $name = $_REQUEST['name'] ?? '';
5364 $json = json_decode($_POST['json'], true);
5365 $users = $json['user'];
5367 // error if no name specified
5369 throw new BadRequestException('group name not specified');
5372 // error if no gid specified
5374 throw new BadRequestException('gid not specified');
5378 $members = Contact\Group::getById($gid);
5379 foreach ($members as $member) {
5380 $cid = $member['id'];
5381 foreach ($users as $user) {
5382 $found = ($user['cid'] == $cid ? true : false);
5384 if (!isset($found) || !$found) {
5385 $gid = Group::getIdByName($uid, $name);
5386 Group::removeMember($gid, $cid);
5391 $erroraddinguser = false;
5393 foreach ($users as $user) {
5394 $cid = $user['cid'];
5396 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
5397 Group::addMember($gid, $cid);
5399 $erroraddinguser = true;
5400 $errorusers[] = $cid;
5404 // return success message incl. missing users in array
5405 $status = ($erroraddinguser ? "missing user" : "ok");
5406 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5407 return api_format_data("group_update", $type, ['result' => $success]);
5410 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5413 * Update information about a group.
5415 * @param string $type Return type (atom, rss, xml, json)
5417 * @return array|string
5418 * @throws BadRequestException
5419 * @throws ForbiddenException
5420 * @throws ImagickException
5421 * @throws InternalServerErrorException
5422 * @throws UnauthorizedException
5423 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5425 function api_lists_update($type)
5429 if (api_user() === false) {
5430 throw new ForbiddenException();
5434 $user_info = api_get_user($a);
5435 $gid = $_REQUEST['list_id'] ?? 0;
5436 $name = $_REQUEST['name'] ?? '';
5437 $uid = $user_info['uid'];
5439 // error if no gid specified
5441 throw new BadRequestException('gid not specified');
5444 // get data of the specified group id
5445 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5446 // error message if specified gid is not in database
5448 throw new BadRequestException('gid not available');
5451 if (Group::update($gid, $name)) {
5454 'id' => intval($gid),
5455 'id_str' => (string) $gid,
5456 'user' => $user_info
5459 return api_format_data("lists", $type, ['lists' => $list]);
5463 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5467 * @param string $type Return type (atom, rss, xml, json)
5469 * @return array|string
5470 * @throws BadRequestException
5471 * @throws ForbiddenException
5472 * @throws ImagickException
5473 * @throws InternalServerErrorException
5475 function api_friendica_activity($type)
5479 if (api_user() === false) {
5480 throw new ForbiddenException();
5482 $verb = strtolower(DI::args()->getArgv()[3]);
5483 $verb = preg_replace("|\..*$|", "", $verb);
5485 $id = $_REQUEST['id'] ?? 0;
5487 $res = Item::performActivity($id, $verb, api_user());
5490 if ($type == "xml") {
5495 return api_format_data('ok', $type, ['ok' => $ok]);
5497 throw new BadRequestException('Error adding activity');
5501 /// @TODO move to top of file or somewhere better
5502 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5503 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5504 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5505 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5506 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5507 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5508 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5509 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5510 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5511 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5514 * Returns notifications
5516 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5518 * @return string|array
5519 * @throws ForbiddenException
5520 * @throws BadRequestException
5523 function api_friendica_notification($type)
5525 if (api_user() === false) {
5526 throw new ForbiddenException();
5528 if (DI::args()->getArgc()!==3) {
5529 throw new BadRequestException('Invalid argument count');
5532 $Notifies = DI::notify()->selectAllForUser(local_user(), 50);
5534 $notifications = new ApiNotifications();
5535 foreach ($Notifies as $Notify) {
5536 $notifications[] = new ApiNotification($Notify);
5539 if ($type == 'xml') {
5541 foreach ($notifications as $notification) {
5542 $xmlnotes[] = ['@attributes' => $notification->toArray()];
5545 $result = $xmlnotes;
5546 } elseif (count($notifications) > 0) {
5547 $result = $notifications->getArrayCopy();
5552 return api_format_data('notes', $type, ['note' => $result]);
5556 * Set notification as seen and returns associated item (if possible)
5558 * POST request with 'id' param as notification id
5560 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5561 * @return string|array
5562 * @throws BadRequestException
5563 * @throws ForbiddenException
5564 * @throws ImagickException
5565 * @throws InternalServerErrorException
5566 * @throws UnauthorizedException
5568 function api_friendica_notification_seen($type)
5571 $user_info = api_get_user($a);
5573 if (api_user() === false || $user_info === false) {
5574 throw new ForbiddenException();
5576 if (DI::args()->getArgc() !== 4) {
5577 throw new BadRequestException('Invalid argument count');
5580 $id = intval($_REQUEST['id'] ?? 0);
5583 $Notify = DI::notify()->selectOneById($id);
5584 if ($Notify->uid !== api_user()) {
5585 throw new NotFoundException();
5588 if ($Notify->uriId) {
5589 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
5593 DI::notify()->save($Notify);
5595 if ($Notify->otype === Notification\ObjectType::ITEM) {
5596 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
5597 if (DBA::isResult($item)) {
5598 // we found the item, return it to the user
5599 $ret = api_format_items([$item], $user_info, false, $type);
5600 $data = ['status' => $ret];
5601 return api_format_data('status', $type, $data);
5603 // the item can't be found, but we set the notification as seen, so we count this as a success
5606 return api_format_data('result', $type, ['result' => 'success']);
5607 } catch (NotFoundException $e) {
5608 throw new BadRequestException('Invalid argument', $e);
5609 } catch (Exception $e) {
5610 throw new InternalServerErrorException('Internal Server exception', $e);
5614 /// @TODO move to top of file or somewhere better
5615 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5616 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5619 * update a direct_message to seen state
5621 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5622 * @return string|array (success result=ok, error result=error with error message)
5623 * @throws BadRequestException
5624 * @throws ForbiddenException
5625 * @throws ImagickException
5626 * @throws InternalServerErrorException
5627 * @throws UnauthorizedException
5629 function api_friendica_direct_messages_setseen($type)
5632 if (api_user() === false) {
5633 throw new ForbiddenException();
5637 $user_info = api_get_user($a);
5638 $uid = $user_info['uid'];
5639 $id = $_REQUEST['id'] ?? 0;
5641 // return error if id is zero
5643 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5644 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5647 // error message if specified id is not in database
5648 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5649 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5650 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5653 // update seen indicator
5654 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5658 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5659 return api_format_data("direct_message_setseen", $type, ['$result' => $answer]);
5661 $answer = ['result' => 'error', 'message' => 'unknown error'];
5662 return api_format_data("direct_messages_setseen", $type, ['$result' => $answer]);
5666 /// @TODO move to top of file or somewhere better
5667 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5670 * search for direct_messages containing a searchstring through api
5672 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5673 * @param string $box
5674 * @return string|array (success: success=true if found and search_result contains found messages,
5675 * success=false if nothing was found, search_result='nothing found',
5676 * error: result=error with error message)
5677 * @throws BadRequestException
5678 * @throws ForbiddenException
5679 * @throws ImagickException
5680 * @throws InternalServerErrorException
5681 * @throws UnauthorizedException
5683 function api_friendica_direct_messages_search($type, $box = "")
5687 if (api_user() === false) {
5688 throw new ForbiddenException();
5692 $user_info = api_get_user($a);
5693 $searchstring = $_REQUEST['searchstring'] ?? '';
5694 $uid = $user_info['uid'];
5696 // error if no searchstring specified
5697 if ($searchstring == "") {
5698 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5699 return api_format_data("direct_messages_search", $type, ['$result' => $answer]);
5702 // get data for the specified searchstring
5703 $r = DBA::toArray(DBA::p(
5704 "SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid` = ? AND `body` LIKE ? ORDER BY `mail`.`id` DESC",
5706 '%'.$searchstring.'%'
5709 $profile_url = $user_info["url"];
5711 // message if nothing was found
5712 if (!DBA::isResult($r)) {
5713 $success = ['success' => false, 'search_results' => 'problem with query'];
5714 } elseif (count($r) == 0) {
5715 $success = ['success' => false, 'search_results' => 'nothing found'];
5718 foreach ($r as $item) {
5719 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5720 $recipient = $user_info;
5721 $sender = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5722 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5723 $recipient = api_get_user($a, Strings::normaliseLink($item['contact-url']));
5724 $sender = $user_info;
5727 if (isset($recipient) && isset($sender)) {
5728 $ret[] = api_format_messages($item, $recipient, $sender);
5731 $success = ['success' => true, 'search_results' => $ret];
5734 return api_format_data("direct_message_search", $type, ['$result' => $success]);
5737 /// @TODO move to top of file or somewhere better
5738 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5741 * Returns a list of saved searches.
5743 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-saved_searches-list
5745 * @param string $type Return format: json or xml
5747 * @return string|array
5750 function api_saved_searches_list($type)
5752 $terms = DBA::select('search', ['id', 'term'], ['uid' => local_user()]);
5755 while ($term = DBA::fetch($terms)) {
5757 'created_at' => api_date(time()),
5758 'id' => intval($term['id']),
5759 'id_str' => $term['id'],
5760 'name' => $term['term'],
5762 'query' => $term['term']
5768 return api_format_data("terms", $type, ['terms' => $result]);
5771 /// @TODO move to top of file or somewhere better
5772 api_register_func('api/saved_searches/list', 'api_saved_searches_list', true);
5775 * Number of comments
5777 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5779 * @param object $data [Status, Status]
5783 function bindComments(&$data)
5785 if (count($data) == 0) {
5791 foreach ($data as $item) {
5792 $ids[] = $item['id'];
5795 $idStr = DBA::escape(implode(', ', $ids));
5796 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5797 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5798 $itemsData = DBA::toArray($items);
5800 foreach ($itemsData as $item) {
5801 $comments[$item['parent']] = $item['comments'];
5804 foreach ($data as $idx => $item) {
5806 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5811 @TODO Maybe open to implement?
5813 [pagename] => api/1.1/statuses/lookup.json
5814 [id] => 605138389168451584
5815 [include_cards] => true
5816 [cards_platform] => Android-12
5817 [include_entities] => true
5818 [include_my_retweet] => 1
5820 [include_reply_count] => true
5821 [include_descendent_reply_count] => true
5825 Not implemented by now:
5826 statuses/retweets_of_me
5831 account/update_location
5832 account/update_profile_background_image
5835 friendica/profile/update
5836 friendica/profile/create
5837 friendica/profile/delete
5839 Not implemented in status.net:
5840 statuses/retweeted_to_me
5841 statuses/retweeted_by_me
5842 direct_messages/destroy
5844 account/update_delivery_device
5845 notifications/follow