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\BaseApi;
46 use Friendica\Network\HTTPException;
47 use Friendica\Network\HTTPException\BadRequestException;
48 use Friendica\Network\HTTPException\ForbiddenException;
49 use Friendica\Network\HTTPException\InternalServerErrorException;
50 use Friendica\Network\HTTPException\MethodNotAllowedException;
51 use Friendica\Network\HTTPException\NotFoundException;
52 use Friendica\Network\HTTPException\TooManyRequestsException;
53 use Friendica\Network\HTTPException\UnauthorizedException;
54 use Friendica\Object\Image;
55 use Friendica\Protocol\Activity;
56 use Friendica\Security\BasicAuth;
57 use Friendica\Util\DateTimeFormat;
58 use Friendica\Util\Images;
59 use Friendica\Util\Network;
60 use Friendica\Util\Strings;
62 require_once __DIR__ . '/../mod/item.php';
63 require_once __DIR__ . '/../mod/wall_upload.php';
65 define('API_METHOD_ANY', '*');
66 define('API_METHOD_GET', 'GET');
67 define('API_METHOD_POST', 'POST,PUT');
68 define('API_METHOD_DELETE', 'POST,DELETE');
70 define('API_LOG_PREFIX', 'API {action} - ');
75 * Get source name from API client
77 * Clients can send 'source' parameter to be show in post metadata
78 * as "sent via <source>".
79 * Some clients doesn't send a source param, we support ones we know
83 * Client source name, default to "api" if unset/unknown
88 if (requestdata('source')) {
89 return requestdata('source');
92 // Support for known clients that doesn't send a source name
93 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
94 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
98 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
100 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
107 * Register a function to be the endpoint for defined API path.
109 * @param string $path API URL path, relative to DI::baseUrl()
110 * @param string $func Function name to call on path request
111 * @param bool $auth API need logged user
112 * @param string $method HTTP method reqiured to call this endpoint.
113 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
114 * Default to API_METHOD_ANY
116 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
126 // Workaround for hotot
127 $path = str_replace("api/", "api/1.1/", $path);
137 * Main API entry point
139 * Authenticate user, call registered API function, set HTTP headers
142 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
143 * @return string|array API call result
146 function api_call(App $a, App\Arguments $args = null)
155 if (strpos($args->getCommand(), ".xml") > 0) {
158 if (strpos($args->getCommand(), ".json") > 0) {
161 if (strpos($args->getCommand(), ".rss") > 0) {
164 if (strpos($args->getCommand(), ".atom") > 0) {
169 foreach ($API as $p => $info) {
170 if (strpos($args->getCommand(), $p) === 0) {
171 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
172 BasicAuth::getCurrentUserID(true);
173 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
176 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
178 $stamp = microtime(true);
179 $return = call_user_func($info['func'], $type);
180 $duration = floatval(microtime(true) - $stamp);
182 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
184 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
186 if (false === $return) {
188 * api function returned false withour throw an
189 * exception. This should not happend, throw a 500
191 throw new InternalServerErrorException();
196 header("Content-Type: text/xml");
199 header("Content-Type: application/json");
200 if (!empty($return)) {
201 $json = json_encode(end($return));
202 if (!empty($_GET['callback'])) {
203 $json = $_GET['callback'] . "(" . $json . ")";
209 header("Content-Type: application/rss+xml");
210 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
213 header("Content-Type: application/atom+xml");
214 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
221 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
222 throw new NotFoundException();
223 } catch (HTTPException $e) {
224 Logger::notice(API_LOG_PREFIX . 'got exception', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString(), 'error' => $e]);
225 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
234 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
235 * returns a 401 status code and an error message if not.
237 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
239 * @param string $type Return type (atom, rss, xml, json)
240 * @return array|string
241 * @throws BadRequestException
242 * @throws ForbiddenException
243 * @throws ImagickException
244 * @throws InternalServerErrorException
245 * @throws UnauthorizedException
247 function api_account_verify_credentials($type)
249 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
250 $uid = BaseApi::getCurrentUserID();
252 unset($_REQUEST['user_id']);
253 unset($_GET['user_id']);
255 unset($_REQUEST['screen_name']);
256 unset($_GET['screen_name']);
258 $skip_status = $_REQUEST['skip_status'] ?? false;
260 $user_info = DI::twitterUser()->createFromUserId($uid, $skip_status)->toArray();
262 // "verified" isn't used here in the standard
263 unset($user_info["verified"]);
265 // - Adding last status
267 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
269 $user_info['status'] = api_format_item($item, $type);
273 // "uid" and "self" are only needed for some internal stuff, so remove it from here
274 unset($user_info['uid']);
275 unset($user_info['self']);
277 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
280 /// @TODO move to top of file or somewhere better
281 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
284 * Get data from $_POST or $_GET
289 function requestdata($k)
291 if (!empty($_POST[$k])) {
294 if (!empty($_GET[$k])) {
301 * Deprecated function to upload media.
303 * @param string $type Return type (atom, rss, xml, json)
305 * @return array|string
306 * @throws BadRequestException
307 * @throws ForbiddenException
308 * @throws ImagickException
309 * @throws InternalServerErrorException
310 * @throws UnauthorizedException
312 function api_statuses_mediap($type)
314 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
315 $uid = BaseApi::getCurrentUserID();
319 $_REQUEST['profile_uid'] = $uid;
320 $_REQUEST['api_source'] = true;
321 $txt = requestdata('status') ?? '';
323 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
324 $txt = HTML::toBBCodeVideo($txt);
325 $config = HTMLPurifier_Config::createDefault();
326 $config->set('Cache.DefinitionImpl', null);
327 $purifier = new HTMLPurifier($config);
328 $txt = $purifier->purify($txt);
330 $txt = HTML::toBBCode($txt);
332 $picture = wall_upload_post($a, false);
334 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
335 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
336 $item_id = item_post($a);
338 // output the post that we just posted.
339 return api_status_show($type, $item_id);
342 /// @TODO move this to top of file or somewhere better!
343 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
346 * Updates the user’s current status.
348 * @param string $type Return type (atom, rss, xml, json)
350 * @return array|string
351 * @throws BadRequestException
352 * @throws ForbiddenException
353 * @throws ImagickException
354 * @throws InternalServerErrorException
355 * @throws TooManyRequestsException
356 * @throws UnauthorizedException
357 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
359 function api_statuses_update($type)
361 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
362 $uid = BaseApi::getCurrentUserID();
366 // convert $_POST array items to the form we use for web posts.
367 if (requestdata('htmlstatus')) {
368 $txt = requestdata('htmlstatus') ?? '';
369 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
370 $txt = HTML::toBBCodeVideo($txt);
372 $config = HTMLPurifier_Config::createDefault();
373 $config->set('Cache.DefinitionImpl', null);
375 $purifier = new HTMLPurifier($config);
376 $txt = $purifier->purify($txt);
378 $_REQUEST['body'] = HTML::toBBCode($txt);
381 $_REQUEST['body'] = requestdata('status');
384 $_REQUEST['title'] = requestdata('title');
386 $parent = requestdata('in_reply_to_status_id');
388 // Twidere sends "-1" if it is no reply ...
393 if (ctype_digit($parent)) {
394 $_REQUEST['parent'] = $parent;
396 $_REQUEST['parent_uri'] = $parent;
399 if (requestdata('lat') && requestdata('long')) {
400 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
402 $_REQUEST['profile_uid'] = $uid;
405 // Check for throttling (maximum posts per day, week and month)
406 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
407 if ($throttle_day > 0) {
408 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
410 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
411 $posts_day = Post::count($condition);
413 if ($posts_day > $throttle_day) {
414 logger::info('Daily posting limit reached for user ' . $uid);
415 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
416 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));
420 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
421 if ($throttle_week > 0) {
422 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
424 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
425 $posts_week = Post::count($condition);
427 if ($posts_week > $throttle_week) {
428 logger::info('Weekly posting limit reached for user ' . $uid);
429 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
430 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));
434 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
435 if ($throttle_month > 0) {
436 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
438 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
439 $posts_month = Post::count($condition);
441 if ($posts_month > $throttle_month) {
442 logger::info('Monthly posting limit reached for user ' . $uid);
443 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
444 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));
449 if (requestdata('media_ids')) {
450 $ids = explode(',', requestdata('media_ids') ?? '');
451 } elseif (!empty($_FILES['media'])) {
452 // upload the image if we have one
453 $picture = wall_upload_post($a, false);
454 if (is_array($picture)) {
455 $ids[] = $picture['id'];
463 foreach ($ids as $id) {
464 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
465 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
466 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
467 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
469 if (!empty($media)) {
470 $ressources[] = $media[0]['resource-id'];
471 $phototypes = Images::supportedTypes();
472 $ext = $phototypes[$media[0]['type']];
474 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
475 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
476 'size' => $media[0]['datasize'],
477 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
478 'description' => $media[0]['desc'] ?? '',
479 'width' => $media[0]['width'],
480 'height' => $media[0]['height']];
482 if (count($media) > 1) {
483 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
484 $attachment['preview-width'] = $media[1]['width'];
485 $attachment['preview-height'] = $media[1]['height'];
487 $attachments[] = $attachment;
491 // We have to avoid that the post is rejected because of an empty body
492 if (empty($_REQUEST['body'])) {
493 $_REQUEST['body'] = '[hr]';
497 if (!empty($attachments)) {
498 $_REQUEST['attachments'] = $attachments;
501 // set this so that the item_post() function is quiet and doesn't redirect or emit json
503 $_REQUEST['api_source'] = true;
505 if (empty($_REQUEST['source'])) {
506 $_REQUEST['source'] = api_source();
509 // call out normal post function
510 $item_id = item_post($a);
512 if (!empty($ressources) && !empty($item_id)) {
513 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
514 foreach ($ressources as $ressource) {
515 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
519 // output the post that we just posted.
520 return api_status_show($type, $item_id);
523 /// @TODO move to top of file or somewhere better
524 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
525 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
528 * Uploads an image to Friendica.
531 * @throws BadRequestException
532 * @throws ForbiddenException
533 * @throws ImagickException
534 * @throws InternalServerErrorException
535 * @throws UnauthorizedException
536 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
538 function api_media_upload()
540 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
542 if (empty($_FILES['media'])) {
544 throw new BadRequestException("No media.");
547 $media = wall_upload_post(DI::app(), false);
550 throw new InternalServerErrorException();
554 $returndata["media_id"] = $media["id"];
555 $returndata["media_id_string"] = (string)$media["id"];
556 $returndata["size"] = $media["size"];
557 $returndata["image"] = ["w" => $media["width"],
558 "h" => $media["height"],
559 "image_type" => $media["type"],
560 "friendica_preview_url" => $media["preview"]];
562 Logger::info('Media uploaded', ['return' => $returndata]);
564 return ["media" => $returndata];
567 /// @TODO move to top of file or somewhere better
568 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
571 * Updates media meta data (picture descriptions)
573 * @param string $type Return type (atom, rss, xml, json)
575 * @return array|string
576 * @throws BadRequestException
577 * @throws ForbiddenException
578 * @throws ImagickException
579 * @throws InternalServerErrorException
580 * @throws TooManyRequestsException
581 * @throws UnauthorizedException
582 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
584 * @todo Compare the corresponding Twitter function for correct return values
586 function api_media_metadata_create($type)
588 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
589 $uid = BaseApi::getCurrentUserID();
591 $postdata = Network::postdata();
593 if (empty($postdata)) {
594 throw new BadRequestException("No post data");
597 $data = json_decode($postdata, true);
599 throw new BadRequestException("Invalid post data");
602 if (empty($data['media_id']) || empty($data['alt_text'])) {
603 throw new BadRequestException("Missing post data values");
606 if (empty($data['alt_text']['text'])) {
607 throw new BadRequestException("No alt text.");
610 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
612 $condition = ['id' => $data['media_id'], 'uid' => $uid];
613 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
614 if (!DBA::isResult($photo)) {
615 throw new BadRequestException("Metadata not found.");
618 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
621 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
624 * @param string $type Return format (atom, rss, xml, json)
625 * @param int $item_id
626 * @return array|string
629 function api_status_show($type, $item_id)
631 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
635 $item = api_get_item(['id' => $item_id]);
637 $status_info = api_format_item($item, $type);
640 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
642 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
646 * Retrieves the last public status of the provided user info
648 * @param int $ownerId Public contact Id
649 * @param int $uid User Id
653 function api_get_last_status($ownerId, $uid)
656 'author-id'=> $ownerId,
658 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
659 'private' => [Item::PUBLIC, Item::UNLISTED]
662 $item = api_get_item($condition);
668 * Retrieves a single item record based on the provided condition and converts it for API use.
670 * @param array $condition Item table condition array
674 function api_get_item(array $condition)
676 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
682 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
683 * The author's most recent status will be returned inline.
685 * @param string $type Return type (atom, rss, xml, json)
686 * @return array|string
687 * @throws BadRequestException
688 * @throws ImagickException
689 * @throws InternalServerErrorException
690 * @throws UnauthorizedException
691 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
693 function api_users_show($type)
695 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
696 $uid = BaseApi::getCurrentUserID();
698 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
700 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
702 $user_info['status'] = api_format_item($item, $type);
705 // "uid" and "self" are only needed for some internal stuff, so remove it from here
706 unset($user_info['uid']);
707 unset($user_info['self']);
709 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
712 /// @TODO move to top of file or somewhere better
713 api_register_func('api/users/show', 'api_users_show');
714 api_register_func('api/externalprofile/show', 'api_users_show');
717 * Search a public user account.
719 * @param string $type Return type (atom, rss, xml, json)
721 * @return array|string
722 * @throws BadRequestException
723 * @throws ImagickException
724 * @throws InternalServerErrorException
725 * @throws UnauthorizedException
726 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
728 function api_users_search($type)
730 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
731 $uid = BaseApi::getCurrentUserID();
735 if (!empty($_GET['q'])) {
736 $contacts = Contact::selectToArray(
739 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
747 if (DBA::isResult($contacts)) {
749 foreach ($contacts as $contact) {
750 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid)->toArray();
752 if ($type == 'xml') {
753 $userlist[$k++ . ':user'] = $user_info;
755 $userlist[] = $user_info;
758 $userlist = ['users' => $userlist];
760 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
763 throw new BadRequestException('No search term specified.');
766 return DI::apiResponse()->formatData('users', $type, $userlist);
769 /// @TODO move to top of file or somewhere better
770 api_register_func('api/users/search', 'api_users_search');
773 * Return user objects
775 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
777 * @param string $type Return format: json or xml
779 * @return array|string
780 * @throws BadRequestException
781 * @throws ImagickException
782 * @throws InternalServerErrorException
783 * @throws NotFoundException if the results are empty.
784 * @throws UnauthorizedException
786 function api_users_lookup($type)
788 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
789 $uid = BaseApi::getCurrentUserID();
793 if (!empty($_REQUEST['user_id'])) {
794 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
795 if (!empty($cid) && is_numeric($cid)) {
796 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid)->toArray();
802 throw new NotFoundException;
805 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
808 /// @TODO move to top of file or somewhere better
809 api_register_func('api/users/lookup', 'api_users_lookup', true);
812 * Returns statuses that match a specified query.
814 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
816 * @param string $type Return format: json, xml, atom, rss
818 * @return array|string
819 * @throws BadRequestException if the "q" parameter is missing.
820 * @throws ForbiddenException
821 * @throws ImagickException
822 * @throws InternalServerErrorException
823 * @throws UnauthorizedException
825 function api_search($type)
827 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
828 $uid = BaseApi::getCurrentUserID();
830 if (empty($_REQUEST['q'])) {
831 throw new BadRequestException('q parameter is required.');
834 $searchTerm = trim(rawurldecode($_REQUEST['q']));
837 $data['status'] = [];
839 $exclude_replies = !empty($_REQUEST['exclude_replies']);
840 if (!empty($_REQUEST['rpp'])) {
841 $count = $_REQUEST['rpp'];
842 } elseif (!empty($_REQUEST['count'])) {
843 $count = $_REQUEST['count'];
846 $since_id = $_REQUEST['since_id'] ?? 0;
847 $max_id = $_REQUEST['max_id'] ?? 0;
848 $page = $_REQUEST['page'] ?? 1;
850 $start = max(0, ($page - 1) * $count);
852 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
853 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
854 $searchTerm = $matches[1];
855 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
856 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
858 while ($tag = DBA::fetch($tags)) {
859 $uriids[] = $tag['uri-id'];
863 if (empty($uriids)) {
864 return DI::apiResponse()->formatData('statuses', $type, $data);
867 $condition = ['uri-id' => $uriids];
868 if ($exclude_replies) {
869 $condition['gravity'] = GRAVITY_PARENT;
872 $params['group_by'] = ['uri-id'];
874 $condition = ["`id` > ?
875 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
876 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
877 AND `body` LIKE CONCAT('%',?,'%')",
878 $since_id, $uid, $_REQUEST['q']];
880 $condition[0] .= ' AND `id` <= ?';
881 $condition[] = $max_id;
887 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
888 $id = Item::fetchByLink($searchTerm, $uid);
891 $id = Item::fetchByLink($searchTerm);
895 $statuses = Post::select([], ['id' => $id]);
899 $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
902 while ($status = DBA::fetch($statuses)) {
903 $ret[] = api_format_item($status, $type);
905 DBA::close($statuses);
907 $data['status'] = $ret;
909 return DI::apiResponse()->formatData('statuses', $type, $data);
912 /// @TODO move to top of file or somewhere better
913 api_register_func('api/search/tweets', 'api_search', true);
914 api_register_func('api/search', 'api_search', true);
917 * Returns the most recent statuses posted by the user and the users they follow.
919 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
921 * @param string $type Return type (atom, rss, xml, json)
923 * @return array|string
924 * @throws BadRequestException
925 * @throws ForbiddenException
926 * @throws ImagickException
927 * @throws InternalServerErrorException
928 * @throws UnauthorizedException
929 * @todo Optional parameters
930 * @todo Add reply info
932 function api_statuses_home_timeline($type)
934 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
935 $uid = BaseApi::getCurrentUserID();
937 unset($_REQUEST['user_id']);
938 unset($_GET['user_id']);
940 unset($_REQUEST['screen_name']);
941 unset($_GET['screen_name']);
943 // get last network messages
946 $count = $_REQUEST['count'] ?? 20;
947 $page = $_REQUEST['page']?? 0;
948 $since_id = $_REQUEST['since_id'] ?? 0;
949 $max_id = $_REQUEST['max_id'] ?? 0;
950 $exclude_replies = !empty($_REQUEST['exclude_replies']);
951 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
953 $start = max(0, ($page - 1) * $count);
955 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
956 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
959 $condition[0] .= " AND `id` <= ?";
960 $condition[] = $max_id;
962 if ($exclude_replies) {
963 $condition[0] .= ' AND `gravity` = ?';
964 $condition[] = GRAVITY_PARENT;
966 if ($conversation_id > 0) {
967 $condition[0] .= " AND `parent` = ?";
968 $condition[] = $conversation_id;
971 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
972 $statuses = Post::selectForUser($uid, [], $condition, $params);
976 while ($status = DBA::fetch($statuses)) {
977 $ret[] = api_format_item($status, $type);
978 $idarray[] = intval($status['id']);
980 DBA::close($statuses);
982 if (!empty($idarray)) {
983 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
985 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
989 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
993 /// @TODO move to top of file or somewhere better
994 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
995 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
998 * Returns the most recent statuses from public users.
1000 * @param string $type Return type (atom, rss, xml, json)
1002 * @return array|string
1003 * @throws BadRequestException
1004 * @throws ForbiddenException
1005 * @throws ImagickException
1006 * @throws InternalServerErrorException
1007 * @throws UnauthorizedException
1009 function api_statuses_public_timeline($type)
1011 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1012 $uid = BaseApi::getCurrentUserID();
1014 // get last network messages
1017 $count = $_REQUEST['count'] ?? 20;
1018 $page = $_REQUEST['page'] ?? 1;
1019 $since_id = $_REQUEST['since_id'] ?? 0;
1020 $max_id = $_REQUEST['max_id'] ?? 0;
1021 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1022 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1024 $start = max(0, ($page - 1) * $count);
1026 if ($exclude_replies && !$conversation_id) {
1027 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1028 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1031 $condition[0] .= " AND `id` <= ?";
1032 $condition[] = $max_id;
1035 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1036 $statuses = Post::selectForUser($uid, [], $condition, $params);
1038 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1039 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1042 $condition[0] .= " AND `id` <= ?";
1043 $condition[] = $max_id;
1045 if ($conversation_id > 0) {
1046 $condition[0] .= " AND `parent` = ?";
1047 $condition[] = $conversation_id;
1050 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1051 $statuses = Post::selectForUser($uid, [], $condition, $params);
1055 while ($status = DBA::fetch($statuses)) {
1056 $ret[] = api_format_item($status, $type);
1058 DBA::close($statuses);
1060 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1063 /// @TODO move to top of file or somewhere better
1064 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1067 * Returns the most recent statuses posted by users this node knows about.
1069 * @param string $type Return format: json, xml, atom, rss
1070 * @return array|string
1071 * @throws BadRequestException
1072 * @throws ForbiddenException
1073 * @throws ImagickException
1074 * @throws InternalServerErrorException
1075 * @throws UnauthorizedException
1077 function api_statuses_networkpublic_timeline($type)
1079 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1080 $uid = BaseApi::getCurrentUserID();
1082 $since_id = $_REQUEST['since_id'] ?? 0;
1083 $max_id = $_REQUEST['max_id'] ?? 0;
1086 $count = $_REQUEST['count'] ?? 20;
1087 $page = $_REQUEST['page'] ?? 1;
1089 $start = max(0, ($page - 1) * $count);
1091 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1092 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1095 $condition[0] .= " AND `id` <= ?";
1096 $condition[] = $max_id;
1099 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1100 $statuses = Post::selectForUser($uid, Item::DISPLAY_FIELDLIST, $condition, $params);
1103 while ($status = DBA::fetch($statuses)) {
1104 $ret[] = api_format_item($status, $type);
1106 DBA::close($statuses);
1108 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1111 /// @TODO move to top of file or somewhere better
1112 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1115 * Returns a single status.
1117 * @param string $type Return type (atom, rss, xml, json)
1119 * @return array|string
1120 * @throws BadRequestException
1121 * @throws ForbiddenException
1122 * @throws ImagickException
1123 * @throws InternalServerErrorException
1124 * @throws UnauthorizedException
1125 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1127 function api_statuses_show($type)
1129 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1130 $uid = BaseApi::getCurrentUserID();
1133 $id = intval(DI::args()->getArgv()[3] ?? 0);
1136 $id = intval($_REQUEST['id'] ?? 0);
1141 $id = intval(DI::args()->getArgv()[4] ?? 0);
1144 logger::notice('API: api_statuses_show: ' . $id);
1146 $conversation = !empty($_REQUEST['conversation']);
1148 // try to fetch the item for the local user - or the public item, if there is no local one
1149 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1150 if (!DBA::isResult($uri_item)) {
1151 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1154 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1155 if (!DBA::isResult($item)) {
1156 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1161 if ($conversation) {
1162 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1163 $params = ['order' => ['id' => true]];
1165 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1169 $statuses = Post::selectForUser($uid, [], $condition, $params);
1171 /// @TODO How about copying this to above methods which don't check $r ?
1172 if (!DBA::isResult($statuses)) {
1173 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1177 while ($status = DBA::fetch($statuses)) {
1178 $ret[] = api_format_item($status, $type);
1180 DBA::close($statuses);
1182 if ($conversation) {
1183 $data = ['status' => $ret];
1184 return DI::apiResponse()->formatData("statuses", $type, $data);
1186 $data = ['status' => $ret[0]];
1187 return DI::apiResponse()->formatData("status", $type, $data);
1191 /// @TODO move to top of file or somewhere better
1192 api_register_func('api/statuses/show', 'api_statuses_show', true);
1196 * @param string $type Return type (atom, rss, xml, json)
1198 * @return array|string
1199 * @throws BadRequestException
1200 * @throws ForbiddenException
1201 * @throws ImagickException
1202 * @throws InternalServerErrorException
1203 * @throws UnauthorizedException
1204 * @todo nothing to say?
1206 function api_conversation_show($type)
1208 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1209 $uid = BaseApi::getCurrentUserID();
1212 $id = intval(DI::args()->getArgv()[3] ?? 0);
1213 $since_id = intval($_REQUEST['since_id'] ?? 0);
1214 $max_id = intval($_REQUEST['max_id'] ?? 0);
1215 $count = intval($_REQUEST['count'] ?? 20);
1216 $page = intval($_REQUEST['page'] ?? 1);
1218 $start = max(0, ($page - 1) * $count);
1221 $id = intval($_REQUEST['id'] ?? 0);
1226 $id = intval(DI::args()->getArgv()[4] ?? 0);
1229 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1231 // try to fetch the item for the local user - or the public item, if there is no local one
1232 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1233 if (!DBA::isResult($item)) {
1234 throw new BadRequestException("There is no status with the id $id.");
1237 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1238 if (!DBA::isResult($parent)) {
1239 throw new BadRequestException("There is no status with this id.");
1242 $id = $parent['id'];
1244 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1245 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1248 $condition[0] .= " AND `id` <= ?";
1249 $condition[] = $max_id;
1252 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1253 $statuses = Post::selectForUser($uid, [], $condition, $params);
1255 if (!DBA::isResult($statuses)) {
1256 throw new BadRequestException("There is no status with id $id.");
1260 while ($status = DBA::fetch($statuses)) {
1261 $ret[] = api_format_item($status, $type);
1263 DBA::close($statuses);
1265 $data = ['status' => $ret];
1266 return DI::apiResponse()->formatData("statuses", $type, $data);
1269 /// @TODO move to top of file or somewhere better
1270 api_register_func('api/conversation/show', 'api_conversation_show', true);
1271 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1276 * @param string $type Return type (atom, rss, xml, json)
1278 * @return array|string
1279 * @throws BadRequestException
1280 * @throws ForbiddenException
1281 * @throws ImagickException
1282 * @throws InternalServerErrorException
1283 * @throws UnauthorizedException
1284 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1286 function api_statuses_repeat($type)
1288 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1289 $uid = BaseApi::getCurrentUserID();
1292 $id = intval(DI::args()->getArgv()[3] ?? 0);
1295 $id = intval($_REQUEST['id'] ?? 0);
1300 $id = intval(DI::args()->getArgv()[4] ?? 0);
1303 logger::notice('API: api_statuses_repeat: ' . $id);
1305 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1306 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1308 if (DBA::isResult($item) && !empty($item['body'])) {
1309 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1310 if (!Item::performActivity($id, 'announce', $uid)) {
1311 throw new InternalServerErrorException();
1316 if (strpos($item['body'], "[/share]") !== false) {
1317 $pos = strpos($item['body'], "[share");
1318 $post = substr($item['body'], $pos);
1320 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1322 if (!empty($item['title'])) {
1323 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1326 $post .= $item['body'];
1327 $post .= "[/share]";
1329 $_REQUEST['body'] = $post;
1330 $_REQUEST['profile_uid'] = $uid;
1331 $_REQUEST['api_source'] = true;
1333 if (empty($_REQUEST['source'])) {
1334 $_REQUEST['source'] = api_source();
1337 $item_id = item_post(DI::app());
1340 throw new ForbiddenException();
1343 // output the post that we just posted.
1344 return api_status_show($type, $item_id);
1347 /// @TODO move to top of file or somewhere better
1348 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1351 * Destroys a specific status.
1353 * @param string $type Return type (atom, rss, xml, json)
1355 * @return array|string
1356 * @throws BadRequestException
1357 * @throws ForbiddenException
1358 * @throws ImagickException
1359 * @throws InternalServerErrorException
1360 * @throws UnauthorizedException
1361 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1363 function api_statuses_destroy($type)
1365 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1366 $uid = BaseApi::getCurrentUserID();
1369 $id = intval(DI::args()->getArgv()[3] ?? 0);
1372 $id = intval($_REQUEST['id'] ?? 0);
1377 $id = intval(DI::args()->getArgv()[4] ?? 0);
1380 logger::notice('API: api_statuses_destroy: ' . $id);
1382 $ret = api_statuses_show($type);
1384 Item::deleteForUser(['id' => $id], $uid);
1389 /// @TODO move to top of file or somewhere better
1390 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1393 * Returns the most recent mentions.
1395 * @param string $type Return type (atom, rss, xml, json)
1397 * @return array|string
1398 * @throws BadRequestException
1399 * @throws ForbiddenException
1400 * @throws ImagickException
1401 * @throws InternalServerErrorException
1402 * @throws UnauthorizedException
1403 * @see http://developer.twitter.com/doc/get/statuses/mentions
1405 function api_statuses_mentions($type)
1407 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1408 $uid = BaseApi::getCurrentUserID();
1410 unset($_REQUEST['user_id']);
1411 unset($_GET['user_id']);
1413 unset($_REQUEST['screen_name']);
1414 unset($_GET['screen_name']);
1416 // get last network messages
1419 $since_id = intval($_REQUEST['since_id'] ?? 0);
1420 $max_id = intval($_REQUEST['max_id'] ?? 0);
1421 $count = intval($_REQUEST['count'] ?? 20);
1422 $page = intval($_REQUEST['page'] ?? 1);
1424 $start = max(0, ($page - 1) * $count);
1426 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1427 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1428 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1431 GRAVITY_PARENT, GRAVITY_COMMENT,
1433 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1434 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1435 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1440 $query .= " AND `id` <= ?";
1441 $condition[] = $max_id;
1444 array_unshift($condition, $query);
1446 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1447 $statuses = Post::selectForUser($uid, [], $condition, $params);
1450 while ($status = DBA::fetch($statuses)) {
1451 $ret[] = api_format_item($status, $type);
1453 DBA::close($statuses);
1455 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1458 /// @TODO move to top of file or somewhere better
1459 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1460 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1463 * Returns the most recent statuses posted by the user.
1465 * @param string $type Either "json" or "xml"
1466 * @return string|array
1467 * @throws BadRequestException
1468 * @throws ForbiddenException
1469 * @throws ImagickException
1470 * @throws InternalServerErrorException
1471 * @throws UnauthorizedException
1472 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1474 function api_statuses_user_timeline($type)
1476 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1477 $uid = BaseApi::getCurrentUserID();
1479 Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1481 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1482 $since_id = $_REQUEST['since_id'] ?? 0;
1483 $max_id = $_REQUEST['max_id'] ?? 0;
1484 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1485 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1488 $count = $_REQUEST['count'] ?? 20;
1489 $page = $_REQUEST['page'] ?? 1;
1491 $start = max(0, ($page - 1) * $count);
1493 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1494 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1496 if ($exclude_replies) {
1497 $condition[0] .= ' AND `gravity` = ?';
1498 $condition[] = GRAVITY_PARENT;
1501 if ($conversation_id > 0) {
1502 $condition[0] .= " AND `parent` = ?";
1503 $condition[] = $conversation_id;
1507 $condition[0] .= " AND `id` <= ?";
1508 $condition[] = $max_id;
1510 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1511 $statuses = Post::selectForUser($uid, [], $condition, $params);
1514 while ($status = DBA::fetch($statuses)) {
1515 $ret[] = api_format_item($status, $type);
1517 DBA::close($statuses);
1519 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1522 /// @TODO move to top of file or somewhere better
1523 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1526 * Star/unstar an item.
1527 * param: id : id of the item
1529 * @param string $type Return type (atom, rss, xml, json)
1531 * @return array|string
1532 * @throws BadRequestException
1533 * @throws ForbiddenException
1534 * @throws ImagickException
1535 * @throws InternalServerErrorException
1536 * @throws UnauthorizedException
1537 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1539 function api_favorites_create_destroy($type)
1541 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1542 $uid = BaseApi::getCurrentUserID();
1544 // for versioned api.
1545 /// @TODO We need a better global soluton
1546 $action_argv_id = 2;
1547 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1548 $action_argv_id = 3;
1551 if (DI::args()->getArgc() <= $action_argv_id) {
1552 throw new BadRequestException("Invalid request.");
1554 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1555 if (DI::args()->getArgc() == $action_argv_id + 2) {
1556 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1558 $itemid = intval($_REQUEST['id'] ?? 0);
1561 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1563 if (!DBA::isResult($item)) {
1564 throw new BadRequestException("Invalid item.");
1569 $item['starred'] = 1;
1572 $item['starred'] = 0;
1575 throw new BadRequestException("Invalid action ".$action);
1578 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1581 throw new InternalServerErrorException("DB error");
1584 $ret = api_format_item($item, $type);
1586 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1589 /// @TODO move to top of file or somewhere better
1590 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1591 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1594 * Returns the most recent favorite statuses.
1596 * @param string $type Return type (atom, rss, xml, json)
1598 * @return string|array
1599 * @throws BadRequestException
1600 * @throws ForbiddenException
1601 * @throws ImagickException
1602 * @throws InternalServerErrorException
1603 * @throws UnauthorizedException
1605 function api_favorites($type)
1607 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1608 $uid = BaseApi::getCurrentUserID();
1610 // in friendica starred item are private
1611 // return favorites only for self
1612 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
1615 $since_id = $_REQUEST['since_id'] ?? 0;
1616 $max_id = $_REQUEST['max_id'] ?? 0;
1617 $count = $_GET['count'] ?? 20;
1618 $page = $_REQUEST['page'] ?? 1;
1620 $start = max(0, ($page - 1) * $count);
1622 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1623 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1625 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1628 $condition[0] .= " AND `id` <= ?";
1629 $condition[] = $max_id;
1632 $statuses = Post::selectForUser($uid, [], $condition, $params);
1635 while ($status = DBA::fetch($statuses)) {
1636 $ret[] = api_format_item($status, $type);
1638 DBA::close($statuses);
1640 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1643 /// @TODO move to top of file or somewhere better
1644 api_register_func('api/favorites', 'api_favorites', true);
1648 * @param array $item
1649 * @param array $recipient
1650 * @param array $sender
1653 * @throws InternalServerErrorException
1655 function api_format_messages($item, $recipient, $sender)
1657 // standard meta information
1659 'id' => $item['id'],
1660 'sender_id' => $sender['id'],
1662 'recipient_id' => $recipient['id'],
1663 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
1664 'sender_screen_name' => $sender['screen_name'],
1665 'recipient_screen_name' => $recipient['screen_name'],
1666 'sender' => $sender,
1667 'recipient' => $recipient,
1669 'friendica_seen' => $item['seen'] ?? 0,
1670 'friendica_parent_uri' => $item['parent-uri'] ?? '',
1673 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1674 if (isset($ret['sender']['uid'])) {
1675 unset($ret['sender']['uid']);
1677 if (isset($ret['sender']['self'])) {
1678 unset($ret['sender']['self']);
1680 if (isset($ret['recipient']['uid'])) {
1681 unset($ret['recipient']['uid']);
1683 if (isset($ret['recipient']['self'])) {
1684 unset($ret['recipient']['self']);
1687 //don't send title to regular StatusNET requests to avoid confusing these apps
1688 if (!empty($_GET['getText'])) {
1689 $ret['title'] = $item['title'];
1690 if ($_GET['getText'] == 'html') {
1691 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
1692 } elseif ($_GET['getText'] == 'plain') {
1693 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
1696 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
1698 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
1699 unset($ret['sender']);
1700 unset($ret['recipient']);
1708 * @param array $item
1711 * @throws InternalServerErrorException
1713 function api_convert_item($item)
1715 $body = api_add_attachments_to_body($item);
1717 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
1719 // Add pictures to the attachment array and remove them from the body
1720 $attachments = api_get_attachments($body, $item['uri-id']);
1722 // Workaround for ostatus messages where the title is identically to the body
1723 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
1724 $statusbody = trim(HTML::toPlaintext($html, 0));
1726 // handle data: images
1727 $statusbody = api_format_items_embeded_images($item, $statusbody);
1729 $statustitle = trim($item['title']);
1731 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
1732 $statustext = trim($statusbody);
1734 $statustext = trim($statustitle."\n\n".$statusbody);
1737 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
1738 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
1741 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
1743 // Workaround for clients with limited HTML parser functionality
1744 $search = ["<br>", "<blockquote>", "</blockquote>",
1745 "<h1>", "</h1>", "<h2>", "</h2>",
1746 "<h3>", "</h3>", "<h4>", "</h4>",
1747 "<h5>", "</h5>", "<h6>", "</h6>"];
1748 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
1749 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
1750 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
1751 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
1752 $statushtml = str_replace($search, $replace, $statushtml);
1754 if ($item['title'] != "") {
1755 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
1759 $oldtext = $statushtml;
1760 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
1761 } while ($oldtext != $statushtml);
1763 if (substr($statushtml, 0, 4) == '<br>') {
1764 $statushtml = substr($statushtml, 4);
1767 if (substr($statushtml, 0, -4) == '<br>') {
1768 $statushtml = substr($statushtml, -4);
1771 // feeds without body should contain the link
1772 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
1773 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
1777 "text" => $statustext,
1778 "html" => $statushtml,
1779 "attachments" => $attachments,
1780 "entities" => $entities
1785 * Add media attachments to the body
1787 * @param array $item
1788 * @return string body with added media
1790 function api_add_attachments_to_body(array $item)
1792 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1794 if (strpos($body, '[/img]') !== false) {
1798 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
1799 if (!empty($media['preview'])) {
1800 $description = $media['description'] ?: $media['name'];
1801 if (!empty($description)) {
1802 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
1804 $body .= "\n[img]" . $media['preview'] .'[/img]';
1814 * @param string $body
1818 * @throws InternalServerErrorException
1820 function api_get_attachments(&$body, $uriid)
1822 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1823 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1825 $URLSearchString = "^\[\]";
1826 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
1830 // Remove all embedded pictures, since they are added as attachments
1831 foreach ($images[0] as $orig) {
1832 $body = str_replace($orig, '', $body);
1837 foreach ($images[1] as $image) {
1838 $imagedata = Images::getInfoFromURLCached($image);
1841 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
1845 return $attachments;
1850 * @param string $text
1851 * @param string $bbcode
1854 * @throws InternalServerErrorException
1855 * @todo Links at the first character of the post
1857 function api_get_entitities(&$text, $bbcode, $uriid)
1859 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
1861 if ($include_entities != "true") {
1862 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1864 foreach ($images[1] as $image) {
1865 $replace = Post\Link::getByLink($uriid, $image);
1866 $text = str_replace($image, $replace, $text);
1871 $bbcode = BBCode::cleanPictureLinks($bbcode);
1873 // Change pure links in text to bbcode uris
1874 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1877 $entities["hashtags"] = [];
1878 $entities["symbols"] = [];
1879 $entities["urls"] = [];
1880 $entities["user_mentions"] = [];
1882 $URLSearchString = "^\[\]";
1884 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
1886 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
1887 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
1889 $bbcode = preg_replace(
1890 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1891 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
1894 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
1896 $bbcode = preg_replace(
1897 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1898 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
1901 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
1903 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1905 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1908 foreach ($urls[1] as $id => $url) {
1909 $start = iconv_strpos($text, $url, 0, "UTF-8");
1910 if (!($start === false)) {
1911 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
1915 ksort($ordered_urls);
1919 foreach ($ordered_urls as $url) {
1920 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
1921 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
1923 $display_url = $url["title"];
1925 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
1926 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
1928 if (strlen($display_url) > 26) {
1929 $display_url = substr($display_url, 0, 25)."…";
1933 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1934 if (!($start === false)) {
1935 $entities["urls"][] = ["url" => $url["url"],
1936 "expanded_url" => $url["url"],
1937 "display_url" => $display_url,
1938 "indices" => [$start, $start+strlen($url["url"])]];
1939 $offset = $start + 1;
1943 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
1944 $ordered_images = [];
1945 foreach ($images as $image) {
1946 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
1947 if (!($start === false)) {
1948 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
1952 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1953 foreach ($images[1] as $image) {
1954 $start = iconv_strpos($text, $image, 0, "UTF-8");
1955 if (!($start === false)) {
1956 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
1962 foreach ($ordered_images as $image) {
1963 $url = $image['url'];
1964 $ext_alt_text = $image['alt'];
1966 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
1967 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
1969 if (strlen($display_url) > 26) {
1970 $display_url = substr($display_url, 0, 25)."…";
1973 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1974 if (!($start === false)) {
1975 $image = Images::getInfoFromURLCached($url);
1977 $media_url = Post\Link::getByLink($uriid, $url);
1978 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
1980 $entities["media"][] = [
1982 "id_str" => (string) ($start + 1),
1983 "indices" => [$start, $start+strlen($url)],
1984 "media_url" => Strings::normaliseLink($media_url),
1985 "media_url_https" => $media_url,
1987 "display_url" => $display_url,
1988 "expanded_url" => $url,
1989 "ext_alt_text" => $ext_alt_text,
1993 $offset = $start + 1;
2002 * @param array $item
2003 * @param string $text
2007 function api_format_items_embeded_images($item, $text)
2009 $text = preg_replace_callback(
2010 '|data:image/([^;]+)[^=]+=*|m',
2011 function () use ($item) {
2012 return DI::baseUrl() . '/display/' . $item['guid'];
2020 * return <a href='url'>name</a> as array
2022 * @param string $txt text
2027 function api_contactlink_to_array($txt)
2030 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2031 if ($r && count($match)==3) {
2033 'name' => $match[2],
2047 * return likes, dislikes and attend status for item
2049 * @param array $item array
2050 * @param string $type Return type (atom, rss, xml, json)
2053 * likes => int count,
2054 * dislikes => int count
2055 * @throws BadRequestException
2056 * @throws ImagickException
2057 * @throws InternalServerErrorException
2058 * @throws UnauthorizedException
2060 function api_format_items_activities($item, $type = "json")
2067 'attendmaybe' => [],
2071 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2072 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2074 while ($parent_item = Post::fetch($ret)) {
2075 // not used as result should be structured like other user data
2076 //builtin_activity_puller($i, $activities);
2078 // get user data and add it to the array of the activity
2079 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], $item['uid'])->toArray();
2080 switch ($parent_item['verb']) {
2081 case Activity::LIKE:
2082 $activities['like'][] = $user;
2084 case Activity::DISLIKE:
2085 $activities['dislike'][] = $user;
2087 case Activity::ATTEND:
2088 $activities['attendyes'][] = $user;
2090 case Activity::ATTENDNO:
2091 $activities['attendno'][] = $user;
2093 case Activity::ATTENDMAYBE:
2094 $activities['attendmaybe'][] = $user;
2096 case Activity::ANNOUNCE:
2097 $activities['announce'][] = $user;
2106 if ($type == "xml") {
2107 $xml_activities = [];
2108 foreach ($activities as $k => $v) {
2109 // change xml element from "like" to "friendica:like"
2110 $xml_activities["friendica:".$k] = $v;
2111 // add user data into xml output
2113 foreach ($v as $user) {
2114 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2117 $activities = $xml_activities;
2124 * @param array $item Item record
2125 * @param string $type Return format (atom, rss, xml, json)
2126 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2127 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2128 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2129 * @return array API-formatted status
2130 * @throws BadRequestException
2131 * @throws ImagickException
2132 * @throws InternalServerErrorException
2133 * @throws UnauthorizedException
2135 function api_format_item($item, $type = "json")
2137 $author_user = DI::twitterUser()->createFromContactId($item['author-id'], $item['uid'])->toArray();
2138 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], $item['uid'])->toArray();
2140 DI::contentItem()->localize($item);
2142 $in_reply_to = api_in_reply_to($item);
2144 $converted = api_convert_item($item);
2146 if ($type == "xml") {
2147 $geo = "georss:point";
2153 'text' => $converted["text"],
2154 'truncated' => false,
2155 'created_at'=> DateTimeFormat::utc($item['created'], DateTimeFormat::API),
2156 'in_reply_to_status_id' => $in_reply_to['status_id'],
2157 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2158 'source' => (($item['app']) ? $item['app'] : 'web'),
2159 'id' => intval($item['id']),
2160 'id_str' => (string) intval($item['id']),
2161 'in_reply_to_user_id' => $in_reply_to['user_id'],
2162 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2163 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2165 'favorited' => $item['starred'] ? true : false,
2166 'user' => $author_user,
2167 'friendica_author' => $author_user,
2168 'friendica_owner' => $owner_user,
2169 'friendica_private' => $item['private'] == Item::PRIVATE,
2170 //'entities' => NULL,
2171 'statusnet_html' => $converted["html"],
2172 'statusnet_conversation_id' => $item['parent'],
2173 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2174 'friendica_activities' => api_format_items_activities($item, $type),
2175 'friendica_title' => $item['title'],
2176 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL),
2177 'friendica_comments' => Post::countPosts(['thr-parent-id' => $item['uri-id'], 'deleted' => false, 'gravity' => GRAVITY_COMMENT])
2180 if (count($converted["attachments"]) > 0) {
2181 $status["attachments"] = $converted["attachments"];
2184 if (count($converted["entities"]) > 0) {
2185 $status["entities"] = $converted["entities"];
2188 if ($status["source"] == 'web') {
2189 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2190 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2191 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2194 $retweeted_item = [];
2197 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2198 $announce = api_get_announce($item);
2199 if (!empty($announce)) {
2200 $retweeted_item = $item;
2202 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], $item['uid'])->toArray();
2206 if (!empty($quoted_item)) {
2207 if ($quoted_item['id'] != $item['id']) {
2208 $quoted_status = api_format_item($quoted_item);
2209 /// @todo Only remove the attachments that are also contained in the quotes status
2210 unset($status['attachments']);
2211 unset($status['entities']);
2213 $conv_quoted = api_convert_item($quoted_item);
2214 $quoted_status = $status;
2215 unset($quoted_status['attachments']);
2216 unset($quoted_status['entities']);
2217 unset($quoted_status['statusnet_conversation_id']);
2218 $quoted_status['text'] = $conv_quoted['text'];
2219 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2221 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], $item['uid'])->toArray();
2222 } catch (BadRequestException $e) {
2223 // user not found. should be found?
2224 /// @todo check if the user should be always found
2225 $quoted_status["user"] = [];
2228 unset($quoted_status['friendica_author']);
2229 unset($quoted_status['friendica_owner']);
2230 unset($quoted_status['friendica_activities']);
2231 unset($quoted_status['friendica_private']);
2234 if (!empty($retweeted_item)) {
2235 $retweeted_status = $status;
2236 unset($retweeted_status['friendica_author']);
2237 unset($retweeted_status['friendica_owner']);
2238 unset($retweeted_status['friendica_activities']);
2239 unset($retweeted_status['friendica_private']);
2240 unset($retweeted_status['statusnet_conversation_id']);
2241 $status['user'] = $status['friendica_owner'];
2243 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], $item['uid'])->toArray();
2244 } catch (BadRequestException $e) {
2245 // user not found. should be found?
2246 /// @todo check if the user should be always found
2247 $retweeted_status["user"] = [];
2250 $rt_converted = api_convert_item($retweeted_item);
2252 $retweeted_status['text'] = $rt_converted["text"];
2253 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2254 $retweeted_status['friendica_html'] = $rt_converted["html"];
2255 $retweeted_status['created_at'] = DateTimeFormat::utc($retweeted_item['created'], DateTimeFormat::API);
2257 if (!empty($quoted_status)) {
2258 $retweeted_status['quoted_status'] = $quoted_status;
2261 $status['friendica_author'] = $retweeted_status['user'];
2262 $status['retweeted_status'] = $retweeted_status;
2263 } elseif (!empty($quoted_status)) {
2264 $root_status = api_convert_item($item);
2266 $status['text'] = $root_status["text"];
2267 $status['statusnet_html'] = $root_status["html"];
2268 $status['quoted_status'] = $quoted_status;
2271 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2272 unset($status["user"]['uid']);
2273 unset($status["user"]['self']);
2275 if ($item["coord"] != "") {
2276 $coords = explode(' ', $item["coord"]);
2277 if (count($coords) == 2) {
2278 if ($type == "json") {
2279 $status["geo"] = ['type' => 'Point',
2280 'coordinates' => [(float) $coords[0],
2281 (float) $coords[1]]];
2282 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2283 $status["georss:point"] = $item["coord"];
2292 * Returns all lists the user subscribes to.
2294 * @param string $type Return type (atom, rss, xml, json)
2296 * @return array|string
2297 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2299 function api_lists_list($type)
2302 /// @TODO $ret is not filled here?
2303 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2306 /// @TODO move to top of file or somewhere better
2307 api_register_func('api/lists/list', 'api_lists_list', true);
2308 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2311 * Returns all groups the user owns.
2313 * @param string $type Return type (atom, rss, xml, json)
2315 * @return array|string
2316 * @throws BadRequestException
2317 * @throws ForbiddenException
2318 * @throws ImagickException
2319 * @throws InternalServerErrorException
2320 * @throws UnauthorizedException
2321 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2323 function api_lists_ownerships($type)
2325 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2326 $uid = BaseApi::getCurrentUserID();
2329 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2331 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2333 // loop through all groups
2335 foreach ($groups as $group) {
2336 if ($group['visible']) {
2342 'name' => $group['name'],
2343 'id' => intval($group['id']),
2344 'id_str' => (string) $group['id'],
2345 'user' => $user_info,
2349 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2352 /// @TODO move to top of file or somewhere better
2353 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2356 * Returns recent statuses from users in the specified group.
2358 * @param string $type Return type (atom, rss, xml, json)
2360 * @return array|string
2361 * @throws BadRequestException
2362 * @throws ForbiddenException
2363 * @throws ImagickException
2364 * @throws InternalServerErrorException
2365 * @throws UnauthorizedException
2366 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2368 function api_lists_statuses($type)
2370 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2371 $uid = BaseApi::getCurrentUserID();
2373 unset($_REQUEST['user_id']);
2374 unset($_GET['user_id']);
2376 unset($_REQUEST['screen_name']);
2377 unset($_GET['screen_name']);
2379 if (empty($_REQUEST['list_id'])) {
2380 throw new BadRequestException('list_id not specified');
2384 $count = $_REQUEST['count'] ?? 20;
2385 $page = $_REQUEST['page'] ?? 1;
2386 $since_id = $_REQUEST['since_id'] ?? 0;
2387 $max_id = $_REQUEST['max_id'] ?? 0;
2388 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2389 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2391 $start = max(0, ($page - 1) * $count);
2393 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2394 $gids = array_column($groups, 'contact-id');
2395 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2396 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2399 $condition[0] .= " AND `id` <= ?";
2400 $condition[] = $max_id;
2402 if ($exclude_replies > 0) {
2403 $condition[0] .= ' AND `gravity` = ?';
2404 $condition[] = GRAVITY_PARENT;
2406 if ($conversation_id > 0) {
2407 $condition[0] .= " AND `parent` = ?";
2408 $condition[] = $conversation_id;
2411 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2412 $statuses = Post::selectForUser($uid, [], $condition, $params);
2415 while ($status = DBA::fetch($statuses)) {
2416 $items[] = api_format_item($status, $type);
2418 DBA::close($statuses);
2420 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2423 /// @TODO move to top of file or somewhere better
2424 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2427 * Returns either the friends of the follower list
2429 * Considers friends and followers lists to be private and won't return
2430 * anything if any user_id parameter is passed.
2432 * @param string $qtype Either "friends" or "followers"
2433 * @return boolean|array
2434 * @throws BadRequestException
2435 * @throws ForbiddenException
2436 * @throws ImagickException
2437 * @throws InternalServerErrorException
2438 * @throws UnauthorizedException
2440 function api_statuses_f($qtype)
2442 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2443 $uid = BaseApi::getCurrentUserID();
2446 $count = $_GET['count'] ?? 20;
2447 $page = $_GET['page'] ?? 1;
2449 $start = max(0, ($page - 1) * $count);
2451 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2453 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2454 /* this is to stop Hotot to load friends multiple times
2455 * I'm not sure if I'm missing return something or
2456 * is a bug in hotot. Workaround, meantime
2460 return array('$users' => $ret);*/
2465 if ($qtype == 'friends') {
2466 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2467 } elseif ($qtype == 'followers') {
2468 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2471 if ($qtype == 'blocks') {
2472 $sql_filter = 'AND `blocked` AND NOT `pending`';
2473 } elseif ($qtype == 'incoming') {
2474 $sql_filter = 'AND `pending`';
2476 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2479 // @todo This query most likely can be replaced with a Contact::select...
2480 $r = DBA::toArray(DBA::p(
2495 foreach ($r as $cid) {
2496 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid)->toArray();
2497 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2498 unset($user['uid']);
2499 unset($user['self']);
2506 return ['user' => $ret];
2511 * Returns the list of friends of the provided user
2513 * @deprecated By Twitter API in favor of friends/list
2515 * @param string $type Either "json" or "xml"
2516 * @return boolean|string|array
2517 * @throws BadRequestException
2518 * @throws ForbiddenException
2520 function api_statuses_friends($type)
2522 $data = api_statuses_f("friends");
2523 if ($data === false) {
2526 return DI::apiResponse()->formatData("users", $type, $data);
2530 * Returns the list of followers of the provided user
2532 * @deprecated By Twitter API in favor of friends/list
2534 * @param string $type Either "json" or "xml"
2535 * @return boolean|string|array
2536 * @throws BadRequestException
2537 * @throws ForbiddenException
2539 function api_statuses_followers($type)
2541 $data = api_statuses_f("followers");
2542 if ($data === false) {
2545 return DI::apiResponse()->formatData("users", $type, $data);
2548 /// @TODO move to top of file or somewhere better
2549 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2550 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2553 * Returns the list of blocked users
2555 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2557 * @param string $type Either "json" or "xml"
2559 * @return boolean|string|array
2560 * @throws BadRequestException
2561 * @throws ForbiddenException
2563 function api_blocks_list($type)
2565 $data = api_statuses_f('blocks');
2566 if ($data === false) {
2569 return DI::apiResponse()->formatData("users", $type, $data);
2572 /// @TODO move to top of file or somewhere better
2573 api_register_func('api/blocks/list', 'api_blocks_list', true);
2576 * Returns the list of pending users IDs
2578 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2580 * @param string $type Either "json" or "xml"
2582 * @return boolean|string|array
2583 * @throws BadRequestException
2584 * @throws ForbiddenException
2586 function api_friendships_incoming($type)
2588 $data = api_statuses_f('incoming');
2589 if ($data === false) {
2594 foreach ($data['user'] as $user) {
2595 $ids[] = $user['id'];
2598 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2601 /// @TODO move to top of file or somewhere better
2602 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2605 * Sends a new direct message.
2607 * @param string $type Return type (atom, rss, xml, json)
2609 * @return array|string
2610 * @throws BadRequestException
2611 * @throws ForbiddenException
2612 * @throws ImagickException
2613 * @throws InternalServerErrorException
2614 * @throws NotFoundException
2615 * @throws UnauthorizedException
2616 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2618 function api_direct_messages_new($type)
2620 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2621 $uid = BaseApi::getCurrentUserID();
2623 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2627 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2629 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2631 throw new NotFoundException('Recipient not found');
2635 if (!empty($_REQUEST['replyto'])) {
2636 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2637 $replyto = $mail['parent-uri'];
2638 $sub = $mail['title'];
2640 if (!empty($_REQUEST['title'])) {
2641 $sub = $_REQUEST['title'];
2643 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2647 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2649 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2652 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2653 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid)->toArray(), $sender);
2655 $ret = ["error" => $id];
2658 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2661 /// @TODO move to top of file or somewhere better
2662 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2665 * delete a direct_message from mail table through api
2667 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2668 * @return string|array
2669 * @throws BadRequestException
2670 * @throws ForbiddenException
2671 * @throws ImagickException
2672 * @throws InternalServerErrorException
2673 * @throws UnauthorizedException
2674 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2676 function api_direct_messages_destroy($type)
2678 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2679 $uid = BaseApi::getCurrentUserID();
2682 $id = $_REQUEST['id'] ?? 0;
2684 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2685 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2686 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2688 // error if no id or parenturi specified (for clients posting parent-uri as well)
2689 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2690 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2691 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2694 // BadRequestException if no id specified (for clients using Twitter API)
2696 throw new BadRequestException('Message id not specified');
2699 // add parent-uri to sql command if specified by calling app
2700 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2702 // error message if specified id is not in database
2703 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2704 if ($verbose == "true") {
2705 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2706 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2708 /// @todo BadRequestException ok for Twitter API clients?
2709 throw new BadRequestException('message id not in database');
2713 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2715 if ($verbose == "true") {
2718 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2719 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2721 $answer = ['result' => 'error', 'message' => 'unknown error'];
2722 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2725 /// @todo return JSON data like Twitter API not yet implemented
2728 /// @TODO move to top of file or somewhere better
2729 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2734 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2735 * @return string|array
2736 * @throws HTTPException\BadRequestException
2737 * @throws HTTPException\ExpectationFailedException
2738 * @throws HTTPException\ForbiddenException
2739 * @throws HTTPException\InternalServerErrorException
2740 * @throws HTTPException\NotFoundException
2741 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2743 function api_friendships_destroy($type)
2745 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2746 $uid = BaseApi::getCurrentUserID();
2748 $owner = User::getOwnerDataById($uid);
2750 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2751 throw new HTTPException\NotFoundException('Error Processing Request');
2754 $contact_id = $_REQUEST['user_id'] ?? 0;
2756 if (empty($contact_id)) {
2757 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2758 throw new HTTPException\BadRequestException('no user_id specified');
2761 // Get Contact by given id
2762 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2764 if(!DBA::isResult($contact)) {
2765 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2766 throw new HTTPException\NotFoundException('no contact found to given ID');
2769 $url = $contact['url'];
2771 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2772 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2773 Strings::normaliseLink($url), $url];
2774 $contact = DBA::selectFirst('contact', [], $condition);
2776 if (!DBA::isResult($contact)) {
2777 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2778 throw new HTTPException\NotFoundException('Not following Contact');
2782 $result = Contact::terminateFriendship($owner, $contact);
2784 if ($result === null) {
2785 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2786 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2789 if ($result === false) {
2790 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2792 } catch (Exception $e) {
2793 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2794 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2797 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2798 unset($contact['uid']);
2799 unset($contact['self']);
2801 // Set screen_name since Twidere requests it
2802 $contact['screen_name'] = $contact['nick'];
2804 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2807 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2811 * @param string $type Return type (atom, rss, xml, json)
2812 * @param string $box
2813 * @param string $verbose
2815 * @return array|string
2816 * @throws BadRequestException
2817 * @throws ForbiddenException
2818 * @throws ImagickException
2819 * @throws InternalServerErrorException
2820 * @throws UnauthorizedException
2822 function api_direct_messages_box($type, $box, $verbose)
2824 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2825 $uid = BaseApi::getCurrentUserID();
2828 $count = $_GET['count'] ?? 20;
2829 $page = $_REQUEST['page'] ?? 1;
2831 $since_id = $_REQUEST['since_id'] ?? 0;
2832 $max_id = $_REQUEST['max_id'] ?? 0;
2834 $user_id = $_REQUEST['user_id'] ?? '';
2835 $screen_name = $_REQUEST['screen_name'] ?? '';
2838 unset($_REQUEST['user_id']);
2839 unset($_GET['user_id']);
2841 unset($_REQUEST['screen_name']);
2842 unset($_GET['screen_name']);
2844 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2846 $profile_url = $user_info["url"];
2849 $start = max(0, ($page - 1) * $count);
2854 if ($box=="sentbox") {
2855 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2856 } elseif ($box == "conversation") {
2857 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2858 } elseif ($box == "all") {
2859 $sql_extra = "true";
2860 } elseif ($box == "inbox") {
2861 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2865 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2868 if ($user_id != "") {
2869 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2870 } elseif ($screen_name !="") {
2871 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2874 $r = DBA::toArray(DBA::p(
2875 "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 ?,?",
2881 if ($verbose == "true" && !DBA::isResult($r)) {
2882 $answer = ['result' => 'error', 'message' => 'no mails available'];
2883 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2887 foreach ($r as $item) {
2888 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2889 $recipient = $user_info;
2890 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2891 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2892 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2893 $sender = $user_info;
2896 if (isset($recipient) && isset($sender)) {
2897 $ret[] = api_format_messages($item, $recipient, $sender);
2901 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2905 * Returns the most recent direct messages sent by the user.
2907 * @param string $type Return type (atom, rss, xml, json)
2909 * @return array|string
2910 * @throws BadRequestException
2911 * @throws ForbiddenException
2912 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2914 function api_direct_messages_sentbox($type)
2916 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2917 return api_direct_messages_box($type, "sentbox", $verbose);
2921 * Returns the most recent direct messages sent to the user.
2923 * @param string $type Return type (atom, rss, xml, json)
2925 * @return array|string
2926 * @throws BadRequestException
2927 * @throws ForbiddenException
2928 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2930 function api_direct_messages_inbox($type)
2932 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2933 return api_direct_messages_box($type, "inbox", $verbose);
2938 * @param string $type Return type (atom, rss, xml, json)
2940 * @return array|string
2941 * @throws BadRequestException
2942 * @throws ForbiddenException
2944 function api_direct_messages_all($type)
2946 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2947 return api_direct_messages_box($type, "all", $verbose);
2952 * @param string $type Return type (atom, rss, xml, json)
2954 * @return array|string
2955 * @throws BadRequestException
2956 * @throws ForbiddenException
2958 function api_direct_messages_conversation($type)
2960 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2961 return api_direct_messages_box($type, "conversation", $verbose);
2964 /// @TODO move to top of file or somewhere better
2965 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2966 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2967 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2968 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2971 * list all photos of the authenticated user
2973 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2974 * @return string|array
2975 * @throws ForbiddenException
2976 * @throws InternalServerErrorException
2978 function api_fr_photos_list($type)
2980 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2981 $uid = BaseApi::getCurrentUserID();
2983 $r = DBA::toArray(DBA::p(
2984 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2985 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2986 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2987 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2990 'image/jpeg' => 'jpg',
2991 'image/png' => 'png',
2992 'image/gif' => 'gif'
2994 $data = ['photo'=>[]];
2995 if (DBA::isResult($r)) {
2996 foreach ($r as $rr) {
2998 $photo['id'] = $rr['resource-id'];
2999 $photo['album'] = $rr['album'];
3000 $photo['filename'] = $rr['filename'];
3001 $photo['type'] = $rr['type'];
3002 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3003 $photo['created'] = $rr['created'];
3004 $photo['edited'] = $rr['edited'];
3005 $photo['desc'] = $rr['desc'];
3007 if ($type == "xml") {
3008 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3010 $photo['thumb'] = $thumb;
3011 $data['photo'][] = $photo;
3015 return DI::apiResponse()->formatData("photos", $type, $data);
3019 * upload a new photo or change an existing photo
3021 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3022 * @return string|array
3023 * @throws BadRequestException
3024 * @throws ForbiddenException
3025 * @throws ImagickException
3026 * @throws InternalServerErrorException
3027 * @throws NotFoundException
3029 function api_fr_photo_create_update($type)
3031 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3032 $uid = BaseApi::getCurrentUserID();
3035 $photo_id = $_REQUEST['photo_id'] ?? null;
3036 $desc = $_REQUEST['desc'] ?? null;
3037 $album = $_REQUEST['album'] ?? null;
3038 $album_new = $_REQUEST['album_new'] ?? null;
3039 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3040 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3041 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3042 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3043 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3045 // do several checks on input parameters
3046 // we do not allow calls without album string
3047 if ($album == null) {
3048 throw new BadRequestException("no albumname specified");
3050 // if photo_id == null --> we are uploading a new photo
3051 if ($photo_id == null) {
3054 // error if no media posted in create-mode
3055 if (empty($_FILES['media'])) {
3057 throw new BadRequestException("no media data submitted");
3060 // album_new will be ignored in create-mode
3065 // check if photo is existing in databasei
3066 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
3067 throw new BadRequestException("photo not available");
3071 // checks on acl strings provided by clients
3072 $acl_input_error = false;
3073 $acl_input_error |= check_acl_input($allow_cid, $uid);
3074 $acl_input_error |= check_acl_input($deny_cid, $uid);
3075 $acl_input_error |= check_acl_input($allow_gid, $uid);
3076 $acl_input_error |= check_acl_input($deny_gid, $uid);
3077 if ($acl_input_error) {
3078 throw new BadRequestException("acl data invalid");
3080 // now let's upload the new media in create-mode
3081 if ($mode == "create") {
3082 $media = $_FILES['media'];
3083 $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, null, $uid);
3085 // return success of updating or error message
3086 if (!is_null($data)) {
3087 return DI::apiResponse()->formatData("photo_create", $type, $data);
3089 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3093 // now let's do the changes in update-mode
3094 if ($mode == "update") {
3095 $updated_fields = [];
3097 if (!is_null($desc)) {
3098 $updated_fields['desc'] = $desc;
3101 if (!is_null($album_new)) {
3102 $updated_fields['album'] = $album_new;
3105 if (!is_null($allow_cid)) {
3106 $allow_cid = trim($allow_cid);
3107 $updated_fields['allow_cid'] = $allow_cid;
3110 if (!is_null($deny_cid)) {
3111 $deny_cid = trim($deny_cid);
3112 $updated_fields['deny_cid'] = $deny_cid;
3115 if (!is_null($allow_gid)) {
3116 $allow_gid = trim($allow_gid);
3117 $updated_fields['allow_gid'] = $allow_gid;
3120 if (!is_null($deny_gid)) {
3121 $deny_gid = trim($deny_gid);
3122 $updated_fields['deny_gid'] = $deny_gid;
3126 if (count($updated_fields) > 0) {
3127 $nothingtodo = false;
3128 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
3130 $nothingtodo = true;
3133 if (!empty($_FILES['media'])) {
3134 $nothingtodo = false;
3135 $media = $_FILES['media'];
3136 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
3137 if (!is_null($data)) {
3138 return DI::apiResponse()->formatData("photo_update", $type, $data);
3142 // return success of updating or error message
3144 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3145 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3148 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3149 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3151 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3154 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3158 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3160 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3161 * @return string|array
3162 * @throws BadRequestException
3163 * @throws ForbiddenException
3164 * @throws InternalServerErrorException
3165 * @throws NotFoundException
3167 function api_fr_photo_detail($type)
3169 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3171 if (empty($_REQUEST['photo_id'])) {
3172 throw new BadRequestException("No photo id.");
3175 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3176 $photo_id = $_REQUEST['photo_id'];
3178 // prepare json/xml output with data from database for the requested photo
3179 $data = prepare_photo_data($type, $scale, $photo_id);
3181 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3186 * updates the profile image for the user (either a specified profile or the default profile)
3188 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3190 * @return string|array
3191 * @throws BadRequestException
3192 * @throws ForbiddenException
3193 * @throws ImagickException
3194 * @throws InternalServerErrorException
3195 * @throws NotFoundException
3196 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3198 function api_account_update_profile_image($type)
3200 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3201 $uid = BaseApi::getCurrentUserID();
3204 $profile_id = $_REQUEST['profile_id'] ?? 0;
3206 // error if image data is missing
3207 if (empty($_FILES['image'])) {
3208 throw new BadRequestException("no media data submitted");
3211 // check if specified profile id is valid
3212 if ($profile_id != 0) {
3213 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
3214 // error message if specified profile id is not in database
3215 if (!DBA::isResult($profile)) {
3216 throw new BadRequestException("profile_id not available");
3218 $is_default_profile = $profile['is-default'];
3220 $is_default_profile = 1;
3223 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3225 if (!empty($_FILES['image'])) {
3226 $media = $_FILES['image'];
3227 } elseif (!empty($_FILES['media'])) {
3228 $media = $_FILES['media'];
3230 // save new profile image
3231 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
3234 if (is_array($media['type'])) {
3235 $filetype = $media['type'][0];
3237 $filetype = $media['type'];
3239 if ($filetype == "image/jpeg") {
3241 } elseif ($filetype == "image/png") {
3244 throw new InternalServerErrorException('Unsupported filetype');
3247 // change specified profile or all profiles to the new resource-id
3248 if ($is_default_profile) {
3249 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
3250 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3252 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3253 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3254 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
3257 Contact::updateSelfFromUserID($uid, true);
3259 // Update global directory in background
3260 Profile::publishUpdate($uid);
3262 // output for client
3264 return api_account_verify_credentials($type);
3266 // SaveMediaToDatabase failed for some reason
3267 throw new InternalServerErrorException("image upload failed");
3271 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3272 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3273 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3274 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3275 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3276 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3279 * Update user profile
3281 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3283 * @return array|string
3284 * @throws BadRequestException
3285 * @throws ForbiddenException
3286 * @throws ImagickException
3287 * @throws InternalServerErrorException
3288 * @throws UnauthorizedException
3290 function api_account_update_profile($type)
3292 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3293 $uid = BaseApi::getCurrentUserID();
3295 $api_user = DI::twitterUser()->createFromUserId($uid)->toArray();
3297 if (!empty($_POST['name'])) {
3298 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
3299 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
3300 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
3301 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3304 if (isset($_POST['description'])) {
3305 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3306 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3307 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3310 Profile::publishUpdate($uid);
3312 return api_account_verify_credentials($type);
3315 /// @TODO move to top of file or somewhere better
3316 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3320 * @param string $acl_string
3325 function check_acl_input($acl_string, $uid)
3327 if (empty($acl_string)) {
3331 $contact_not_found = false;
3333 // split <x><y><z> into array of cid's
3334 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3336 // check for each cid if it is available on server
3337 $cid_array = $array[0];
3338 foreach ($cid_array as $cid) {
3339 $cid = str_replace("<", "", $cid);
3340 $cid = str_replace(">", "", $cid);
3341 $condition = ['id' => $cid, 'uid' => $uid];
3342 $contact_not_found |= !DBA::exists('contact', $condition);
3344 return $contact_not_found;
3348 * @param string $mediatype
3349 * @param array $media
3350 * @param string $type
3351 * @param string $album
3352 * @param string $allow_cid
3353 * @param string $deny_cid
3354 * @param string $allow_gid
3355 * @param string $deny_gid
3356 * @param string $desc
3357 * @param integer $phototype
3358 * @param boolean $visibility
3359 * @param string $photo_id
3362 * @throws BadRequestException
3363 * @throws ForbiddenException
3364 * @throws ImagickException
3365 * @throws InternalServerErrorException
3366 * @throws NotFoundException
3367 * @throws UnauthorizedException
3369 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
3377 if (is_array($media)) {
3378 if (is_array($media['tmp_name'])) {
3379 $src = $media['tmp_name'][0];
3381 $src = $media['tmp_name'];
3383 if (is_array($media['name'])) {
3384 $filename = basename($media['name'][0]);
3386 $filename = basename($media['name']);
3388 if (is_array($media['size'])) {
3389 $filesize = intval($media['size'][0]);
3391 $filesize = intval($media['size']);
3393 if (is_array($media['type'])) {
3394 $filetype = $media['type'][0];
3396 $filetype = $media['type'];
3400 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3403 "File upload src: " . $src . " - filename: " . $filename .
3404 " - size: " . $filesize . " - type: " . $filetype);
3406 // check if there was a php upload error
3407 if ($filesize == 0 && $media['error'] == 1) {
3408 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3410 // check against max upload size within Friendica instance
3411 $maximagesize = DI::config()->get('system', 'maximagesize');
3412 if ($maximagesize && ($filesize > $maximagesize)) {
3413 $formattedBytes = Strings::formatBytes($maximagesize);
3414 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3417 // create Photo instance with the data of the image
3418 $imagedata = @file_get_contents($src);
3419 $Image = new Image($imagedata, $filetype);
3420 if (!$Image->isValid()) {
3421 throw new InternalServerErrorException("unable to process image data");
3424 // check orientation of image
3425 $Image->orient($src);
3428 // check max length of images on server
3429 $max_length = DI::config()->get('system', 'max_image_length');
3430 if ($max_length > 0) {
3431 $Image->scaleDown($max_length);
3432 logger::info("File upload: Scaling picture to new size " . $max_length);
3434 $width = $Image->getWidth();
3435 $height = $Image->getHeight();
3437 // create a new resource-id if not already provided
3438 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3440 if ($mediatype == "photo") {
3441 // upload normal image (scales 0, 1, 2)
3442 logger::info("photo upload: starting new photo upload");
3444 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3446 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3448 if ($width > 640 || $height > 640) {
3449 $Image->scaleDown(640);
3450 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3452 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3456 if ($width > 320 || $height > 320) {
3457 $Image->scaleDown(320);
3458 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3460 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3463 logger::info("photo upload: new photo upload ended");
3464 } elseif ($mediatype == "profileimage") {
3465 // upload profile image (scales 4, 5, 6)
3466 logger::info("photo upload: starting new profile image upload");
3468 if ($width > 300 || $height > 300) {
3469 $Image->scaleDown(300);
3470 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3472 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3476 if ($width > 80 || $height > 80) {
3477 $Image->scaleDown(80);
3478 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3480 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3484 if ($width > 48 || $height > 48) {
3485 $Image->scaleDown(48);
3486 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3488 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3491 $Image->__destruct();
3492 logger::info("photo upload: new profile image upload ended");
3496 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3497 if ($photo_id == null && $mediatype == "photo") {
3498 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
3500 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3501 return prepare_photo_data($type, false, $resource_id);
3503 throw new InternalServerErrorException("image upload failed");
3509 * @param string $hash
3510 * @param string $allow_cid
3511 * @param string $deny_cid
3512 * @param string $allow_gid
3513 * @param string $deny_gid
3514 * @param string $filetype
3515 * @param boolean $visibility
3517 * @throws InternalServerErrorException
3519 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
3521 // get data about the api authenticated user
3522 $uri = Item::newURI(intval($uid));
3523 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3526 $arr['guid'] = System::createUUID();
3527 $arr['uid'] = intval($uid);
3529 $arr['type'] = 'photo';
3531 $arr['resource-id'] = $hash;
3532 $arr['contact-id'] = $owner_record['id'];
3533 $arr['owner-name'] = $owner_record['name'];
3534 $arr['owner-link'] = $owner_record['url'];
3535 $arr['owner-avatar'] = $owner_record['thumb'];
3536 $arr['author-name'] = $owner_record['name'];
3537 $arr['author-link'] = $owner_record['url'];
3538 $arr['author-avatar'] = $owner_record['thumb'];
3540 $arr['allow_cid'] = $allow_cid;
3541 $arr['allow_gid'] = $allow_gid;
3542 $arr['deny_cid'] = $deny_cid;
3543 $arr['deny_gid'] = $deny_gid;
3544 $arr['visible'] = $visibility;
3548 'image/jpeg' => 'jpg',
3549 'image/png' => 'png',
3550 'image/gif' => 'gif'
3553 // adds link to the thumbnail scale photo
3554 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3555 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3558 // do the magic for storing the item in the database and trigger the federation to other contacts
3564 * @param string $type
3566 * @param string $photo_id
3569 * @throws BadRequestException
3570 * @throws ForbiddenException
3571 * @throws ImagickException
3572 * @throws InternalServerErrorException
3573 * @throws NotFoundException
3574 * @throws UnauthorizedException
3576 function prepare_photo_data($type, $scale, $photo_id)
3578 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3579 $uid = BaseApi::getCurrentUserID();
3581 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3582 $data_sql = ($scale === false ? "" : "data, ");
3584 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3585 // clients needs to convert this in their way for further processing
3586 $r = DBA::toArray(DBA::p(
3587 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3588 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3589 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3590 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
3591 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3592 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
3598 'image/jpeg' => 'jpg',
3599 'image/png' => 'png',
3600 'image/gif' => 'gif'
3603 // prepare output data for photo
3604 if (DBA::isResult($r)) {
3605 $data = ['photo' => $r[0]];
3606 $data['photo']['id'] = $data['photo']['resource-id'];
3607 if ($scale !== false) {
3608 $data['photo']['data'] = base64_encode($data['photo']['data']);
3610 unset($data['photo']['datasize']); //needed only with scale param
3612 if ($type == "xml") {
3613 $data['photo']['links'] = [];
3614 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3615 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
3617 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
3620 $data['photo']['link'] = [];
3621 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
3623 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3624 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3628 unset($data['photo']['resource-id']);
3629 unset($data['photo']['minscale']);
3630 unset($data['photo']['maxscale']);
3632 throw new NotFoundException();
3635 // retrieve item element for getting activities (like, dislike etc.) related to photo
3636 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
3637 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
3638 if (!DBA::isResult($item)) {
3639 throw new NotFoundException('Photo-related item not found.');
3642 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
3644 // retrieve comments on photo
3645 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
3646 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
3648 $statuses = Post::selectForUser($uid, [], $condition);
3650 // prepare output of comments
3652 while ($status = DBA::fetch($statuses)) {
3653 $commentData[] = api_format_item($status, $type);
3655 DBA::close($statuses);
3658 if ($type == "xml") {
3660 foreach ($commentData as $comment) {
3661 $comments[$k++ . ":comment"] = $comment;
3664 foreach ($commentData as $comment) {
3665 $comments[] = $comment;
3668 $data['photo']['friendica_comments'] = $comments;
3670 // include info if rights on photo and rights on item are mismatching
3671 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
3672 $data['photo']['deny_cid'] != $item['deny_cid'] ||
3673 $data['photo']['allow_gid'] != $item['allow_gid'] ||
3674 $data['photo']['deny_gid'] != $item['deny_gid'];
3675 $data['photo']['rights_mismatch'] = $rights_mismatch;
3681 * Return an item with announcer data if it had been announced
3683 * @param array $item Item array
3684 * @return array Item array with announce data
3686 function api_get_announce($item)
3688 // Quit if the item already has got a different owner and author
3689 if ($item['owner-id'] != $item['author-id']) {
3693 // Don't change original or Diaspora posts
3694 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
3698 // Quit if we do now the original author and it had been a post from a native network
3699 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
3703 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
3704 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
3705 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
3706 if (!DBA::isResult($announce)) {
3710 return array_merge($item, $announce);
3715 * @param array $item
3720 function api_in_reply_to($item)
3724 $in_reply_to['status_id'] = null;
3725 $in_reply_to['user_id'] = null;
3726 $in_reply_to['status_id_str'] = null;
3727 $in_reply_to['user_id_str'] = null;
3728 $in_reply_to['screen_name'] = null;
3730 if (!empty($item['thr-parent']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
3731 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
3732 if (DBA::isResult($parent)) {
3733 $in_reply_to['status_id'] = intval($parent['id']);
3735 $in_reply_to['status_id'] = intval($item['parent']);
3738 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3740 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
3741 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
3743 if (DBA::isResult($parent)) {
3744 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
3745 $in_reply_to['user_id'] = intval($parent['author-id']);
3746 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
3749 // There seems to be situation, where both fields are identical:
3750 // https://github.com/friendica/friendica/issues/1010
3751 // This is a bugfix for that.
3752 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3753 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']]);
3754 $in_reply_to['status_id'] = null;
3755 $in_reply_to['user_id'] = null;
3756 $in_reply_to['status_id_str'] = null;
3757 $in_reply_to['user_id_str'] = null;
3758 $in_reply_to['screen_name'] = null;
3762 return $in_reply_to;
3767 * @param string $text
3770 * @throws InternalServerErrorException
3772 function api_clean_plain_items($text)
3774 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
3776 $text = BBCode::cleanPictureLinks($text);
3777 $URLSearchString = "^\[\]";
3779 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
3781 if ($include_entities == "true") {
3782 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
3785 // Simplify "attachment" element
3786 $text = BBCode::removeAttachment($text);
3792 * Return all or a specified group of the user with the containing contacts.
3794 * @param string $type Return type (atom, rss, xml, json)
3796 * @return array|string
3797 * @throws BadRequestException
3798 * @throws ForbiddenException
3799 * @throws ImagickException
3800 * @throws InternalServerErrorException
3801 * @throws UnauthorizedException
3803 function api_friendica_group_show($type)
3805 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3806 $uid = BaseApi::getCurrentUserID();
3809 $gid = $_REQUEST['gid'] ?? 0;
3811 // get data of the specified group id or all groups if not specified
3813 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3815 // error message if specified gid is not in database
3816 if (!DBA::isResult($groups)) {
3817 throw new BadRequestException("gid not available");
3820 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3823 // loop through all groups and retrieve all members for adding data in the user array
3825 foreach ($groups as $rr) {
3826 $members = Contact\Group::getById($rr['id']);
3829 if ($type == "xml") {
3830 $user_element = "users";
3832 foreach ($members as $member) {
3833 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3834 $users[$k++.":user"] = $user;
3837 $user_element = "user";
3838 foreach ($members as $member) {
3839 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3843 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3845 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3848 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3853 * @param string $type Return type (atom, rss, xml, json)
3855 * @return array|string
3856 * @throws BadRequestException
3857 * @throws ForbiddenException
3858 * @throws ImagickException
3859 * @throws InternalServerErrorException
3860 * @throws UnauthorizedException
3861 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3863 function api_lists_destroy($type)
3865 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3866 $uid = BaseApi::getCurrentUserID();
3869 $gid = $_REQUEST['list_id'] ?? 0;
3871 // error if no gid specified
3873 throw new BadRequestException('gid not specified');
3876 // get data of the specified group id
3877 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3878 // error message if specified gid is not in database
3880 throw new BadRequestException('gid not available');
3883 if (Group::remove($gid)) {
3885 'name' => $group['name'],
3886 'id' => intval($gid),
3887 'id_str' => (string) $gid,
3888 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3891 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3895 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3898 * Add a new group to the database.
3900 * @param string $name Group name
3901 * @param int $uid User ID
3902 * @param array $users List of users to add to the group
3905 * @throws BadRequestException
3907 function group_create($name, $uid, $users = [])
3909 // error if no name specified
3911 throw new BadRequestException('group name not specified');
3914 // error message if specified group name already exists
3915 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
3916 throw new BadRequestException('group name already exists');
3919 // Check if the group needs to be reactivated
3920 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
3921 $reactivate_group = true;
3925 $ret = Group::create($uid, $name);
3927 $gid = Group::getIdByName($uid, $name);
3929 throw new BadRequestException('other API error');
3933 $erroraddinguser = false;
3935 foreach ($users as $user) {
3936 $cid = $user['cid'];
3937 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3938 Group::addMember($gid, $cid);
3940 $erroraddinguser = true;
3941 $errorusers[] = $cid;
3945 // return success message incl. missing users in array
3946 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
3948 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3952 * Create the specified group with the posted array of contacts.
3954 * @param string $type Return type (atom, rss, xml, json)
3956 * @return array|string
3957 * @throws BadRequestException
3958 * @throws ForbiddenException
3959 * @throws ImagickException
3960 * @throws InternalServerErrorException
3961 * @throws UnauthorizedException
3963 function api_friendica_group_create($type)
3965 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3966 $uid = BaseApi::getCurrentUserID();
3969 $name = $_REQUEST['name'] ?? '';
3970 $json = json_decode($_POST['json'], true);
3971 $users = $json['user'];
3973 $success = group_create($name, $uid, $users);
3975 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3978 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3981 * Create a new group.
3983 * @param string $type Return type (atom, rss, xml, json)
3985 * @return array|string
3986 * @throws BadRequestException
3987 * @throws ForbiddenException
3988 * @throws ImagickException
3989 * @throws InternalServerErrorException
3990 * @throws UnauthorizedException
3991 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3993 function api_lists_create($type)
3995 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3996 $uid = BaseApi::getCurrentUserID();
3999 $name = $_REQUEST['name'] ?? '';
4001 $success = group_create($name, $uid);
4002 if ($success['success']) {
4004 'name' => $success['name'],
4005 'id' => intval($success['gid']),
4006 'id_str' => (string) $success['gid'],
4007 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
4010 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4014 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4017 * Update the specified group with the posted array of contacts.
4019 * @param string $type Return type (atom, rss, xml, json)
4021 * @return array|string
4022 * @throws BadRequestException
4023 * @throws ForbiddenException
4024 * @throws ImagickException
4025 * @throws InternalServerErrorException
4026 * @throws UnauthorizedException
4028 function api_friendica_group_update($type)
4030 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4031 $uid = BaseApi::getCurrentUserID();
4034 $gid = $_REQUEST['gid'] ?? 0;
4035 $name = $_REQUEST['name'] ?? '';
4036 $json = json_decode($_POST['json'], true);
4037 $users = $json['user'];
4039 // error if no name specified
4041 throw new BadRequestException('group name not specified');
4044 // error if no gid specified
4046 throw new BadRequestException('gid not specified');
4050 $members = Contact\Group::getById($gid);
4051 foreach ($members as $member) {
4052 $cid = $member['id'];
4053 foreach ($users as $user) {
4054 $found = ($user['cid'] == $cid ? true : false);
4056 if (!isset($found) || !$found) {
4057 $gid = Group::getIdByName($uid, $name);
4058 Group::removeMember($gid, $cid);
4063 $erroraddinguser = false;
4065 foreach ($users as $user) {
4066 $cid = $user['cid'];
4068 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4069 Group::addMember($gid, $cid);
4071 $erroraddinguser = true;
4072 $errorusers[] = $cid;
4076 // return success message incl. missing users in array
4077 $status = ($erroraddinguser ? "missing user" : "ok");
4078 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4079 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4082 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4085 * Update information about a group.
4087 * @param string $type Return type (atom, rss, xml, json)
4089 * @return array|string
4090 * @throws BadRequestException
4091 * @throws ForbiddenException
4092 * @throws ImagickException
4093 * @throws InternalServerErrorException
4094 * @throws UnauthorizedException
4095 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4097 function api_lists_update($type)
4099 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4100 $uid = BaseApi::getCurrentUserID();
4103 $gid = $_REQUEST['list_id'] ?? 0;
4104 $name = $_REQUEST['name'] ?? '';
4106 // error if no gid specified
4108 throw new BadRequestException('gid not specified');
4111 // get data of the specified group id
4112 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4113 // error message if specified gid is not in database
4115 throw new BadRequestException('gid not available');
4118 if (Group::update($gid, $name)) {
4121 'id' => intval($gid),
4122 'id_str' => (string) $gid,
4123 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
4126 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4130 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4133 * Set notification as seen and returns associated item (if possible)
4135 * POST request with 'id' param as notification id
4137 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4138 * @return string|array
4139 * @throws BadRequestException
4140 * @throws ForbiddenException
4141 * @throws ImagickException
4142 * @throws InternalServerErrorException
4143 * @throws UnauthorizedException
4145 function api_friendica_notification_seen($type)
4147 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4148 $uid = BaseApi::getCurrentUserID();
4150 if (DI::args()->getArgc() !== 4) {
4151 throw new BadRequestException('Invalid argument count');
4154 $id = intval($_REQUEST['id'] ?? 0);
4157 $Notify = DI::notify()->selectOneById($id);
4158 if ($Notify->uid !== $uid) {
4159 throw new NotFoundException();
4162 if ($Notify->uriId) {
4163 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4167 DI::notify()->save($Notify);
4169 if ($Notify->otype === Notification\ObjectType::ITEM) {
4170 $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
4171 if (DBA::isResult($item)) {
4172 // we found the item, return it to the user
4173 $ret = [api_format_item($item, $type)];
4174 $data = ['status' => $ret];
4175 return DI::apiResponse()->formatData('status', $type, $data);
4177 // the item can't be found, but we set the notification as seen, so we count this as a success
4180 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4181 } catch (NotFoundException $e) {
4182 throw new BadRequestException('Invalid argument', $e);
4183 } catch (Exception $e) {
4184 throw new InternalServerErrorException('Internal Server exception', $e);
4188 /// @TODO move to top of file or somewhere better
4189 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4192 * search for direct_messages containing a searchstring through api
4194 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4195 * @param string $box
4196 * @return string|array (success: success=true if found and search_result contains found messages,
4197 * success=false if nothing was found, search_result='nothing found',
4198 * error: result=error with error message)
4199 * @throws BadRequestException
4200 * @throws ForbiddenException
4201 * @throws ImagickException
4202 * @throws InternalServerErrorException
4203 * @throws UnauthorizedException
4205 function api_friendica_direct_messages_search($type, $box = "")
4207 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4208 $uid = BaseApi::getCurrentUserID();
4211 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
4212 $searchstring = $_REQUEST['searchstring'] ?? '';
4214 // error if no searchstring specified
4215 if ($searchstring == "") {
4216 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4217 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4220 // get data for the specified searchstring
4221 $r = DBA::toArray(DBA::p(
4222 "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",
4224 '%'.$searchstring.'%'
4227 $profile_url = $user_info["url"];
4229 // message if nothing was found
4230 if (!DBA::isResult($r)) {
4231 $success = ['success' => false, 'search_results' => 'problem with query'];
4232 } elseif (count($r) == 0) {
4233 $success = ['success' => false, 'search_results' => 'nothing found'];
4236 foreach ($r as $item) {
4237 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4238 $recipient = $user_info;
4239 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
4240 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4241 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
4242 $sender = $user_info;
4245 if (isset($recipient) && isset($sender)) {
4246 $ret[] = api_format_messages($item, $recipient, $sender);
4249 $success = ['success' => true, 'search_results' => $ret];
4252 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4255 /// @TODO move to top of file or somewhere better
4256 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);