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\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\System;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Group;
38 use Friendica\Model\Item;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Notification;
41 use Friendica\Model\Photo;
42 use Friendica\Model\Post;
43 use Friendica\Model\Profile;
44 use Friendica\Model\User;
45 use Friendica\Model\Verb;
46 use Friendica\Module\BaseApi;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ForbiddenException;
50 use Friendica\Network\HTTPException\InternalServerErrorException;
51 use Friendica\Network\HTTPException\MethodNotAllowedException;
52 use Friendica\Network\HTTPException\NotFoundException;
53 use Friendica\Network\HTTPException\TooManyRequestsException;
54 use Friendica\Network\HTTPException\UnauthorizedException;
55 use Friendica\Object\Api\Friendica\Notification as ApiNotification;
56 use Friendica\Object\Image;
57 use Friendica\Protocol\Activity;
58 use Friendica\Security\BasicAuth;
59 use Friendica\Security\OAuth;
60 use Friendica\Util\DateTimeFormat;
61 use Friendica\Util\Images;
62 use Friendica\Util\Network;
63 use Friendica\Util\Proxy;
64 use Friendica\Util\Strings;
66 require_once __DIR__ . '/../mod/item.php';
67 require_once __DIR__ . '/../mod/wall_upload.php';
69 define('API_METHOD_ANY', '*');
70 define('API_METHOD_GET', 'GET');
71 define('API_METHOD_POST', 'POST,PUT');
72 define('API_METHOD_DELETE', 'POST,DELETE');
74 define('API_LOG_PREFIX', 'API {action} - ');
82 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
83 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
84 * into a page, and visitors will post something without noticing it).
88 $user = OAuth::getCurrentUserID();
93 if (!empty($_SESSION['allow_api'])) {
101 * Get source name from API client
103 * Clients can send 'source' parameter to be show in post metadata
104 * as "sent via <source>".
105 * Some clients doesn't send a source param, we support ones we know
106 * (only Twidere, atm)
109 * Client source name, default to "api" if unset/unknown
112 function api_source()
114 if (requestdata('source')) {
115 return requestdata('source');
118 // Support for known clients that doesn't send a source name
119 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
120 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
124 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
126 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
133 * Format date for API
135 * @param string $str Source date, as UTC
136 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
139 function api_date($str)
141 // Wed May 23 06:01:13 +0000 2007
142 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
146 * Register a function to be the endpoint for defined API path.
148 * @param string $path API URL path, relative to DI::baseUrl()
149 * @param string $func Function name to call on path request
150 * @param bool $auth API need logged user
151 * @param string $method HTTP method reqiured to call this endpoint.
152 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
153 * Default to API_METHOD_ANY
155 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
165 // Workaround for hotot
166 $path = str_replace("api/", "api/1.1/", $path);
176 * Check HTTP method of called API
178 * API endpoints can define which HTTP method to accept when called.
179 * This function check the current HTTP method agains endpoint
182 * @param string $method Required methods, uppercase, separated by comma
185 function api_check_method($method)
187 if ($method == "*") {
190 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
194 * Main API entry point
196 * Authenticate user, call registered API function, set HTTP headers
199 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
200 * @return string|array API call result
203 function api_call(App $a, App\Arguments $args = null)
205 global $API, $called_api;
212 if (strpos($args->getCommand(), ".xml") > 0) {
215 if (strpos($args->getCommand(), ".json") > 0) {
218 if (strpos($args->getCommand(), ".rss") > 0) {
221 if (strpos($args->getCommand(), ".atom") > 0) {
226 foreach ($API as $p => $info) {
227 if (strpos($args->getCommand(), $p) === 0) {
228 if (!api_check_method($info['method'])) {
229 throw new MethodNotAllowedException();
232 $called_api = explode("/", $p);
234 if (!empty($info['auth']) && api_user() === false) {
235 BasicAuth::getCurrentUserID(true);
236 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
239 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
241 $stamp = microtime(true);
242 $return = call_user_func($info['func'], $type);
243 $duration = floatval(microtime(true) - $stamp);
245 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
247 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
249 if (false === $return) {
251 * api function returned false withour throw an
252 * exception. This should not happend, throw a 500
254 throw new InternalServerErrorException();
259 header("Content-Type: text/xml");
262 header("Content-Type: application/json");
263 if (!empty($return)) {
264 $json = json_encode(end($return));
265 if (!empty($_GET['callback'])) {
266 $json = $_GET['callback'] . "(" . $json . ")";
272 header("Content-Type: application/rss+xml");
273 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
276 header("Content-Type: application/atom+xml");
277 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
284 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
285 throw new NotFoundException();
286 } catch (HTTPException $e) {
287 BaseApi::error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
292 * Set values for RSS template
295 * @param array $arr Array to be passed to template
296 * @param array $user_info User info
298 * @throws BadRequestException
299 * @throws ImagickException
300 * @throws InternalServerErrorException
301 * @throws UnauthorizedException
302 * @todo find proper type-hints
304 function api_rss_extra(App $a, $arr, $user_info)
306 if (is_null($user_info)) {
307 $user_info = api_get_user();
310 $arr['$user'] = $user_info;
312 'alternate' => $user_info['url'],
313 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
314 'base' => DI::baseUrl(),
315 'updated' => api_date(null),
316 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
317 'language' => $user_info['lang'],
318 'logo' => DI::baseUrl() . "/images/friendica-32.png",
326 * Unique contact to contact url.
328 * @param int $id Contact id
329 * @return bool|string
330 * Contact url or False if contact id is unknown
333 function api_unique_id_to_nurl($id)
335 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
337 if (DBA::isResult($r)) {
345 * Get user info array.
348 * @param int|string $contact_id Contact ID or URL
350 * @throws BadRequestException
351 * @throws ImagickException
352 * @throws InternalServerErrorException
353 * @throws UnauthorizedException
355 function api_get_user($contact_id = null)
363 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
365 // Searching for contact URL
366 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
367 $user = Strings::normaliseLink($contact_id);
369 $extra_query = "AND `contact`.`nurl` = ? ";
370 if (api_user() !== false) {
371 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
375 // Searching for contact id with uid = 0
376 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
377 $user = api_unique_id_to_nurl(intval($contact_id));
380 throw new BadRequestException("User ID ".$contact_id." not found.");
384 $extra_query = "AND `contact`.`nurl` = ? ";
385 if (api_user() !== false) {
386 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
390 if (is_null($user) && !empty($_GET['user_id'])) {
391 $user = api_unique_id_to_nurl($_GET['user_id']);
394 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
398 $extra_query = "AND `contact`.`nurl` = ? ";
399 if (api_user() !== false) {
400 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
403 if (is_null($user) && !empty($_GET['screen_name'])) {
404 $user = $_GET['screen_name'];
405 $extra_query = "AND `contact`.`nick` = ? ";
406 if (api_user() !== false) {
407 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
411 if (is_null($user) && !empty($_GET['profileurl'])) {
412 $user = Strings::normaliseLink($_GET['profileurl']);
413 $extra_query = "AND `contact`.`nurl` = ? ";
414 if (api_user() !== false) {
415 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
419 // $called_api is the API path exploded on / and is expected to have at least 2 elements
420 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
421 $argid = count($called_api);
422 if (!empty(DI::args()->getArgv()[$argid])) {
423 $data = explode(".", DI::args()->getArgv()[$argid]);
424 if (count($data) > 1) {
425 list($user, $null) = $data;
428 if (is_numeric($user)) {
429 $user = api_unique_id_to_nurl(intval($user));
433 $extra_query = "AND `contact`.`nurl` = ? ";
434 if (api_user() !== false) {
435 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
439 $extra_query = "AND `contact`.`nick` = ? ";
440 if (api_user() !== false) {
441 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
446 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
449 if (api_user() === false) {
450 BasicAuth::getCurrentUserID(true);
454 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
458 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
461 $uinfo = DBA::toArray(DBA::p(
462 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
468 // Selecting the id by priority, friendica first
469 if (is_array($uinfo)) {
470 api_best_nickname($uinfo);
473 // if the contact wasn't found, fetch it from the contacts with uid = 0
474 if (!DBA::isResult($uinfo)) {
476 throw new BadRequestException("User not found.");
479 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
481 if (DBA::isResult($contact)) {
483 'id' => $contact["id"],
484 'id_str' => (string) $contact["id"],
485 'name' => $contact["name"],
486 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
487 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
488 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
489 'profile_image_url' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
490 'profile_image_url_https' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
491 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_THUMB),
492 'profile_image_url_large' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_SMALL),
493 'url' => $contact["url"],
494 'protected' => false,
495 'followers_count' => 0,
496 'friends_count' => 0,
498 'created_at' => api_date($contact["created"]),
499 'favourites_count' => 0,
501 'time_zone' => 'UTC',
502 'geo_enabled' => false,
504 'statuses_count' => 0,
506 'contributors_enabled' => false,
507 'is_translator' => false,
508 'is_translation_enabled' => false,
509 'following' => false,
510 'follow_request_sent' => false,
511 'statusnet_blocking' => false,
512 'notifications' => false,
513 'statusnet_profile_url' => $contact["url"],
515 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
516 'pid' => Contact::getIdForURL($contact["url"], 0, false),
518 'network' => $contact["network"],
523 throw new BadRequestException("User ".$url." not found.");
527 if ($uinfo[0]['self']) {
528 if ($uinfo[0]['network'] == "") {
529 $uinfo[0]['network'] = Protocol::DFRN;
532 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
533 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
540 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
542 if (!empty($profile['about'])) {
543 $description = $profile['about'];
545 $description = $uinfo[0]["about"];
548 if (!empty($usr['default-location'])) {
549 $location = $usr['default-location'];
550 } elseif (!empty($uinfo[0]["location"])) {
551 $location = $uinfo[0]["location"];
553 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
557 'id' => intval($pcontact_id),
558 'id_str' => (string) intval($pcontact_id),
559 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
560 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
561 'location' => $location,
562 'description' => BBCode::toPlaintext($description ?? ''),
563 'profile_image_url' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
564 'profile_image_url_https' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
565 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_THUMB),
566 'profile_image_url_large' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_SMALL),
567 'url' => $uinfo[0]['url'],
568 'protected' => false,
569 'followers_count' => intval($countfollowers),
570 'friends_count' => intval($countfriends),
572 'created_at' => api_date($uinfo[0]['created']),
573 'favourites_count' => intval($starred),
575 'time_zone' => 'UTC',
576 'geo_enabled' => false,
578 'statuses_count' => intval($countitems),
580 'contributors_enabled' => false,
581 'is_translator' => false,
582 'is_translation_enabled' => false,
583 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
584 'follow_request_sent' => false,
585 'statusnet_blocking' => false,
586 'notifications' => false,
588 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
589 'statusnet_profile_url' => $uinfo[0]['url'],
590 'uid' => intval($uinfo[0]['uid']),
591 'cid' => intval($uinfo[0]['cid']),
592 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
593 'self' => $uinfo[0]['self'],
594 'network' => $uinfo[0]['network'],
597 // If this is a local user and it uses Frio, we can get its color preferences.
599 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
600 if ($theme_info['theme'] === 'frio') {
601 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
603 if ($schema && ($schema != '---')) {
604 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
605 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
606 require_once $schemefile;
609 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
610 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
611 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
613 if (empty($nav_bg)) {
616 if (empty($link_color)) {
617 $link_color = "#6fdbe8";
619 if (empty($bgcolor)) {
620 $bgcolor = "#ededed";
623 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
624 $ret['profile_link_color'] = str_replace('#', '', $link_color);
625 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
633 * return api-formatted array for item's author and owner
636 * @param array $item item from db
637 * @return array(array:author, array:owner)
638 * @throws BadRequestException
639 * @throws ImagickException
640 * @throws InternalServerErrorException
641 * @throws UnauthorizedException
643 function api_item_get_user(App $a, $item)
645 $status_user = api_get_user($item['author-id'] ?? null);
647 $author_user = $status_user;
649 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
651 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
652 $owner_user = api_get_user($item['owner-id'] ?? null);
654 $owner_user = $author_user;
657 return ([$status_user, $author_user, $owner_user]);
665 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
666 * returns a 401 status code and an error message if not.
668 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
670 * @param string $type Return type (atom, rss, xml, json)
671 * @return array|string
672 * @throws BadRequestException
673 * @throws ForbiddenException
674 * @throws ImagickException
675 * @throws InternalServerErrorException
676 * @throws UnauthorizedException
678 function api_account_verify_credentials($type)
682 if (api_user() === false) {
683 throw new ForbiddenException();
686 unset($_REQUEST["user_id"]);
687 unset($_GET["user_id"]);
689 unset($_REQUEST["screen_name"]);
690 unset($_GET["screen_name"]);
692 $skip_status = $_REQUEST['skip_status'] ?? false;
694 $user_info = api_get_user();
696 // "verified" isn't used here in the standard
697 unset($user_info["verified"]);
699 // - Adding last status
701 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
703 $user_info['status'] = api_format_item($item, $type);
707 // "uid" and "self" are only needed for some internal stuff, so remove it from here
708 unset($user_info["uid"]);
709 unset($user_info["self"]);
711 return BaseApi::formatData("user", $type, ['user' => $user_info]);
714 /// @TODO move to top of file or somewhere better
715 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
718 * Get data from $_POST or $_GET
723 function requestdata($k)
725 if (!empty($_POST[$k])) {
728 if (!empty($_GET[$k])) {
735 * Deprecated function to upload media.
737 * @param string $type Return type (atom, rss, xml, json)
739 * @return array|string
740 * @throws BadRequestException
741 * @throws ForbiddenException
742 * @throws ImagickException
743 * @throws InternalServerErrorException
744 * @throws UnauthorizedException
746 function api_statuses_mediap($type)
750 if (api_user() === false) {
751 logger::notice('api_statuses_update: no user');
752 throw new ForbiddenException();
754 $user_info = api_get_user();
756 $_REQUEST['profile_uid'] = api_user();
757 $_REQUEST['api_source'] = true;
758 $txt = requestdata('status') ?? '';
759 /// @TODO old-lost code?
760 //$txt = urldecode(requestdata('status'));
762 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
763 $txt = HTML::toBBCodeVideo($txt);
764 $config = HTMLPurifier_Config::createDefault();
765 $config->set('Cache.DefinitionImpl', null);
766 $purifier = new HTMLPurifier($config);
767 $txt = $purifier->purify($txt);
769 $txt = HTML::toBBCode($txt);
771 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
773 $picture = wall_upload_post($a, false);
775 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
776 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
777 $item_id = item_post($a);
779 // output the post that we just posted.
780 return api_status_show($type, $item_id);
783 /// @TODO move this to top of file or somewhere better!
784 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
787 * Updates the user’s current status.
789 * @param string $type Return type (atom, rss, xml, json)
791 * @return array|string
792 * @throws BadRequestException
793 * @throws ForbiddenException
794 * @throws ImagickException
795 * @throws InternalServerErrorException
796 * @throws TooManyRequestsException
797 * @throws UnauthorizedException
798 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
800 function api_statuses_update($type)
804 if (api_user() === false) {
805 logger::notice('api_statuses_update: no user');
806 throw new ForbiddenException();
811 // convert $_POST array items to the form we use for web posts.
812 if (requestdata('htmlstatus')) {
813 $txt = requestdata('htmlstatus') ?? '';
814 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
815 $txt = HTML::toBBCodeVideo($txt);
817 $config = HTMLPurifier_Config::createDefault();
818 $config->set('Cache.DefinitionImpl', null);
820 $purifier = new HTMLPurifier($config);
821 $txt = $purifier->purify($txt);
823 $_REQUEST['body'] = HTML::toBBCode($txt);
826 $_REQUEST['body'] = requestdata('status');
829 $_REQUEST['title'] = requestdata('title');
831 $parent = requestdata('in_reply_to_status_id');
833 // Twidere sends "-1" if it is no reply ...
838 if (ctype_digit($parent)) {
839 $_REQUEST['parent'] = $parent;
841 $_REQUEST['parent_uri'] = $parent;
844 if (requestdata('lat') && requestdata('long')) {
845 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
847 $_REQUEST['profile_uid'] = api_user();
850 // Check for throttling (maximum posts per day, week and month)
851 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
852 if ($throttle_day > 0) {
853 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
855 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
856 $posts_day = Post::count($condition);
858 if ($posts_day > $throttle_day) {
859 logger::info('Daily posting limit reached for user '.api_user());
860 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
861 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));
865 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
866 if ($throttle_week > 0) {
867 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
869 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
870 $posts_week = Post::count($condition);
872 if ($posts_week > $throttle_week) {
873 logger::info('Weekly posting limit reached for user '.api_user());
874 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
875 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));
879 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
880 if ($throttle_month > 0) {
881 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
883 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
884 $posts_month = Post::count($condition);
886 if ($posts_month > $throttle_month) {
887 logger::info('Monthly posting limit reached for user '.api_user());
888 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
889 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));
894 if (requestdata('media_ids')) {
895 $ids = explode(',', requestdata('media_ids') ?? '');
896 } elseif (!empty($_FILES['media'])) {
897 // upload the image if we have one
898 $picture = wall_upload_post($a, false);
899 if (is_array($picture)) {
900 $ids[] = $picture['id'];
908 foreach ($ids as $id) {
909 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
910 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
911 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
912 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
914 if (!empty($media)) {
915 $ressources[] = $media[0]['resource-id'];
916 $phototypes = Images::supportedTypes();
917 $ext = $phototypes[$media[0]['type']];
919 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
920 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
921 'size' => $media[0]['datasize'],
922 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
923 'description' => $media[0]['desc'] ?? '',
924 'width' => $media[0]['width'],
925 'height' => $media[0]['height']];
927 if (count($media) > 1) {
928 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
929 $attachment['preview-width'] = $media[1]['width'];
930 $attachment['preview-height'] = $media[1]['height'];
932 $attachments[] = $attachment;
936 // We have to avoid that the post is rejected because of an empty body
937 if (empty($_REQUEST['body'])) {
938 $_REQUEST['body'] = '[hr]';
942 if (!empty($attachments)) {
943 $_REQUEST['attachments'] = $attachments;
946 // set this so that the item_post() function is quiet and doesn't redirect or emit json
948 $_REQUEST['api_source'] = true;
950 if (empty($_REQUEST['source'])) {
951 $_REQUEST["source"] = api_source();
954 // call out normal post function
955 $item_id = item_post($a);
957 if (!empty($ressources) && !empty($item_id)) {
958 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
959 foreach ($ressources as $ressource) {
960 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
964 // output the post that we just posted.
965 return api_status_show($type, $item_id);
968 /// @TODO move to top of file or somewhere better
969 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
970 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
973 * Uploads an image to Friendica.
976 * @throws BadRequestException
977 * @throws ForbiddenException
978 * @throws ImagickException
979 * @throws InternalServerErrorException
980 * @throws UnauthorizedException
981 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
983 function api_media_upload()
987 if (api_user() === false) {
988 logger::notice('no user');
989 throw new ForbiddenException();
994 if (empty($_FILES['media'])) {
996 throw new BadRequestException("No media.");
999 $media = wall_upload_post($a, false);
1002 throw new InternalServerErrorException();
1006 $returndata["media_id"] = $media["id"];
1007 $returndata["media_id_string"] = (string)$media["id"];
1008 $returndata["size"] = $media["size"];
1009 $returndata["image"] = ["w" => $media["width"],
1010 "h" => $media["height"],
1011 "image_type" => $media["type"],
1012 "friendica_preview_url" => $media["preview"]];
1014 Logger::info('Media uploaded', ['return' => $returndata]);
1016 return ["media" => $returndata];
1019 /// @TODO move to top of file or somewhere better
1020 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1023 * Updates media meta data (picture descriptions)
1025 * @param string $type Return type (atom, rss, xml, json)
1027 * @return array|string
1028 * @throws BadRequestException
1029 * @throws ForbiddenException
1030 * @throws ImagickException
1031 * @throws InternalServerErrorException
1032 * @throws TooManyRequestsException
1033 * @throws UnauthorizedException
1034 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1036 * @todo Compare the corresponding Twitter function for correct return values
1038 function api_media_metadata_create($type)
1042 if (api_user() === false) {
1043 Logger::info('no user');
1044 throw new ForbiddenException();
1049 $postdata = Network::postdata();
1051 if (empty($postdata)) {
1052 throw new BadRequestException("No post data");
1055 $data = json_decode($postdata, true);
1057 throw new BadRequestException("Invalid post data");
1060 if (empty($data['media_id']) || empty($data['alt_text'])) {
1061 throw new BadRequestException("Missing post data values");
1064 if (empty($data['alt_text']['text'])) {
1065 throw new BadRequestException("No alt text.");
1068 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1070 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1071 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1072 if (!DBA::isResult($photo)) {
1073 throw new BadRequestException("Metadata not found.");
1076 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1079 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1082 * @param string $type Return format (atom, rss, xml, json)
1083 * @param int $item_id
1084 * @return array|string
1087 function api_status_show($type, $item_id)
1089 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1093 $item = api_get_item(['id' => $item_id]);
1094 if (!empty($item)) {
1095 $status_info = api_format_item($item, $type);
1098 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1100 return BaseApi::formatData('statuses', $type, ['status' => $status_info]);
1104 * Retrieves the last public status of the provided user info
1106 * @param int $ownerId Public contact Id
1107 * @param int $uid User Id
1111 function api_get_last_status($ownerId, $uid)
1114 'author-id'=> $ownerId,
1116 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1117 'private' => [Item::PUBLIC, Item::UNLISTED]
1120 $item = api_get_item($condition);
1126 * Retrieves a single item record based on the provided condition and converts it for API use.
1128 * @param array $condition Item table condition array
1132 function api_get_item(array $condition)
1134 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1140 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1141 * The author's most recent status will be returned inline.
1143 * @param string $type Return type (atom, rss, xml, json)
1144 * @return array|string
1145 * @throws BadRequestException
1146 * @throws ImagickException
1147 * @throws InternalServerErrorException
1148 * @throws UnauthorizedException
1149 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1151 function api_users_show($type)
1153 $a = Friendica\DI::app();
1155 $user_info = api_get_user();
1157 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1158 if (!empty($item)) {
1159 $user_info['status'] = api_format_item($item, $type);
1162 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1163 unset($user_info['uid']);
1164 unset($user_info['self']);
1166 return BaseApi::formatData('user', $type, ['user' => $user_info]);
1169 /// @TODO move to top of file or somewhere better
1170 api_register_func('api/users/show', 'api_users_show');
1171 api_register_func('api/externalprofile/show', 'api_users_show');
1174 * Search a public user account.
1176 * @param string $type Return type (atom, rss, xml, json)
1178 * @return array|string
1179 * @throws BadRequestException
1180 * @throws ImagickException
1181 * @throws InternalServerErrorException
1182 * @throws UnauthorizedException
1183 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1185 function api_users_search($type)
1191 if (!empty($_GET['q'])) {
1192 $contacts = Contact::selectToArray(
1195 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1203 if (DBA::isResult($contacts)) {
1205 foreach ($contacts as $contact) {
1206 $user_info = api_get_user($contact['id']);
1208 if ($type == 'xml') {
1209 $userlist[$k++ . ':user'] = $user_info;
1211 $userlist[] = $user_info;
1214 $userlist = ['users' => $userlist];
1216 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1219 throw new BadRequestException('No search term specified.');
1222 return BaseApi::formatData('users', $type, $userlist);
1225 /// @TODO move to top of file or somewhere better
1226 api_register_func('api/users/search', 'api_users_search');
1229 * Return user objects
1231 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1233 * @param string $type Return format: json or xml
1235 * @return array|string
1236 * @throws BadRequestException
1237 * @throws ImagickException
1238 * @throws InternalServerErrorException
1239 * @throws NotFoundException if the results are empty.
1240 * @throws UnauthorizedException
1242 function api_users_lookup($type)
1246 if (!empty($_REQUEST['user_id'])) {
1247 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1249 $users[] = api_get_user($id);
1254 if (empty($users)) {
1255 throw new NotFoundException;
1258 return BaseApi::formatData("users", $type, ['users' => $users]);
1261 /// @TODO move to top of file or somewhere better
1262 api_register_func('api/users/lookup', 'api_users_lookup', true);
1265 * Returns statuses that match a specified query.
1267 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1269 * @param string $type Return format: json, xml, atom, rss
1271 * @return array|string
1272 * @throws BadRequestException if the "q" parameter is missing.
1273 * @throws ForbiddenException
1274 * @throws ImagickException
1275 * @throws InternalServerErrorException
1276 * @throws UnauthorizedException
1278 function api_search($type)
1281 $user_info = api_get_user();
1283 if (api_user() === false || $user_info === false) {
1284 throw new ForbiddenException();
1287 if (empty($_REQUEST['q'])) {
1288 throw new BadRequestException('q parameter is required.');
1291 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1294 $data['status'] = [];
1296 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1297 if (!empty($_REQUEST['rpp'])) {
1298 $count = $_REQUEST['rpp'];
1299 } elseif (!empty($_REQUEST['count'])) {
1300 $count = $_REQUEST['count'];
1303 $since_id = $_REQUEST['since_id'] ?? 0;
1304 $max_id = $_REQUEST['max_id'] ?? 0;
1305 $page = $_REQUEST['page'] ?? 1;
1307 $start = max(0, ($page - 1) * $count);
1309 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1310 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1311 $searchTerm = $matches[1];
1312 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1313 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1315 while ($tag = DBA::fetch($tags)) {
1316 $uriids[] = $tag['uri-id'];
1320 if (empty($uriids)) {
1321 return BaseApi::formatData('statuses', $type, $data);
1324 $condition = ['uri-id' => $uriids];
1325 if ($exclude_replies) {
1326 $condition['gravity'] = GRAVITY_PARENT;
1329 $params['group_by'] = ['uri-id'];
1331 $condition = ["`id` > ?
1332 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1333 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1334 AND `body` LIKE CONCAT('%',?,'%')",
1335 $since_id, api_user(), $_REQUEST['q']];
1337 $condition[0] .= ' AND `id` <= ?';
1338 $condition[] = $max_id;
1344 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1345 $id = Item::fetchByLink($searchTerm, api_user());
1348 $id = Item::fetchByLink($searchTerm);
1352 $statuses = Post::select([], ['id' => $id]);
1356 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1358 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1360 bindComments($data['status']);
1362 return BaseApi::formatData('statuses', $type, $data);
1365 /// @TODO move to top of file or somewhere better
1366 api_register_func('api/search/tweets', 'api_search', true);
1367 api_register_func('api/search', 'api_search', true);
1370 * Returns the most recent statuses posted by the user and the users they follow.
1372 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1374 * @param string $type Return type (atom, rss, xml, json)
1376 * @return array|string
1377 * @throws BadRequestException
1378 * @throws ForbiddenException
1379 * @throws ImagickException
1380 * @throws InternalServerErrorException
1381 * @throws UnauthorizedException
1382 * @todo Optional parameters
1383 * @todo Add reply info
1385 function api_statuses_home_timeline($type)
1388 $user_info = api_get_user();
1390 if (api_user() === false || $user_info === false) {
1391 throw new ForbiddenException();
1394 unset($_REQUEST["user_id"]);
1395 unset($_GET["user_id"]);
1397 unset($_REQUEST["screen_name"]);
1398 unset($_GET["screen_name"]);
1400 // get last network messages
1403 $count = $_REQUEST['count'] ?? 20;
1404 $page = $_REQUEST['page']?? 0;
1405 $since_id = $_REQUEST['since_id'] ?? 0;
1406 $max_id = $_REQUEST['max_id'] ?? 0;
1407 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1408 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1410 $start = max(0, ($page - 1) * $count);
1412 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1413 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1416 $condition[0] .= " AND `id` <= ?";
1417 $condition[] = $max_id;
1419 if ($exclude_replies) {
1420 $condition[0] .= ' AND `gravity` = ?';
1421 $condition[] = GRAVITY_PARENT;
1423 if ($conversation_id > 0) {
1424 $condition[0] .= " AND `parent` = ?";
1425 $condition[] = $conversation_id;
1428 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1429 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1431 $items = Post::toArray($statuses);
1433 $ret = api_format_items($items, $user_info, false, $type);
1435 // Set all posts from the query above to seen
1437 foreach ($items as $item) {
1438 $idarray[] = intval($item["id"]);
1441 if (!empty($idarray)) {
1442 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1444 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1450 $data = ['status' => $ret];
1455 $data = api_rss_extra($a, $data, $user_info);
1459 return BaseApi::formatData("statuses", $type, $data);
1463 /// @TODO move to top of file or somewhere better
1464 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1465 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1468 * Returns the most recent statuses from public users.
1470 * @param string $type Return type (atom, rss, xml, json)
1472 * @return array|string
1473 * @throws BadRequestException
1474 * @throws ForbiddenException
1475 * @throws ImagickException
1476 * @throws InternalServerErrorException
1477 * @throws UnauthorizedException
1479 function api_statuses_public_timeline($type)
1482 $user_info = api_get_user();
1484 if (api_user() === false || $user_info === false) {
1485 throw new ForbiddenException();
1488 // get last network messages
1491 $count = $_REQUEST['count'] ?? 20;
1492 $page = $_REQUEST['page'] ?? 1;
1493 $since_id = $_REQUEST['since_id'] ?? 0;
1494 $max_id = $_REQUEST['max_id'] ?? 0;
1495 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1496 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1498 $start = max(0, ($page - 1) * $count);
1500 if ($exclude_replies && !$conversation_id) {
1501 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1502 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1505 $condition[0] .= " AND `id` <= ?";
1506 $condition[] = $max_id;
1509 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1510 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1512 $r = Post::toArray($statuses);
1514 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1515 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1518 $condition[0] .= " AND `id` <= ?";
1519 $condition[] = $max_id;
1521 if ($conversation_id > 0) {
1522 $condition[0] .= " AND `parent` = ?";
1523 $condition[] = $conversation_id;
1526 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1527 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1529 $r = Post::toArray($statuses);
1532 $ret = api_format_items($r, $user_info, false, $type);
1536 $data = ['status' => $ret];
1541 $data = api_rss_extra($a, $data, $user_info);
1545 return BaseApi::formatData("statuses", $type, $data);
1548 /// @TODO move to top of file or somewhere better
1549 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1552 * Returns the most recent statuses posted by users this node knows about.
1554 * @param string $type Return format: json, xml, atom, rss
1555 * @return array|string
1556 * @throws BadRequestException
1557 * @throws ForbiddenException
1558 * @throws ImagickException
1559 * @throws InternalServerErrorException
1560 * @throws UnauthorizedException
1562 function api_statuses_networkpublic_timeline($type)
1565 $user_info = api_get_user();
1567 if (api_user() === false || $user_info === false) {
1568 throw new ForbiddenException();
1571 $since_id = $_REQUEST['since_id'] ?? 0;
1572 $max_id = $_REQUEST['max_id'] ?? 0;
1575 $count = $_REQUEST['count'] ?? 20;
1576 $page = $_REQUEST['page'] ?? 1;
1578 $start = max(0, ($page - 1) * $count);
1580 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1581 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1584 $condition[0] .= " AND `id` <= ?";
1585 $condition[] = $max_id;
1588 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1589 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1591 $ret = api_format_items($statuses, $user_info, false, $type);
1595 $data = ['status' => $ret];
1600 $data = api_rss_extra($a, $data, $user_info);
1604 return BaseApi::formatData("statuses", $type, $data);
1607 /// @TODO move to top of file or somewhere better
1608 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1611 * Returns a single status.
1613 * @param string $type Return type (atom, rss, xml, json)
1615 * @return array|string
1616 * @throws BadRequestException
1617 * @throws ForbiddenException
1618 * @throws ImagickException
1619 * @throws InternalServerErrorException
1620 * @throws UnauthorizedException
1621 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1623 function api_statuses_show($type)
1626 $user_info = api_get_user();
1628 if (api_user() === false || $user_info === false) {
1629 throw new ForbiddenException();
1633 $id = intval(DI::args()->getArgv()[3] ?? 0);
1636 $id = intval($_REQUEST['id'] ?? 0);
1641 $id = intval(DI::args()->getArgv()[4] ?? 0);
1644 logger::notice('API: api_statuses_show: ' . $id);
1646 $conversation = !empty($_REQUEST['conversation']);
1648 // try to fetch the item for the local user - or the public item, if there is no local one
1649 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1650 if (!DBA::isResult($uri_item)) {
1651 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1654 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1655 if (!DBA::isResult($item)) {
1656 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1661 if ($conversation) {
1662 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1663 $params = ['order' => ['id' => true]];
1665 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1669 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1671 /// @TODO How about copying this to above methods which don't check $r ?
1672 if (!DBA::isResult($statuses)) {
1673 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1676 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1678 if ($conversation) {
1679 $data = ['status' => $ret];
1680 return BaseApi::formatData("statuses", $type, $data);
1682 $data = ['status' => $ret[0]];
1683 return BaseApi::formatData("status", $type, $data);
1687 /// @TODO move to top of file or somewhere better
1688 api_register_func('api/statuses/show', 'api_statuses_show', true);
1692 * @param string $type Return type (atom, rss, xml, json)
1694 * @return array|string
1695 * @throws BadRequestException
1696 * @throws ForbiddenException
1697 * @throws ImagickException
1698 * @throws InternalServerErrorException
1699 * @throws UnauthorizedException
1700 * @todo nothing to say?
1702 function api_conversation_show($type)
1705 $user_info = api_get_user();
1707 if (api_user() === false || $user_info === false) {
1708 throw new ForbiddenException();
1712 $id = intval(DI::args()->getArgv()[3] ?? 0);
1713 $since_id = intval($_REQUEST['since_id'] ?? 0);
1714 $max_id = intval($_REQUEST['max_id'] ?? 0);
1715 $count = intval($_REQUEST['count'] ?? 20);
1716 $page = intval($_REQUEST['page'] ?? 1);
1718 $start = max(0, ($page - 1) * $count);
1721 $id = intval($_REQUEST['id'] ?? 0);
1726 $id = intval(DI::args()->getArgv()[4] ?? 0);
1729 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1731 // try to fetch the item for the local user - or the public item, if there is no local one
1732 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1733 if (!DBA::isResult($item)) {
1734 throw new BadRequestException("There is no status with the id $id.");
1737 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1738 if (!DBA::isResult($parent)) {
1739 throw new BadRequestException("There is no status with this id.");
1742 $id = $parent['id'];
1744 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1745 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1748 $condition[0] .= " AND `id` <= ?";
1749 $condition[] = $max_id;
1752 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1753 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1755 if (!DBA::isResult($statuses)) {
1756 throw new BadRequestException("There is no status with id $id.");
1759 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1761 $data = ['status' => $ret];
1762 return BaseApi::formatData("statuses", $type, $data);
1765 /// @TODO move to top of file or somewhere better
1766 api_register_func('api/conversation/show', 'api_conversation_show', true);
1767 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1772 * @param string $type Return type (atom, rss, xml, json)
1774 * @return array|string
1775 * @throws BadRequestException
1776 * @throws ForbiddenException
1777 * @throws ImagickException
1778 * @throws InternalServerErrorException
1779 * @throws UnauthorizedException
1780 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1782 function api_statuses_repeat($type)
1788 if (api_user() === false) {
1789 throw new ForbiddenException();
1795 $id = intval(DI::args()->getArgv()[3] ?? 0);
1798 $id = intval($_REQUEST['id'] ?? 0);
1803 $id = intval(DI::args()->getArgv()[4] ?? 0);
1806 logger::notice('API: api_statuses_repeat: ' . $id);
1808 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1809 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1811 if (DBA::isResult($item) && !empty($item['body'])) {
1812 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1813 if (!Item::performActivity($id, 'announce', local_user())) {
1814 throw new InternalServerErrorException();
1819 if (strpos($item['body'], "[/share]") !== false) {
1820 $pos = strpos($item['body'], "[share");
1821 $post = substr($item['body'], $pos);
1823 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1825 if (!empty($item['title'])) {
1826 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1829 $post .= $item['body'];
1830 $post .= "[/share]";
1832 $_REQUEST['body'] = $post;
1833 $_REQUEST['profile_uid'] = api_user();
1834 $_REQUEST['api_source'] = true;
1836 if (empty($_REQUEST['source'])) {
1837 $_REQUEST["source"] = api_source();
1840 $item_id = item_post($a);
1843 throw new ForbiddenException();
1846 // output the post that we just posted.
1848 return api_status_show($type, $item_id);
1851 /// @TODO move to top of file or somewhere better
1852 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1855 * Destroys a specific status.
1857 * @param string $type Return type (atom, rss, xml, json)
1859 * @return array|string
1860 * @throws BadRequestException
1861 * @throws ForbiddenException
1862 * @throws ImagickException
1863 * @throws InternalServerErrorException
1864 * @throws UnauthorizedException
1865 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1867 function api_statuses_destroy($type)
1871 if (api_user() === false) {
1872 throw new ForbiddenException();
1878 $id = intval(DI::args()->getArgv()[3] ?? 0);
1881 $id = intval($_REQUEST['id'] ?? 0);
1886 $id = intval(DI::args()->getArgv()[4] ?? 0);
1889 logger::notice('API: api_statuses_destroy: ' . $id);
1891 $ret = api_statuses_show($type);
1893 Item::deleteForUser(['id' => $id], api_user());
1898 /// @TODO move to top of file or somewhere better
1899 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1902 * Returns the most recent mentions.
1904 * @param string $type Return type (atom, rss, xml, json)
1906 * @return array|string
1907 * @throws BadRequestException
1908 * @throws ForbiddenException
1909 * @throws ImagickException
1910 * @throws InternalServerErrorException
1911 * @throws UnauthorizedException
1912 * @see http://developer.twitter.com/doc/get/statuses/mentions
1914 function api_statuses_mentions($type)
1917 $user_info = api_get_user();
1919 if (api_user() === false || $user_info === false) {
1920 throw new ForbiddenException();
1923 unset($_REQUEST["user_id"]);
1924 unset($_GET["user_id"]);
1926 unset($_REQUEST["screen_name"]);
1927 unset($_GET["screen_name"]);
1929 // get last network messages
1932 $since_id = intval($_REQUEST['since_id'] ?? 0);
1933 $max_id = intval($_REQUEST['max_id'] ?? 0);
1934 $count = intval($_REQUEST['count'] ?? 20);
1935 $page = intval($_REQUEST['page'] ?? 1);
1937 $start = max(0, ($page - 1) * $count);
1939 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1940 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1941 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1944 GRAVITY_PARENT, GRAVITY_COMMENT,
1946 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1947 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1948 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1949 api_user(), $since_id,
1953 $query .= " AND `id` <= ?";
1954 $condition[] = $max_id;
1957 array_unshift($condition, $query);
1959 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1960 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1962 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1964 $data = ['status' => $ret];
1969 $data = api_rss_extra($a, $data, $user_info);
1973 return BaseApi::formatData("statuses", $type, $data);
1976 /// @TODO move to top of file or somewhere better
1977 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1978 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1981 * Returns the most recent statuses posted by the user.
1983 * @param string $type Either "json" or "xml"
1984 * @return string|array
1985 * @throws BadRequestException
1986 * @throws ForbiddenException
1987 * @throws ImagickException
1988 * @throws InternalServerErrorException
1989 * @throws UnauthorizedException
1990 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1992 function api_statuses_user_timeline($type)
1995 $user_info = api_get_user();
1997 if (api_user() === false || $user_info === false) {
1998 throw new ForbiddenException();
2001 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2003 $since_id = $_REQUEST['since_id'] ?? 0;
2004 $max_id = $_REQUEST['max_id'] ?? 0;
2005 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2006 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2009 $count = $_REQUEST['count'] ?? 20;
2010 $page = $_REQUEST['page'] ?? 1;
2012 $start = max(0, ($page - 1) * $count);
2014 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2015 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2017 if ($user_info['self'] == 1) {
2018 $condition[0] .= ' AND `wall` ';
2021 if ($exclude_replies) {
2022 $condition[0] .= ' AND `gravity` = ?';
2023 $condition[] = GRAVITY_PARENT;
2026 if ($conversation_id > 0) {
2027 $condition[0] .= " AND `parent` = ?";
2028 $condition[] = $conversation_id;
2032 $condition[0] .= " AND `id` <= ?";
2033 $condition[] = $max_id;
2035 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2036 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2038 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2042 $data = ['status' => $ret];
2047 $data = api_rss_extra($a, $data, $user_info);
2051 return BaseApi::formatData("statuses", $type, $data);
2054 /// @TODO move to top of file or somewhere better
2055 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2058 * Star/unstar an item.
2059 * param: id : id of the item
2061 * @param string $type Return type (atom, rss, xml, json)
2063 * @return array|string
2064 * @throws BadRequestException
2065 * @throws ForbiddenException
2066 * @throws ImagickException
2067 * @throws InternalServerErrorException
2068 * @throws UnauthorizedException
2069 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2071 function api_favorites_create_destroy($type)
2075 if (api_user() === false) {
2076 throw new ForbiddenException();
2079 // for versioned api.
2080 /// @TODO We need a better global soluton
2081 $action_argv_id = 2;
2082 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2083 $action_argv_id = 3;
2086 if (DI::args()->getArgc() <= $action_argv_id) {
2087 throw new BadRequestException("Invalid request.");
2089 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2090 if (DI::args()->getArgc() == $action_argv_id + 2) {
2091 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2093 $itemid = intval($_REQUEST['id'] ?? 0);
2096 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2098 if (!DBA::isResult($item)) {
2099 throw new BadRequestException("Invalid item.");
2104 $item['starred'] = 1;
2107 $item['starred'] = 0;
2110 throw new BadRequestException("Invalid action ".$action);
2113 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2116 throw new InternalServerErrorException("DB error");
2120 $user_info = api_get_user();
2121 $rets = api_format_items([$item], $user_info, false, $type);
2124 $data = ['status' => $ret];
2129 $data = api_rss_extra($a, $data, $user_info);
2133 return BaseApi::formatData("status", $type, $data);
2136 /// @TODO move to top of file or somewhere better
2137 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2138 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2141 * Returns the most recent favorite statuses.
2143 * @param string $type Return type (atom, rss, xml, json)
2145 * @return string|array
2146 * @throws BadRequestException
2147 * @throws ForbiddenException
2148 * @throws ImagickException
2149 * @throws InternalServerErrorException
2150 * @throws UnauthorizedException
2152 function api_favorites($type)
2157 $user_info = api_get_user();
2159 if (api_user() === false || $user_info === false) {
2160 throw new ForbiddenException();
2165 // in friendica starred item are private
2166 // return favorites only for self
2167 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2169 if ($user_info['self'] == 0) {
2173 $since_id = $_REQUEST['since_id'] ?? 0;
2174 $max_id = $_REQUEST['max_id'] ?? 0;
2175 $count = $_GET['count'] ?? 20;
2176 $page = $_REQUEST['page'] ?? 1;
2178 $start = max(0, ($page - 1) * $count);
2180 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2181 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2183 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2186 $condition[0] .= " AND `id` <= ?";
2187 $condition[] = $max_id;
2190 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2192 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2197 $data = ['status' => $ret];
2202 $data = api_rss_extra($a, $data, $user_info);
2206 return BaseApi::formatData("statuses", $type, $data);
2209 /// @TODO move to top of file or somewhere better
2210 api_register_func('api/favorites', 'api_favorites', true);
2214 * @param array $item
2215 * @param array $recipient
2216 * @param array $sender
2219 * @throws InternalServerErrorException
2221 function api_format_messages($item, $recipient, $sender)
2223 // standard meta information
2225 'id' => $item['id'],
2226 'sender_id' => $sender['id'],
2228 'recipient_id' => $recipient['id'],
2229 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2230 'sender_screen_name' => $sender['screen_name'],
2231 'recipient_screen_name' => $recipient['screen_name'],
2232 'sender' => $sender,
2233 'recipient' => $recipient,
2235 'friendica_seen' => $item['seen'] ?? 0,
2236 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2239 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2240 if (isset($ret['sender']['uid'])) {
2241 unset($ret['sender']['uid']);
2243 if (isset($ret['sender']['self'])) {
2244 unset($ret['sender']['self']);
2246 if (isset($ret['recipient']['uid'])) {
2247 unset($ret['recipient']['uid']);
2249 if (isset($ret['recipient']['self'])) {
2250 unset($ret['recipient']['self']);
2253 //don't send title to regular StatusNET requests to avoid confusing these apps
2254 if (!empty($_GET['getText'])) {
2255 $ret['title'] = $item['title'];
2256 if ($_GET['getText'] == 'html') {
2257 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2258 } elseif ($_GET['getText'] == 'plain') {
2259 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2262 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2264 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2265 unset($ret['sender']);
2266 unset($ret['recipient']);
2274 * @param array $item
2277 * @throws InternalServerErrorException
2279 function api_convert_item($item)
2281 $body = api_add_attachments_to_body($item);
2283 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2285 // Add pictures to the attachment array and remove them from the body
2286 $attachments = api_get_attachments($body, $item['uri-id']);
2288 // Workaround for ostatus messages where the title is identically to the body
2289 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2290 $statusbody = trim(HTML::toPlaintext($html, 0));
2292 // handle data: images
2293 $statusbody = api_format_items_embeded_images($item, $statusbody);
2295 $statustitle = trim($item['title']);
2297 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2298 $statustext = trim($statusbody);
2300 $statustext = trim($statustitle."\n\n".$statusbody);
2303 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2304 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2307 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2309 // Workaround for clients with limited HTML parser functionality
2310 $search = ["<br>", "<blockquote>", "</blockquote>",
2311 "<h1>", "</h1>", "<h2>", "</h2>",
2312 "<h3>", "</h3>", "<h4>", "</h4>",
2313 "<h5>", "</h5>", "<h6>", "</h6>"];
2314 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2315 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2316 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2317 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2318 $statushtml = str_replace($search, $replace, $statushtml);
2320 if ($item['title'] != "") {
2321 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2325 $oldtext = $statushtml;
2326 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2327 } while ($oldtext != $statushtml);
2329 if (substr($statushtml, 0, 4) == '<br>') {
2330 $statushtml = substr($statushtml, 4);
2333 if (substr($statushtml, 0, -4) == '<br>') {
2334 $statushtml = substr($statushtml, -4);
2337 // feeds without body should contain the link
2338 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2339 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2343 "text" => $statustext,
2344 "html" => $statushtml,
2345 "attachments" => $attachments,
2346 "entities" => $entities
2351 * Add media attachments to the body
2353 * @param array $item
2354 * @return string body with added media
2356 function api_add_attachments_to_body(array $item)
2358 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2360 if (strpos($body, '[/img]') !== false) {
2364 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2365 if (!empty($media['preview'])) {
2366 $description = $media['description'] ?: $media['name'];
2367 if (!empty($description)) {
2368 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2370 $body .= "\n[img]" . $media['preview'] .'[/img]';
2380 * @param string $body
2384 * @throws InternalServerErrorException
2386 function api_get_attachments(&$body, $uriid)
2388 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2389 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2391 $URLSearchString = "^\[\]";
2392 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2396 // Remove all embedded pictures, since they are added as attachments
2397 foreach ($images[0] as $orig) {
2398 $body = str_replace($orig, '', $body);
2403 foreach ($images[1] as $image) {
2404 $imagedata = Images::getInfoFromURLCached($image);
2407 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2411 return $attachments;
2416 * @param string $text
2417 * @param string $bbcode
2420 * @throws InternalServerErrorException
2421 * @todo Links at the first character of the post
2423 function api_get_entitities(&$text, $bbcode, $uriid)
2425 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2427 if ($include_entities != "true") {
2428 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2430 foreach ($images[1] as $image) {
2431 $replace = Post\Link::getByLink($uriid, $image);
2432 $text = str_replace($image, $replace, $text);
2437 $bbcode = BBCode::cleanPictureLinks($bbcode);
2439 // Change pure links in text to bbcode uris
2440 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2443 $entities["hashtags"] = [];
2444 $entities["symbols"] = [];
2445 $entities["urls"] = [];
2446 $entities["user_mentions"] = [];
2448 $URLSearchString = "^\[\]";
2450 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2452 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2453 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2455 $bbcode = preg_replace(
2456 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2457 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2460 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2462 $bbcode = preg_replace(
2463 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2464 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2467 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2469 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2471 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2474 foreach ($urls[1] as $id => $url) {
2475 $start = iconv_strpos($text, $url, 0, "UTF-8");
2476 if (!($start === false)) {
2477 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2481 ksort($ordered_urls);
2485 foreach ($ordered_urls as $url) {
2486 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2487 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2489 $display_url = $url["title"];
2491 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2492 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2494 if (strlen($display_url) > 26) {
2495 $display_url = substr($display_url, 0, 25)."…";
2499 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2500 if (!($start === false)) {
2501 $entities["urls"][] = ["url" => $url["url"],
2502 "expanded_url" => $url["url"],
2503 "display_url" => $display_url,
2504 "indices" => [$start, $start+strlen($url["url"])]];
2505 $offset = $start + 1;
2509 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2510 $ordered_images = [];
2511 foreach ($images as $image) {
2512 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2513 if (!($start === false)) {
2514 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2518 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2519 foreach ($images[1] as $image) {
2520 $start = iconv_strpos($text, $image, 0, "UTF-8");
2521 if (!($start === false)) {
2522 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2528 foreach ($ordered_images as $image) {
2529 $url = $image['url'];
2530 $ext_alt_text = $image['alt'];
2532 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2533 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2535 if (strlen($display_url) > 26) {
2536 $display_url = substr($display_url, 0, 25)."…";
2539 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2540 if (!($start === false)) {
2541 $image = Images::getInfoFromURLCached($url);
2543 $media_url = Post\Link::getByLink($uriid, $url);
2544 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2546 $entities["media"][] = [
2548 "id_str" => (string) ($start + 1),
2549 "indices" => [$start, $start+strlen($url)],
2550 "media_url" => Strings::normaliseLink($media_url),
2551 "media_url_https" => $media_url,
2553 "display_url" => $display_url,
2554 "expanded_url" => $url,
2555 "ext_alt_text" => $ext_alt_text,
2559 $offset = $start + 1;
2568 * @param array $item
2569 * @param string $text
2573 function api_format_items_embeded_images($item, $text)
2575 $text = preg_replace_callback(
2576 '|data:image/([^;]+)[^=]+=*|m',
2577 function () use ($item) {
2578 return DI::baseUrl() . '/display/' . $item['guid'];
2586 * return <a href='url'>name</a> as array
2588 * @param string $txt text
2593 function api_contactlink_to_array($txt)
2596 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2597 if ($r && count($match)==3) {
2599 'name' => $match[2],
2613 * return likes, dislikes and attend status for item
2615 * @param array $item array
2616 * @param string $type Return type (atom, rss, xml, json)
2619 * likes => int count,
2620 * dislikes => int count
2621 * @throws BadRequestException
2622 * @throws ImagickException
2623 * @throws InternalServerErrorException
2624 * @throws UnauthorizedException
2626 function api_format_items_activities($item, $type = "json")
2635 'attendmaybe' => [],
2639 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2640 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2642 while ($parent_item = Post::fetch($ret)) {
2643 // not used as result should be structured like other user data
2644 //builtin_activity_puller($i, $activities);
2646 // get user data and add it to the array of the activity
2647 $user = api_get_user($parent_item['author-id']);
2648 switch ($parent_item['verb']) {
2649 case Activity::LIKE:
2650 $activities['like'][] = $user;
2652 case Activity::DISLIKE:
2653 $activities['dislike'][] = $user;
2655 case Activity::ATTEND:
2656 $activities['attendyes'][] = $user;
2658 case Activity::ATTENDNO:
2659 $activities['attendno'][] = $user;
2661 case Activity::ATTENDMAYBE:
2662 $activities['attendmaybe'][] = $user;
2664 case Activity::ANNOUNCE:
2665 $activities['announce'][] = $user;
2674 if ($type == "xml") {
2675 $xml_activities = [];
2676 foreach ($activities as $k => $v) {
2677 // change xml element from "like" to "friendica:like"
2678 $xml_activities["friendica:".$k] = $v;
2679 // add user data into xml output
2681 foreach ($v as $user) {
2682 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2685 $activities = $xml_activities;
2692 * format items to be returned by api
2694 * @param array $items array of items
2695 * @param array $user_info
2696 * @param bool $filter_user filter items by $user_info
2697 * @param string $type Return type (atom, rss, xml, json)
2699 * @throws BadRequestException
2700 * @throws ImagickException
2701 * @throws InternalServerErrorException
2702 * @throws UnauthorizedException
2704 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2706 $a = Friendica\DI::app();
2710 if (empty($items)) {
2714 foreach ((array)$items as $item) {
2715 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2717 // Look if the posts are matching if they should be filtered by user id
2718 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2722 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2731 * @param array $item Item record
2732 * @param string $type Return format (atom, rss, xml, json)
2733 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2734 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2735 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2736 * @return array API-formatted status
2737 * @throws BadRequestException
2738 * @throws ImagickException
2739 * @throws InternalServerErrorException
2740 * @throws UnauthorizedException
2742 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2744 $a = Friendica\DI::app();
2746 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2747 list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item);
2750 DI::contentItem()->localize($item);
2752 $in_reply_to = api_in_reply_to($item);
2754 $converted = api_convert_item($item);
2756 if ($type == "xml") {
2757 $geo = "georss:point";
2763 'text' => $converted["text"],
2764 'truncated' => false,
2765 'created_at'=> api_date($item['created']),
2766 'in_reply_to_status_id' => $in_reply_to['status_id'],
2767 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2768 'source' => (($item['app']) ? $item['app'] : 'web'),
2769 'id' => intval($item['id']),
2770 'id_str' => (string) intval($item['id']),
2771 'in_reply_to_user_id' => $in_reply_to['user_id'],
2772 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2773 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2775 'favorited' => $item['starred'] ? true : false,
2776 'user' => $status_user,
2777 'friendica_author' => $author_user,
2778 'friendica_owner' => $owner_user,
2779 'friendica_private' => $item['private'] == Item::PRIVATE,
2780 //'entities' => NULL,
2781 'statusnet_html' => $converted["html"],
2782 'statusnet_conversation_id' => $item['parent'],
2783 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2784 'friendica_activities' => api_format_items_activities($item, $type),
2785 'friendica_title' => $item['title'],
2786 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2789 if (count($converted["attachments"]) > 0) {
2790 $status["attachments"] = $converted["attachments"];
2793 if (count($converted["entities"]) > 0) {
2794 $status["entities"] = $converted["entities"];
2797 if ($status["source"] == 'web') {
2798 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2799 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2800 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2803 $retweeted_item = [];
2806 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2807 $announce = api_get_announce($item);
2808 if (!empty($announce)) {
2809 $retweeted_item = $item;
2811 $status['friendica_owner'] = api_get_user($announce['author-id']);
2815 if (!empty($quoted_item)) {
2816 if ($quoted_item['id'] != $item['id']) {
2817 $quoted_status = api_format_item($quoted_item);
2818 /// @todo Only remove the attachments that are also contained in the quotes status
2819 unset($status['attachments']);
2820 unset($status['entities']);
2822 $conv_quoted = api_convert_item($quoted_item);
2823 $quoted_status = $status;
2824 unset($quoted_status['attachments']);
2825 unset($quoted_status['entities']);
2826 unset($quoted_status['statusnet_conversation_id']);
2827 $quoted_status['text'] = $conv_quoted['text'];
2828 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2830 $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
2831 } catch (BadRequestException $e) {
2832 // user not found. should be found?
2833 /// @todo check if the user should be always found
2834 $quoted_status["user"] = [];
2837 unset($quoted_status['friendica_author']);
2838 unset($quoted_status['friendica_owner']);
2839 unset($quoted_status['friendica_activities']);
2840 unset($quoted_status['friendica_private']);
2843 if (!empty($retweeted_item)) {
2844 $retweeted_status = $status;
2845 unset($retweeted_status['friendica_author']);
2846 unset($retweeted_status['friendica_owner']);
2847 unset($retweeted_status['friendica_activities']);
2848 unset($retweeted_status['friendica_private']);
2849 unset($retweeted_status['statusnet_conversation_id']);
2850 $status['user'] = $status['friendica_owner'];
2852 $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
2853 } catch (BadRequestException $e) {
2854 // user not found. should be found?
2855 /// @todo check if the user should be always found
2856 $retweeted_status["user"] = [];
2859 $rt_converted = api_convert_item($retweeted_item);
2861 $retweeted_status['text'] = $rt_converted["text"];
2862 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2863 $retweeted_status['friendica_html'] = $rt_converted["html"];
2864 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2866 if (!empty($quoted_status)) {
2867 $retweeted_status['quoted_status'] = $quoted_status;
2870 $status['friendica_author'] = $retweeted_status['user'];
2871 $status['retweeted_status'] = $retweeted_status;
2872 } elseif (!empty($quoted_status)) {
2873 $root_status = api_convert_item($item);
2875 $status['text'] = $root_status["text"];
2876 $status['statusnet_html'] = $root_status["html"];
2877 $status['quoted_status'] = $quoted_status;
2880 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2881 unset($status["user"]["uid"]);
2882 unset($status["user"]["self"]);
2884 if ($item["coord"] != "") {
2885 $coords = explode(' ', $item["coord"]);
2886 if (count($coords) == 2) {
2887 if ($type == "json") {
2888 $status["geo"] = ['type' => 'Point',
2889 'coordinates' => [(float) $coords[0],
2890 (float) $coords[1]]];
2891 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2892 $status["georss:point"] = $item["coord"];
2901 * Returns all lists the user subscribes to.
2903 * @param string $type Return type (atom, rss, xml, json)
2905 * @return array|string
2906 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2908 function api_lists_list($type)
2911 /// @TODO $ret is not filled here?
2912 return BaseApi::formatData('lists', $type, ["lists_list" => $ret]);
2915 /// @TODO move to top of file or somewhere better
2916 api_register_func('api/lists/list', 'api_lists_list', true);
2917 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2920 * Returns all groups the user owns.
2922 * @param string $type Return type (atom, rss, xml, json)
2924 * @return array|string
2925 * @throws BadRequestException
2926 * @throws ForbiddenException
2927 * @throws ImagickException
2928 * @throws InternalServerErrorException
2929 * @throws UnauthorizedException
2930 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2932 function api_lists_ownerships($type)
2936 if (api_user() === false) {
2937 throw new ForbiddenException();
2941 $user_info = api_get_user();
2942 $uid = $user_info['uid'];
2944 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2946 // loop through all groups
2948 foreach ($groups as $group) {
2949 if ($group['visible']) {
2955 'name' => $group['name'],
2956 'id' => intval($group['id']),
2957 'id_str' => (string) $group['id'],
2958 'user' => $user_info,
2962 return BaseApi::formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2965 /// @TODO move to top of file or somewhere better
2966 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2969 * Returns recent statuses from users in the specified group.
2971 * @param string $type Return type (atom, rss, xml, json)
2973 * @return array|string
2974 * @throws BadRequestException
2975 * @throws ForbiddenException
2976 * @throws ImagickException
2977 * @throws InternalServerErrorException
2978 * @throws UnauthorizedException
2979 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2981 function api_lists_statuses($type)
2985 $user_info = api_get_user();
2986 if (api_user() === false || $user_info === false) {
2987 throw new ForbiddenException();
2990 unset($_REQUEST["user_id"]);
2991 unset($_GET["user_id"]);
2993 unset($_REQUEST["screen_name"]);
2994 unset($_GET["screen_name"]);
2996 if (empty($_REQUEST['list_id'])) {
2997 throw new BadRequestException('list_id not specified');
3001 $count = $_REQUEST['count'] ?? 20;
3002 $page = $_REQUEST['page'] ?? 1;
3003 $since_id = $_REQUEST['since_id'] ?? 0;
3004 $max_id = $_REQUEST['max_id'] ?? 0;
3005 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3006 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3008 $start = max(0, ($page - 1) * $count);
3010 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3011 $gids = array_column($groups, 'contact-id');
3012 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3013 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3016 $condition[0] .= " AND `id` <= ?";
3017 $condition[] = $max_id;
3019 if ($exclude_replies > 0) {
3020 $condition[0] .= ' AND `gravity` = ?';
3021 $condition[] = GRAVITY_PARENT;
3023 if ($conversation_id > 0) {
3024 $condition[0] .= " AND `parent` = ?";
3025 $condition[] = $conversation_id;
3028 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3029 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3031 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3033 $data = ['status' => $items];
3038 $data = api_rss_extra($a, $data, $user_info);
3042 return BaseApi::formatData("statuses", $type, $data);
3045 /// @TODO move to top of file or somewhere better
3046 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3049 * Returns either the friends of the follower list
3051 * Considers friends and followers lists to be private and won't return
3052 * anything if any user_id parameter is passed.
3054 * @param string $qtype Either "friends" or "followers"
3055 * @return boolean|array
3056 * @throws BadRequestException
3057 * @throws ForbiddenException
3058 * @throws ImagickException
3059 * @throws InternalServerErrorException
3060 * @throws UnauthorizedException
3062 function api_statuses_f($qtype)
3066 if (api_user() === false) {
3067 throw new ForbiddenException();
3071 $count = $_GET['count'] ?? 20;
3072 $page = $_GET['page'] ?? 1;
3074 $start = max(0, ($page - 1) * $count);
3076 $user_info = api_get_user();
3078 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3079 /* this is to stop Hotot to load friends multiple times
3080 * I'm not sure if I'm missing return something or
3081 * is a bug in hotot. Workaround, meantime
3085 return array('$users' => $ret);*/
3090 if ($qtype == 'friends') {
3091 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3092 } elseif ($qtype == 'followers') {
3093 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3096 // friends and followers only for self
3097 if ($user_info['self'] == 0) {
3098 $sql_extra = " AND false ";
3101 if ($qtype == 'blocks') {
3102 $sql_filter = 'AND `blocked` AND NOT `pending`';
3103 } elseif ($qtype == 'incoming') {
3104 $sql_filter = 'AND `pending`';
3106 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3109 // @todo This query most likely can be replaced with a Contact::select...
3110 $r = DBA::toArray(DBA::p(
3125 foreach ($r as $cid) {
3126 $user = api_get_user($cid['nurl']);
3127 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3128 unset($user["uid"]);
3129 unset($user["self"]);
3136 return ['user' => $ret];
3141 * Returns the list of friends of the provided user
3143 * @deprecated By Twitter API in favor of friends/list
3145 * @param string $type Either "json" or "xml"
3146 * @return boolean|string|array
3147 * @throws BadRequestException
3148 * @throws ForbiddenException
3150 function api_statuses_friends($type)
3152 $data = api_statuses_f("friends");
3153 if ($data === false) {
3156 return BaseApi::formatData("users", $type, $data);
3160 * Returns the list of followers of the provided user
3162 * @deprecated By Twitter API in favor of friends/list
3164 * @param string $type Either "json" or "xml"
3165 * @return boolean|string|array
3166 * @throws BadRequestException
3167 * @throws ForbiddenException
3169 function api_statuses_followers($type)
3171 $data = api_statuses_f("followers");
3172 if ($data === false) {
3175 return BaseApi::formatData("users", $type, $data);
3178 /// @TODO move to top of file or somewhere better
3179 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3180 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3183 * Returns the list of blocked users
3185 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3187 * @param string $type Either "json" or "xml"
3189 * @return boolean|string|array
3190 * @throws BadRequestException
3191 * @throws ForbiddenException
3193 function api_blocks_list($type)
3195 $data = api_statuses_f('blocks');
3196 if ($data === false) {
3199 return BaseApi::formatData("users", $type, $data);
3202 /// @TODO move to top of file or somewhere better
3203 api_register_func('api/blocks/list', 'api_blocks_list', true);
3206 * Returns the list of pending users IDs
3208 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3210 * @param string $type Either "json" or "xml"
3212 * @return boolean|string|array
3213 * @throws BadRequestException
3214 * @throws ForbiddenException
3216 function api_friendships_incoming($type)
3218 $data = api_statuses_f('incoming');
3219 if ($data === false) {
3224 foreach ($data['user'] as $user) {
3225 $ids[] = $user['id'];
3228 return BaseApi::formatData("ids", $type, ['id' => $ids]);
3231 /// @TODO move to top of file or somewhere better
3232 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3235 * Returns the instance's configuration information.
3237 * @param string $type Return type (atom, rss, xml, json)
3239 * @return array|string
3240 * @throws InternalServerErrorException
3242 function api_statusnet_config($type)
3244 $name = DI::config()->get('config', 'sitename');
3245 $server = DI::baseUrl()->getHostname();
3246 $logo = DI::baseUrl() . '/images/friendica-64.png';
3247 $email = DI::config()->get('config', 'admin_email');
3248 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3249 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3250 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3251 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3252 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3255 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3256 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3257 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3258 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3259 'shorturllength' => '30',
3261 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3262 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3263 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3264 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3269 return BaseApi::formatData('config', $type, ['config' => $config]);
3272 /// @TODO move to top of file or somewhere better
3273 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3274 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3277 * Sends a new direct message.
3279 * @param string $type Return type (atom, rss, xml, json)
3281 * @return array|string
3282 * @throws BadRequestException
3283 * @throws ForbiddenException
3284 * @throws ImagickException
3285 * @throws InternalServerErrorException
3286 * @throws NotFoundException
3287 * @throws UnauthorizedException
3288 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3290 function api_direct_messages_new($type)
3294 if (api_user() === false) {
3295 throw new ForbiddenException();
3298 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3302 $sender = api_get_user();
3305 if (!empty($_POST['screen_name'])) {
3306 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3307 if (DBA::isResult($contacts)) {
3308 // Selecting the id by priority, friendica first
3309 api_best_nickname($contacts);
3311 $recipient = api_get_user($contacts[0]['nurl']);
3314 $recipient = api_get_user($_POST['user_id']);
3317 if (empty($recipient)) {
3318 throw new NotFoundException('Recipient not found');
3322 if (!empty($_REQUEST['replyto'])) {
3323 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3324 $replyto = $mail['parent-uri'];
3325 $sub = $mail['title'];
3327 if (!empty($_REQUEST['title'])) {
3328 $sub = $_REQUEST['title'];
3330 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3334 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3337 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3338 $ret = api_format_messages($mail, $recipient, $sender);
3340 $ret = ["error" => $id];
3343 $data = ['direct_message'=>$ret];
3349 $data = api_rss_extra($a, $data, $sender);
3353 return BaseApi::formatData("direct-messages", $type, $data);
3356 /// @TODO move to top of file or somewhere better
3357 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3360 * delete a direct_message from mail table through api
3362 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3363 * @return string|array
3364 * @throws BadRequestException
3365 * @throws ForbiddenException
3366 * @throws ImagickException
3367 * @throws InternalServerErrorException
3368 * @throws UnauthorizedException
3369 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3371 function api_direct_messages_destroy($type)
3375 if (api_user() === false) {
3376 throw new ForbiddenException();
3380 $user_info = api_get_user();
3382 $id = $_REQUEST['id'] ?? 0;
3384 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3385 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3386 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3388 $uid = $user_info['uid'];
3389 // error if no id or parenturi specified (for clients posting parent-uri as well)
3390 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3391 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3392 return BaseApi::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3395 // BadRequestException if no id specified (for clients using Twitter API)
3397 throw new BadRequestException('Message id not specified');
3400 // add parent-uri to sql command if specified by calling app
3401 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3403 // error message if specified id is not in database
3404 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3405 if ($verbose == "true") {
3406 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3407 return BaseApi::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3409 /// @todo BadRequestException ok for Twitter API clients?
3410 throw new BadRequestException('message id not in database');
3414 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3416 if ($verbose == "true") {
3419 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3420 return BaseApi::formatData("direct_message_delete", $type, ['$result' => $answer]);
3422 $answer = ['result' => 'error', 'message' => 'unknown error'];
3423 return BaseApi::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3426 /// @todo return JSON data like Twitter API not yet implemented
3429 /// @TODO move to top of file or somewhere better
3430 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3435 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3436 * @return string|array
3437 * @throws HTTPException\BadRequestException
3438 * @throws HTTPException\ExpectationFailedException
3439 * @throws HTTPException\ForbiddenException
3440 * @throws HTTPException\InternalServerErrorException
3441 * @throws HTTPException\NotFoundException
3442 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3444 function api_friendships_destroy($type)
3448 if ($uid === false) {
3449 throw new HTTPException\ForbiddenException();
3452 $owner = User::getOwnerDataById($uid);
3454 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3455 throw new HTTPException\NotFoundException('Error Processing Request');
3458 $contact_id = $_REQUEST['user_id'] ?? 0;
3460 if (empty($contact_id)) {
3461 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3462 throw new HTTPException\BadRequestException('no user_id specified');
3465 // Get Contact by given id
3466 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3468 if(!DBA::isResult($contact)) {
3469 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3470 throw new HTTPException\NotFoundException('no contact found to given ID');
3473 $url = $contact['url'];
3475 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3476 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3477 Strings::normaliseLink($url), $url];
3478 $contact = DBA::selectFirst('contact', [], $condition);
3480 if (!DBA::isResult($contact)) {
3481 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3482 throw new HTTPException\NotFoundException('Not following Contact');
3486 $result = Contact::terminateFriendship($owner, $contact);
3488 if ($result === null) {
3489 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3490 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3493 if ($result === false) {
3494 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3496 } catch (Exception $e) {
3497 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3498 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3501 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3502 unset($contact['uid']);
3503 unset($contact['self']);
3505 // Set screen_name since Twidere requests it
3506 $contact['screen_name'] = $contact['nick'];
3508 return BaseApi::formatData('friendships-destroy', $type, ['user' => $contact]);
3510 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3514 * @param string $type Return type (atom, rss, xml, json)
3515 * @param string $box
3516 * @param string $verbose
3518 * @return array|string
3519 * @throws BadRequestException
3520 * @throws ForbiddenException
3521 * @throws ImagickException
3522 * @throws InternalServerErrorException
3523 * @throws UnauthorizedException
3525 function api_direct_messages_box($type, $box, $verbose)
3528 if (api_user() === false) {
3529 throw new ForbiddenException();
3532 $count = $_GET['count'] ?? 20;
3533 $page = $_REQUEST['page'] ?? 1;
3535 $since_id = $_REQUEST['since_id'] ?? 0;
3536 $max_id = $_REQUEST['max_id'] ?? 0;
3538 $user_id = $_REQUEST['user_id'] ?? '';
3539 $screen_name = $_REQUEST['screen_name'] ?? '';
3542 unset($_REQUEST["user_id"]);
3543 unset($_GET["user_id"]);
3545 unset($_REQUEST["screen_name"]);
3546 unset($_GET["screen_name"]);
3548 $user_info = api_get_user();
3549 if ($user_info === false) {
3550 throw new ForbiddenException();
3552 $profile_url = $user_info["url"];
3555 $start = max(0, ($page - 1) * $count);
3560 if ($box=="sentbox") {
3561 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3562 } elseif ($box == "conversation") {
3563 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3564 } elseif ($box == "all") {
3565 $sql_extra = "true";
3566 } elseif ($box == "inbox") {
3567 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3571 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3574 if ($user_id != "") {
3575 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3576 } elseif ($screen_name !="") {
3577 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3580 $r = DBA::toArray(DBA::p(
3581 "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 ?,?",
3587 if ($verbose == "true" && !DBA::isResult($r)) {
3588 $answer = ['result' => 'error', 'message' => 'no mails available'];
3589 return BaseApi::formatData("direct_messages_all", $type, ['$result' => $answer]);
3593 foreach ($r as $item) {
3594 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3595 $recipient = $user_info;
3596 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
3597 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3598 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
3599 $sender = $user_info;
3602 if (isset($recipient) && isset($sender)) {
3603 $ret[] = api_format_messages($item, $recipient, $sender);
3608 $data = ['direct_message' => $ret];
3613 $data = api_rss_extra($a, $data, $user_info);
3617 return BaseApi::formatData("direct-messages", $type, $data);
3621 * Returns the most recent direct messages sent by the user.
3623 * @param string $type Return type (atom, rss, xml, json)
3625 * @return array|string
3626 * @throws BadRequestException
3627 * @throws ForbiddenException
3628 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3630 function api_direct_messages_sentbox($type)
3632 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3633 return api_direct_messages_box($type, "sentbox", $verbose);
3637 * Returns the most recent direct messages sent to the user.
3639 * @param string $type Return type (atom, rss, xml, json)
3641 * @return array|string
3642 * @throws BadRequestException
3643 * @throws ForbiddenException
3644 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3646 function api_direct_messages_inbox($type)
3648 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3649 return api_direct_messages_box($type, "inbox", $verbose);
3654 * @param string $type Return type (atom, rss, xml, json)
3656 * @return array|string
3657 * @throws BadRequestException
3658 * @throws ForbiddenException
3660 function api_direct_messages_all($type)
3662 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3663 return api_direct_messages_box($type, "all", $verbose);
3668 * @param string $type Return type (atom, rss, xml, json)
3670 * @return array|string
3671 * @throws BadRequestException
3672 * @throws ForbiddenException
3674 function api_direct_messages_conversation($type)
3676 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3677 return api_direct_messages_box($type, "conversation", $verbose);
3680 /// @TODO move to top of file or somewhere better
3681 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3682 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3683 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3684 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3687 * delete a complete photoalbum with all containing photos from database through api
3689 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3690 * @return string|array
3691 * @throws BadRequestException
3692 * @throws ForbiddenException
3693 * @throws InternalServerErrorException
3695 function api_fr_photoalbum_delete($type)
3697 if (api_user() === false) {
3698 throw new ForbiddenException();
3701 $album = $_REQUEST['album'] ?? '';
3703 // we do not allow calls without album string
3705 throw new BadRequestException("no albumname specified");
3707 // check if album is existing
3709 $photos = DBA::selectToArray('photo', ['resource-id'], ['uid' => api_user(), 'album' => $album], ['group_by' => ['resource-id']]);
3710 if (!DBA::isResult($photos)) {
3711 throw new BadRequestException("album not available");
3714 $resourceIds = array_column($photos, 'resource-id');
3716 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3717 // to the user and the contacts of the users (drop_items() performs the federation of the deletion to other networks
3718 $condition = ['uid' => api_user(), 'resource-id' => $resourceIds, 'type' => 'photo'];
3719 Item::deleteForUser($condition, api_user());
3721 // now let's delete all photos from the album
3722 $result = Photo::delete(['uid' => api_user(), 'album' => $album]);
3724 // return success of deletion or error message
3726 $answer = ['result' => 'deleted', 'message' => 'album `' . $album . '` with all containing photos has been deleted.'];
3727 return BaseApi::formatData("photoalbum_delete", $type, ['$result' => $answer]);
3729 throw new InternalServerErrorException("unknown error - deleting from database failed");
3734 * update the name of the album for all photos of an album
3736 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3737 * @return string|array
3738 * @throws BadRequestException
3739 * @throws ForbiddenException
3740 * @throws InternalServerErrorException
3742 function api_fr_photoalbum_update($type)
3744 if (api_user() === false) {
3745 throw new ForbiddenException();
3748 $album = $_REQUEST['album'] ?? '';
3749 $album_new = $_REQUEST['album_new'] ?? '';
3751 // we do not allow calls without album string
3753 throw new BadRequestException("no albumname specified");
3755 if ($album_new == "") {
3756 throw new BadRequestException("no new albumname specified");
3758 // check if album is existing
3759 if (!Photo::exists(['uid' => api_user(), 'album' => $album])) {
3760 throw new BadRequestException("album not available");
3762 // now let's update all photos to the albumname
3763 $result = Photo::update(['album' => $album_new], ['uid' => api_user(), 'album' => $album]);
3765 // return success of updating or error message
3767 $answer = ['result' => 'updated', 'message' => 'album `' . $album . '` with all containing photos has been renamed to `' . $album_new . '`.'];
3768 return BaseApi::formatData("photoalbum_update", $type, ['$result' => $answer]);
3770 throw new InternalServerErrorException("unknown error - updating in database failed");
3776 * list all photos of the authenticated user
3778 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3779 * @return string|array
3780 * @throws ForbiddenException
3781 * @throws InternalServerErrorException
3783 function api_fr_photos_list($type)
3785 if (api_user() === false) {
3786 throw new ForbiddenException();
3788 $r = DBA::toArray(DBA::p(
3789 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3790 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3791 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3792 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3795 'image/jpeg' => 'jpg',
3796 'image/png' => 'png',
3797 'image/gif' => 'gif'
3799 $data = ['photo'=>[]];
3800 if (DBA::isResult($r)) {
3801 foreach ($r as $rr) {
3803 $photo['id'] = $rr['resource-id'];
3804 $photo['album'] = $rr['album'];
3805 $photo['filename'] = $rr['filename'];
3806 $photo['type'] = $rr['type'];
3807 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3808 $photo['created'] = $rr['created'];
3809 $photo['edited'] = $rr['edited'];
3810 $photo['desc'] = $rr['desc'];
3812 if ($type == "xml") {
3813 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3815 $photo['thumb'] = $thumb;
3816 $data['photo'][] = $photo;
3820 return BaseApi::formatData("photos", $type, $data);
3824 * upload a new photo or change an existing photo
3826 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3827 * @return string|array
3828 * @throws BadRequestException
3829 * @throws ForbiddenException
3830 * @throws ImagickException
3831 * @throws InternalServerErrorException
3832 * @throws NotFoundException
3834 function api_fr_photo_create_update($type)
3836 if (api_user() === false) {
3837 throw new ForbiddenException();
3840 $photo_id = $_REQUEST['photo_id'] ?? null;
3841 $desc = $_REQUEST['desc'] ?? null;
3842 $album = $_REQUEST['album'] ?? null;
3843 $album_new = $_REQUEST['album_new'] ?? null;
3844 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3845 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3846 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3847 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3848 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3850 // do several checks on input parameters
3851 // we do not allow calls without album string
3852 if ($album == null) {
3853 throw new BadRequestException("no albumname specified");
3855 // if photo_id == null --> we are uploading a new photo
3856 if ($photo_id == null) {
3859 // error if no media posted in create-mode
3860 if (empty($_FILES['media'])) {
3862 throw new BadRequestException("no media data submitted");
3865 // album_new will be ignored in create-mode
3870 // check if photo is existing in databasei
3871 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3872 throw new BadRequestException("photo not available");
3876 // checks on acl strings provided by clients
3877 $acl_input_error = false;
3878 $acl_input_error |= check_acl_input($allow_cid);
3879 $acl_input_error |= check_acl_input($deny_cid);
3880 $acl_input_error |= check_acl_input($allow_gid);
3881 $acl_input_error |= check_acl_input($deny_gid);
3882 if ($acl_input_error) {
3883 throw new BadRequestException("acl data invalid");
3885 // now let's upload the new media in create-mode
3886 if ($mode == "create") {
3887 $media = $_FILES['media'];
3888 $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);
3890 // return success of updating or error message
3891 if (!is_null($data)) {
3892 return BaseApi::formatData("photo_create", $type, $data);
3894 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3898 // now let's do the changes in update-mode
3899 if ($mode == "update") {
3900 $updated_fields = [];
3902 if (!is_null($desc)) {
3903 $updated_fields['desc'] = $desc;
3906 if (!is_null($album_new)) {
3907 $updated_fields['album'] = $album_new;
3910 if (!is_null($allow_cid)) {
3911 $allow_cid = trim($allow_cid);
3912 $updated_fields['allow_cid'] = $allow_cid;
3915 if (!is_null($deny_cid)) {
3916 $deny_cid = trim($deny_cid);
3917 $updated_fields['deny_cid'] = $deny_cid;
3920 if (!is_null($allow_gid)) {
3921 $allow_gid = trim($allow_gid);
3922 $updated_fields['allow_gid'] = $allow_gid;
3925 if (!is_null($deny_gid)) {
3926 $deny_gid = trim($deny_gid);
3927 $updated_fields['deny_gid'] = $deny_gid;
3931 if (count($updated_fields) > 0) {
3932 $nothingtodo = false;
3933 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3935 $nothingtodo = true;
3938 if (!empty($_FILES['media'])) {
3939 $nothingtodo = false;
3940 $media = $_FILES['media'];
3941 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3942 if (!is_null($data)) {
3943 return BaseApi::formatData("photo_update", $type, $data);
3947 // return success of updating or error message
3949 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3950 return BaseApi::formatData("photo_update", $type, ['$result' => $answer]);
3953 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3954 return BaseApi::formatData("photo_update", $type, ['$result' => $answer]);
3956 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3959 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3963 * delete a single photo from the database through api
3965 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3966 * @return string|array
3967 * @throws BadRequestException
3968 * @throws ForbiddenException
3969 * @throws InternalServerErrorException
3971 function api_fr_photo_delete($type)
3973 if (api_user() === false) {
3974 throw new ForbiddenException();
3978 $photo_id = $_REQUEST['photo_id'] ?? null;
3980 // do several checks on input parameters
3981 // we do not allow calls without photo id
3982 if ($photo_id == null) {
3983 throw new BadRequestException("no photo_id specified");
3986 // check if photo is existing in database
3987 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user()])) {
3988 throw new BadRequestException("photo not available");
3991 // now we can perform on the deletion of the photo
3992 $result = Photo::delete(['uid' => api_user(), 'resource-id' => $photo_id]);
3994 // return success of deletion or error message
3996 // function for setting the items to "deleted = 1" which ensures that comments, likes etc. are not shown anymore
3997 // to the user and the contacts of the users (drop_items() do all the necessary magic to avoid orphans in database and federate deletion)
3998 $condition = ['uid' => api_user(), 'resource-id' => $photo_id, 'type' => 'photo'];
3999 Item::deleteForUser($condition, api_user());
4001 $result = ['result' => 'deleted', 'message' => 'photo with id `' . $photo_id . '` has been deleted from server.'];
4002 return BaseApi::formatData("photo_delete", $type, ['$result' => $result]);
4004 throw new InternalServerErrorException("unknown error on deleting photo from database table");
4010 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
4012 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4013 * @return string|array
4014 * @throws BadRequestException
4015 * @throws ForbiddenException
4016 * @throws InternalServerErrorException
4017 * @throws NotFoundException
4019 function api_fr_photo_detail($type)
4021 if (api_user() === false) {
4022 throw new ForbiddenException();
4024 if (empty($_REQUEST['photo_id'])) {
4025 throw new BadRequestException("No photo id.");
4028 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
4029 $photo_id = $_REQUEST['photo_id'];
4031 // prepare json/xml output with data from database for the requested photo
4032 $data = prepare_photo_data($type, $scale, $photo_id);
4034 return BaseApi::formatData("photo_detail", $type, $data);
4039 * updates the profile image for the user (either a specified profile or the default profile)
4041 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4043 * @return string|array
4044 * @throws BadRequestException
4045 * @throws ForbiddenException
4046 * @throws ImagickException
4047 * @throws InternalServerErrorException
4048 * @throws NotFoundException
4049 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
4051 function api_account_update_profile_image($type)
4053 if (api_user() === false) {
4054 throw new ForbiddenException();
4057 $profile_id = $_REQUEST['profile_id'] ?? 0;
4059 // error if image data is missing
4060 if (empty($_FILES['image'])) {
4061 throw new BadRequestException("no media data submitted");
4064 // check if specified profile id is valid
4065 if ($profile_id != 0) {
4066 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
4067 // error message if specified profile id is not in database
4068 if (!DBA::isResult($profile)) {
4069 throw new BadRequestException("profile_id not available");
4071 $is_default_profile = $profile['is-default'];
4073 $is_default_profile = 1;
4076 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
4078 if (!empty($_FILES['image'])) {
4079 $media = $_FILES['image'];
4080 } elseif (!empty($_FILES['media'])) {
4081 $media = $_FILES['media'];
4083 // save new profile image
4084 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
4087 if (is_array($media['type'])) {
4088 $filetype = $media['type'][0];
4090 $filetype = $media['type'];
4092 if ($filetype == "image/jpeg") {
4094 } elseif ($filetype == "image/png") {
4097 throw new InternalServerErrorException('Unsupported filetype');
4100 // change specified profile or all profiles to the new resource-id
4101 if ($is_default_profile) {
4102 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
4103 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
4105 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
4106 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
4107 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
4110 Contact::updateSelfFromUserID(api_user(), true);
4112 // Update global directory in background
4113 Profile::publishUpdate(api_user());
4115 // output for client
4117 return api_account_verify_credentials($type);
4119 // SaveMediaToDatabase failed for some reason
4120 throw new InternalServerErrorException("image upload failed");
4124 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
4125 api_register_func('api/friendica/photoalbum/delete', 'api_fr_photoalbum_delete', true, API_METHOD_DELETE);
4126 api_register_func('api/friendica/photoalbum/update', 'api_fr_photoalbum_update', true, API_METHOD_POST);
4127 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
4128 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
4129 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
4130 api_register_func('api/friendica/photo/delete', 'api_fr_photo_delete', true, API_METHOD_DELETE);
4131 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
4132 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
4135 * Update user profile
4137 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4139 * @return array|string
4140 * @throws BadRequestException
4141 * @throws ForbiddenException
4142 * @throws ImagickException
4143 * @throws InternalServerErrorException
4144 * @throws UnauthorizedException
4146 function api_account_update_profile($type)
4148 $local_user = api_user();
4149 $api_user = api_get_user();
4151 if (!empty($_POST['name'])) {
4152 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4153 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4154 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4155 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
4158 if (isset($_POST['description'])) {
4159 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4160 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4161 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
4164 Profile::publishUpdate($local_user);
4166 return api_account_verify_credentials($type);
4169 /// @TODO move to top of file or somewhere better
4170 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4174 * @param string $acl_string
4178 function check_acl_input($acl_string)
4180 if (empty($acl_string)) {
4184 $contact_not_found = false;
4186 // split <x><y><z> into array of cid's
4187 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4189 // check for each cid if it is available on server
4190 $cid_array = $array[0];
4191 foreach ($cid_array as $cid) {
4192 $cid = str_replace("<", "", $cid);
4193 $cid = str_replace(">", "", $cid);
4194 $condition = ['id' => $cid, 'uid' => api_user()];
4195 $contact_not_found |= !DBA::exists('contact', $condition);
4197 return $contact_not_found;
4201 * @param string $mediatype
4202 * @param array $media
4203 * @param string $type
4204 * @param string $album
4205 * @param string $allow_cid
4206 * @param string $deny_cid
4207 * @param string $allow_gid
4208 * @param string $deny_gid
4209 * @param string $desc
4210 * @param integer $phototype
4211 * @param boolean $visibility
4212 * @param string $photo_id
4214 * @throws BadRequestException
4215 * @throws ForbiddenException
4216 * @throws ImagickException
4217 * @throws InternalServerErrorException
4218 * @throws NotFoundException
4219 * @throws UnauthorizedException
4221 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)
4229 if (is_array($media)) {
4230 if (is_array($media['tmp_name'])) {
4231 $src = $media['tmp_name'][0];
4233 $src = $media['tmp_name'];
4235 if (is_array($media['name'])) {
4236 $filename = basename($media['name'][0]);
4238 $filename = basename($media['name']);
4240 if (is_array($media['size'])) {
4241 $filesize = intval($media['size'][0]);
4243 $filesize = intval($media['size']);
4245 if (is_array($media['type'])) {
4246 $filetype = $media['type'][0];
4248 $filetype = $media['type'];
4252 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4255 "File upload src: " . $src . " - filename: " . $filename .
4256 " - size: " . $filesize . " - type: " . $filetype);
4258 // check if there was a php upload error
4259 if ($filesize == 0 && $media['error'] == 1) {
4260 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4262 // check against max upload size within Friendica instance
4263 $maximagesize = DI::config()->get('system', 'maximagesize');
4264 if ($maximagesize && ($filesize > $maximagesize)) {
4265 $formattedBytes = Strings::formatBytes($maximagesize);
4266 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4269 // create Photo instance with the data of the image
4270 $imagedata = @file_get_contents($src);
4271 $Image = new Image($imagedata, $filetype);
4272 if (!$Image->isValid()) {
4273 throw new InternalServerErrorException("unable to process image data");
4276 // check orientation of image
4277 $Image->orient($src);
4280 // check max length of images on server
4281 $max_length = DI::config()->get('system', 'max_image_length');
4282 if ($max_length > 0) {
4283 $Image->scaleDown($max_length);
4284 logger::info("File upload: Scaling picture to new size " . $max_length);
4286 $width = $Image->getWidth();
4287 $height = $Image->getHeight();
4289 // create a new resource-id if not already provided
4290 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4292 if ($mediatype == "photo") {
4293 // upload normal image (scales 0, 1, 2)
4294 logger::info("photo upload: starting new photo upload");
4296 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4298 logger::notice("photo upload: image upload with scale 0 (original size) failed");
4300 if ($width > 640 || $height > 640) {
4301 $Image->scaleDown(640);
4302 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4304 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
4308 if ($width > 320 || $height > 320) {
4309 $Image->scaleDown(320);
4310 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4312 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
4315 logger::info("photo upload: new photo upload ended");
4316 } elseif ($mediatype == "profileimage") {
4317 // upload profile image (scales 4, 5, 6)
4318 logger::info("photo upload: starting new profile image upload");
4320 if ($width > 300 || $height > 300) {
4321 $Image->scaleDown(300);
4322 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4324 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4328 if ($width > 80 || $height > 80) {
4329 $Image->scaleDown(80);
4330 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4332 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4336 if ($width > 48 || $height > 48) {
4337 $Image->scaleDown(48);
4338 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4340 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4343 $Image->__destruct();
4344 logger::info("photo upload: new profile image upload ended");
4348 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4349 if ($photo_id == null && $mediatype == "photo") {
4350 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4352 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4353 return prepare_photo_data($type, false, $resource_id);
4355 throw new InternalServerErrorException("image upload failed");
4361 * @param string $hash
4362 * @param string $allow_cid
4363 * @param string $deny_cid
4364 * @param string $allow_gid
4365 * @param string $deny_gid
4366 * @param string $filetype
4367 * @param boolean $visibility
4368 * @throws InternalServerErrorException
4370 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4372 // get data about the api authenticated user
4373 $uri = Item::newURI(intval(api_user()));
4374 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4377 $arr['guid'] = System::createUUID();
4378 $arr['uid'] = intval(api_user());
4380 $arr['type'] = 'photo';
4382 $arr['resource-id'] = $hash;
4383 $arr['contact-id'] = $owner_record['id'];
4384 $arr['owner-name'] = $owner_record['name'];
4385 $arr['owner-link'] = $owner_record['url'];
4386 $arr['owner-avatar'] = $owner_record['thumb'];
4387 $arr['author-name'] = $owner_record['name'];
4388 $arr['author-link'] = $owner_record['url'];
4389 $arr['author-avatar'] = $owner_record['thumb'];
4391 $arr['allow_cid'] = $allow_cid;
4392 $arr['allow_gid'] = $allow_gid;
4393 $arr['deny_cid'] = $deny_cid;
4394 $arr['deny_gid'] = $deny_gid;
4395 $arr['visible'] = $visibility;
4399 'image/jpeg' => 'jpg',
4400 'image/png' => 'png',
4401 'image/gif' => 'gif'
4404 // adds link to the thumbnail scale photo
4405 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4406 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4409 // do the magic for storing the item in the database and trigger the federation to other contacts
4415 * @param string $type
4417 * @param string $photo_id
4420 * @throws BadRequestException
4421 * @throws ForbiddenException
4422 * @throws ImagickException
4423 * @throws InternalServerErrorException
4424 * @throws NotFoundException
4425 * @throws UnauthorizedException
4427 function prepare_photo_data($type, $scale, $photo_id)
4430 $user_info = api_get_user();
4432 if ($user_info === false) {
4433 throw new ForbiddenException();
4436 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4437 $data_sql = ($scale === false ? "" : "data, ");
4439 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4440 // clients needs to convert this in their way for further processing
4441 $r = DBA::toArray(DBA::p(
4442 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4443 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4444 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4445 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4446 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4447 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4453 'image/jpeg' => 'jpg',
4454 'image/png' => 'png',
4455 'image/gif' => 'gif'
4458 // prepare output data for photo
4459 if (DBA::isResult($r)) {
4460 $data = ['photo' => $r[0]];
4461 $data['photo']['id'] = $data['photo']['resource-id'];
4462 if ($scale !== false) {
4463 $data['photo']['data'] = base64_encode($data['photo']['data']);
4465 unset($data['photo']['datasize']); //needed only with scale param
4467 if ($type == "xml") {
4468 $data['photo']['links'] = [];
4469 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4470 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4472 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4475 $data['photo']['link'] = [];
4476 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4478 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4479 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4483 unset($data['photo']['resource-id']);
4484 unset($data['photo']['minscale']);
4485 unset($data['photo']['maxscale']);
4487 throw new NotFoundException();
4490 // retrieve item element for getting activities (like, dislike etc.) related to photo
4491 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4492 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4493 if (!DBA::isResult($item)) {
4494 throw new NotFoundException('Photo-related item not found.');
4497 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4499 // retrieve comments on photo
4500 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4501 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4503 $statuses = Post::selectForUser(api_user(), [], $condition);
4505 // prepare output of comments
4506 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4508 if ($type == "xml") {
4510 foreach ($commentData as $comment) {
4511 $comments[$k++ . ":comment"] = $comment;
4514 foreach ($commentData as $comment) {
4515 $comments[] = $comment;
4518 $data['photo']['friendica_comments'] = $comments;
4520 // include info if rights on photo and rights on item are mismatching
4521 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4522 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4523 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4524 $data['photo']['deny_gid'] != $item['deny_gid'];
4525 $data['photo']['rights_mismatch'] = $rights_mismatch;
4531 * Return an item with announcer data if it had been announced
4533 * @param array $item Item array
4534 * @return array Item array with announce data
4536 function api_get_announce($item)
4538 // Quit if the item already has got a different owner and author
4539 if ($item['owner-id'] != $item['author-id']) {
4543 // Don't change original or Diaspora posts
4544 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4548 // Quit if we do now the original author and it had been a post from a native network
4549 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4553 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4554 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4555 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4556 if (!DBA::isResult($announce)) {
4560 return array_merge($item, $announce);
4565 * @param array $item
4570 function api_in_reply_to($item)
4574 $in_reply_to['status_id'] = null;
4575 $in_reply_to['user_id'] = null;
4576 $in_reply_to['status_id_str'] = null;
4577 $in_reply_to['user_id_str'] = null;
4578 $in_reply_to['screen_name'] = null;
4580 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4581 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4582 if (DBA::isResult($parent)) {
4583 $in_reply_to['status_id'] = intval($parent['id']);
4585 $in_reply_to['status_id'] = intval($item['parent']);
4588 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4590 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4591 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4593 if (DBA::isResult($parent)) {
4594 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4595 $in_reply_to['user_id'] = intval($parent['author-id']);
4596 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4599 // There seems to be situation, where both fields are identical:
4600 // https://github.com/friendica/friendica/issues/1010
4601 // This is a bugfix for that.
4602 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4603 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']]);
4604 $in_reply_to['status_id'] = null;
4605 $in_reply_to['user_id'] = null;
4606 $in_reply_to['status_id_str'] = null;
4607 $in_reply_to['user_id_str'] = null;
4608 $in_reply_to['screen_name'] = null;
4612 return $in_reply_to;
4617 * @param string $text
4620 * @throws InternalServerErrorException
4622 function api_clean_plain_items($text)
4624 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4626 $text = BBCode::cleanPictureLinks($text);
4627 $URLSearchString = "^\[\]";
4629 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4631 if ($include_entities == "true") {
4632 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4635 // Simplify "attachment" element
4636 $text = BBCode::removeAttachment($text);
4643 * @param array $contacts
4647 function api_best_nickname(&$contacts)
4651 if (count($contacts) == 0) {
4655 foreach ($contacts as $contact) {
4656 if ($contact["network"] == "") {
4657 $contact["network"] = "dfrn";
4658 $best_contact = [$contact];
4662 if (sizeof($best_contact) == 0) {
4663 foreach ($contacts as $contact) {
4664 if ($contact["network"] == "dfrn") {
4665 $best_contact = [$contact];
4670 if (sizeof($best_contact) == 0) {
4671 foreach ($contacts as $contact) {
4672 if ($contact["network"] == "dspr") {
4673 $best_contact = [$contact];
4678 if (sizeof($best_contact) == 0) {
4679 foreach ($contacts as $contact) {
4680 if ($contact["network"] == "stat") {
4681 $best_contact = [$contact];
4686 if (sizeof($best_contact) == 0) {
4687 foreach ($contacts as $contact) {
4688 if ($contact["network"] == "pump") {
4689 $best_contact = [$contact];
4694 if (sizeof($best_contact) == 0) {
4695 foreach ($contacts as $contact) {
4696 if ($contact["network"] == "twit") {
4697 $best_contact = [$contact];
4702 if (sizeof($best_contact) == 1) {
4703 $contacts = $best_contact;
4705 $contacts = [$contacts[0]];
4710 * Return all or a specified group of the user with the containing contacts.
4712 * @param string $type Return type (atom, rss, xml, json)
4714 * @return array|string
4715 * @throws BadRequestException
4716 * @throws ForbiddenException
4717 * @throws ImagickException
4718 * @throws InternalServerErrorException
4719 * @throws UnauthorizedException
4721 function api_friendica_group_show($type)
4725 if (api_user() === false) {
4726 throw new ForbiddenException();
4730 $user_info = api_get_user();
4731 $gid = $_REQUEST['gid'] ?? 0;
4732 $uid = $user_info['uid'];
4734 // get data of the specified group id or all groups if not specified
4736 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4738 // error message if specified gid is not in database
4739 if (!DBA::isResult($groups)) {
4740 throw new BadRequestException("gid not available");
4743 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4746 // loop through all groups and retrieve all members for adding data in the user array
4748 foreach ($groups as $rr) {
4749 $members = Contact\Group::getById($rr['id']);
4752 if ($type == "xml") {
4753 $user_element = "users";
4755 foreach ($members as $member) {
4756 $user = api_get_user($member['nurl']);
4757 $users[$k++.":user"] = $user;
4760 $user_element = "user";
4761 foreach ($members as $member) {
4762 $user = api_get_user($member['nurl']);
4766 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4768 return BaseApi::formatData("groups", $type, ['group' => $grps]);
4770 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4774 * Delete the specified group of the user.
4776 * @param string $type Return type (atom, rss, xml, json)
4778 * @return array|string
4779 * @throws BadRequestException
4780 * @throws ForbiddenException
4781 * @throws ImagickException
4782 * @throws InternalServerErrorException
4783 * @throws UnauthorizedException
4785 function api_friendica_group_delete($type)
4789 if (api_user() === false) {
4790 throw new ForbiddenException();
4794 $user_info = api_get_user();
4795 $gid = $_REQUEST['gid'] ?? 0;
4796 $name = $_REQUEST['name'] ?? '';
4797 $uid = $user_info['uid'];
4799 // error if no gid specified
4800 if ($gid == 0 || $name == "") {
4801 throw new BadRequestException('gid or name not specified');
4804 // error message if specified gid is not in database
4805 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) {
4806 throw new BadRequestException('gid not available');
4809 // error message if specified gid is not in database
4810 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) {
4811 throw new BadRequestException('wrong group name');
4815 $gid = Group::getIdByName($uid, $name);
4817 throw new BadRequestException('other API error');
4820 $ret = Group::remove($gid);
4824 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
4825 return BaseApi::formatData("group_delete", $type, ['result' => $success]);
4827 throw new BadRequestException('other API error');
4830 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4835 * @param string $type Return type (atom, rss, xml, json)
4837 * @return array|string
4838 * @throws BadRequestException
4839 * @throws ForbiddenException
4840 * @throws ImagickException
4841 * @throws InternalServerErrorException
4842 * @throws UnauthorizedException
4843 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4845 function api_lists_destroy($type)
4849 if (api_user() === false) {
4850 throw new ForbiddenException();
4854 $user_info = api_get_user();
4855 $gid = $_REQUEST['list_id'] ?? 0;
4856 $uid = $user_info['uid'];
4858 // error if no gid specified
4860 throw new BadRequestException('gid not specified');
4863 // get data of the specified group id
4864 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4865 // error message if specified gid is not in database
4867 throw new BadRequestException('gid not available');
4870 if (Group::remove($gid)) {
4872 'name' => $group['name'],
4873 'id' => intval($gid),
4874 'id_str' => (string) $gid,
4875 'user' => $user_info
4878 return BaseApi::formatData("lists", $type, ['lists' => $list]);
4881 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4884 * Add a new group to the database.
4886 * @param string $name Group name
4887 * @param int $uid User ID
4888 * @param array $users List of users to add to the group
4891 * @throws BadRequestException
4893 function group_create($name, $uid, $users = [])
4895 // error if no name specified
4897 throw new BadRequestException('group name not specified');
4900 // error message if specified group name already exists
4901 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4902 throw new BadRequestException('group name already exists');
4905 // Check if the group needs to be reactivated
4906 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4907 $reactivate_group = true;
4911 $ret = Group::create($uid, $name);
4913 $gid = Group::getIdByName($uid, $name);
4915 throw new BadRequestException('other API error');
4919 $erroraddinguser = false;
4921 foreach ($users as $user) {
4922 $cid = $user['cid'];
4923 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4924 Group::addMember($gid, $cid);
4926 $erroraddinguser = true;
4927 $errorusers[] = $cid;
4931 // return success message incl. missing users in array
4932 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4934 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4938 * Create the specified group with the posted array of contacts.
4940 * @param string $type Return type (atom, rss, xml, json)
4942 * @return array|string
4943 * @throws BadRequestException
4944 * @throws ForbiddenException
4945 * @throws ImagickException
4946 * @throws InternalServerErrorException
4947 * @throws UnauthorizedException
4949 function api_friendica_group_create($type)
4953 if (api_user() === false) {
4954 throw new ForbiddenException();
4958 $user_info = api_get_user();
4959 $name = $_REQUEST['name'] ?? '';
4960 $uid = $user_info['uid'];
4961 $json = json_decode($_POST['json'], true);
4962 $users = $json['user'];
4964 $success = group_create($name, $uid, $users);
4966 return BaseApi::formatData("group_create", $type, ['result' => $success]);
4968 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4971 * Create a new group.
4973 * @param string $type Return type (atom, rss, xml, json)
4975 * @return array|string
4976 * @throws BadRequestException
4977 * @throws ForbiddenException
4978 * @throws ImagickException
4979 * @throws InternalServerErrorException
4980 * @throws UnauthorizedException
4981 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4983 function api_lists_create($type)
4987 if (api_user() === false) {
4988 throw new ForbiddenException();
4992 $user_info = api_get_user();
4993 $name = $_REQUEST['name'] ?? '';
4994 $uid = $user_info['uid'];
4996 $success = group_create($name, $uid);
4997 if ($success['success']) {
4999 'name' => $success['name'],
5000 'id' => intval($success['gid']),
5001 'id_str' => (string) $success['gid'],
5002 'user' => $user_info
5005 return BaseApi::formatData("lists", $type, ['lists'=>$grp]);
5008 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
5011 * Update the specified group with the posted array of contacts.
5013 * @param string $type Return type (atom, rss, xml, json)
5015 * @return array|string
5016 * @throws BadRequestException
5017 * @throws ForbiddenException
5018 * @throws ImagickException
5019 * @throws InternalServerErrorException
5020 * @throws UnauthorizedException
5022 function api_friendica_group_update($type)
5026 if (api_user() === false) {
5027 throw new ForbiddenException();
5031 $user_info = api_get_user();
5032 $uid = $user_info['uid'];
5033 $gid = $_REQUEST['gid'] ?? 0;
5034 $name = $_REQUEST['name'] ?? '';
5035 $json = json_decode($_POST['json'], true);
5036 $users = $json['user'];
5038 // error if no name specified
5040 throw new BadRequestException('group name not specified');
5043 // error if no gid specified
5045 throw new BadRequestException('gid not specified');
5049 $members = Contact\Group::getById($gid);
5050 foreach ($members as $member) {
5051 $cid = $member['id'];
5052 foreach ($users as $user) {
5053 $found = ($user['cid'] == $cid ? true : false);
5055 if (!isset($found) || !$found) {
5056 $gid = Group::getIdByName($uid, $name);
5057 Group::removeMember($gid, $cid);
5062 $erroraddinguser = false;
5064 foreach ($users as $user) {
5065 $cid = $user['cid'];
5067 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
5068 Group::addMember($gid, $cid);
5070 $erroraddinguser = true;
5071 $errorusers[] = $cid;
5075 // return success message incl. missing users in array
5076 $status = ($erroraddinguser ? "missing user" : "ok");
5077 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
5078 return BaseApi::formatData("group_update", $type, ['result' => $success]);
5081 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
5084 * Update information about a group.
5086 * @param string $type Return type (atom, rss, xml, json)
5088 * @return array|string
5089 * @throws BadRequestException
5090 * @throws ForbiddenException
5091 * @throws ImagickException
5092 * @throws InternalServerErrorException
5093 * @throws UnauthorizedException
5094 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
5096 function api_lists_update($type)
5100 if (api_user() === false) {
5101 throw new ForbiddenException();
5105 $user_info = api_get_user();
5106 $gid = $_REQUEST['list_id'] ?? 0;
5107 $name = $_REQUEST['name'] ?? '';
5108 $uid = $user_info['uid'];
5110 // error if no gid specified
5112 throw new BadRequestException('gid not specified');
5115 // get data of the specified group id
5116 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
5117 // error message if specified gid is not in database
5119 throw new BadRequestException('gid not available');
5122 if (Group::update($gid, $name)) {
5125 'id' => intval($gid),
5126 'id_str' => (string) $gid,
5127 'user' => $user_info
5130 return BaseApi::formatData("lists", $type, ['lists' => $list]);
5134 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5138 * @param string $type Return type (atom, rss, xml, json)
5140 * @return array|string
5141 * @throws BadRequestException
5142 * @throws ForbiddenException
5143 * @throws ImagickException
5144 * @throws InternalServerErrorException
5146 function api_friendica_activity($type)
5150 if (api_user() === false) {
5151 throw new ForbiddenException();
5153 $verb = strtolower(DI::args()->getArgv()[3]);
5154 $verb = preg_replace("|\..*$|", "", $verb);
5156 $id = $_REQUEST['id'] ?? 0;
5158 $res = Item::performActivity($id, $verb, api_user());
5161 if ($type == "xml") {
5166 return BaseApi::formatData('ok', $type, ['ok' => $ok]);
5168 throw new BadRequestException('Error adding activity');
5172 /// @TODO move to top of file or somewhere better
5173 api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
5174 api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
5175 api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
5176 api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
5177 api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5178 api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
5179 api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
5180 api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
5181 api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
5182 api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
5185 * Returns notifications
5187 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5189 * @return string|array
5190 * @throws ForbiddenException
5191 * @throws BadRequestException
5194 function api_friendica_notification($type)
5196 if (api_user() === false) {
5197 throw new ForbiddenException();
5199 if (DI::args()->getArgc()!==3) {
5200 throw new BadRequestException('Invalid argument count');
5203 $Notifies = DI::notify()->selectAllForUser(local_user(), 50);
5205 $notifications = new ApiNotifications();
5206 foreach ($Notifies as $Notify) {
5207 $notifications[] = new ApiNotification($Notify);
5210 if ($type == 'xml') {
5212 foreach ($notifications as $notification) {
5213 $xmlnotes[] = ['@attributes' => $notification->toArray()];
5216 $result = $xmlnotes;
5217 } elseif (count($notifications) > 0) {
5218 $result = $notifications->getArrayCopy();
5223 return BaseApi::formatData('notes', $type, ['note' => $result]);
5227 * Set notification as seen and returns associated item (if possible)
5229 * POST request with 'id' param as notification id
5231 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5232 * @return string|array
5233 * @throws BadRequestException
5234 * @throws ForbiddenException
5235 * @throws ImagickException
5236 * @throws InternalServerErrorException
5237 * @throws UnauthorizedException
5239 function api_friendica_notification_seen($type)
5242 $user_info = api_get_user();
5244 if (api_user() === false || $user_info === false) {
5245 throw new ForbiddenException();
5247 if (DI::args()->getArgc() !== 4) {
5248 throw new BadRequestException('Invalid argument count');
5251 $id = intval($_REQUEST['id'] ?? 0);
5254 $Notify = DI::notify()->selectOneById($id);
5255 if ($Notify->uid !== api_user()) {
5256 throw new NotFoundException();
5259 if ($Notify->uriId) {
5260 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
5264 DI::notify()->save($Notify);
5266 if ($Notify->otype === Notification\ObjectType::ITEM) {
5267 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
5268 if (DBA::isResult($item)) {
5269 // we found the item, return it to the user
5270 $ret = api_format_items([$item], $user_info, false, $type);
5271 $data = ['status' => $ret];
5272 return BaseApi::formatData('status', $type, $data);
5274 // the item can't be found, but we set the notification as seen, so we count this as a success
5277 return BaseApi::formatData('result', $type, ['result' => 'success']);
5278 } catch (NotFoundException $e) {
5279 throw new BadRequestException('Invalid argument', $e);
5280 } catch (Exception $e) {
5281 throw new InternalServerErrorException('Internal Server exception', $e);
5285 /// @TODO move to top of file or somewhere better
5286 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5287 api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
5290 * update a direct_message to seen state
5292 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5293 * @return string|array (success result=ok, error result=error with error message)
5294 * @throws BadRequestException
5295 * @throws ForbiddenException
5296 * @throws ImagickException
5297 * @throws InternalServerErrorException
5298 * @throws UnauthorizedException
5300 function api_friendica_direct_messages_setseen($type)
5303 if (api_user() === false) {
5304 throw new ForbiddenException();
5308 $user_info = api_get_user();
5309 $uid = $user_info['uid'];
5310 $id = $_REQUEST['id'] ?? 0;
5312 // return error if id is zero
5314 $answer = ['result' => 'error', 'message' => 'message id not specified'];
5315 return BaseApi::formatData("direct_messages_setseen", $type, ['$result' => $answer]);
5318 // error message if specified id is not in database
5319 if (!DBA::exists('mail', ['id' => $id, 'uid' => $uid])) {
5320 $answer = ['result' => 'error', 'message' => 'message id not in database'];
5321 return BaseApi::formatData("direct_messages_setseen", $type, ['$result' => $answer]);
5324 // update seen indicator
5325 $result = DBA::update('mail', ['seen' => true], ['id' => $id]);
5329 $answer = ['result' => 'ok', 'message' => 'message set to seen'];
5330 return BaseApi::formatData("direct_message_setseen", $type, ['$result' => $answer]);
5332 $answer = ['result' => 'error', 'message' => 'unknown error'];
5333 return BaseApi::formatData("direct_messages_setseen", $type, ['$result' => $answer]);
5337 /// @TODO move to top of file or somewhere better
5338 api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
5341 * search for direct_messages containing a searchstring through api
5343 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5344 * @param string $box
5345 * @return string|array (success: success=true if found and search_result contains found messages,
5346 * success=false if nothing was found, search_result='nothing found',
5347 * error: result=error with error message)
5348 * @throws BadRequestException
5349 * @throws ForbiddenException
5350 * @throws ImagickException
5351 * @throws InternalServerErrorException
5352 * @throws UnauthorizedException
5354 function api_friendica_direct_messages_search($type, $box = "")
5358 if (api_user() === false) {
5359 throw new ForbiddenException();
5363 $user_info = api_get_user();
5364 $searchstring = $_REQUEST['searchstring'] ?? '';
5365 $uid = $user_info['uid'];
5367 // error if no searchstring specified
5368 if ($searchstring == "") {
5369 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5370 return BaseApi::formatData("direct_messages_search", $type, ['$result' => $answer]);
5373 // get data for the specified searchstring
5374 $r = DBA::toArray(DBA::p(
5375 "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",
5377 '%'.$searchstring.'%'
5380 $profile_url = $user_info["url"];
5382 // message if nothing was found
5383 if (!DBA::isResult($r)) {
5384 $success = ['success' => false, 'search_results' => 'problem with query'];
5385 } elseif (count($r) == 0) {
5386 $success = ['success' => false, 'search_results' => 'nothing found'];
5389 foreach ($r as $item) {
5390 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5391 $recipient = $user_info;
5392 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
5393 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5394 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
5395 $sender = $user_info;
5398 if (isset($recipient) && isset($sender)) {
5399 $ret[] = api_format_messages($item, $recipient, $sender);
5402 $success = ['success' => true, 'search_results' => $ret];
5405 return BaseApi::formatData("direct_message_search", $type, ['$result' => $success]);
5408 /// @TODO move to top of file or somewhere better
5409 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5412 * Number of comments
5414 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5416 * @param object $data [Status, Status]
5420 function bindComments(&$data)
5422 if (count($data) == 0) {
5428 foreach ($data as $item) {
5429 $ids[] = $item['id'];
5432 $idStr = DBA::escape(implode(', ', $ids));
5433 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5434 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5435 $itemsData = DBA::toArray($items);
5437 foreach ($itemsData as $item) {
5438 $comments[$item['parent']] = $item['comments'];
5441 foreach ($data as $idx => $item) {
5443 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5448 @TODO Maybe open to implement?
5450 [pagename] => api/1.1/statuses/lookup.json
5451 [id] => 605138389168451584
5452 [include_cards] => true
5453 [cards_platform] => Android-12
5454 [include_entities] => true
5455 [include_my_retweet] => 1
5457 [include_reply_count] => true
5458 [include_descendent_reply_count] => true
5462 Not implemented by now:
5463 statuses/retweets_of_me
5468 account/update_location
5469 account/update_profile_background_image
5472 friendica/profile/update
5473 friendica/profile/create
5474 friendica/profile/delete
5476 Not implemented in status.net:
5477 statuses/retweeted_to_me
5478 statuses/retweeted_by_me
5479 direct_messages/destroy
5481 account/update_delivery_device
5482 notifications/follow