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\Content\ContactSelector;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\System;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Group;
37 use Friendica\Model\Item;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Notification;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Profile;
43 use Friendica\Model\User;
44 use Friendica\Model\Verb;
45 use Friendica\Module\Api\ApiResponse;
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\Image;
56 use Friendica\Protocol\Activity;
57 use Friendica\Security\BasicAuth;
58 use Friendica\Security\OAuth;
59 use Friendica\Util\DateTimeFormat;
60 use Friendica\Util\Images;
61 use Friendica\Util\Network;
62 use Friendica\Util\Proxy;
63 use Friendica\Util\Strings;
65 require_once __DIR__ . '/../mod/item.php';
66 require_once __DIR__ . '/../mod/wall_upload.php';
68 define('API_METHOD_ANY', '*');
69 define('API_METHOD_GET', 'GET');
70 define('API_METHOD_POST', 'POST,PUT');
71 define('API_METHOD_DELETE', 'POST,DELETE');
73 define('API_LOG_PREFIX', 'API {action} - ');
81 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
82 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
83 * into a page, and visitors will post something without noticing it).
87 $user = OAuth::getCurrentUserID();
92 if (!empty($_SESSION['allow_api'])) {
100 * Get source name from API client
102 * Clients can send 'source' parameter to be show in post metadata
103 * as "sent via <source>".
104 * Some clients doesn't send a source param, we support ones we know
105 * (only Twidere, atm)
108 * Client source name, default to "api" if unset/unknown
111 function api_source()
113 if (requestdata('source')) {
114 return requestdata('source');
117 // Support for known clients that doesn't send a source name
118 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
119 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
123 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
125 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
132 * Format date for API
134 * @param string $str Source date, as UTC
135 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
138 function api_date($str)
140 // Wed May 23 06:01:13 +0000 2007
141 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
145 * Register a function to be the endpoint for defined API path.
147 * @param string $path API URL path, relative to DI::baseUrl()
148 * @param string $func Function name to call on path request
149 * @param bool $auth API need logged user
150 * @param string $method HTTP method reqiured to call this endpoint.
151 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152 * Default to API_METHOD_ANY
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
164 // Workaround for hotot
165 $path = str_replace("api/", "api/1.1/", $path);
175 * Check HTTP method of called API
177 * API endpoints can define which HTTP method to accept when called.
178 * This function check the current HTTP method agains endpoint
181 * @param string $method Required methods, uppercase, separated by comma
184 function api_check_method($method)
186 if ($method == "*") {
189 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
193 * Main API entry point
195 * Authenticate user, call registered API function, set HTTP headers
198 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
199 * @return string|array API call result
202 function api_call(App $a, App\Arguments $args = null)
204 global $API, $called_api;
211 if (strpos($args->getCommand(), ".xml") > 0) {
214 if (strpos($args->getCommand(), ".json") > 0) {
217 if (strpos($args->getCommand(), ".rss") > 0) {
220 if (strpos($args->getCommand(), ".atom") > 0) {
225 foreach ($API as $p => $info) {
226 if (strpos($args->getCommand(), $p) === 0) {
227 if (!api_check_method($info['method'])) {
228 throw new MethodNotAllowedException();
231 $called_api = explode("/", $p);
233 if (!empty($info['auth']) && api_user() === false) {
234 BasicAuth::getCurrentUserID(true);
235 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
238 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
240 $stamp = microtime(true);
241 $return = call_user_func($info['func'], $type);
242 $duration = floatval(microtime(true) - $stamp);
244 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
246 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
248 if (false === $return) {
250 * api function returned false withour throw an
251 * exception. This should not happend, throw a 500
253 throw new InternalServerErrorException();
258 header("Content-Type: text/xml");
261 header("Content-Type: application/json");
262 if (!empty($return)) {
263 $json = json_encode(end($return));
264 if (!empty($_GET['callback'])) {
265 $json = $_GET['callback'] . "(" . $json . ")";
271 header("Content-Type: application/rss+xml");
272 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
275 header("Content-Type: application/atom+xml");
276 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
283 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
284 throw new NotFoundException();
285 } catch (HTTPException $e) {
286 ApiResponse::error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
291 * Set values for RSS template
294 * @param array $arr Array to be passed to template
295 * @param array $user_info User info
297 * @throws BadRequestException
298 * @throws ImagickException
299 * @throws InternalServerErrorException
300 * @throws UnauthorizedException
301 * @todo find proper type-hints
303 function api_rss_extra(App $a, $arr, $user_info)
305 if (is_null($user_info)) {
306 $user_info = api_get_user();
309 $arr['$user'] = $user_info;
311 'alternate' => $user_info['url'],
312 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
313 'base' => DI::baseUrl(),
314 'updated' => api_date(null),
315 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
316 'language' => $user_info['lang'],
317 'logo' => DI::baseUrl() . "/images/friendica-32.png",
325 * Unique contact to contact url.
327 * @param int $id Contact id
328 * @return bool|string
329 * Contact url or False if contact id is unknown
332 function api_unique_id_to_nurl($id)
334 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
336 if (DBA::isResult($r)) {
344 * Get user info array.
347 * @param int|string $contact_id Contact ID or URL
349 * @throws BadRequestException
350 * @throws ImagickException
351 * @throws InternalServerErrorException
352 * @throws UnauthorizedException
354 function api_get_user($contact_id = null)
362 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
364 // Searching for contact URL
365 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
366 $user = Strings::normaliseLink($contact_id);
368 $extra_query = "AND `contact`.`nurl` = ? ";
369 if (api_user() !== false) {
370 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
374 // Searching for contact id with uid = 0
375 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
376 $user = api_unique_id_to_nurl(intval($contact_id));
379 throw new BadRequestException("User ID ".$contact_id." not found.");
383 $extra_query = "AND `contact`.`nurl` = ? ";
384 if (api_user() !== false) {
385 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
389 if (is_null($user) && !empty($_GET['user_id'])) {
390 $user = api_unique_id_to_nurl($_GET['user_id']);
393 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
397 $extra_query = "AND `contact`.`nurl` = ? ";
398 if (api_user() !== false) {
399 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
402 if (is_null($user) && !empty($_GET['screen_name'])) {
403 $user = $_GET['screen_name'];
404 $extra_query = "AND `contact`.`nick` = ? ";
405 if (api_user() !== false) {
406 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
410 if (is_null($user) && !empty($_GET['profileurl'])) {
411 $user = Strings::normaliseLink($_GET['profileurl']);
412 $extra_query = "AND `contact`.`nurl` = ? ";
413 if (api_user() !== false) {
414 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
418 // $called_api is the API path exploded on / and is expected to have at least 2 elements
419 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
420 $argid = count($called_api);
421 if (!empty(DI::args()->getArgv()[$argid])) {
422 $data = explode(".", DI::args()->getArgv()[$argid]);
423 if (count($data) > 1) {
424 [$user, $null] = $data;
427 if (is_numeric($user)) {
428 $user = api_unique_id_to_nurl(intval($user));
432 $extra_query = "AND `contact`.`nurl` = ? ";
433 if (api_user() !== false) {
434 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
438 $extra_query = "AND `contact`.`nick` = ? ";
439 if (api_user() !== false) {
440 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
445 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
448 if (api_user() === false) {
449 BasicAuth::getCurrentUserID(true);
453 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
457 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
460 $uinfo = DBA::toArray(DBA::p(
461 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
467 // Selecting the id by priority, friendica first
468 if (is_array($uinfo)) {
469 api_best_nickname($uinfo);
472 // if the contact wasn't found, fetch it from the contacts with uid = 0
473 if (!DBA::isResult($uinfo)) {
475 throw new BadRequestException("User not found.");
478 $contact = DBA::selectFirst('contact', [], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
480 if (DBA::isResult($contact)) {
482 'id' => $contact["id"],
483 'id_str' => (string) $contact["id"],
484 'name' => $contact["name"],
485 'screen_name' => (($contact['nick']) ? $contact['nick'] : $contact['name']),
486 'location' => ($contact["location"] != "") ? $contact["location"] : ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol']),
487 'description' => BBCode::toPlaintext($contact["about"] ?? ''),
488 'profile_image_url' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
489 'profile_image_url_https' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_MICRO),
490 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_THUMB),
491 'profile_image_url_large' => Contact::getAvatarUrlForUrl($contact['url'], api_user(), Proxy::SIZE_SMALL),
492 'url' => $contact["url"],
493 'protected' => false,
494 'followers_count' => 0,
495 'friends_count' => 0,
497 'created_at' => api_date($contact["created"]),
498 'favourites_count' => 0,
500 'time_zone' => 'UTC',
501 'geo_enabled' => false,
503 'statuses_count' => 0,
505 'contributors_enabled' => false,
506 'is_translator' => false,
507 'is_translation_enabled' => false,
508 'following' => false,
509 'follow_request_sent' => false,
510 'statusnet_blocking' => false,
511 'notifications' => false,
512 'statusnet_profile_url' => $contact["url"],
514 'cid' => Contact::getIdForURL($contact["url"], api_user(), false),
515 'pid' => Contact::getIdForURL($contact["url"], 0, false),
517 'network' => $contact["network"],
522 throw new BadRequestException("User ".$url." not found.");
526 if ($uinfo[0]['self']) {
527 if ($uinfo[0]['network'] == "") {
528 $uinfo[0]['network'] = Protocol::DFRN;
531 $usr = DBA::selectFirst('user', ['default-location'], ['uid' => api_user()]);
532 $profile = DBA::selectFirst('profile', ['about'], ['uid' => api_user(), 'is-default' => true]);
539 $pcontact_id = Contact::getIdForURL($uinfo[0]['url'], 0, false);
541 if (!empty($profile['about'])) {
542 $description = $profile['about'];
544 $description = $uinfo[0]["about"];
547 if (!empty($usr['default-location'])) {
548 $location = $usr['default-location'];
549 } elseif (!empty($uinfo[0]["location"])) {
550 $location = $uinfo[0]["location"];
552 $location = ContactSelector::networkToName($uinfo[0]['network'], $uinfo[0]['url'], $uinfo[0]['protocol']);
556 'id' => intval($pcontact_id),
557 'id_str' => (string) intval($pcontact_id),
558 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
559 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
560 'location' => $location,
561 'description' => BBCode::toPlaintext($description ?? ''),
562 'profile_image_url' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
563 'profile_image_url_https' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_MICRO),
564 'profile_image_url_profile_size' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_THUMB),
565 'profile_image_url_large' => Contact::getAvatarUrlForUrl($uinfo[0]['url'], api_user(), Proxy::SIZE_SMALL),
566 'url' => $uinfo[0]['url'],
567 'protected' => false,
568 'followers_count' => intval($countfollowers),
569 'friends_count' => intval($countfriends),
571 'created_at' => api_date($uinfo[0]['created']),
572 'favourites_count' => intval($starred),
574 'time_zone' => 'UTC',
575 'geo_enabled' => false,
577 'statuses_count' => intval($countitems),
579 'contributors_enabled' => false,
580 'is_translator' => false,
581 'is_translation_enabled' => false,
582 'following' => (($uinfo[0]['rel'] == Contact::FOLLOWER) || ($uinfo[0]['rel'] == Contact::FRIEND)),
583 'follow_request_sent' => false,
584 'statusnet_blocking' => false,
585 'notifications' => false,
587 //'statusnet_profile_url' => DI::baseUrl()."/contact/".$uinfo[0]['cid'],
588 'statusnet_profile_url' => $uinfo[0]['url'],
589 'uid' => intval($uinfo[0]['uid']),
590 'cid' => intval($uinfo[0]['cid']),
591 'pid' => Contact::getIdForURL($uinfo[0]["url"], 0, false),
592 'self' => $uinfo[0]['self'],
593 'network' => $uinfo[0]['network'],
596 // If this is a local user and it uses Frio, we can get its color preferences.
598 $theme_info = DBA::selectFirst('user', ['theme'], ['uid' => $ret['uid']]);
599 if ($theme_info['theme'] === 'frio') {
600 $schema = DI::pConfig()->get($ret['uid'], 'frio', 'schema');
602 if ($schema && ($schema != '---')) {
603 if (file_exists('view/theme/frio/schema/'.$schema.'.php')) {
604 $schemefile = 'view/theme/frio/schema/'.$schema.'.php';
605 require_once $schemefile;
608 $nav_bg = DI::pConfig()->get($ret['uid'], 'frio', 'nav_bg');
609 $link_color = DI::pConfig()->get($ret['uid'], 'frio', 'link_color');
610 $bgcolor = DI::pConfig()->get($ret['uid'], 'frio', 'background_color');
612 if (empty($nav_bg)) {
615 if (empty($link_color)) {
616 $link_color = "#6fdbe8";
618 if (empty($bgcolor)) {
619 $bgcolor = "#ededed";
622 $ret['profile_sidebar_fill_color'] = str_replace('#', '', $nav_bg);
623 $ret['profile_link_color'] = str_replace('#', '', $link_color);
624 $ret['profile_background_color'] = str_replace('#', '', $bgcolor);
632 * return api-formatted array for item's author and owner
635 * @param array $item item from db
636 * @return array(array:author, array:owner)
637 * @throws BadRequestException
638 * @throws ImagickException
639 * @throws InternalServerErrorException
640 * @throws UnauthorizedException
642 function api_item_get_user(App $a, $item)
644 $status_user = api_get_user($item['author-id'] ?? null);
646 $author_user = $status_user;
648 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
650 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
651 $owner_user = api_get_user($item['owner-id'] ?? null);
653 $owner_user = $author_user;
656 return ([$status_user, $author_user, $owner_user]);
664 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
665 * returns a 401 status code and an error message if not.
667 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
669 * @param string $type Return type (atom, rss, xml, json)
670 * @return array|string
671 * @throws BadRequestException
672 * @throws ForbiddenException
673 * @throws ImagickException
674 * @throws InternalServerErrorException
675 * @throws UnauthorizedException
677 function api_account_verify_credentials($type)
681 if (api_user() === false) {
682 throw new ForbiddenException();
685 unset($_REQUEST["user_id"]);
686 unset($_GET["user_id"]);
688 unset($_REQUEST["screen_name"]);
689 unset($_GET["screen_name"]);
691 $skip_status = $_REQUEST['skip_status'] ?? false;
693 $user_info = api_get_user();
695 // "verified" isn't used here in the standard
696 unset($user_info["verified"]);
698 // - Adding last status
700 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
702 $user_info['status'] = api_format_item($item, $type);
706 // "uid" and "self" are only needed for some internal stuff, so remove it from here
707 unset($user_info["uid"]);
708 unset($user_info["self"]);
710 return ApiResponse::formatData("user", $type, ['user' => $user_info]);
713 /// @TODO move to top of file or somewhere better
714 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
717 * Get data from $_POST or $_GET
722 function requestdata($k)
724 if (!empty($_POST[$k])) {
727 if (!empty($_GET[$k])) {
734 * Deprecated function to upload media.
736 * @param string $type Return type (atom, rss, xml, json)
738 * @return array|string
739 * @throws BadRequestException
740 * @throws ForbiddenException
741 * @throws ImagickException
742 * @throws InternalServerErrorException
743 * @throws UnauthorizedException
745 function api_statuses_mediap($type)
749 if (api_user() === false) {
750 logger::notice('api_statuses_update: no user');
751 throw new ForbiddenException();
753 $user_info = api_get_user();
755 $_REQUEST['profile_uid'] = api_user();
756 $_REQUEST['api_source'] = true;
757 $txt = requestdata('status') ?? '';
758 /// @TODO old-lost code?
759 //$txt = urldecode(requestdata('status'));
761 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
762 $txt = HTML::toBBCodeVideo($txt);
763 $config = HTMLPurifier_Config::createDefault();
764 $config->set('Cache.DefinitionImpl', null);
765 $purifier = new HTMLPurifier($config);
766 $txt = $purifier->purify($txt);
768 $txt = HTML::toBBCode($txt);
770 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
772 $picture = wall_upload_post($a, false);
774 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
775 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
776 $item_id = item_post($a);
778 // output the post that we just posted.
779 return api_status_show($type, $item_id);
782 /// @TODO move this to top of file or somewhere better!
783 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
786 * Updates the user’s current status.
788 * @param string $type Return type (atom, rss, xml, json)
790 * @return array|string
791 * @throws BadRequestException
792 * @throws ForbiddenException
793 * @throws ImagickException
794 * @throws InternalServerErrorException
795 * @throws TooManyRequestsException
796 * @throws UnauthorizedException
797 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
799 function api_statuses_update($type)
803 if (api_user() === false) {
804 logger::notice('api_statuses_update: no user');
805 throw new ForbiddenException();
810 // convert $_POST array items to the form we use for web posts.
811 if (requestdata('htmlstatus')) {
812 $txt = requestdata('htmlstatus') ?? '';
813 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
814 $txt = HTML::toBBCodeVideo($txt);
816 $config = HTMLPurifier_Config::createDefault();
817 $config->set('Cache.DefinitionImpl', null);
819 $purifier = new HTMLPurifier($config);
820 $txt = $purifier->purify($txt);
822 $_REQUEST['body'] = HTML::toBBCode($txt);
825 $_REQUEST['body'] = requestdata('status');
828 $_REQUEST['title'] = requestdata('title');
830 $parent = requestdata('in_reply_to_status_id');
832 // Twidere sends "-1" if it is no reply ...
837 if (ctype_digit($parent)) {
838 $_REQUEST['parent'] = $parent;
840 $_REQUEST['parent_uri'] = $parent;
843 if (requestdata('lat') && requestdata('long')) {
844 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
846 $_REQUEST['profile_uid'] = api_user();
849 // Check for throttling (maximum posts per day, week and month)
850 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
851 if ($throttle_day > 0) {
852 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
854 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
855 $posts_day = Post::count($condition);
857 if ($posts_day > $throttle_day) {
858 logger::info('Daily posting limit reached for user '.api_user());
859 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
860 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));
864 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
865 if ($throttle_week > 0) {
866 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
868 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
869 $posts_week = Post::count($condition);
871 if ($posts_week > $throttle_week) {
872 logger::info('Weekly posting limit reached for user '.api_user());
873 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
874 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));
878 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
879 if ($throttle_month > 0) {
880 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
882 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
883 $posts_month = Post::count($condition);
885 if ($posts_month > $throttle_month) {
886 logger::info('Monthly posting limit reached for user '.api_user());
887 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
888 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));
893 if (requestdata('media_ids')) {
894 $ids = explode(',', requestdata('media_ids') ?? '');
895 } elseif (!empty($_FILES['media'])) {
896 // upload the image if we have one
897 $picture = wall_upload_post($a, false);
898 if (is_array($picture)) {
899 $ids[] = $picture['id'];
907 foreach ($ids as $id) {
908 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
909 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
910 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
911 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
913 if (!empty($media)) {
914 $ressources[] = $media[0]['resource-id'];
915 $phototypes = Images::supportedTypes();
916 $ext = $phototypes[$media[0]['type']];
918 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
919 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
920 'size' => $media[0]['datasize'],
921 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
922 'description' => $media[0]['desc'] ?? '',
923 'width' => $media[0]['width'],
924 'height' => $media[0]['height']];
926 if (count($media) > 1) {
927 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
928 $attachment['preview-width'] = $media[1]['width'];
929 $attachment['preview-height'] = $media[1]['height'];
931 $attachments[] = $attachment;
935 // We have to avoid that the post is rejected because of an empty body
936 if (empty($_REQUEST['body'])) {
937 $_REQUEST['body'] = '[hr]';
941 if (!empty($attachments)) {
942 $_REQUEST['attachments'] = $attachments;
945 // set this so that the item_post() function is quiet and doesn't redirect or emit json
947 $_REQUEST['api_source'] = true;
949 if (empty($_REQUEST['source'])) {
950 $_REQUEST["source"] = api_source();
953 // call out normal post function
954 $item_id = item_post($a);
956 if (!empty($ressources) && !empty($item_id)) {
957 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
958 foreach ($ressources as $ressource) {
959 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
963 // output the post that we just posted.
964 return api_status_show($type, $item_id);
967 /// @TODO move to top of file or somewhere better
968 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
969 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
972 * Uploads an image to Friendica.
975 * @throws BadRequestException
976 * @throws ForbiddenException
977 * @throws ImagickException
978 * @throws InternalServerErrorException
979 * @throws UnauthorizedException
980 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
982 function api_media_upload()
986 if (api_user() === false) {
987 logger::notice('no user');
988 throw new ForbiddenException();
993 if (empty($_FILES['media'])) {
995 throw new BadRequestException("No media.");
998 $media = wall_upload_post($a, false);
1001 throw new InternalServerErrorException();
1005 $returndata["media_id"] = $media["id"];
1006 $returndata["media_id_string"] = (string)$media["id"];
1007 $returndata["size"] = $media["size"];
1008 $returndata["image"] = ["w" => $media["width"],
1009 "h" => $media["height"],
1010 "image_type" => $media["type"],
1011 "friendica_preview_url" => $media["preview"]];
1013 Logger::info('Media uploaded', ['return' => $returndata]);
1015 return ["media" => $returndata];
1018 /// @TODO move to top of file or somewhere better
1019 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
1022 * Updates media meta data (picture descriptions)
1024 * @param string $type Return type (atom, rss, xml, json)
1026 * @return array|string
1027 * @throws BadRequestException
1028 * @throws ForbiddenException
1029 * @throws ImagickException
1030 * @throws InternalServerErrorException
1031 * @throws TooManyRequestsException
1032 * @throws UnauthorizedException
1033 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
1035 * @todo Compare the corresponding Twitter function for correct return values
1037 function api_media_metadata_create($type)
1041 if (api_user() === false) {
1042 Logger::info('no user');
1043 throw new ForbiddenException();
1048 $postdata = Network::postdata();
1050 if (empty($postdata)) {
1051 throw new BadRequestException("No post data");
1054 $data = json_decode($postdata, true);
1056 throw new BadRequestException("Invalid post data");
1059 if (empty($data['media_id']) || empty($data['alt_text'])) {
1060 throw new BadRequestException("Missing post data values");
1063 if (empty($data['alt_text']['text'])) {
1064 throw new BadRequestException("No alt text.");
1067 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
1069 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
1070 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
1071 if (!DBA::isResult($photo)) {
1072 throw new BadRequestException("Metadata not found.");
1075 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
1078 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
1081 * @param string $type Return format (atom, rss, xml, json)
1082 * @param int $item_id
1083 * @return array|string
1086 function api_status_show($type, $item_id)
1088 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
1092 $item = api_get_item(['id' => $item_id]);
1093 if (!empty($item)) {
1094 $status_info = api_format_item($item, $type);
1097 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
1099 return ApiResponse::formatData('statuses', $type, ['status' => $status_info]);
1103 * Retrieves the last public status of the provided user info
1105 * @param int $ownerId Public contact Id
1106 * @param int $uid User Id
1110 function api_get_last_status($ownerId, $uid)
1113 'author-id'=> $ownerId,
1115 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
1116 'private' => [Item::PUBLIC, Item::UNLISTED]
1119 $item = api_get_item($condition);
1125 * Retrieves a single item record based on the provided condition and converts it for API use.
1127 * @param array $condition Item table condition array
1131 function api_get_item(array $condition)
1133 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
1139 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1140 * The author's most recent status will be returned inline.
1142 * @param string $type Return type (atom, rss, xml, json)
1143 * @return array|string
1144 * @throws BadRequestException
1145 * @throws ImagickException
1146 * @throws InternalServerErrorException
1147 * @throws UnauthorizedException
1148 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1150 function api_users_show($type)
1152 $a = Friendica\DI::app();
1154 $user_info = api_get_user();
1156 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1157 if (!empty($item)) {
1158 $user_info['status'] = api_format_item($item, $type);
1161 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1162 unset($user_info['uid']);
1163 unset($user_info['self']);
1165 return ApiResponse::formatData('user', $type, ['user' => $user_info]);
1168 /// @TODO move to top of file or somewhere better
1169 api_register_func('api/users/show', 'api_users_show');
1170 api_register_func('api/externalprofile/show', 'api_users_show');
1173 * Search a public user account.
1175 * @param string $type Return type (atom, rss, xml, json)
1177 * @return array|string
1178 * @throws BadRequestException
1179 * @throws ImagickException
1180 * @throws InternalServerErrorException
1181 * @throws UnauthorizedException
1182 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1184 function api_users_search($type)
1190 if (!empty($_GET['q'])) {
1191 $contacts = Contact::selectToArray(
1194 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1202 if (DBA::isResult($contacts)) {
1204 foreach ($contacts as $contact) {
1205 $user_info = api_get_user($contact['id']);
1207 if ($type == 'xml') {
1208 $userlist[$k++ . ':user'] = $user_info;
1210 $userlist[] = $user_info;
1213 $userlist = ['users' => $userlist];
1215 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1218 throw new BadRequestException('No search term specified.');
1221 return ApiResponse::formatData('users', $type, $userlist);
1224 /// @TODO move to top of file or somewhere better
1225 api_register_func('api/users/search', 'api_users_search');
1228 * Return user objects
1230 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1232 * @param string $type Return format: json or xml
1234 * @return array|string
1235 * @throws BadRequestException
1236 * @throws ImagickException
1237 * @throws InternalServerErrorException
1238 * @throws NotFoundException if the results are empty.
1239 * @throws UnauthorizedException
1241 function api_users_lookup($type)
1245 if (!empty($_REQUEST['user_id'])) {
1246 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1248 $users[] = api_get_user($id);
1253 if (empty($users)) {
1254 throw new NotFoundException;
1257 return ApiResponse::formatData("users", $type, ['users' => $users]);
1260 /// @TODO move to top of file or somewhere better
1261 api_register_func('api/users/lookup', 'api_users_lookup', true);
1264 * Returns statuses that match a specified query.
1266 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1268 * @param string $type Return format: json, xml, atom, rss
1270 * @return array|string
1271 * @throws BadRequestException if the "q" parameter is missing.
1272 * @throws ForbiddenException
1273 * @throws ImagickException
1274 * @throws InternalServerErrorException
1275 * @throws UnauthorizedException
1277 function api_search($type)
1280 $user_info = api_get_user();
1282 if (api_user() === false || $user_info === false) {
1283 throw new ForbiddenException();
1286 if (empty($_REQUEST['q'])) {
1287 throw new BadRequestException('q parameter is required.');
1290 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1293 $data['status'] = [];
1295 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1296 if (!empty($_REQUEST['rpp'])) {
1297 $count = $_REQUEST['rpp'];
1298 } elseif (!empty($_REQUEST['count'])) {
1299 $count = $_REQUEST['count'];
1302 $since_id = $_REQUEST['since_id'] ?? 0;
1303 $max_id = $_REQUEST['max_id'] ?? 0;
1304 $page = $_REQUEST['page'] ?? 1;
1306 $start = max(0, ($page - 1) * $count);
1308 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1309 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1310 $searchTerm = $matches[1];
1311 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1312 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1314 while ($tag = DBA::fetch($tags)) {
1315 $uriids[] = $tag['uri-id'];
1319 if (empty($uriids)) {
1320 return ApiResponse::formatData('statuses', $type, $data);
1323 $condition = ['uri-id' => $uriids];
1324 if ($exclude_replies) {
1325 $condition['gravity'] = GRAVITY_PARENT;
1328 $params['group_by'] = ['uri-id'];
1330 $condition = ["`id` > ?
1331 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1332 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1333 AND `body` LIKE CONCAT('%',?,'%')",
1334 $since_id, api_user(), $_REQUEST['q']];
1336 $condition[0] .= ' AND `id` <= ?';
1337 $condition[] = $max_id;
1343 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1344 $id = Item::fetchByLink($searchTerm, api_user());
1347 $id = Item::fetchByLink($searchTerm);
1351 $statuses = Post::select([], ['id' => $id]);
1355 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1357 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1359 bindComments($data['status']);
1361 return ApiResponse::formatData('statuses', $type, $data);
1364 /// @TODO move to top of file or somewhere better
1365 api_register_func('api/search/tweets', 'api_search', true);
1366 api_register_func('api/search', 'api_search', true);
1369 * Returns the most recent statuses posted by the user and the users they follow.
1371 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1373 * @param string $type Return type (atom, rss, xml, json)
1375 * @return array|string
1376 * @throws BadRequestException
1377 * @throws ForbiddenException
1378 * @throws ImagickException
1379 * @throws InternalServerErrorException
1380 * @throws UnauthorizedException
1381 * @todo Optional parameters
1382 * @todo Add reply info
1384 function api_statuses_home_timeline($type)
1387 $user_info = api_get_user();
1389 if (api_user() === false || $user_info === false) {
1390 throw new ForbiddenException();
1393 unset($_REQUEST["user_id"]);
1394 unset($_GET["user_id"]);
1396 unset($_REQUEST["screen_name"]);
1397 unset($_GET["screen_name"]);
1399 // get last network messages
1402 $count = $_REQUEST['count'] ?? 20;
1403 $page = $_REQUEST['page']?? 0;
1404 $since_id = $_REQUEST['since_id'] ?? 0;
1405 $max_id = $_REQUEST['max_id'] ?? 0;
1406 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1407 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1409 $start = max(0, ($page - 1) * $count);
1411 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1412 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1415 $condition[0] .= " AND `id` <= ?";
1416 $condition[] = $max_id;
1418 if ($exclude_replies) {
1419 $condition[0] .= ' AND `gravity` = ?';
1420 $condition[] = GRAVITY_PARENT;
1422 if ($conversation_id > 0) {
1423 $condition[0] .= " AND `parent` = ?";
1424 $condition[] = $conversation_id;
1427 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1428 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1430 $items = Post::toArray($statuses);
1432 $ret = api_format_items($items, $user_info, false, $type);
1434 // Set all posts from the query above to seen
1436 foreach ($items as $item) {
1437 $idarray[] = intval($item["id"]);
1440 if (!empty($idarray)) {
1441 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1443 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1449 $data = ['status' => $ret];
1454 $data = api_rss_extra($a, $data, $user_info);
1458 return ApiResponse::formatData("statuses", $type, $data);
1462 /// @TODO move to top of file or somewhere better
1463 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1464 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1467 * Returns the most recent statuses from public users.
1469 * @param string $type Return type (atom, rss, xml, json)
1471 * @return array|string
1472 * @throws BadRequestException
1473 * @throws ForbiddenException
1474 * @throws ImagickException
1475 * @throws InternalServerErrorException
1476 * @throws UnauthorizedException
1478 function api_statuses_public_timeline($type)
1481 $user_info = api_get_user();
1483 if (api_user() === false || $user_info === false) {
1484 throw new ForbiddenException();
1487 // get last network messages
1490 $count = $_REQUEST['count'] ?? 20;
1491 $page = $_REQUEST['page'] ?? 1;
1492 $since_id = $_REQUEST['since_id'] ?? 0;
1493 $max_id = $_REQUEST['max_id'] ?? 0;
1494 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1495 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1497 $start = max(0, ($page - 1) * $count);
1499 if ($exclude_replies && !$conversation_id) {
1500 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1501 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1504 $condition[0] .= " AND `id` <= ?";
1505 $condition[] = $max_id;
1508 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1509 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1511 $r = Post::toArray($statuses);
1513 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1514 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1517 $condition[0] .= " AND `id` <= ?";
1518 $condition[] = $max_id;
1520 if ($conversation_id > 0) {
1521 $condition[0] .= " AND `parent` = ?";
1522 $condition[] = $conversation_id;
1525 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1526 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1528 $r = Post::toArray($statuses);
1531 $ret = api_format_items($r, $user_info, false, $type);
1535 $data = ['status' => $ret];
1540 $data = api_rss_extra($a, $data, $user_info);
1544 return ApiResponse::formatData("statuses", $type, $data);
1547 /// @TODO move to top of file or somewhere better
1548 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1551 * Returns the most recent statuses posted by users this node knows about.
1553 * @param string $type Return format: json, xml, atom, rss
1554 * @return array|string
1555 * @throws BadRequestException
1556 * @throws ForbiddenException
1557 * @throws ImagickException
1558 * @throws InternalServerErrorException
1559 * @throws UnauthorizedException
1561 function api_statuses_networkpublic_timeline($type)
1564 $user_info = api_get_user();
1566 if (api_user() === false || $user_info === false) {
1567 throw new ForbiddenException();
1570 $since_id = $_REQUEST['since_id'] ?? 0;
1571 $max_id = $_REQUEST['max_id'] ?? 0;
1574 $count = $_REQUEST['count'] ?? 20;
1575 $page = $_REQUEST['page'] ?? 1;
1577 $start = max(0, ($page - 1) * $count);
1579 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1580 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1583 $condition[0] .= " AND `id` <= ?";
1584 $condition[] = $max_id;
1587 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1588 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1590 $ret = api_format_items($statuses, $user_info, false, $type);
1594 $data = ['status' => $ret];
1599 $data = api_rss_extra($a, $data, $user_info);
1603 return ApiResponse::formatData("statuses", $type, $data);
1606 /// @TODO move to top of file or somewhere better
1607 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1610 * Returns a single status.
1612 * @param string $type Return type (atom, rss, xml, json)
1614 * @return array|string
1615 * @throws BadRequestException
1616 * @throws ForbiddenException
1617 * @throws ImagickException
1618 * @throws InternalServerErrorException
1619 * @throws UnauthorizedException
1620 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1622 function api_statuses_show($type)
1625 $user_info = api_get_user();
1627 if (api_user() === false || $user_info === false) {
1628 throw new ForbiddenException();
1632 $id = intval(DI::args()->getArgv()[3] ?? 0);
1635 $id = intval($_REQUEST['id'] ?? 0);
1640 $id = intval(DI::args()->getArgv()[4] ?? 0);
1643 logger::notice('API: api_statuses_show: ' . $id);
1645 $conversation = !empty($_REQUEST['conversation']);
1647 // try to fetch the item for the local user - or the public item, if there is no local one
1648 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1649 if (!DBA::isResult($uri_item)) {
1650 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1653 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1654 if (!DBA::isResult($item)) {
1655 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1660 if ($conversation) {
1661 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1662 $params = ['order' => ['id' => true]];
1664 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1668 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1670 /// @TODO How about copying this to above methods which don't check $r ?
1671 if (!DBA::isResult($statuses)) {
1672 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1675 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1677 if ($conversation) {
1678 $data = ['status' => $ret];
1679 return ApiResponse::formatData("statuses", $type, $data);
1681 $data = ['status' => $ret[0]];
1682 return ApiResponse::formatData("status", $type, $data);
1686 /// @TODO move to top of file or somewhere better
1687 api_register_func('api/statuses/show', 'api_statuses_show', true);
1691 * @param string $type Return type (atom, rss, xml, json)
1693 * @return array|string
1694 * @throws BadRequestException
1695 * @throws ForbiddenException
1696 * @throws ImagickException
1697 * @throws InternalServerErrorException
1698 * @throws UnauthorizedException
1699 * @todo nothing to say?
1701 function api_conversation_show($type)
1704 $user_info = api_get_user();
1706 if (api_user() === false || $user_info === false) {
1707 throw new ForbiddenException();
1711 $id = intval(DI::args()->getArgv()[3] ?? 0);
1712 $since_id = intval($_REQUEST['since_id'] ?? 0);
1713 $max_id = intval($_REQUEST['max_id'] ?? 0);
1714 $count = intval($_REQUEST['count'] ?? 20);
1715 $page = intval($_REQUEST['page'] ?? 1);
1717 $start = max(0, ($page - 1) * $count);
1720 $id = intval($_REQUEST['id'] ?? 0);
1725 $id = intval(DI::args()->getArgv()[4] ?? 0);
1728 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1730 // try to fetch the item for the local user - or the public item, if there is no local one
1731 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1732 if (!DBA::isResult($item)) {
1733 throw new BadRequestException("There is no status with the id $id.");
1736 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1737 if (!DBA::isResult($parent)) {
1738 throw new BadRequestException("There is no status with this id.");
1741 $id = $parent['id'];
1743 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1744 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1747 $condition[0] .= " AND `id` <= ?";
1748 $condition[] = $max_id;
1751 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1752 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1754 if (!DBA::isResult($statuses)) {
1755 throw new BadRequestException("There is no status with id $id.");
1758 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1760 $data = ['status' => $ret];
1761 return ApiResponse::formatData("statuses", $type, $data);
1764 /// @TODO move to top of file or somewhere better
1765 api_register_func('api/conversation/show', 'api_conversation_show', true);
1766 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1771 * @param string $type Return type (atom, rss, xml, json)
1773 * @return array|string
1774 * @throws BadRequestException
1775 * @throws ForbiddenException
1776 * @throws ImagickException
1777 * @throws InternalServerErrorException
1778 * @throws UnauthorizedException
1779 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1781 function api_statuses_repeat($type)
1787 if (api_user() === false) {
1788 throw new ForbiddenException();
1794 $id = intval(DI::args()->getArgv()[3] ?? 0);
1797 $id = intval($_REQUEST['id'] ?? 0);
1802 $id = intval(DI::args()->getArgv()[4] ?? 0);
1805 logger::notice('API: api_statuses_repeat: ' . $id);
1807 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1808 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1810 if (DBA::isResult($item) && !empty($item['body'])) {
1811 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1812 if (!Item::performActivity($id, 'announce', local_user())) {
1813 throw new InternalServerErrorException();
1818 if (strpos($item['body'], "[/share]") !== false) {
1819 $pos = strpos($item['body'], "[share");
1820 $post = substr($item['body'], $pos);
1822 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1824 if (!empty($item['title'])) {
1825 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1828 $post .= $item['body'];
1829 $post .= "[/share]";
1831 $_REQUEST['body'] = $post;
1832 $_REQUEST['profile_uid'] = api_user();
1833 $_REQUEST['api_source'] = true;
1835 if (empty($_REQUEST['source'])) {
1836 $_REQUEST["source"] = api_source();
1839 $item_id = item_post($a);
1842 throw new ForbiddenException();
1845 // output the post that we just posted.
1847 return api_status_show($type, $item_id);
1850 /// @TODO move to top of file or somewhere better
1851 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1854 * Destroys a specific status.
1856 * @param string $type Return type (atom, rss, xml, json)
1858 * @return array|string
1859 * @throws BadRequestException
1860 * @throws ForbiddenException
1861 * @throws ImagickException
1862 * @throws InternalServerErrorException
1863 * @throws UnauthorizedException
1864 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1866 function api_statuses_destroy($type)
1870 if (api_user() === false) {
1871 throw new ForbiddenException();
1877 $id = intval(DI::args()->getArgv()[3] ?? 0);
1880 $id = intval($_REQUEST['id'] ?? 0);
1885 $id = intval(DI::args()->getArgv()[4] ?? 0);
1888 logger::notice('API: api_statuses_destroy: ' . $id);
1890 $ret = api_statuses_show($type);
1892 Item::deleteForUser(['id' => $id], api_user());
1897 /// @TODO move to top of file or somewhere better
1898 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1901 * Returns the most recent mentions.
1903 * @param string $type Return type (atom, rss, xml, json)
1905 * @return array|string
1906 * @throws BadRequestException
1907 * @throws ForbiddenException
1908 * @throws ImagickException
1909 * @throws InternalServerErrorException
1910 * @throws UnauthorizedException
1911 * @see http://developer.twitter.com/doc/get/statuses/mentions
1913 function api_statuses_mentions($type)
1916 $user_info = api_get_user();
1918 if (api_user() === false || $user_info === false) {
1919 throw new ForbiddenException();
1922 unset($_REQUEST["user_id"]);
1923 unset($_GET["user_id"]);
1925 unset($_REQUEST["screen_name"]);
1926 unset($_GET["screen_name"]);
1928 // get last network messages
1931 $since_id = intval($_REQUEST['since_id'] ?? 0);
1932 $max_id = intval($_REQUEST['max_id'] ?? 0);
1933 $count = intval($_REQUEST['count'] ?? 20);
1934 $page = intval($_REQUEST['page'] ?? 1);
1936 $start = max(0, ($page - 1) * $count);
1938 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1939 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1940 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1943 GRAVITY_PARENT, GRAVITY_COMMENT,
1945 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1946 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1947 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1948 api_user(), $since_id,
1952 $query .= " AND `id` <= ?";
1953 $condition[] = $max_id;
1956 array_unshift($condition, $query);
1958 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1959 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1961 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1963 $data = ['status' => $ret];
1968 $data = api_rss_extra($a, $data, $user_info);
1972 return ApiResponse::formatData("statuses", $type, $data);
1975 /// @TODO move to top of file or somewhere better
1976 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1977 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1980 * Returns the most recent statuses posted by the user.
1982 * @param string $type Either "json" or "xml"
1983 * @return string|array
1984 * @throws BadRequestException
1985 * @throws ForbiddenException
1986 * @throws ImagickException
1987 * @throws InternalServerErrorException
1988 * @throws UnauthorizedException
1989 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1991 function api_statuses_user_timeline($type)
1994 $user_info = api_get_user();
1996 if (api_user() === false || $user_info === false) {
1997 throw new ForbiddenException();
2000 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
2002 $since_id = $_REQUEST['since_id'] ?? 0;
2003 $max_id = $_REQUEST['max_id'] ?? 0;
2004 $exclude_replies = !empty($_REQUEST['exclude_replies']);
2005 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2008 $count = $_REQUEST['count'] ?? 20;
2009 $page = $_REQUEST['page'] ?? 1;
2011 $start = max(0, ($page - 1) * $count);
2013 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
2014 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
2016 if ($user_info['self'] == 1) {
2017 $condition[0] .= ' AND `wall` ';
2020 if ($exclude_replies) {
2021 $condition[0] .= ' AND `gravity` = ?';
2022 $condition[] = GRAVITY_PARENT;
2025 if ($conversation_id > 0) {
2026 $condition[0] .= " AND `parent` = ?";
2027 $condition[] = $conversation_id;
2031 $condition[0] .= " AND `id` <= ?";
2032 $condition[] = $max_id;
2034 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2035 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2037 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
2041 $data = ['status' => $ret];
2046 $data = api_rss_extra($a, $data, $user_info);
2050 return ApiResponse::formatData("statuses", $type, $data);
2053 /// @TODO move to top of file or somewhere better
2054 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
2057 * Star/unstar an item.
2058 * param: id : id of the item
2060 * @param string $type Return type (atom, rss, xml, json)
2062 * @return array|string
2063 * @throws BadRequestException
2064 * @throws ForbiddenException
2065 * @throws ImagickException
2066 * @throws InternalServerErrorException
2067 * @throws UnauthorizedException
2068 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
2070 function api_favorites_create_destroy($type)
2074 if (api_user() === false) {
2075 throw new ForbiddenException();
2078 // for versioned api.
2079 /// @TODO We need a better global soluton
2080 $action_argv_id = 2;
2081 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
2082 $action_argv_id = 3;
2085 if (DI::args()->getArgc() <= $action_argv_id) {
2086 throw new BadRequestException("Invalid request.");
2088 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
2089 if (DI::args()->getArgc() == $action_argv_id + 2) {
2090 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
2092 $itemid = intval($_REQUEST['id'] ?? 0);
2095 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
2097 if (!DBA::isResult($item)) {
2098 throw new BadRequestException("Invalid item.");
2103 $item['starred'] = 1;
2106 $item['starred'] = 0;
2109 throw new BadRequestException("Invalid action ".$action);
2112 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
2115 throw new InternalServerErrorException("DB error");
2119 $user_info = api_get_user();
2120 $rets = api_format_items([$item], $user_info, false, $type);
2123 $data = ['status' => $ret];
2128 $data = api_rss_extra($a, $data, $user_info);
2132 return ApiResponse::formatData("status", $type, $data);
2135 /// @TODO move to top of file or somewhere better
2136 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
2137 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
2140 * Returns the most recent favorite statuses.
2142 * @param string $type Return type (atom, rss, xml, json)
2144 * @return string|array
2145 * @throws BadRequestException
2146 * @throws ForbiddenException
2147 * @throws ImagickException
2148 * @throws InternalServerErrorException
2149 * @throws UnauthorizedException
2151 function api_favorites($type)
2156 $user_info = api_get_user();
2158 if (api_user() === false || $user_info === false) {
2159 throw new ForbiddenException();
2164 // in friendica starred item are private
2165 // return favorites only for self
2166 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2168 if ($user_info['self'] == 0) {
2172 $since_id = $_REQUEST['since_id'] ?? 0;
2173 $max_id = $_REQUEST['max_id'] ?? 0;
2174 $count = $_GET['count'] ?? 20;
2175 $page = $_REQUEST['page'] ?? 1;
2177 $start = max(0, ($page - 1) * $count);
2179 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2180 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2182 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2185 $condition[0] .= " AND `id` <= ?";
2186 $condition[] = $max_id;
2189 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2191 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2196 $data = ['status' => $ret];
2201 $data = api_rss_extra($a, $data, $user_info);
2205 return ApiResponse::formatData("statuses", $type, $data);
2208 /// @TODO move to top of file or somewhere better
2209 api_register_func('api/favorites', 'api_favorites', true);
2213 * @param array $item
2214 * @param array $recipient
2215 * @param array $sender
2218 * @throws InternalServerErrorException
2220 function api_format_messages($item, $recipient, $sender)
2222 // standard meta information
2224 'id' => $item['id'],
2225 'sender_id' => $sender['id'],
2227 'recipient_id' => $recipient['id'],
2228 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2229 'sender_screen_name' => $sender['screen_name'],
2230 'recipient_screen_name' => $recipient['screen_name'],
2231 'sender' => $sender,
2232 'recipient' => $recipient,
2234 'friendica_seen' => $item['seen'] ?? 0,
2235 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2238 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2239 if (isset($ret['sender']['uid'])) {
2240 unset($ret['sender']['uid']);
2242 if (isset($ret['sender']['self'])) {
2243 unset($ret['sender']['self']);
2245 if (isset($ret['recipient']['uid'])) {
2246 unset($ret['recipient']['uid']);
2248 if (isset($ret['recipient']['self'])) {
2249 unset($ret['recipient']['self']);
2252 //don't send title to regular StatusNET requests to avoid confusing these apps
2253 if (!empty($_GET['getText'])) {
2254 $ret['title'] = $item['title'];
2255 if ($_GET['getText'] == 'html') {
2256 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2257 } elseif ($_GET['getText'] == 'plain') {
2258 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2261 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2263 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2264 unset($ret['sender']);
2265 unset($ret['recipient']);
2273 * @param array $item
2276 * @throws InternalServerErrorException
2278 function api_convert_item($item)
2280 $body = api_add_attachments_to_body($item);
2282 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2284 // Add pictures to the attachment array and remove them from the body
2285 $attachments = api_get_attachments($body, $item['uri-id']);
2287 // Workaround for ostatus messages where the title is identically to the body
2288 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2289 $statusbody = trim(HTML::toPlaintext($html, 0));
2291 // handle data: images
2292 $statusbody = api_format_items_embeded_images($item, $statusbody);
2294 $statustitle = trim($item['title']);
2296 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2297 $statustext = trim($statusbody);
2299 $statustext = trim($statustitle."\n\n".$statusbody);
2302 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2303 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2306 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2308 // Workaround for clients with limited HTML parser functionality
2309 $search = ["<br>", "<blockquote>", "</blockquote>",
2310 "<h1>", "</h1>", "<h2>", "</h2>",
2311 "<h3>", "</h3>", "<h4>", "</h4>",
2312 "<h5>", "</h5>", "<h6>", "</h6>"];
2313 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2314 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2315 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2316 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2317 $statushtml = str_replace($search, $replace, $statushtml);
2319 if ($item['title'] != "") {
2320 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2324 $oldtext = $statushtml;
2325 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2326 } while ($oldtext != $statushtml);
2328 if (substr($statushtml, 0, 4) == '<br>') {
2329 $statushtml = substr($statushtml, 4);
2332 if (substr($statushtml, 0, -4) == '<br>') {
2333 $statushtml = substr($statushtml, -4);
2336 // feeds without body should contain the link
2337 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2338 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2342 "text" => $statustext,
2343 "html" => $statushtml,
2344 "attachments" => $attachments,
2345 "entities" => $entities
2350 * Add media attachments to the body
2352 * @param array $item
2353 * @return string body with added media
2355 function api_add_attachments_to_body(array $item)
2357 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2359 if (strpos($body, '[/img]') !== false) {
2363 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2364 if (!empty($media['preview'])) {
2365 $description = $media['description'] ?: $media['name'];
2366 if (!empty($description)) {
2367 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2369 $body .= "\n[img]" . $media['preview'] .'[/img]';
2379 * @param string $body
2383 * @throws InternalServerErrorException
2385 function api_get_attachments(&$body, $uriid)
2387 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2388 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2390 $URLSearchString = "^\[\]";
2391 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2395 // Remove all embedded pictures, since they are added as attachments
2396 foreach ($images[0] as $orig) {
2397 $body = str_replace($orig, '', $body);
2402 foreach ($images[1] as $image) {
2403 $imagedata = Images::getInfoFromURLCached($image);
2406 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2410 return $attachments;
2415 * @param string $text
2416 * @param string $bbcode
2419 * @throws InternalServerErrorException
2420 * @todo Links at the first character of the post
2422 function api_get_entitities(&$text, $bbcode, $uriid)
2424 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2426 if ($include_entities != "true") {
2427 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2429 foreach ($images[1] as $image) {
2430 $replace = Post\Link::getByLink($uriid, $image);
2431 $text = str_replace($image, $replace, $text);
2436 $bbcode = BBCode::cleanPictureLinks($bbcode);
2438 // Change pure links in text to bbcode uris
2439 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2442 $entities["hashtags"] = [];
2443 $entities["symbols"] = [];
2444 $entities["urls"] = [];
2445 $entities["user_mentions"] = [];
2447 $URLSearchString = "^\[\]";
2449 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2451 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2452 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2454 $bbcode = preg_replace(
2455 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2456 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2459 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2461 $bbcode = preg_replace(
2462 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2463 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2466 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2468 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2470 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2473 foreach ($urls[1] as $id => $url) {
2474 $start = iconv_strpos($text, $url, 0, "UTF-8");
2475 if (!($start === false)) {
2476 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2480 ksort($ordered_urls);
2484 foreach ($ordered_urls as $url) {
2485 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2486 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2488 $display_url = $url["title"];
2490 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2491 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2493 if (strlen($display_url) > 26) {
2494 $display_url = substr($display_url, 0, 25)."…";
2498 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2499 if (!($start === false)) {
2500 $entities["urls"][] = ["url" => $url["url"],
2501 "expanded_url" => $url["url"],
2502 "display_url" => $display_url,
2503 "indices" => [$start, $start+strlen($url["url"])]];
2504 $offset = $start + 1;
2508 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2509 $ordered_images = [];
2510 foreach ($images as $image) {
2511 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2512 if (!($start === false)) {
2513 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2517 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2518 foreach ($images[1] as $image) {
2519 $start = iconv_strpos($text, $image, 0, "UTF-8");
2520 if (!($start === false)) {
2521 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2527 foreach ($ordered_images as $image) {
2528 $url = $image['url'];
2529 $ext_alt_text = $image['alt'];
2531 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2532 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2534 if (strlen($display_url) > 26) {
2535 $display_url = substr($display_url, 0, 25)."…";
2538 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2539 if (!($start === false)) {
2540 $image = Images::getInfoFromURLCached($url);
2542 $media_url = Post\Link::getByLink($uriid, $url);
2543 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2545 $entities["media"][] = [
2547 "id_str" => (string) ($start + 1),
2548 "indices" => [$start, $start+strlen($url)],
2549 "media_url" => Strings::normaliseLink($media_url),
2550 "media_url_https" => $media_url,
2552 "display_url" => $display_url,
2553 "expanded_url" => $url,
2554 "ext_alt_text" => $ext_alt_text,
2558 $offset = $start + 1;
2567 * @param array $item
2568 * @param string $text
2572 function api_format_items_embeded_images($item, $text)
2574 $text = preg_replace_callback(
2575 '|data:image/([^;]+)[^=]+=*|m',
2576 function () use ($item) {
2577 return DI::baseUrl() . '/display/' . $item['guid'];
2585 * return <a href='url'>name</a> as array
2587 * @param string $txt text
2592 function api_contactlink_to_array($txt)
2595 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2596 if ($r && count($match)==3) {
2598 'name' => $match[2],
2612 * return likes, dislikes and attend status for item
2614 * @param array $item array
2615 * @param string $type Return type (atom, rss, xml, json)
2618 * likes => int count,
2619 * dislikes => int count
2620 * @throws BadRequestException
2621 * @throws ImagickException
2622 * @throws InternalServerErrorException
2623 * @throws UnauthorizedException
2625 function api_format_items_activities($item, $type = "json")
2634 'attendmaybe' => [],
2638 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2639 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2641 while ($parent_item = Post::fetch($ret)) {
2642 // not used as result should be structured like other user data
2643 //builtin_activity_puller($i, $activities);
2645 // get user data and add it to the array of the activity
2646 $user = api_get_user($parent_item['author-id']);
2647 switch ($parent_item['verb']) {
2648 case Activity::LIKE:
2649 $activities['like'][] = $user;
2651 case Activity::DISLIKE:
2652 $activities['dislike'][] = $user;
2654 case Activity::ATTEND:
2655 $activities['attendyes'][] = $user;
2657 case Activity::ATTENDNO:
2658 $activities['attendno'][] = $user;
2660 case Activity::ATTENDMAYBE:
2661 $activities['attendmaybe'][] = $user;
2663 case Activity::ANNOUNCE:
2664 $activities['announce'][] = $user;
2673 if ($type == "xml") {
2674 $xml_activities = [];
2675 foreach ($activities as $k => $v) {
2676 // change xml element from "like" to "friendica:like"
2677 $xml_activities["friendica:".$k] = $v;
2678 // add user data into xml output
2680 foreach ($v as $user) {
2681 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2684 $activities = $xml_activities;
2691 * format items to be returned by api
2693 * @param array $items array of items
2694 * @param array $user_info
2695 * @param bool $filter_user filter items by $user_info
2696 * @param string $type Return type (atom, rss, xml, json)
2698 * @throws BadRequestException
2699 * @throws ImagickException
2700 * @throws InternalServerErrorException
2701 * @throws UnauthorizedException
2703 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2705 $a = Friendica\DI::app();
2709 if (empty($items)) {
2713 foreach ((array)$items as $item) {
2714 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2716 // Look if the posts are matching if they should be filtered by user id
2717 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2721 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2730 * @param array $item Item record
2731 * @param string $type Return format (atom, rss, xml, json)
2732 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2733 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2734 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2735 * @return array API-formatted status
2736 * @throws BadRequestException
2737 * @throws ImagickException
2738 * @throws InternalServerErrorException
2739 * @throws UnauthorizedException
2741 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2743 $a = Friendica\DI::app();
2745 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2746 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2749 DI::contentItem()->localize($item);
2751 $in_reply_to = api_in_reply_to($item);
2753 $converted = api_convert_item($item);
2755 if ($type == "xml") {
2756 $geo = "georss:point";
2762 'text' => $converted["text"],
2763 'truncated' => false,
2764 'created_at'=> api_date($item['created']),
2765 'in_reply_to_status_id' => $in_reply_to['status_id'],
2766 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2767 'source' => (($item['app']) ? $item['app'] : 'web'),
2768 'id' => intval($item['id']),
2769 'id_str' => (string) intval($item['id']),
2770 'in_reply_to_user_id' => $in_reply_to['user_id'],
2771 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2772 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2774 'favorited' => $item['starred'] ? true : false,
2775 'user' => $status_user,
2776 'friendica_author' => $author_user,
2777 'friendica_owner' => $owner_user,
2778 'friendica_private' => $item['private'] == Item::PRIVATE,
2779 //'entities' => NULL,
2780 'statusnet_html' => $converted["html"],
2781 'statusnet_conversation_id' => $item['parent'],
2782 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2783 'friendica_activities' => api_format_items_activities($item, $type),
2784 'friendica_title' => $item['title'],
2785 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2788 if (count($converted["attachments"]) > 0) {
2789 $status["attachments"] = $converted["attachments"];
2792 if (count($converted["entities"]) > 0) {
2793 $status["entities"] = $converted["entities"];
2796 if ($status["source"] == 'web') {
2797 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2798 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2799 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2802 $retweeted_item = [];
2805 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2806 $announce = api_get_announce($item);
2807 if (!empty($announce)) {
2808 $retweeted_item = $item;
2810 $status['friendica_owner'] = api_get_user($announce['author-id']);
2814 if (!empty($quoted_item)) {
2815 if ($quoted_item['id'] != $item['id']) {
2816 $quoted_status = api_format_item($quoted_item);
2817 /// @todo Only remove the attachments that are also contained in the quotes status
2818 unset($status['attachments']);
2819 unset($status['entities']);
2821 $conv_quoted = api_convert_item($quoted_item);
2822 $quoted_status = $status;
2823 unset($quoted_status['attachments']);
2824 unset($quoted_status['entities']);
2825 unset($quoted_status['statusnet_conversation_id']);
2826 $quoted_status['text'] = $conv_quoted['text'];
2827 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2829 $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
2830 } catch (BadRequestException $e) {
2831 // user not found. should be found?
2832 /// @todo check if the user should be always found
2833 $quoted_status["user"] = [];
2836 unset($quoted_status['friendica_author']);
2837 unset($quoted_status['friendica_owner']);
2838 unset($quoted_status['friendica_activities']);
2839 unset($quoted_status['friendica_private']);
2842 if (!empty($retweeted_item)) {
2843 $retweeted_status = $status;
2844 unset($retweeted_status['friendica_author']);
2845 unset($retweeted_status['friendica_owner']);
2846 unset($retweeted_status['friendica_activities']);
2847 unset($retweeted_status['friendica_private']);
2848 unset($retweeted_status['statusnet_conversation_id']);
2849 $status['user'] = $status['friendica_owner'];
2851 $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
2852 } catch (BadRequestException $e) {
2853 // user not found. should be found?
2854 /// @todo check if the user should be always found
2855 $retweeted_status["user"] = [];
2858 $rt_converted = api_convert_item($retweeted_item);
2860 $retweeted_status['text'] = $rt_converted["text"];
2861 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2862 $retweeted_status['friendica_html'] = $rt_converted["html"];
2863 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2865 if (!empty($quoted_status)) {
2866 $retweeted_status['quoted_status'] = $quoted_status;
2869 $status['friendica_author'] = $retweeted_status['user'];
2870 $status['retweeted_status'] = $retweeted_status;
2871 } elseif (!empty($quoted_status)) {
2872 $root_status = api_convert_item($item);
2874 $status['text'] = $root_status["text"];
2875 $status['statusnet_html'] = $root_status["html"];
2876 $status['quoted_status'] = $quoted_status;
2879 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2880 unset($status["user"]["uid"]);
2881 unset($status["user"]["self"]);
2883 if ($item["coord"] != "") {
2884 $coords = explode(' ', $item["coord"]);
2885 if (count($coords) == 2) {
2886 if ($type == "json") {
2887 $status["geo"] = ['type' => 'Point',
2888 'coordinates' => [(float) $coords[0],
2889 (float) $coords[1]]];
2890 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2891 $status["georss:point"] = $item["coord"];
2900 * Returns all lists the user subscribes to.
2902 * @param string $type Return type (atom, rss, xml, json)
2904 * @return array|string
2905 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2907 function api_lists_list($type)
2910 /// @TODO $ret is not filled here?
2911 return ApiResponse::formatData('lists', $type, ["lists_list" => $ret]);
2914 /// @TODO move to top of file or somewhere better
2915 api_register_func('api/lists/list', 'api_lists_list', true);
2916 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2919 * Returns all groups the user owns.
2921 * @param string $type Return type (atom, rss, xml, json)
2923 * @return array|string
2924 * @throws BadRequestException
2925 * @throws ForbiddenException
2926 * @throws ImagickException
2927 * @throws InternalServerErrorException
2928 * @throws UnauthorizedException
2929 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2931 function api_lists_ownerships($type)
2935 if (api_user() === false) {
2936 throw new ForbiddenException();
2940 $user_info = api_get_user();
2941 $uid = $user_info['uid'];
2943 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2945 // loop through all groups
2947 foreach ($groups as $group) {
2948 if ($group['visible']) {
2954 'name' => $group['name'],
2955 'id' => intval($group['id']),
2956 'id_str' => (string) $group['id'],
2957 'user' => $user_info,
2961 return ApiResponse::formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2964 /// @TODO move to top of file or somewhere better
2965 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2968 * Returns recent statuses from users in the specified group.
2970 * @param string $type Return type (atom, rss, xml, json)
2972 * @return array|string
2973 * @throws BadRequestException
2974 * @throws ForbiddenException
2975 * @throws ImagickException
2976 * @throws InternalServerErrorException
2977 * @throws UnauthorizedException
2978 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2980 function api_lists_statuses($type)
2984 $user_info = api_get_user();
2985 if (api_user() === false || $user_info === false) {
2986 throw new ForbiddenException();
2989 unset($_REQUEST["user_id"]);
2990 unset($_GET["user_id"]);
2992 unset($_REQUEST["screen_name"]);
2993 unset($_GET["screen_name"]);
2995 if (empty($_REQUEST['list_id'])) {
2996 throw new BadRequestException('list_id not specified');
3000 $count = $_REQUEST['count'] ?? 20;
3001 $page = $_REQUEST['page'] ?? 1;
3002 $since_id = $_REQUEST['since_id'] ?? 0;
3003 $max_id = $_REQUEST['max_id'] ?? 0;
3004 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
3005 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
3007 $start = max(0, ($page - 1) * $count);
3009 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
3010 $gids = array_column($groups, 'contact-id');
3011 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
3012 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
3015 $condition[0] .= " AND `id` <= ?";
3016 $condition[] = $max_id;
3018 if ($exclude_replies > 0) {
3019 $condition[0] .= ' AND `gravity` = ?';
3020 $condition[] = GRAVITY_PARENT;
3022 if ($conversation_id > 0) {
3023 $condition[0] .= " AND `parent` = ?";
3024 $condition[] = $conversation_id;
3027 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
3028 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
3030 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3032 $data = ['status' => $items];
3037 $data = api_rss_extra($a, $data, $user_info);
3041 return ApiResponse::formatData("statuses", $type, $data);
3044 /// @TODO move to top of file or somewhere better
3045 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
3048 * Returns either the friends of the follower list
3050 * Considers friends and followers lists to be private and won't return
3051 * anything if any user_id parameter is passed.
3053 * @param string $qtype Either "friends" or "followers"
3054 * @return boolean|array
3055 * @throws BadRequestException
3056 * @throws ForbiddenException
3057 * @throws ImagickException
3058 * @throws InternalServerErrorException
3059 * @throws UnauthorizedException
3061 function api_statuses_f($qtype)
3065 if (api_user() === false) {
3066 throw new ForbiddenException();
3070 $count = $_GET['count'] ?? 20;
3071 $page = $_GET['page'] ?? 1;
3073 $start = max(0, ($page - 1) * $count);
3075 $user_info = api_get_user();
3077 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
3078 /* this is to stop Hotot to load friends multiple times
3079 * I'm not sure if I'm missing return something or
3080 * is a bug in hotot. Workaround, meantime
3084 return array('$users' => $ret);*/
3089 if ($qtype == 'friends') {
3090 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
3091 } elseif ($qtype == 'followers') {
3092 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
3095 // friends and followers only for self
3096 if ($user_info['self'] == 0) {
3097 $sql_extra = " AND false ";
3100 if ($qtype == 'blocks') {
3101 $sql_filter = 'AND `blocked` AND NOT `pending`';
3102 } elseif ($qtype == 'incoming') {
3103 $sql_filter = 'AND `pending`';
3105 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
3108 // @todo This query most likely can be replaced with a Contact::select...
3109 $r = DBA::toArray(DBA::p(
3124 foreach ($r as $cid) {
3125 $user = api_get_user($cid['nurl']);
3126 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3127 unset($user["uid"]);
3128 unset($user["self"]);
3135 return ['user' => $ret];
3140 * Returns the list of friends of the provided user
3142 * @deprecated By Twitter API in favor of friends/list
3144 * @param string $type Either "json" or "xml"
3145 * @return boolean|string|array
3146 * @throws BadRequestException
3147 * @throws ForbiddenException
3149 function api_statuses_friends($type)
3151 $data = api_statuses_f("friends");
3152 if ($data === false) {
3155 return ApiResponse::formatData("users", $type, $data);
3159 * Returns the list of followers of the provided user
3161 * @deprecated By Twitter API in favor of friends/list
3163 * @param string $type Either "json" or "xml"
3164 * @return boolean|string|array
3165 * @throws BadRequestException
3166 * @throws ForbiddenException
3168 function api_statuses_followers($type)
3170 $data = api_statuses_f("followers");
3171 if ($data === false) {
3174 return ApiResponse::formatData("users", $type, $data);
3177 /// @TODO move to top of file or somewhere better
3178 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3179 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3182 * Returns the list of blocked users
3184 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3186 * @param string $type Either "json" or "xml"
3188 * @return boolean|string|array
3189 * @throws BadRequestException
3190 * @throws ForbiddenException
3192 function api_blocks_list($type)
3194 $data = api_statuses_f('blocks');
3195 if ($data === false) {
3198 return ApiResponse::formatData("users", $type, $data);
3201 /// @TODO move to top of file or somewhere better
3202 api_register_func('api/blocks/list', 'api_blocks_list', true);
3205 * Returns the list of pending users IDs
3207 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3209 * @param string $type Either "json" or "xml"
3211 * @return boolean|string|array
3212 * @throws BadRequestException
3213 * @throws ForbiddenException
3215 function api_friendships_incoming($type)
3217 $data = api_statuses_f('incoming');
3218 if ($data === false) {
3223 foreach ($data['user'] as $user) {
3224 $ids[] = $user['id'];
3227 return ApiResponse::formatData("ids", $type, ['id' => $ids]);
3230 /// @TODO move to top of file or somewhere better
3231 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3234 * Returns the instance's configuration information.
3236 * @param string $type Return type (atom, rss, xml, json)
3238 * @return array|string
3239 * @throws InternalServerErrorException
3241 function api_statusnet_config($type)
3243 $name = DI::config()->get('config', 'sitename');
3244 $server = DI::baseUrl()->getHostname();
3245 $logo = DI::baseUrl() . '/images/friendica-64.png';
3246 $email = DI::config()->get('config', 'admin_email');
3247 $closed = intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 'true' : 'false';
3248 $private = DI::config()->get('system', 'block_public') ? 'true' : 'false';
3249 $textlimit = (string) DI::config()->get('config', 'api_import_size', DI::config()->get('config', 'max_import_size', 200000));
3250 $ssl = DI::config()->get('system', 'have_ssl') ? 'true' : 'false';
3251 $sslserver = DI::config()->get('system', 'have_ssl') ? str_replace('http:', 'https:', DI::baseUrl()) : '';
3254 'site' => ['name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
3255 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
3256 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
3257 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
3258 'shorturllength' => '30',
3260 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
3261 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
3262 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
3263 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
3268 return ApiResponse::formatData('config', $type, ['config' => $config]);
3271 /// @TODO move to top of file or somewhere better
3272 api_register_func('api/gnusocial/config', 'api_statusnet_config', false);
3273 api_register_func('api/statusnet/config', 'api_statusnet_config', false);
3276 * Sends a new direct message.
3278 * @param string $type Return type (atom, rss, xml, json)
3280 * @return array|string
3281 * @throws BadRequestException
3282 * @throws ForbiddenException
3283 * @throws ImagickException
3284 * @throws InternalServerErrorException
3285 * @throws NotFoundException
3286 * @throws UnauthorizedException
3287 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3289 function api_direct_messages_new($type)
3293 if (api_user() === false) {
3294 throw new ForbiddenException();
3297 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3301 $sender = api_get_user();
3304 if (!empty($_POST['screen_name'])) {
3305 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3306 if (DBA::isResult($contacts)) {
3307 // Selecting the id by priority, friendica first
3308 api_best_nickname($contacts);
3310 $recipient = api_get_user($contacts[0]['nurl']);
3313 $recipient = api_get_user($_POST['user_id']);
3316 if (empty($recipient)) {
3317 throw new NotFoundException('Recipient not found');
3321 if (!empty($_REQUEST['replyto'])) {
3322 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3323 $replyto = $mail['parent-uri'];
3324 $sub = $mail['title'];
3326 if (!empty($_REQUEST['title'])) {
3327 $sub = $_REQUEST['title'];
3329 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3333 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3336 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3337 $ret = api_format_messages($mail, $recipient, $sender);
3339 $ret = ["error" => $id];
3342 $data = ['direct_message'=>$ret];
3348 $data = api_rss_extra($a, $data, $sender);
3352 return ApiResponse::formatData("direct-messages", $type, $data);
3355 /// @TODO move to top of file or somewhere better
3356 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3359 * delete a direct_message from mail table through api
3361 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3362 * @return string|array
3363 * @throws BadRequestException
3364 * @throws ForbiddenException
3365 * @throws ImagickException
3366 * @throws InternalServerErrorException
3367 * @throws UnauthorizedException
3368 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3370 function api_direct_messages_destroy($type)
3374 if (api_user() === false) {
3375 throw new ForbiddenException();
3379 $user_info = api_get_user();
3381 $id = $_REQUEST['id'] ?? 0;
3383 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3384 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3385 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3387 $uid = $user_info['uid'];
3388 // error if no id or parenturi specified (for clients posting parent-uri as well)
3389 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3390 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3391 return ApiResponse::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3394 // BadRequestException if no id specified (for clients using Twitter API)
3396 throw new BadRequestException('Message id not specified');
3399 // add parent-uri to sql command if specified by calling app
3400 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3402 // error message if specified id is not in database
3403 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3404 if ($verbose == "true") {
3405 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3406 return ApiResponse::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3408 /// @todo BadRequestException ok for Twitter API clients?
3409 throw new BadRequestException('message id not in database');
3413 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3415 if ($verbose == "true") {
3418 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3419 return ApiResponse::formatData("direct_message_delete", $type, ['$result' => $answer]);
3421 $answer = ['result' => 'error', 'message' => 'unknown error'];
3422 return ApiResponse::formatData("direct_messages_delete", $type, ['$result' => $answer]);
3425 /// @todo return JSON data like Twitter API not yet implemented
3428 /// @TODO move to top of file or somewhere better
3429 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3434 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3435 * @return string|array
3436 * @throws HTTPException\BadRequestException
3437 * @throws HTTPException\ExpectationFailedException
3438 * @throws HTTPException\ForbiddenException
3439 * @throws HTTPException\InternalServerErrorException
3440 * @throws HTTPException\NotFoundException
3441 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3443 function api_friendships_destroy($type)
3447 if ($uid === false) {
3448 throw new HTTPException\ForbiddenException();
3451 $owner = User::getOwnerDataById($uid);
3453 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3454 throw new HTTPException\NotFoundException('Error Processing Request');
3457 $contact_id = $_REQUEST['user_id'] ?? 0;
3459 if (empty($contact_id)) {
3460 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3461 throw new HTTPException\BadRequestException('no user_id specified');
3464 // Get Contact by given id
3465 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3467 if(!DBA::isResult($contact)) {
3468 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3469 throw new HTTPException\NotFoundException('no contact found to given ID');
3472 $url = $contact['url'];
3474 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3475 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3476 Strings::normaliseLink($url), $url];
3477 $contact = DBA::selectFirst('contact', [], $condition);
3479 if (!DBA::isResult($contact)) {
3480 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3481 throw new HTTPException\NotFoundException('Not following Contact');
3485 $result = Contact::terminateFriendship($owner, $contact);
3487 if ($result === null) {
3488 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3489 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3492 if ($result === false) {
3493 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3495 } catch (Exception $e) {
3496 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3497 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3500 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3501 unset($contact['uid']);
3502 unset($contact['self']);
3504 // Set screen_name since Twidere requests it
3505 $contact['screen_name'] = $contact['nick'];
3507 return ApiResponse::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 ApiResponse::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 ApiResponse::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 * list all photos of the authenticated user
3689 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3690 * @return string|array
3691 * @throws ForbiddenException
3692 * @throws InternalServerErrorException
3694 function api_fr_photos_list($type)
3696 if (api_user() === false) {
3697 throw new ForbiddenException();
3699 $r = DBA::toArray(DBA::p(
3700 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3701 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3702 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3703 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3706 'image/jpeg' => 'jpg',
3707 'image/png' => 'png',
3708 'image/gif' => 'gif'
3710 $data = ['photo'=>[]];
3711 if (DBA::isResult($r)) {
3712 foreach ($r as $rr) {
3714 $photo['id'] = $rr['resource-id'];
3715 $photo['album'] = $rr['album'];
3716 $photo['filename'] = $rr['filename'];
3717 $photo['type'] = $rr['type'];
3718 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3719 $photo['created'] = $rr['created'];
3720 $photo['edited'] = $rr['edited'];
3721 $photo['desc'] = $rr['desc'];
3723 if ($type == "xml") {
3724 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3726 $photo['thumb'] = $thumb;
3727 $data['photo'][] = $photo;
3731 return ApiResponse::formatData("photos", $type, $data);
3735 * upload a new photo or change an existing photo
3737 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3738 * @return string|array
3739 * @throws BadRequestException
3740 * @throws ForbiddenException
3741 * @throws ImagickException
3742 * @throws InternalServerErrorException
3743 * @throws NotFoundException
3745 function api_fr_photo_create_update($type)
3747 if (api_user() === false) {
3748 throw new ForbiddenException();
3751 $photo_id = $_REQUEST['photo_id'] ?? null;
3752 $desc = $_REQUEST['desc'] ?? null;
3753 $album = $_REQUEST['album'] ?? null;
3754 $album_new = $_REQUEST['album_new'] ?? null;
3755 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3756 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3757 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3758 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3759 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3761 // do several checks on input parameters
3762 // we do not allow calls without album string
3763 if ($album == null) {
3764 throw new BadRequestException("no albumname specified");
3766 // if photo_id == null --> we are uploading a new photo
3767 if ($photo_id == null) {
3770 // error if no media posted in create-mode
3771 if (empty($_FILES['media'])) {
3773 throw new BadRequestException("no media data submitted");
3776 // album_new will be ignored in create-mode
3781 // check if photo is existing in databasei
3782 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3783 throw new BadRequestException("photo not available");
3787 // checks on acl strings provided by clients
3788 $acl_input_error = false;
3789 $acl_input_error |= check_acl_input($allow_cid);
3790 $acl_input_error |= check_acl_input($deny_cid);
3791 $acl_input_error |= check_acl_input($allow_gid);
3792 $acl_input_error |= check_acl_input($deny_gid);
3793 if ($acl_input_error) {
3794 throw new BadRequestException("acl data invalid");
3796 // now let's upload the new media in create-mode
3797 if ($mode == "create") {
3798 $media = $_FILES['media'];
3799 $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);
3801 // return success of updating or error message
3802 if (!is_null($data)) {
3803 return ApiResponse::formatData("photo_create", $type, $data);
3805 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3809 // now let's do the changes in update-mode
3810 if ($mode == "update") {
3811 $updated_fields = [];
3813 if (!is_null($desc)) {
3814 $updated_fields['desc'] = $desc;
3817 if (!is_null($album_new)) {
3818 $updated_fields['album'] = $album_new;
3821 if (!is_null($allow_cid)) {
3822 $allow_cid = trim($allow_cid);
3823 $updated_fields['allow_cid'] = $allow_cid;
3826 if (!is_null($deny_cid)) {
3827 $deny_cid = trim($deny_cid);
3828 $updated_fields['deny_cid'] = $deny_cid;
3831 if (!is_null($allow_gid)) {
3832 $allow_gid = trim($allow_gid);
3833 $updated_fields['allow_gid'] = $allow_gid;
3836 if (!is_null($deny_gid)) {
3837 $deny_gid = trim($deny_gid);
3838 $updated_fields['deny_gid'] = $deny_gid;
3842 if (count($updated_fields) > 0) {
3843 $nothingtodo = false;
3844 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3846 $nothingtodo = true;
3849 if (!empty($_FILES['media'])) {
3850 $nothingtodo = false;
3851 $media = $_FILES['media'];
3852 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3853 if (!is_null($data)) {
3854 return ApiResponse::formatData("photo_update", $type, $data);
3858 // return success of updating or error message
3860 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3861 return ApiResponse::formatData("photo_update", $type, ['$result' => $answer]);
3864 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3865 return ApiResponse::formatData("photo_update", $type, ['$result' => $answer]);
3867 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3870 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3874 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3876 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3877 * @return string|array
3878 * @throws BadRequestException
3879 * @throws ForbiddenException
3880 * @throws InternalServerErrorException
3881 * @throws NotFoundException
3883 function api_fr_photo_detail($type)
3885 if (api_user() === false) {
3886 throw new ForbiddenException();
3888 if (empty($_REQUEST['photo_id'])) {
3889 throw new BadRequestException("No photo id.");
3892 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3893 $photo_id = $_REQUEST['photo_id'];
3895 // prepare json/xml output with data from database for the requested photo
3896 $data = prepare_photo_data($type, $scale, $photo_id);
3898 return ApiResponse::formatData("photo_detail", $type, $data);
3903 * updates the profile image for the user (either a specified profile or the default profile)
3905 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3907 * @return string|array
3908 * @throws BadRequestException
3909 * @throws ForbiddenException
3910 * @throws ImagickException
3911 * @throws InternalServerErrorException
3912 * @throws NotFoundException
3913 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3915 function api_account_update_profile_image($type)
3917 if (api_user() === false) {
3918 throw new ForbiddenException();
3921 $profile_id = $_REQUEST['profile_id'] ?? 0;
3923 // error if image data is missing
3924 if (empty($_FILES['image'])) {
3925 throw new BadRequestException("no media data submitted");
3928 // check if specified profile id is valid
3929 if ($profile_id != 0) {
3930 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
3931 // error message if specified profile id is not in database
3932 if (!DBA::isResult($profile)) {
3933 throw new BadRequestException("profile_id not available");
3935 $is_default_profile = $profile['is-default'];
3937 $is_default_profile = 1;
3940 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3942 if (!empty($_FILES['image'])) {
3943 $media = $_FILES['image'];
3944 } elseif (!empty($_FILES['media'])) {
3945 $media = $_FILES['media'];
3947 // save new profile image
3948 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3951 if (is_array($media['type'])) {
3952 $filetype = $media['type'][0];
3954 $filetype = $media['type'];
3956 if ($filetype == "image/jpeg") {
3958 } elseif ($filetype == "image/png") {
3961 throw new InternalServerErrorException('Unsupported filetype');
3964 // change specified profile or all profiles to the new resource-id
3965 if ($is_default_profile) {
3966 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
3967 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3969 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3970 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3971 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
3974 Contact::updateSelfFromUserID(api_user(), true);
3976 // Update global directory in background
3977 Profile::publishUpdate(api_user());
3979 // output for client
3981 return api_account_verify_credentials($type);
3983 // SaveMediaToDatabase failed for some reason
3984 throw new InternalServerErrorException("image upload failed");
3988 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3989 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3990 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3991 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3992 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3993 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3996 * Update user profile
3998 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4000 * @return array|string
4001 * @throws BadRequestException
4002 * @throws ForbiddenException
4003 * @throws ImagickException
4004 * @throws InternalServerErrorException
4005 * @throws UnauthorizedException
4007 function api_account_update_profile($type)
4009 $local_user = api_user();
4010 $api_user = api_get_user();
4012 if (!empty($_POST['name'])) {
4013 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
4014 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
4015 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
4016 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
4019 if (isset($_POST['description'])) {
4020 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
4021 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
4022 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
4025 Profile::publishUpdate($local_user);
4027 return api_account_verify_credentials($type);
4030 /// @TODO move to top of file or somewhere better
4031 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
4035 * @param string $acl_string
4039 function check_acl_input($acl_string)
4041 if (empty($acl_string)) {
4045 $contact_not_found = false;
4047 // split <x><y><z> into array of cid's
4048 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
4050 // check for each cid if it is available on server
4051 $cid_array = $array[0];
4052 foreach ($cid_array as $cid) {
4053 $cid = str_replace("<", "", $cid);
4054 $cid = str_replace(">", "", $cid);
4055 $condition = ['id' => $cid, 'uid' => api_user()];
4056 $contact_not_found |= !DBA::exists('contact', $condition);
4058 return $contact_not_found;
4062 * @param string $mediatype
4063 * @param array $media
4064 * @param string $type
4065 * @param string $album
4066 * @param string $allow_cid
4067 * @param string $deny_cid
4068 * @param string $allow_gid
4069 * @param string $deny_gid
4070 * @param string $desc
4071 * @param integer $phototype
4072 * @param boolean $visibility
4073 * @param string $photo_id
4075 * @throws BadRequestException
4076 * @throws ForbiddenException
4077 * @throws ImagickException
4078 * @throws InternalServerErrorException
4079 * @throws NotFoundException
4080 * @throws UnauthorizedException
4082 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)
4090 if (is_array($media)) {
4091 if (is_array($media['tmp_name'])) {
4092 $src = $media['tmp_name'][0];
4094 $src = $media['tmp_name'];
4096 if (is_array($media['name'])) {
4097 $filename = basename($media['name'][0]);
4099 $filename = basename($media['name']);
4101 if (is_array($media['size'])) {
4102 $filesize = intval($media['size'][0]);
4104 $filesize = intval($media['size']);
4106 if (is_array($media['type'])) {
4107 $filetype = $media['type'][0];
4109 $filetype = $media['type'];
4113 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
4116 "File upload src: " . $src . " - filename: " . $filename .
4117 " - size: " . $filesize . " - type: " . $filetype);
4119 // check if there was a php upload error
4120 if ($filesize == 0 && $media['error'] == 1) {
4121 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
4123 // check against max upload size within Friendica instance
4124 $maximagesize = DI::config()->get('system', 'maximagesize');
4125 if ($maximagesize && ($filesize > $maximagesize)) {
4126 $formattedBytes = Strings::formatBytes($maximagesize);
4127 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
4130 // create Photo instance with the data of the image
4131 $imagedata = @file_get_contents($src);
4132 $Image = new Image($imagedata, $filetype);
4133 if (!$Image->isValid()) {
4134 throw new InternalServerErrorException("unable to process image data");
4137 // check orientation of image
4138 $Image->orient($src);
4141 // check max length of images on server
4142 $max_length = DI::config()->get('system', 'max_image_length');
4143 if ($max_length > 0) {
4144 $Image->scaleDown($max_length);
4145 logger::info("File upload: Scaling picture to new size " . $max_length);
4147 $width = $Image->getWidth();
4148 $height = $Image->getHeight();
4150 // create a new resource-id if not already provided
4151 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
4153 if ($mediatype == "photo") {
4154 // upload normal image (scales 0, 1, 2)
4155 logger::info("photo upload: starting new photo upload");
4157 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4159 logger::notice("photo upload: image upload with scale 0 (original size) failed");
4161 if ($width > 640 || $height > 640) {
4162 $Image->scaleDown(640);
4163 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4165 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
4169 if ($width > 320 || $height > 320) {
4170 $Image->scaleDown(320);
4171 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4173 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
4176 logger::info("photo upload: new photo upload ended");
4177 } elseif ($mediatype == "profileimage") {
4178 // upload profile image (scales 4, 5, 6)
4179 logger::info("photo upload: starting new profile image upload");
4181 if ($width > 300 || $height > 300) {
4182 $Image->scaleDown(300);
4183 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4185 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4189 if ($width > 80 || $height > 80) {
4190 $Image->scaleDown(80);
4191 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4193 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4197 if ($width > 48 || $height > 48) {
4198 $Image->scaleDown(48);
4199 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4201 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4204 $Image->__destruct();
4205 logger::info("photo upload: new profile image upload ended");
4209 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4210 if ($photo_id == null && $mediatype == "photo") {
4211 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4213 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4214 return prepare_photo_data($type, false, $resource_id);
4216 throw new InternalServerErrorException("image upload failed");
4222 * @param string $hash
4223 * @param string $allow_cid
4224 * @param string $deny_cid
4225 * @param string $allow_gid
4226 * @param string $deny_gid
4227 * @param string $filetype
4228 * @param boolean $visibility
4229 * @throws InternalServerErrorException
4231 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4233 // get data about the api authenticated user
4234 $uri = Item::newURI(intval(api_user()));
4235 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4238 $arr['guid'] = System::createUUID();
4239 $arr['uid'] = intval(api_user());
4241 $arr['type'] = 'photo';
4243 $arr['resource-id'] = $hash;
4244 $arr['contact-id'] = $owner_record['id'];
4245 $arr['owner-name'] = $owner_record['name'];
4246 $arr['owner-link'] = $owner_record['url'];
4247 $arr['owner-avatar'] = $owner_record['thumb'];
4248 $arr['author-name'] = $owner_record['name'];
4249 $arr['author-link'] = $owner_record['url'];
4250 $arr['author-avatar'] = $owner_record['thumb'];
4252 $arr['allow_cid'] = $allow_cid;
4253 $arr['allow_gid'] = $allow_gid;
4254 $arr['deny_cid'] = $deny_cid;
4255 $arr['deny_gid'] = $deny_gid;
4256 $arr['visible'] = $visibility;
4260 'image/jpeg' => 'jpg',
4261 'image/png' => 'png',
4262 'image/gif' => 'gif'
4265 // adds link to the thumbnail scale photo
4266 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4267 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4270 // do the magic for storing the item in the database and trigger the federation to other contacts
4276 * @param string $type
4278 * @param string $photo_id
4281 * @throws BadRequestException
4282 * @throws ForbiddenException
4283 * @throws ImagickException
4284 * @throws InternalServerErrorException
4285 * @throws NotFoundException
4286 * @throws UnauthorizedException
4288 function prepare_photo_data($type, $scale, $photo_id)
4291 $user_info = api_get_user();
4293 if ($user_info === false) {
4294 throw new ForbiddenException();
4297 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4298 $data_sql = ($scale === false ? "" : "data, ");
4300 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4301 // clients needs to convert this in their way for further processing
4302 $r = DBA::toArray(DBA::p(
4303 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4304 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4305 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4306 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4307 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4308 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4314 'image/jpeg' => 'jpg',
4315 'image/png' => 'png',
4316 'image/gif' => 'gif'
4319 // prepare output data for photo
4320 if (DBA::isResult($r)) {
4321 $data = ['photo' => $r[0]];
4322 $data['photo']['id'] = $data['photo']['resource-id'];
4323 if ($scale !== false) {
4324 $data['photo']['data'] = base64_encode($data['photo']['data']);
4326 unset($data['photo']['datasize']); //needed only with scale param
4328 if ($type == "xml") {
4329 $data['photo']['links'] = [];
4330 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4331 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4333 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4336 $data['photo']['link'] = [];
4337 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4339 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4340 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4344 unset($data['photo']['resource-id']);
4345 unset($data['photo']['minscale']);
4346 unset($data['photo']['maxscale']);
4348 throw new NotFoundException();
4351 // retrieve item element for getting activities (like, dislike etc.) related to photo
4352 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4353 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4354 if (!DBA::isResult($item)) {
4355 throw new NotFoundException('Photo-related item not found.');
4358 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4360 // retrieve comments on photo
4361 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4362 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4364 $statuses = Post::selectForUser(api_user(), [], $condition);
4366 // prepare output of comments
4367 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4369 if ($type == "xml") {
4371 foreach ($commentData as $comment) {
4372 $comments[$k++ . ":comment"] = $comment;
4375 foreach ($commentData as $comment) {
4376 $comments[] = $comment;
4379 $data['photo']['friendica_comments'] = $comments;
4381 // include info if rights on photo and rights on item are mismatching
4382 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4383 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4384 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4385 $data['photo']['deny_gid'] != $item['deny_gid'];
4386 $data['photo']['rights_mismatch'] = $rights_mismatch;
4392 * Return an item with announcer data if it had been announced
4394 * @param array $item Item array
4395 * @return array Item array with announce data
4397 function api_get_announce($item)
4399 // Quit if the item already has got a different owner and author
4400 if ($item['owner-id'] != $item['author-id']) {
4404 // Don't change original or Diaspora posts
4405 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4409 // Quit if we do now the original author and it had been a post from a native network
4410 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4414 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4415 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4416 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4417 if (!DBA::isResult($announce)) {
4421 return array_merge($item, $announce);
4426 * @param array $item
4431 function api_in_reply_to($item)
4435 $in_reply_to['status_id'] = null;
4436 $in_reply_to['user_id'] = null;
4437 $in_reply_to['status_id_str'] = null;
4438 $in_reply_to['user_id_str'] = null;
4439 $in_reply_to['screen_name'] = null;
4441 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4442 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4443 if (DBA::isResult($parent)) {
4444 $in_reply_to['status_id'] = intval($parent['id']);
4446 $in_reply_to['status_id'] = intval($item['parent']);
4449 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4451 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4452 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4454 if (DBA::isResult($parent)) {
4455 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4456 $in_reply_to['user_id'] = intval($parent['author-id']);
4457 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4460 // There seems to be situation, where both fields are identical:
4461 // https://github.com/friendica/friendica/issues/1010
4462 // This is a bugfix for that.
4463 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4464 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']]);
4465 $in_reply_to['status_id'] = null;
4466 $in_reply_to['user_id'] = null;
4467 $in_reply_to['status_id_str'] = null;
4468 $in_reply_to['user_id_str'] = null;
4469 $in_reply_to['screen_name'] = null;
4473 return $in_reply_to;
4478 * @param string $text
4481 * @throws InternalServerErrorException
4483 function api_clean_plain_items($text)
4485 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4487 $text = BBCode::cleanPictureLinks($text);
4488 $URLSearchString = "^\[\]";
4490 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4492 if ($include_entities == "true") {
4493 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4496 // Simplify "attachment" element
4497 $text = BBCode::removeAttachment($text);
4504 * @param array $contacts
4508 function api_best_nickname(&$contacts)
4512 if (count($contacts) == 0) {
4516 foreach ($contacts as $contact) {
4517 if ($contact["network"] == "") {
4518 $contact["network"] = "dfrn";
4519 $best_contact = [$contact];
4523 if (sizeof($best_contact) == 0) {
4524 foreach ($contacts as $contact) {
4525 if ($contact["network"] == "dfrn") {
4526 $best_contact = [$contact];
4531 if (sizeof($best_contact) == 0) {
4532 foreach ($contacts as $contact) {
4533 if ($contact["network"] == "dspr") {
4534 $best_contact = [$contact];
4539 if (sizeof($best_contact) == 0) {
4540 foreach ($contacts as $contact) {
4541 if ($contact["network"] == "stat") {
4542 $best_contact = [$contact];
4547 if (sizeof($best_contact) == 0) {
4548 foreach ($contacts as $contact) {
4549 if ($contact["network"] == "pump") {
4550 $best_contact = [$contact];
4555 if (sizeof($best_contact) == 0) {
4556 foreach ($contacts as $contact) {
4557 if ($contact["network"] == "twit") {
4558 $best_contact = [$contact];
4563 if (sizeof($best_contact) == 1) {
4564 $contacts = $best_contact;
4566 $contacts = [$contacts[0]];
4571 * Return all or a specified group of the user with the containing contacts.
4573 * @param string $type Return type (atom, rss, xml, json)
4575 * @return array|string
4576 * @throws BadRequestException
4577 * @throws ForbiddenException
4578 * @throws ImagickException
4579 * @throws InternalServerErrorException
4580 * @throws UnauthorizedException
4582 function api_friendica_group_show($type)
4586 if (api_user() === false) {
4587 throw new ForbiddenException();
4591 $user_info = api_get_user();
4592 $gid = $_REQUEST['gid'] ?? 0;
4593 $uid = $user_info['uid'];
4595 // get data of the specified group id or all groups if not specified
4597 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4599 // error message if specified gid is not in database
4600 if (!DBA::isResult($groups)) {
4601 throw new BadRequestException("gid not available");
4604 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4607 // loop through all groups and retrieve all members for adding data in the user array
4609 foreach ($groups as $rr) {
4610 $members = Contact\Group::getById($rr['id']);
4613 if ($type == "xml") {
4614 $user_element = "users";
4616 foreach ($members as $member) {
4617 $user = api_get_user($member['nurl']);
4618 $users[$k++.":user"] = $user;
4621 $user_element = "user";
4622 foreach ($members as $member) {
4623 $user = api_get_user($member['nurl']);
4627 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4629 return ApiResponse::formatData("groups", $type, ['group' => $grps]);
4632 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4636 * Delete the specified group of the user.
4638 * @param string $type Return type (atom, rss, xml, json)
4640 * @return array|string
4641 * @throws BadRequestException
4642 * @throws ForbiddenException
4643 * @throws ImagickException
4644 * @throws InternalServerErrorException
4645 * @throws UnauthorizedException
4647 function api_friendica_group_delete($type)
4651 if (api_user() === false) {
4652 throw new ForbiddenException();
4656 $user_info = api_get_user();
4657 $gid = $_REQUEST['gid'] ?? 0;
4658 $name = $_REQUEST['name'] ?? '';
4659 $uid = $user_info['uid'];
4661 // error if no gid specified
4662 if ($gid == 0 || $name == "") {
4663 throw new BadRequestException('gid or name not specified');
4666 // error message if specified gid is not in database
4667 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid])) {
4668 throw new BadRequestException('gid not available');
4671 // error message if specified gid is not in database
4672 if (!DBA::exists('group', ['uid' => $uid, 'id' => $gid, 'name' => $name])) {
4673 throw new BadRequestException('wrong group name');
4677 $gid = Group::getIdByName($uid, $name);
4679 throw new BadRequestException('other API error');
4682 $ret = Group::remove($gid);
4686 $success = ['success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => []];
4687 return ApiResponse::formatData("group_delete", $type, ['result' => $success]);
4689 throw new BadRequestException('other API error');
4692 api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
4697 * @param string $type Return type (atom, rss, xml, json)
4699 * @return array|string
4700 * @throws BadRequestException
4701 * @throws ForbiddenException
4702 * @throws ImagickException
4703 * @throws InternalServerErrorException
4704 * @throws UnauthorizedException
4705 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4707 function api_lists_destroy($type)
4711 if (api_user() === false) {
4712 throw new ForbiddenException();
4716 $user_info = api_get_user();
4717 $gid = $_REQUEST['list_id'] ?? 0;
4718 $uid = $user_info['uid'];
4720 // error if no gid specified
4722 throw new BadRequestException('gid not specified');
4725 // get data of the specified group id
4726 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4727 // error message if specified gid is not in database
4729 throw new BadRequestException('gid not available');
4732 if (Group::remove($gid)) {
4734 'name' => $group['name'],
4735 'id' => intval($gid),
4736 'id_str' => (string) $gid,
4737 'user' => $user_info
4740 return ApiResponse::formatData("lists", $type, ['lists' => $list]);
4744 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4747 * Add a new group to the database.
4749 * @param string $name Group name
4750 * @param int $uid User ID
4751 * @param array $users List of users to add to the group
4754 * @throws BadRequestException
4756 function group_create($name, $uid, $users = [])
4758 // error if no name specified
4760 throw new BadRequestException('group name not specified');
4763 // error message if specified group name already exists
4764 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4765 throw new BadRequestException('group name already exists');
4768 // Check if the group needs to be reactivated
4769 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4770 $reactivate_group = true;
4774 $ret = Group::create($uid, $name);
4776 $gid = Group::getIdByName($uid, $name);
4778 throw new BadRequestException('other API error');
4782 $erroraddinguser = false;
4784 foreach ($users as $user) {
4785 $cid = $user['cid'];
4786 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4787 Group::addMember($gid, $cid);
4789 $erroraddinguser = true;
4790 $errorusers[] = $cid;
4794 // return success message incl. missing users in array
4795 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4797 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4801 * Create the specified group with the posted array of contacts.
4803 * @param string $type Return type (atom, rss, xml, json)
4805 * @return array|string
4806 * @throws BadRequestException
4807 * @throws ForbiddenException
4808 * @throws ImagickException
4809 * @throws InternalServerErrorException
4810 * @throws UnauthorizedException
4812 function api_friendica_group_create($type)
4816 if (api_user() === false) {
4817 throw new ForbiddenException();
4821 $user_info = api_get_user();
4822 $name = $_REQUEST['name'] ?? '';
4823 $uid = $user_info['uid'];
4824 $json = json_decode($_POST['json'], true);
4825 $users = $json['user'];
4827 $success = group_create($name, $uid, $users);
4829 return ApiResponse::formatData("group_create", $type, ['result' => $success]);
4832 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4835 * Create a new group.
4837 * @param string $type Return type (atom, rss, xml, json)
4839 * @return array|string
4840 * @throws BadRequestException
4841 * @throws ForbiddenException
4842 * @throws ImagickException
4843 * @throws InternalServerErrorException
4844 * @throws UnauthorizedException
4845 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4847 function api_lists_create($type)
4851 if (api_user() === false) {
4852 throw new ForbiddenException();
4856 $user_info = api_get_user();
4857 $name = $_REQUEST['name'] ?? '';
4858 $uid = $user_info['uid'];
4860 $success = group_create($name, $uid);
4861 if ($success['success']) {
4863 'name' => $success['name'],
4864 'id' => intval($success['gid']),
4865 'id_str' => (string) $success['gid'],
4866 'user' => $user_info
4869 return ApiResponse::formatData("lists", $type, ['lists' => $grp]);
4873 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4876 * Update the specified group with the posted array of contacts.
4878 * @param string $type Return type (atom, rss, xml, json)
4880 * @return array|string
4881 * @throws BadRequestException
4882 * @throws ForbiddenException
4883 * @throws ImagickException
4884 * @throws InternalServerErrorException
4885 * @throws UnauthorizedException
4887 function api_friendica_group_update($type)
4891 if (api_user() === false) {
4892 throw new ForbiddenException();
4896 $user_info = api_get_user();
4897 $uid = $user_info['uid'];
4898 $gid = $_REQUEST['gid'] ?? 0;
4899 $name = $_REQUEST['name'] ?? '';
4900 $json = json_decode($_POST['json'], true);
4901 $users = $json['user'];
4903 // error if no name specified
4905 throw new BadRequestException('group name not specified');
4908 // error if no gid specified
4910 throw new BadRequestException('gid not specified');
4914 $members = Contact\Group::getById($gid);
4915 foreach ($members as $member) {
4916 $cid = $member['id'];
4917 foreach ($users as $user) {
4918 $found = ($user['cid'] == $cid ? true : false);
4920 if (!isset($found) || !$found) {
4921 $gid = Group::getIdByName($uid, $name);
4922 Group::removeMember($gid, $cid);
4927 $erroraddinguser = false;
4929 foreach ($users as $user) {
4930 $cid = $user['cid'];
4932 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4933 Group::addMember($gid, $cid);
4935 $erroraddinguser = true;
4936 $errorusers[] = $cid;
4940 // return success message incl. missing users in array
4941 $status = ($erroraddinguser ? "missing user" : "ok");
4942 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4943 return ApiResponse::formatData("group_update", $type, ['result' => $success]);
4946 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4949 * Update information about a group.
4951 * @param string $type Return type (atom, rss, xml, json)
4953 * @return array|string
4954 * @throws BadRequestException
4955 * @throws ForbiddenException
4956 * @throws ImagickException
4957 * @throws InternalServerErrorException
4958 * @throws UnauthorizedException
4959 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4961 function api_lists_update($type)
4965 if (api_user() === false) {
4966 throw new ForbiddenException();
4970 $user_info = api_get_user();
4971 $gid = $_REQUEST['list_id'] ?? 0;
4972 $name = $_REQUEST['name'] ?? '';
4973 $uid = $user_info['uid'];
4975 // error if no gid specified
4977 throw new BadRequestException('gid not specified');
4980 // get data of the specified group id
4981 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4982 // error message if specified gid is not in database
4984 throw new BadRequestException('gid not available');
4987 if (Group::update($gid, $name)) {
4990 'id' => intval($gid),
4991 'id_str' => (string) $gid,
4992 'user' => $user_info
4995 return ApiResponse::formatData("lists", $type, ['lists' => $list]);
4999 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
5002 * Set notification as seen and returns associated item (if possible)
5004 * POST request with 'id' param as notification id
5006 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5007 * @return string|array
5008 * @throws BadRequestException
5009 * @throws ForbiddenException
5010 * @throws ImagickException
5011 * @throws InternalServerErrorException
5012 * @throws UnauthorizedException
5014 function api_friendica_notification_seen($type)
5017 $user_info = api_get_user();
5019 if (api_user() === false || $user_info === false) {
5020 throw new ForbiddenException();
5022 if (DI::args()->getArgc() !== 4) {
5023 throw new BadRequestException('Invalid argument count');
5026 $id = intval($_REQUEST['id'] ?? 0);
5029 $Notify = DI::notify()->selectOneById($id);
5030 if ($Notify->uid !== api_user()) {
5031 throw new NotFoundException();
5034 if ($Notify->uriId) {
5035 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
5039 DI::notify()->save($Notify);
5041 if ($Notify->otype === Notification\ObjectType::ITEM) {
5042 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
5043 if (DBA::isResult($item)) {
5044 // we found the item, return it to the user
5045 $ret = api_format_items([$item], $user_info, false, $type);
5046 $data = ['status' => $ret];
5047 return ApiResponse::formatData('status', $type, $data);
5049 // the item can't be found, but we set the notification as seen, so we count this as a success
5052 return ApiResponse::formatData('result', $type, ['result' => 'success']);
5053 } catch (NotFoundException $e) {
5054 throw new BadRequestException('Invalid argument', $e);
5055 } catch (Exception $e) {
5056 throw new InternalServerErrorException('Internal Server exception', $e);
5060 /// @TODO move to top of file or somewhere better
5061 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
5064 * search for direct_messages containing a searchstring through api
5066 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
5067 * @param string $box
5068 * @return string|array (success: success=true if found and search_result contains found messages,
5069 * success=false if nothing was found, search_result='nothing found',
5070 * error: result=error with error message)
5071 * @throws BadRequestException
5072 * @throws ForbiddenException
5073 * @throws ImagickException
5074 * @throws InternalServerErrorException
5075 * @throws UnauthorizedException
5077 function api_friendica_direct_messages_search($type, $box = "")
5081 if (api_user() === false) {
5082 throw new ForbiddenException();
5086 $user_info = api_get_user();
5087 $searchstring = $_REQUEST['searchstring'] ?? '';
5088 $uid = $user_info['uid'];
5090 // error if no searchstring specified
5091 if ($searchstring == "") {
5092 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
5093 return ApiResponse::formatData("direct_messages_search", $type, ['$result' => $answer]);
5096 // get data for the specified searchstring
5097 $r = DBA::toArray(DBA::p(
5098 "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",
5100 '%'.$searchstring.'%'
5103 $profile_url = $user_info["url"];
5105 // message if nothing was found
5106 if (!DBA::isResult($r)) {
5107 $success = ['success' => false, 'search_results' => 'problem with query'];
5108 } elseif (count($r) == 0) {
5109 $success = ['success' => false, 'search_results' => 'nothing found'];
5112 foreach ($r as $item) {
5113 if ($box == "inbox" || $item['from-url'] != $profile_url) {
5114 $recipient = $user_info;
5115 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
5116 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
5117 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
5118 $sender = $user_info;
5121 if (isset($recipient) && isset($sender)) {
5122 $ret[] = api_format_messages($item, $recipient, $sender);
5125 $success = ['success' => true, 'search_results' => $ret];
5128 return ApiResponse::formatData("direct_message_search", $type, ['$result' => $success]);
5131 /// @TODO move to top of file or somewhere better
5132 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
5135 * Number of comments
5137 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
5139 * @param object $data [Status, Status]
5143 function bindComments(&$data)
5145 if (count($data) == 0) {
5151 foreach ($data as $item) {
5152 $ids[] = $item['id'];
5155 $idStr = DBA::escape(implode(', ', $ids));
5156 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
5157 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
5158 $itemsData = DBA::toArray($items);
5160 foreach ($itemsData as $item) {
5161 $comments[$item['parent']] = $item['comments'];
5164 foreach ($data as $idx => $item) {
5166 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
5171 @TODO Maybe open to implement?
5173 [pagename] => api/1.1/statuses/lookup.json
5174 [id] => 605138389168451584
5175 [include_cards] => true
5176 [cards_platform] => Android-12
5177 [include_entities] => true
5178 [include_my_retweet] => 1
5180 [include_reply_count] => true
5181 [include_descendent_reply_count] => true
5185 Not implemented by now:
5186 statuses/retweets_of_me
5191 account/update_location
5192 account/update_profile_background_image
5195 friendica/profile/update
5196 friendica/profile/create
5197 friendica/profile/delete
5199 Not implemented in status.net:
5200 statuses/retweeted_to_me
5201 statuses/retweeted_by_me
5202 direct_messages/destroy
5204 account/update_delivery_device
5205 notifications/follow