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'], 0);
269 $user_info['status'] = api_format_item($item, $type);
273 // "uid" is only needed for some internal stuff, so remove it from here
274 unset($user_info['uid']);
276 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
279 /// @TODO move to top of file or somewhere better
280 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
283 * Get data from $_POST or $_GET
288 function requestdata($k)
290 if (!empty($_POST[$k])) {
293 if (!empty($_GET[$k])) {
300 * Deprecated function to upload media.
302 * @param string $type Return type (atom, rss, xml, json)
304 * @return array|string
305 * @throws BadRequestException
306 * @throws ForbiddenException
307 * @throws ImagickException
308 * @throws InternalServerErrorException
309 * @throws UnauthorizedException
311 function api_statuses_mediap($type)
313 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
314 $uid = BaseApi::getCurrentUserID();
318 $_REQUEST['profile_uid'] = $uid;
319 $_REQUEST['api_source'] = true;
320 $txt = requestdata('status') ?? '';
322 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
323 $txt = HTML::toBBCodeVideo($txt);
324 $config = HTMLPurifier_Config::createDefault();
325 $config->set('Cache.DefinitionImpl', null);
326 $purifier = new HTMLPurifier($config);
327 $txt = $purifier->purify($txt);
329 $txt = HTML::toBBCode($txt);
331 $picture = wall_upload_post($a, false);
333 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
334 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
335 $item_id = item_post($a);
337 // output the post that we just posted.
338 return api_status_show($type, $item_id);
341 /// @TODO move this to top of file or somewhere better!
342 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
345 * Updates the user’s current status.
347 * @param string $type Return type (atom, rss, xml, json)
349 * @return array|string
350 * @throws BadRequestException
351 * @throws ForbiddenException
352 * @throws ImagickException
353 * @throws InternalServerErrorException
354 * @throws TooManyRequestsException
355 * @throws UnauthorizedException
356 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
358 function api_statuses_update($type)
360 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
361 $uid = BaseApi::getCurrentUserID();
365 // convert $_POST array items to the form we use for web posts.
366 if (requestdata('htmlstatus')) {
367 $txt = requestdata('htmlstatus') ?? '';
368 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
369 $txt = HTML::toBBCodeVideo($txt);
371 $config = HTMLPurifier_Config::createDefault();
372 $config->set('Cache.DefinitionImpl', null);
374 $purifier = new HTMLPurifier($config);
375 $txt = $purifier->purify($txt);
377 $_REQUEST['body'] = HTML::toBBCode($txt);
380 $_REQUEST['body'] = requestdata('status');
383 $_REQUEST['title'] = requestdata('title');
385 $parent = requestdata('in_reply_to_status_id');
387 // Twidere sends "-1" if it is no reply ...
392 if (ctype_digit($parent)) {
393 $_REQUEST['parent'] = $parent;
395 $_REQUEST['parent_uri'] = $parent;
398 if (requestdata('lat') && requestdata('long')) {
399 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
401 $_REQUEST['profile_uid'] = $uid;
404 // Check for throttling (maximum posts per day, week and month)
405 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
406 if ($throttle_day > 0) {
407 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
409 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
410 $posts_day = Post::count($condition);
412 if ($posts_day > $throttle_day) {
413 logger::info('Daily posting limit reached for user ' . $uid);
414 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
415 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));
419 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
420 if ($throttle_week > 0) {
421 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
423 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
424 $posts_week = Post::count($condition);
426 if ($posts_week > $throttle_week) {
427 logger::info('Weekly posting limit reached for user ' . $uid);
428 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
429 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));
433 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
434 if ($throttle_month > 0) {
435 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
437 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
438 $posts_month = Post::count($condition);
440 if ($posts_month > $throttle_month) {
441 logger::info('Monthly posting limit reached for user ' . $uid);
442 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
443 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));
448 if (requestdata('media_ids')) {
449 $ids = explode(',', requestdata('media_ids') ?? '');
450 } elseif (!empty($_FILES['media'])) {
451 // upload the image if we have one
452 $picture = wall_upload_post($a, false);
453 if (is_array($picture)) {
454 $ids[] = $picture['id'];
462 foreach ($ids as $id) {
463 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
464 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
465 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
466 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
468 if (!empty($media)) {
469 $ressources[] = $media[0]['resource-id'];
470 $phototypes = Images::supportedTypes();
471 $ext = $phototypes[$media[0]['type']];
473 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
474 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
475 'size' => $media[0]['datasize'],
476 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
477 'description' => $media[0]['desc'] ?? '',
478 'width' => $media[0]['width'],
479 'height' => $media[0]['height']];
481 if (count($media) > 1) {
482 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
483 $attachment['preview-width'] = $media[1]['width'];
484 $attachment['preview-height'] = $media[1]['height'];
486 $attachments[] = $attachment;
490 // We have to avoid that the post is rejected because of an empty body
491 if (empty($_REQUEST['body'])) {
492 $_REQUEST['body'] = '[hr]';
496 if (!empty($attachments)) {
497 $_REQUEST['attachments'] = $attachments;
500 // set this so that the item_post() function is quiet and doesn't redirect or emit json
502 $_REQUEST['api_source'] = true;
504 if (empty($_REQUEST['source'])) {
505 $_REQUEST['source'] = api_source();
508 // call out normal post function
509 $item_id = item_post($a);
511 if (!empty($ressources) && !empty($item_id)) {
512 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
513 foreach ($ressources as $ressource) {
514 Photo::setPermissionForRessource($ressource, $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
518 // output the post that we just posted.
519 return api_status_show($type, $item_id);
522 /// @TODO move to top of file or somewhere better
523 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
524 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
527 * Uploads an image to Friendica.
530 * @throws BadRequestException
531 * @throws ForbiddenException
532 * @throws ImagickException
533 * @throws InternalServerErrorException
534 * @throws UnauthorizedException
535 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
537 function api_media_upload()
539 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
541 if (empty($_FILES['media'])) {
543 throw new BadRequestException("No media.");
546 $media = wall_upload_post(DI::app(), false);
549 throw new InternalServerErrorException();
553 $returndata["media_id"] = $media["id"];
554 $returndata["media_id_string"] = (string)$media["id"];
555 $returndata["size"] = $media["size"];
556 $returndata["image"] = ["w" => $media["width"],
557 "h" => $media["height"],
558 "image_type" => $media["type"],
559 "friendica_preview_url" => $media["preview"]];
561 Logger::info('Media uploaded', ['return' => $returndata]);
563 return ["media" => $returndata];
566 /// @TODO move to top of file or somewhere better
567 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
570 * Updates media meta data (picture descriptions)
572 * @param string $type Return type (atom, rss, xml, json)
574 * @return array|string
575 * @throws BadRequestException
576 * @throws ForbiddenException
577 * @throws ImagickException
578 * @throws InternalServerErrorException
579 * @throws TooManyRequestsException
580 * @throws UnauthorizedException
581 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
583 * @todo Compare the corresponding Twitter function for correct return values
585 function api_media_metadata_create($type)
587 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
588 $uid = BaseApi::getCurrentUserID();
590 $postdata = Network::postdata();
592 if (empty($postdata)) {
593 throw new BadRequestException("No post data");
596 $data = json_decode($postdata, true);
598 throw new BadRequestException("Invalid post data");
601 if (empty($data['media_id']) || empty($data['alt_text'])) {
602 throw new BadRequestException("Missing post data values");
605 if (empty($data['alt_text']['text'])) {
606 throw new BadRequestException("No alt text.");
609 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
611 $condition = ['id' => $data['media_id'], 'uid' => $uid];
612 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
613 if (!DBA::isResult($photo)) {
614 throw new BadRequestException("Metadata not found.");
617 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
620 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
623 * @param string $type Return format (atom, rss, xml, json)
624 * @param int $item_id
625 * @return array|string
628 function api_status_show($type, $item_id)
630 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
634 $item = api_get_item(['id' => $item_id]);
636 $status_info = api_format_item($item, $type);
639 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
641 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
645 * Retrieves the last public status of the provided user info
647 * @param int $ownerId Public contact Id
648 * @param int $uid User Id
652 function api_get_last_status($ownerId, $uid)
655 'author-id'=> $ownerId,
657 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
658 'private' => [Item::PUBLIC, Item::UNLISTED]
661 $item = api_get_item($condition);
667 * Retrieves a single item record based on the provided condition and converts it for API use.
669 * @param array $condition Item table condition array
673 function api_get_item(array $condition)
675 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
681 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
682 * The author's most recent status will be returned inline.
684 * @param string $type Return type (atom, rss, xml, json)
685 * @return array|string
686 * @throws BadRequestException
687 * @throws ImagickException
688 * @throws InternalServerErrorException
689 * @throws UnauthorizedException
690 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
692 function api_users_show($type)
694 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
695 $uid = BaseApi::getCurrentUserID();
697 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
699 $item = api_get_last_status($user_info['pid'], 0);
701 $user_info['status'] = api_format_item($item, $type);
704 // "uid" is only needed for some internal stuff, so remove it from here
705 unset($user_info['uid']);
707 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
710 /// @TODO move to top of file or somewhere better
711 api_register_func('api/users/show', 'api_users_show');
712 api_register_func('api/externalprofile/show', 'api_users_show');
715 * Search a public user account.
717 * @param string $type Return type (atom, rss, xml, json)
719 * @return array|string
720 * @throws BadRequestException
721 * @throws ImagickException
722 * @throws InternalServerErrorException
723 * @throws UnauthorizedException
724 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
726 function api_users_search($type)
728 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
729 $uid = BaseApi::getCurrentUserID();
733 if (!empty($_GET['q'])) {
734 $contacts = Contact::selectToArray(
737 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
745 if (DBA::isResult($contacts)) {
747 foreach ($contacts as $contact) {
748 $user_info = DI::twitterUser()->createFromContactId($contact['id'], $uid)->toArray();
750 if ($type == 'xml') {
751 $userlist[$k++ . ':user'] = $user_info;
753 $userlist[] = $user_info;
756 $userlist = ['users' => $userlist];
758 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
761 throw new BadRequestException('No search term specified.');
764 return DI::apiResponse()->formatData('users', $type, $userlist);
767 /// @TODO move to top of file or somewhere better
768 api_register_func('api/users/search', 'api_users_search');
771 * Return user objects
773 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
775 * @param string $type Return format: json or xml
777 * @return array|string
778 * @throws BadRequestException
779 * @throws ImagickException
780 * @throws InternalServerErrorException
781 * @throws NotFoundException if the results are empty.
782 * @throws UnauthorizedException
784 function api_users_lookup($type)
786 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
787 $uid = BaseApi::getCurrentUserID();
791 if (!empty($_REQUEST['user_id'])) {
792 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
793 if (!empty($cid) && is_numeric($cid)) {
794 $users[] = DI::twitterUser()->createFromContactId((int)$cid, $uid)->toArray();
800 throw new NotFoundException;
803 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
806 /// @TODO move to top of file or somewhere better
807 api_register_func('api/users/lookup', 'api_users_lookup', true);
810 * Returns statuses that match a specified query.
812 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
814 * @param string $type Return format: json, xml, atom, rss
816 * @return array|string
817 * @throws BadRequestException if the "q" parameter is missing.
818 * @throws ForbiddenException
819 * @throws ImagickException
820 * @throws InternalServerErrorException
821 * @throws UnauthorizedException
823 function api_search($type)
825 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
826 $uid = BaseApi::getCurrentUserID();
828 if (empty($_REQUEST['q'])) {
829 throw new BadRequestException('q parameter is required.');
832 $searchTerm = trim(rawurldecode($_REQUEST['q']));
835 $data['status'] = [];
837 $exclude_replies = !empty($_REQUEST['exclude_replies']);
838 if (!empty($_REQUEST['rpp'])) {
839 $count = $_REQUEST['rpp'];
840 } elseif (!empty($_REQUEST['count'])) {
841 $count = $_REQUEST['count'];
844 $since_id = $_REQUEST['since_id'] ?? 0;
845 $max_id = $_REQUEST['max_id'] ?? 0;
846 $page = $_REQUEST['page'] ?? 1;
848 $start = max(0, ($page - 1) * $count);
850 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
851 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
852 $searchTerm = $matches[1];
853 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, $uid];
854 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
856 while ($tag = DBA::fetch($tags)) {
857 $uriids[] = $tag['uri-id'];
861 if (empty($uriids)) {
862 return DI::apiResponse()->formatData('statuses', $type, $data);
865 $condition = ['uri-id' => $uriids];
866 if ($exclude_replies) {
867 $condition['gravity'] = GRAVITY_PARENT;
870 $params['group_by'] = ['uri-id'];
872 $condition = ["`id` > ?
873 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
874 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
875 AND `body` LIKE CONCAT('%',?,'%')",
876 $since_id, $uid, $_REQUEST['q']];
878 $condition[0] .= ' AND `id` <= ?';
879 $condition[] = $max_id;
885 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
886 $id = Item::fetchByLink($searchTerm, $uid);
889 $id = Item::fetchByLink($searchTerm);
893 $statuses = Post::select([], ['id' => $id]);
897 $statuses = $statuses ?: Post::selectForUser($uid, [], $condition, $params);
900 while ($status = DBA::fetch($statuses)) {
901 $ret[] = api_format_item($status, $type);
903 DBA::close($statuses);
905 $data['status'] = $ret;
907 return DI::apiResponse()->formatData('statuses', $type, $data);
910 /// @TODO move to top of file or somewhere better
911 api_register_func('api/search/tweets', 'api_search', true);
912 api_register_func('api/search', 'api_search', true);
915 * Returns the most recent statuses posted by the user and the users they follow.
917 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
919 * @param string $type Return type (atom, rss, xml, json)
921 * @return array|string
922 * @throws BadRequestException
923 * @throws ForbiddenException
924 * @throws ImagickException
925 * @throws InternalServerErrorException
926 * @throws UnauthorizedException
927 * @todo Optional parameters
928 * @todo Add reply info
930 function api_statuses_home_timeline($type)
932 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
933 $uid = BaseApi::getCurrentUserID();
935 unset($_REQUEST['user_id']);
936 unset($_GET['user_id']);
938 unset($_REQUEST['screen_name']);
939 unset($_GET['screen_name']);
941 // get last network messages
944 $count = $_REQUEST['count'] ?? 20;
945 $page = $_REQUEST['page']?? 0;
946 $since_id = $_REQUEST['since_id'] ?? 0;
947 $max_id = $_REQUEST['max_id'] ?? 0;
948 $exclude_replies = !empty($_REQUEST['exclude_replies']);
949 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
951 $start = max(0, ($page - 1) * $count);
953 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
954 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
957 $condition[0] .= " AND `id` <= ?";
958 $condition[] = $max_id;
960 if ($exclude_replies) {
961 $condition[0] .= ' AND `gravity` = ?';
962 $condition[] = GRAVITY_PARENT;
964 if ($conversation_id > 0) {
965 $condition[0] .= " AND `parent` = ?";
966 $condition[] = $conversation_id;
969 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
970 $statuses = Post::selectForUser($uid, [], $condition, $params);
974 while ($status = DBA::fetch($statuses)) {
975 $ret[] = api_format_item($status, $type);
976 $idarray[] = intval($status['id']);
978 DBA::close($statuses);
980 if (!empty($idarray)) {
981 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
983 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
987 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
991 /// @TODO move to top of file or somewhere better
992 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
993 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
996 * Returns the most recent statuses from public users.
998 * @param string $type Return type (atom, rss, xml, json)
1000 * @return array|string
1001 * @throws BadRequestException
1002 * @throws ForbiddenException
1003 * @throws ImagickException
1004 * @throws InternalServerErrorException
1005 * @throws UnauthorizedException
1007 function api_statuses_public_timeline($type)
1009 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1010 $uid = BaseApi::getCurrentUserID();
1012 // get last network messages
1015 $count = $_REQUEST['count'] ?? 20;
1016 $page = $_REQUEST['page'] ?? 1;
1017 $since_id = $_REQUEST['since_id'] ?? 0;
1018 $max_id = $_REQUEST['max_id'] ?? 0;
1019 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1020 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1022 $start = max(0, ($page - 1) * $count);
1024 if ($exclude_replies && !$conversation_id) {
1025 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1026 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1029 $condition[0] .= " AND `id` <= ?";
1030 $condition[] = $max_id;
1033 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1034 $statuses = Post::selectForUser($uid, [], $condition, $params);
1036 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1037 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1040 $condition[0] .= " AND `id` <= ?";
1041 $condition[] = $max_id;
1043 if ($conversation_id > 0) {
1044 $condition[0] .= " AND `parent` = ?";
1045 $condition[] = $conversation_id;
1048 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1049 $statuses = Post::selectForUser($uid, [], $condition, $params);
1053 while ($status = DBA::fetch($statuses)) {
1054 $ret[] = api_format_item($status, $type);
1056 DBA::close($statuses);
1058 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1061 /// @TODO move to top of file or somewhere better
1062 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1065 * Returns the most recent statuses posted by users this node knows about.
1067 * @param string $type Return format: json, xml, atom, rss
1068 * @return array|string
1069 * @throws BadRequestException
1070 * @throws ForbiddenException
1071 * @throws ImagickException
1072 * @throws InternalServerErrorException
1073 * @throws UnauthorizedException
1075 function api_statuses_networkpublic_timeline($type)
1077 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1078 $uid = BaseApi::getCurrentUserID();
1080 $since_id = $_REQUEST['since_id'] ?? 0;
1081 $max_id = $_REQUEST['max_id'] ?? 0;
1084 $count = $_REQUEST['count'] ?? 20;
1085 $page = $_REQUEST['page'] ?? 1;
1087 $start = max(0, ($page - 1) * $count);
1089 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1090 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1093 $condition[0] .= " AND `id` <= ?";
1094 $condition[] = $max_id;
1097 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1098 $statuses = Post::selectForUser($uid, Item::DISPLAY_FIELDLIST, $condition, $params);
1101 while ($status = DBA::fetch($statuses)) {
1102 $ret[] = api_format_item($status, $type);
1104 DBA::close($statuses);
1106 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1109 /// @TODO move to top of file or somewhere better
1110 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1113 * Returns a single status.
1115 * @param string $type Return type (atom, rss, xml, json)
1117 * @return array|string
1118 * @throws BadRequestException
1119 * @throws ForbiddenException
1120 * @throws ImagickException
1121 * @throws InternalServerErrorException
1122 * @throws UnauthorizedException
1123 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1125 function api_statuses_show($type)
1127 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1128 $uid = BaseApi::getCurrentUserID();
1131 $id = intval(DI::args()->getArgv()[3] ?? 0);
1134 $id = intval($_REQUEST['id'] ?? 0);
1139 $id = intval(DI::args()->getArgv()[4] ?? 0);
1142 logger::notice('API: api_statuses_show: ' . $id);
1144 $conversation = !empty($_REQUEST['conversation']);
1146 // try to fetch the item for the local user - or the public item, if there is no local one
1147 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1148 if (!DBA::isResult($uri_item)) {
1149 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1152 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1153 if (!DBA::isResult($item)) {
1154 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1159 if ($conversation) {
1160 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1161 $params = ['order' => ['id' => true]];
1163 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1167 $statuses = Post::selectForUser($uid, [], $condition, $params);
1169 /// @TODO How about copying this to above methods which don't check $r ?
1170 if (!DBA::isResult($statuses)) {
1171 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1175 while ($status = DBA::fetch($statuses)) {
1176 $ret[] = api_format_item($status, $type);
1178 DBA::close($statuses);
1180 if ($conversation) {
1181 $data = ['status' => $ret];
1182 return DI::apiResponse()->formatData("statuses", $type, $data);
1184 $data = ['status' => $ret[0]];
1185 return DI::apiResponse()->formatData("status", $type, $data);
1189 /// @TODO move to top of file or somewhere better
1190 api_register_func('api/statuses/show', 'api_statuses_show', true);
1194 * @param string $type Return type (atom, rss, xml, json)
1196 * @return array|string
1197 * @throws BadRequestException
1198 * @throws ForbiddenException
1199 * @throws ImagickException
1200 * @throws InternalServerErrorException
1201 * @throws UnauthorizedException
1202 * @todo nothing to say?
1204 function api_conversation_show($type)
1206 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1207 $uid = BaseApi::getCurrentUserID();
1210 $id = intval(DI::args()->getArgv()[3] ?? 0);
1211 $since_id = intval($_REQUEST['since_id'] ?? 0);
1212 $max_id = intval($_REQUEST['max_id'] ?? 0);
1213 $count = intval($_REQUEST['count'] ?? 20);
1214 $page = intval($_REQUEST['page'] ?? 1);
1216 $start = max(0, ($page - 1) * $count);
1219 $id = intval($_REQUEST['id'] ?? 0);
1224 $id = intval(DI::args()->getArgv()[4] ?? 0);
1227 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1229 // try to fetch the item for the local user - or the public item, if there is no local one
1230 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1231 if (!DBA::isResult($item)) {
1232 throw new BadRequestException("There is no status with the id $id.");
1235 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
1236 if (!DBA::isResult($parent)) {
1237 throw new BadRequestException("There is no status with this id.");
1240 $id = $parent['id'];
1242 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1243 $id, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1246 $condition[0] .= " AND `id` <= ?";
1247 $condition[] = $max_id;
1250 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1251 $statuses = Post::selectForUser($uid, [], $condition, $params);
1253 if (!DBA::isResult($statuses)) {
1254 throw new BadRequestException("There is no status with id $id.");
1258 while ($status = DBA::fetch($statuses)) {
1259 $ret[] = api_format_item($status, $type);
1261 DBA::close($statuses);
1263 $data = ['status' => $ret];
1264 return DI::apiResponse()->formatData("statuses", $type, $data);
1267 /// @TODO move to top of file or somewhere better
1268 api_register_func('api/conversation/show', 'api_conversation_show', true);
1269 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1274 * @param string $type Return type (atom, rss, xml, json)
1276 * @return array|string
1277 * @throws BadRequestException
1278 * @throws ForbiddenException
1279 * @throws ImagickException
1280 * @throws InternalServerErrorException
1281 * @throws UnauthorizedException
1282 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1284 function api_statuses_repeat($type)
1286 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1287 $uid = BaseApi::getCurrentUserID();
1290 $id = intval(DI::args()->getArgv()[3] ?? 0);
1293 $id = intval($_REQUEST['id'] ?? 0);
1298 $id = intval(DI::args()->getArgv()[4] ?? 0);
1301 logger::notice('API: api_statuses_repeat: ' . $id);
1303 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1304 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1306 if (DBA::isResult($item) && !empty($item['body'])) {
1307 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1308 if (!Item::performActivity($id, 'announce', $uid)) {
1309 throw new InternalServerErrorException();
1314 if (strpos($item['body'], "[/share]") !== false) {
1315 $pos = strpos($item['body'], "[share");
1316 $post = substr($item['body'], $pos);
1318 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1320 if (!empty($item['title'])) {
1321 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1324 $post .= $item['body'];
1325 $post .= "[/share]";
1327 $_REQUEST['body'] = $post;
1328 $_REQUEST['profile_uid'] = $uid;
1329 $_REQUEST['api_source'] = true;
1331 if (empty($_REQUEST['source'])) {
1332 $_REQUEST['source'] = api_source();
1335 $item_id = item_post(DI::app());
1338 throw new ForbiddenException();
1341 // output the post that we just posted.
1342 return api_status_show($type, $item_id);
1345 /// @TODO move to top of file or somewhere better
1346 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1349 * Destroys a specific status.
1351 * @param string $type Return type (atom, rss, xml, json)
1353 * @return array|string
1354 * @throws BadRequestException
1355 * @throws ForbiddenException
1356 * @throws ImagickException
1357 * @throws InternalServerErrorException
1358 * @throws UnauthorizedException
1359 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1361 function api_statuses_destroy($type)
1363 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1364 $uid = BaseApi::getCurrentUserID();
1367 $id = intval(DI::args()->getArgv()[3] ?? 0);
1370 $id = intval($_REQUEST['id'] ?? 0);
1375 $id = intval(DI::args()->getArgv()[4] ?? 0);
1378 logger::notice('API: api_statuses_destroy: ' . $id);
1380 $ret = api_statuses_show($type);
1382 Item::deleteForUser(['id' => $id], $uid);
1387 /// @TODO move to top of file or somewhere better
1388 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1391 * Returns the most recent mentions.
1393 * @param string $type Return type (atom, rss, xml, json)
1395 * @return array|string
1396 * @throws BadRequestException
1397 * @throws ForbiddenException
1398 * @throws ImagickException
1399 * @throws InternalServerErrorException
1400 * @throws UnauthorizedException
1401 * @see http://developer.twitter.com/doc/get/statuses/mentions
1403 function api_statuses_mentions($type)
1405 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1406 $uid = BaseApi::getCurrentUserID();
1408 unset($_REQUEST['user_id']);
1409 unset($_GET['user_id']);
1411 unset($_REQUEST['screen_name']);
1412 unset($_GET['screen_name']);
1414 // get last network messages
1417 $since_id = intval($_REQUEST['since_id'] ?? 0);
1418 $max_id = intval($_REQUEST['max_id'] ?? 0);
1419 $count = intval($_REQUEST['count'] ?? 20);
1420 $page = intval($_REQUEST['page'] ?? 1);
1422 $start = max(0, ($page - 1) * $count);
1424 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1425 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1426 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1429 GRAVITY_PARENT, GRAVITY_COMMENT,
1431 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1432 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1433 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1438 $query .= " AND `id` <= ?";
1439 $condition[] = $max_id;
1442 array_unshift($condition, $query);
1444 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1445 $statuses = Post::selectForUser($uid, [], $condition, $params);
1448 while ($status = DBA::fetch($statuses)) {
1449 $ret[] = api_format_item($status, $type);
1451 DBA::close($statuses);
1453 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1456 /// @TODO move to top of file or somewhere better
1457 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1458 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1461 * Returns the most recent statuses posted by the user.
1463 * @param string $type Either "json" or "xml"
1464 * @return string|array
1465 * @throws BadRequestException
1466 * @throws ForbiddenException
1467 * @throws ImagickException
1468 * @throws InternalServerErrorException
1469 * @throws UnauthorizedException
1470 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1472 function api_statuses_user_timeline($type)
1474 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1475 $uid = BaseApi::getCurrentUserID();
1477 Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1479 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1480 $since_id = $_REQUEST['since_id'] ?? 0;
1481 $max_id = $_REQUEST['max_id'] ?? 0;
1482 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1483 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1486 $count = $_REQUEST['count'] ?? 20;
1487 $page = $_REQUEST['page'] ?? 1;
1489 $start = max(0, ($page - 1) * $count);
1491 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1492 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1494 if ($exclude_replies) {
1495 $condition[0] .= ' AND `gravity` = ?';
1496 $condition[] = GRAVITY_PARENT;
1499 if ($conversation_id > 0) {
1500 $condition[0] .= " AND `parent` = ?";
1501 $condition[] = $conversation_id;
1505 $condition[0] .= " AND `id` <= ?";
1506 $condition[] = $max_id;
1508 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1509 $statuses = Post::selectForUser($uid, [], $condition, $params);
1512 while ($status = DBA::fetch($statuses)) {
1513 $ret[] = api_format_item($status, $type);
1515 DBA::close($statuses);
1517 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1520 /// @TODO move to top of file or somewhere better
1521 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1524 * Star/unstar an item.
1525 * param: id : id of the item
1527 * @param string $type Return type (atom, rss, xml, json)
1529 * @return array|string
1530 * @throws BadRequestException
1531 * @throws ForbiddenException
1532 * @throws ImagickException
1533 * @throws InternalServerErrorException
1534 * @throws UnauthorizedException
1535 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1537 function api_favorites_create_destroy($type)
1539 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1540 $uid = BaseApi::getCurrentUserID();
1542 // for versioned api.
1543 /// @TODO We need a better global soluton
1544 $action_argv_id = 2;
1545 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1546 $action_argv_id = 3;
1549 if (DI::args()->getArgc() <= $action_argv_id) {
1550 throw new BadRequestException("Invalid request.");
1552 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1553 if (DI::args()->getArgc() == $action_argv_id + 2) {
1554 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1556 $itemid = intval($_REQUEST['id'] ?? 0);
1559 $item = Post::selectFirstForUser($uid, [], ['id' => $itemid, 'uid' => $uid]);
1561 if (!DBA::isResult($item)) {
1562 throw new BadRequestException("Invalid item.");
1567 $item['starred'] = 1;
1570 $item['starred'] = 0;
1573 throw new BadRequestException("Invalid action ".$action);
1576 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1579 throw new InternalServerErrorException("DB error");
1582 $ret = api_format_item($item, $type);
1584 return DI::apiResponse()->formatData("status", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1587 /// @TODO move to top of file or somewhere better
1588 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1589 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1592 * Returns the most recent favorite statuses.
1594 * @param string $type Return type (atom, rss, xml, json)
1596 * @return string|array
1597 * @throws BadRequestException
1598 * @throws ForbiddenException
1599 * @throws ImagickException
1600 * @throws InternalServerErrorException
1601 * @throws UnauthorizedException
1603 function api_favorites($type)
1605 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1606 $uid = BaseApi::getCurrentUserID();
1608 // in friendica starred item are private
1609 // return favorites only for self
1610 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
1613 $since_id = $_REQUEST['since_id'] ?? 0;
1614 $max_id = $_REQUEST['max_id'] ?? 0;
1615 $count = $_GET['count'] ?? 20;
1616 $page = $_REQUEST['page'] ?? 1;
1618 $start = max(0, ($page - 1) * $count);
1620 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1621 $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1623 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1626 $condition[0] .= " AND `id` <= ?";
1627 $condition[] = $max_id;
1630 $statuses = Post::selectForUser($uid, [], $condition, $params);
1633 while ($status = DBA::fetch($statuses)) {
1634 $ret[] = api_format_item($status, $type);
1636 DBA::close($statuses);
1638 return DI::apiResponse()->formatData("statuses", $type, ['status' => $ret], Contact::getPublicIdByUserId($uid));
1641 /// @TODO move to top of file or somewhere better
1642 api_register_func('api/favorites', 'api_favorites', true);
1646 * @param array $item
1647 * @param array $recipient
1648 * @param array $sender
1651 * @throws InternalServerErrorException
1653 function api_format_messages($item, $recipient, $sender)
1655 // standard meta information
1657 'id' => $item['id'],
1658 'sender_id' => $sender['id'],
1660 'recipient_id' => $recipient['id'],
1661 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
1662 'sender_screen_name' => $sender['screen_name'],
1663 'recipient_screen_name' => $recipient['screen_name'],
1664 'sender' => $sender,
1665 'recipient' => $recipient,
1667 'friendica_seen' => $item['seen'] ?? 0,
1668 'friendica_parent_uri' => $item['parent-uri'] ?? '',
1671 // "uid" is only needed for some internal stuff, so remove it from here
1672 if (isset($ret['sender']['uid'])) {
1673 unset($ret['sender']['uid']);
1675 if (isset($ret['recipient']['uid'])) {
1676 unset($ret['recipient']['uid']);
1679 //don't send title to regular StatusNET requests to avoid confusing these apps
1680 if (!empty($_GET['getText'])) {
1681 $ret['title'] = $item['title'];
1682 if ($_GET['getText'] == 'html') {
1683 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
1684 } elseif ($_GET['getText'] == 'plain') {
1685 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
1688 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
1690 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
1691 unset($ret['sender']);
1692 unset($ret['recipient']);
1700 * @param array $item
1703 * @throws InternalServerErrorException
1705 function api_convert_item($item)
1707 $body = api_add_attachments_to_body($item);
1709 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
1711 // Add pictures to the attachment array and remove them from the body
1712 $attachments = api_get_attachments($body, $item['uri-id']);
1714 // Workaround for ostatus messages where the title is identically to the body
1715 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
1716 $statusbody = trim(HTML::toPlaintext($html, 0));
1718 // handle data: images
1719 $statusbody = api_format_items_embeded_images($item, $statusbody);
1721 $statustitle = trim($item['title']);
1723 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
1724 $statustext = trim($statusbody);
1726 $statustext = trim($statustitle."\n\n".$statusbody);
1729 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
1730 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
1733 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
1735 // Workaround for clients with limited HTML parser functionality
1736 $search = ["<br>", "<blockquote>", "</blockquote>",
1737 "<h1>", "</h1>", "<h2>", "</h2>",
1738 "<h3>", "</h3>", "<h4>", "</h4>",
1739 "<h5>", "</h5>", "<h6>", "</h6>"];
1740 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
1741 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
1742 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
1743 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
1744 $statushtml = str_replace($search, $replace, $statushtml);
1746 if ($item['title'] != "") {
1747 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
1751 $oldtext = $statushtml;
1752 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
1753 } while ($oldtext != $statushtml);
1755 if (substr($statushtml, 0, 4) == '<br>') {
1756 $statushtml = substr($statushtml, 4);
1759 if (substr($statushtml, 0, -4) == '<br>') {
1760 $statushtml = substr($statushtml, -4);
1763 // feeds without body should contain the link
1764 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
1765 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
1769 "text" => $statustext,
1770 "html" => $statushtml,
1771 "attachments" => $attachments,
1772 "entities" => $entities
1777 * Add media attachments to the body
1779 * @param array $item
1780 * @return string body with added media
1782 function api_add_attachments_to_body(array $item)
1784 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1786 if (strpos($body, '[/img]') !== false) {
1790 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
1791 if (!empty($media['preview'])) {
1792 $description = $media['description'] ?: $media['name'];
1793 if (!empty($description)) {
1794 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
1796 $body .= "\n[img]" . $media['preview'] .'[/img]';
1806 * @param string $body
1810 * @throws InternalServerErrorException
1812 function api_get_attachments(&$body, $uriid)
1814 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1815 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1817 $URLSearchString = "^\[\]";
1818 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
1822 // Remove all embedded pictures, since they are added as attachments
1823 foreach ($images[0] as $orig) {
1824 $body = str_replace($orig, '', $body);
1829 foreach ($images[1] as $image) {
1830 $imagedata = Images::getInfoFromURLCached($image);
1833 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
1837 return $attachments;
1842 * @param string $text
1843 * @param string $bbcode
1846 * @throws InternalServerErrorException
1847 * @todo Links at the first character of the post
1849 function api_get_entitities(&$text, $bbcode, $uriid)
1851 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
1853 if ($include_entities != "true") {
1854 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1856 foreach ($images[1] as $image) {
1857 $replace = Post\Link::getByLink($uriid, $image);
1858 $text = str_replace($image, $replace, $text);
1863 $bbcode = BBCode::cleanPictureLinks($bbcode);
1865 // Change pure links in text to bbcode uris
1866 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1869 $entities["hashtags"] = [];
1870 $entities["symbols"] = [];
1871 $entities["urls"] = [];
1872 $entities["user_mentions"] = [];
1874 $URLSearchString = "^\[\]";
1876 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
1878 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
1879 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
1881 $bbcode = preg_replace(
1882 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1883 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
1886 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
1888 $bbcode = preg_replace(
1889 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1890 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
1893 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
1895 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1897 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1900 foreach ($urls[1] as $id => $url) {
1901 $start = iconv_strpos($text, $url, 0, "UTF-8");
1902 if (!($start === false)) {
1903 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
1907 ksort($ordered_urls);
1911 foreach ($ordered_urls as $url) {
1912 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
1913 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
1915 $display_url = $url["title"];
1917 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
1918 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
1920 if (strlen($display_url) > 26) {
1921 $display_url = substr($display_url, 0, 25)."…";
1925 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1926 if (!($start === false)) {
1927 $entities["urls"][] = ["url" => $url["url"],
1928 "expanded_url" => $url["url"],
1929 "display_url" => $display_url,
1930 "indices" => [$start, $start+strlen($url["url"])]];
1931 $offset = $start + 1;
1935 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
1936 $ordered_images = [];
1937 foreach ($images as $image) {
1938 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
1939 if (!($start === false)) {
1940 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
1944 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1945 foreach ($images[1] as $image) {
1946 $start = iconv_strpos($text, $image, 0, "UTF-8");
1947 if (!($start === false)) {
1948 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
1954 foreach ($ordered_images as $image) {
1955 $url = $image['url'];
1956 $ext_alt_text = $image['alt'];
1958 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
1959 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
1961 if (strlen($display_url) > 26) {
1962 $display_url = substr($display_url, 0, 25)."…";
1965 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1966 if (!($start === false)) {
1967 $image = Images::getInfoFromURLCached($url);
1969 $media_url = Post\Link::getByLink($uriid, $url);
1970 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
1972 $entities["media"][] = [
1974 "id_str" => (string) ($start + 1),
1975 "indices" => [$start, $start+strlen($url)],
1976 "media_url" => Strings::normaliseLink($media_url),
1977 "media_url_https" => $media_url,
1979 "display_url" => $display_url,
1980 "expanded_url" => $url,
1981 "ext_alt_text" => $ext_alt_text,
1985 $offset = $start + 1;
1994 * @param array $item
1995 * @param string $text
1999 function api_format_items_embeded_images($item, $text)
2001 $text = preg_replace_callback(
2002 '|data:image/([^;]+)[^=]+=*|m',
2003 function () use ($item) {
2004 return DI::baseUrl() . '/display/' . $item['guid'];
2012 * return <a href='url'>name</a> as array
2014 * @param string $txt text
2019 function api_contactlink_to_array($txt)
2022 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2023 if ($r && count($match)==3) {
2025 'name' => $match[2],
2039 * return likes, dislikes and attend status for item
2041 * @param array $item array
2042 * @param string $type Return type (atom, rss, xml, json)
2045 * likes => int count,
2046 * dislikes => int count
2047 * @throws BadRequestException
2048 * @throws ImagickException
2049 * @throws InternalServerErrorException
2050 * @throws UnauthorizedException
2052 function api_format_items_activities($item, $type = "json")
2059 'attendmaybe' => [],
2063 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2064 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2066 while ($parent_item = Post::fetch($ret)) {
2067 // not used as result should be structured like other user data
2068 //builtin_activity_puller($i, $activities);
2070 // get user data and add it to the array of the activity
2071 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], $item['uid'])->toArray();
2072 switch ($parent_item['verb']) {
2073 case Activity::LIKE:
2074 $activities['like'][] = $user;
2076 case Activity::DISLIKE:
2077 $activities['dislike'][] = $user;
2079 case Activity::ATTEND:
2080 $activities['attendyes'][] = $user;
2082 case Activity::ATTENDNO:
2083 $activities['attendno'][] = $user;
2085 case Activity::ATTENDMAYBE:
2086 $activities['attendmaybe'][] = $user;
2088 case Activity::ANNOUNCE:
2089 $activities['announce'][] = $user;
2098 if ($type == "xml") {
2099 $xml_activities = [];
2100 foreach ($activities as $k => $v) {
2101 // change xml element from "like" to "friendica:like"
2102 $xml_activities["friendica:".$k] = $v;
2103 // add user data into xml output
2105 foreach ($v as $user) {
2106 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2109 $activities = $xml_activities;
2116 * @param array $item Item record
2117 * @param string $type Return format (atom, rss, xml, json)
2118 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2119 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2120 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2121 * @return array API-formatted status
2122 * @throws BadRequestException
2123 * @throws ImagickException
2124 * @throws InternalServerErrorException
2125 * @throws UnauthorizedException
2127 function api_format_item($item, $type = "json")
2129 return DI::twitterStatus()->createFromUriId($item['uri-id'], $item['uid']);
2131 $author_user = DI::twitterUser()->createFromContactId($item['author-id'], $item['uid'])->toArray();
2132 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], $item['uid'])->toArray();
2134 DI::contentItem()->localize($item);
2136 $in_reply_to = api_in_reply_to($item);
2138 $converted = api_convert_item($item);
2140 if ($type == "xml") {
2141 $geo = "georss:point";
2147 'text' => $converted["text"],
2148 'truncated' => false,
2149 'created_at'=> DateTimeFormat::utc($item['created'], DateTimeFormat::API),
2150 'in_reply_to_status_id' => $in_reply_to['status_id'],
2151 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2152 'source' => (($item['app']) ? $item['app'] : 'web'),
2153 'id' => intval($item['id']),
2154 'id_str' => (string) intval($item['id']),
2155 'in_reply_to_user_id' => $in_reply_to['user_id'],
2156 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2157 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2159 'favorited' => $item['starred'] ? true : false,
2160 'user' => $author_user,
2161 'friendica_author' => $author_user,
2162 'friendica_owner' => $owner_user,
2163 'friendica_private' => $item['private'] == Item::PRIVATE,
2164 //'entities' => NULL,
2165 'statusnet_html' => $converted["html"],
2166 'statusnet_conversation_id' => $item['parent'],
2167 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2168 'friendica_activities' => api_format_items_activities($item, $type),
2169 'friendica_title' => $item['title'],
2170 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL),
2171 'friendica_comments' => Post::countPosts(['thr-parent-id' => $item['uri-id'], 'deleted' => false, 'gravity' => GRAVITY_COMMENT])
2174 if (count($converted["attachments"]) > 0) {
2175 $status["attachments"] = $converted["attachments"];
2178 if (count($converted["entities"]) > 0) {
2179 $status["entities"] = $converted["entities"];
2182 if ($status["source"] == 'web') {
2183 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2184 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2185 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2188 $retweeted_item = [];
2191 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2192 $announce = api_get_announce($item);
2193 if (!empty($announce)) {
2194 $retweeted_item = $item;
2196 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], $item['uid'])->toArray();
2200 if (!empty($quoted_item)) {
2201 if ($quoted_item['id'] != $item['id']) {
2202 $quoted_status = api_format_item($quoted_item);
2203 /// @todo Only remove the attachments that are also contained in the quotes status
2204 unset($status['attachments']);
2205 unset($status['entities']);
2207 $conv_quoted = api_convert_item($quoted_item);
2208 $quoted_status = $status;
2209 unset($quoted_status['attachments']);
2210 unset($quoted_status['entities']);
2211 unset($quoted_status['statusnet_conversation_id']);
2212 $quoted_status['text'] = $conv_quoted['text'];
2213 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2215 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], $item['uid'])->toArray();
2216 } catch (BadRequestException $e) {
2217 // user not found. should be found?
2218 /// @todo check if the user should be always found
2219 $quoted_status["user"] = [];
2222 unset($quoted_status['friendica_author']);
2223 unset($quoted_status['friendica_owner']);
2224 unset($quoted_status['friendica_activities']);
2225 unset($quoted_status['friendica_private']);
2228 if (!empty($retweeted_item)) {
2229 $retweeted_status = $status;
2230 unset($retweeted_status['friendica_author']);
2231 unset($retweeted_status['friendica_owner']);
2232 unset($retweeted_status['friendica_activities']);
2233 unset($retweeted_status['friendica_private']);
2234 unset($retweeted_status['statusnet_conversation_id']);
2235 $status['user'] = $status['friendica_owner'];
2237 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], $item['uid'])->toArray();
2238 } catch (BadRequestException $e) {
2239 // user not found. should be found?
2240 /// @todo check if the user should be always found
2241 $retweeted_status["user"] = [];
2244 $rt_converted = api_convert_item($retweeted_item);
2246 $retweeted_status['text'] = $rt_converted["text"];
2247 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2248 $retweeted_status['friendica_html'] = $rt_converted["html"];
2249 $retweeted_status['created_at'] = DateTimeFormat::utc($retweeted_item['created'], DateTimeFormat::API);
2251 if (!empty($quoted_status)) {
2252 $retweeted_status['quoted_status'] = $quoted_status;
2255 $status['friendica_author'] = $retweeted_status['user'];
2256 $status['retweeted_status'] = $retweeted_status;
2257 } elseif (!empty($quoted_status)) {
2258 $root_status = api_convert_item($item);
2260 $status['text'] = $root_status["text"];
2261 $status['statusnet_html'] = $root_status["html"];
2262 $status['quoted_status'] = $quoted_status;
2265 // "uid" is only needed for some internal stuff, so remove it from here
2266 unset($status["user"]['uid']);
2268 if ($item["coord"] != "") {
2269 $coords = explode(' ', $item["coord"]);
2270 if (count($coords) == 2) {
2271 if ($type == "json") {
2272 $status["geo"] = ['type' => 'Point',
2273 'coordinates' => [(float) $coords[0],
2274 (float) $coords[1]]];
2275 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2276 $status["georss:point"] = $item["coord"];
2285 * Returns all lists the user subscribes to.
2287 * @param string $type Return type (atom, rss, xml, json)
2289 * @return array|string
2290 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2292 function api_lists_list($type)
2295 /// @TODO $ret is not filled here?
2296 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2299 /// @TODO move to top of file or somewhere better
2300 api_register_func('api/lists/list', 'api_lists_list', true);
2301 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2304 * Returns all groups the user owns.
2306 * @param string $type Return type (atom, rss, xml, json)
2308 * @return array|string
2309 * @throws BadRequestException
2310 * @throws ForbiddenException
2311 * @throws ImagickException
2312 * @throws InternalServerErrorException
2313 * @throws UnauthorizedException
2314 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2316 function api_lists_ownerships($type)
2318 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2319 $uid = BaseApi::getCurrentUserID();
2322 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2324 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2326 // loop through all groups
2328 foreach ($groups as $group) {
2329 if ($group['visible']) {
2335 'name' => $group['name'],
2336 'id' => intval($group['id']),
2337 'id_str' => (string) $group['id'],
2338 'user' => $user_info,
2342 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2345 /// @TODO move to top of file or somewhere better
2346 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2349 * Returns recent statuses from users in the specified group.
2351 * @param string $type Return type (atom, rss, xml, json)
2353 * @return array|string
2354 * @throws BadRequestException
2355 * @throws ForbiddenException
2356 * @throws ImagickException
2357 * @throws InternalServerErrorException
2358 * @throws UnauthorizedException
2359 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2361 function api_lists_statuses($type)
2363 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2364 $uid = BaseApi::getCurrentUserID();
2366 unset($_REQUEST['user_id']);
2367 unset($_GET['user_id']);
2369 unset($_REQUEST['screen_name']);
2370 unset($_GET['screen_name']);
2372 if (empty($_REQUEST['list_id'])) {
2373 throw new BadRequestException('list_id not specified');
2377 $count = $_REQUEST['count'] ?? 20;
2378 $page = $_REQUEST['page'] ?? 1;
2379 $since_id = $_REQUEST['since_id'] ?? 0;
2380 $max_id = $_REQUEST['max_id'] ?? 0;
2381 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2382 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2384 $start = max(0, ($page - 1) * $count);
2386 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2387 $gids = array_column($groups, 'contact-id');
2388 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2389 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2392 $condition[0] .= " AND `id` <= ?";
2393 $condition[] = $max_id;
2395 if ($exclude_replies > 0) {
2396 $condition[0] .= ' AND `gravity` = ?';
2397 $condition[] = GRAVITY_PARENT;
2399 if ($conversation_id > 0) {
2400 $condition[0] .= " AND `parent` = ?";
2401 $condition[] = $conversation_id;
2404 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2405 $statuses = Post::selectForUser($uid, [], $condition, $params);
2408 while ($status = DBA::fetch($statuses)) {
2409 $items[] = api_format_item($status, $type);
2411 DBA::close($statuses);
2413 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2416 /// @TODO move to top of file or somewhere better
2417 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2420 * Returns either the friends of the follower list
2422 * Considers friends and followers lists to be private and won't return
2423 * anything if any user_id parameter is passed.
2425 * @param string $qtype Either "friends" or "followers"
2426 * @return boolean|array
2427 * @throws BadRequestException
2428 * @throws ForbiddenException
2429 * @throws ImagickException
2430 * @throws InternalServerErrorException
2431 * @throws UnauthorizedException
2433 function api_statuses_f($qtype)
2435 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2436 $uid = BaseApi::getCurrentUserID();
2439 $count = $_GET['count'] ?? 20;
2440 $page = $_GET['page'] ?? 1;
2442 $start = max(0, ($page - 1) * $count);
2444 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2446 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2447 /* this is to stop Hotot to load friends multiple times
2448 * I'm not sure if I'm missing return something or
2449 * is a bug in hotot. Workaround, meantime
2453 return array('$users' => $ret);*/
2458 if ($qtype == 'friends') {
2459 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2460 } elseif ($qtype == 'followers') {
2461 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2464 if ($qtype == 'blocks') {
2465 $sql_filter = 'AND `blocked` AND NOT `pending`';
2466 } elseif ($qtype == 'incoming') {
2467 $sql_filter = 'AND `pending`';
2469 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2472 // @todo This query most likely can be replaced with a Contact::select...
2473 $r = DBA::toArray(DBA::p(
2488 foreach ($r as $cid) {
2489 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid)->toArray();
2490 // "uid" is only needed for some internal stuff, so remove it from here
2491 unset($user['uid']);
2498 return ['user' => $ret];
2503 * Returns the list of friends of the provided user
2505 * @deprecated By Twitter API in favor of friends/list
2507 * @param string $type Either "json" or "xml"
2508 * @return boolean|string|array
2509 * @throws BadRequestException
2510 * @throws ForbiddenException
2512 function api_statuses_friends($type)
2514 $data = api_statuses_f("friends");
2515 if ($data === false) {
2518 return DI::apiResponse()->formatData("users", $type, $data);
2522 * Returns the list of followers of the provided user
2524 * @deprecated By Twitter API in favor of friends/list
2526 * @param string $type Either "json" or "xml"
2527 * @return boolean|string|array
2528 * @throws BadRequestException
2529 * @throws ForbiddenException
2531 function api_statuses_followers($type)
2533 $data = api_statuses_f("followers");
2534 if ($data === false) {
2537 return DI::apiResponse()->formatData("users", $type, $data);
2540 /// @TODO move to top of file or somewhere better
2541 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2542 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2545 * Returns the list of blocked users
2547 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2549 * @param string $type Either "json" or "xml"
2551 * @return boolean|string|array
2552 * @throws BadRequestException
2553 * @throws ForbiddenException
2555 function api_blocks_list($type)
2557 $data = api_statuses_f('blocks');
2558 if ($data === false) {
2561 return DI::apiResponse()->formatData("users", $type, $data);
2564 /// @TODO move to top of file or somewhere better
2565 api_register_func('api/blocks/list', 'api_blocks_list', true);
2568 * Returns the list of pending users IDs
2570 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2572 * @param string $type Either "json" or "xml"
2574 * @return boolean|string|array
2575 * @throws BadRequestException
2576 * @throws ForbiddenException
2578 function api_friendships_incoming($type)
2580 $data = api_statuses_f('incoming');
2581 if ($data === false) {
2586 foreach ($data['user'] as $user) {
2587 $ids[] = $user['id'];
2590 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2593 /// @TODO move to top of file or somewhere better
2594 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2597 * Sends a new direct message.
2599 * @param string $type Return type (atom, rss, xml, json)
2601 * @return array|string
2602 * @throws BadRequestException
2603 * @throws ForbiddenException
2604 * @throws ImagickException
2605 * @throws InternalServerErrorException
2606 * @throws NotFoundException
2607 * @throws UnauthorizedException
2608 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2610 function api_direct_messages_new($type)
2612 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2613 $uid = BaseApi::getCurrentUserID();
2615 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2619 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2621 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2623 throw new NotFoundException('Recipient not found');
2627 if (!empty($_REQUEST['replyto'])) {
2628 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2629 $replyto = $mail['parent-uri'];
2630 $sub = $mail['title'];
2632 if (!empty($_REQUEST['title'])) {
2633 $sub = $_REQUEST['title'];
2635 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2639 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2641 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2644 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2645 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid)->toArray(), $sender);
2647 $ret = ["error" => $id];
2650 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2653 /// @TODO move to top of file or somewhere better
2654 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2657 * delete a direct_message from mail table through api
2659 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2660 * @return string|array
2661 * @throws BadRequestException
2662 * @throws ForbiddenException
2663 * @throws ImagickException
2664 * @throws InternalServerErrorException
2665 * @throws UnauthorizedException
2666 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2668 function api_direct_messages_destroy($type)
2670 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2671 $uid = BaseApi::getCurrentUserID();
2674 $id = $_REQUEST['id'] ?? 0;
2676 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2677 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2678 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2680 // error if no id or parenturi specified (for clients posting parent-uri as well)
2681 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2682 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2683 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2686 // BadRequestException if no id specified (for clients using Twitter API)
2688 throw new BadRequestException('Message id not specified');
2691 // add parent-uri to sql command if specified by calling app
2692 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2694 // error message if specified id is not in database
2695 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2696 if ($verbose == "true") {
2697 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2698 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2700 /// @todo BadRequestException ok for Twitter API clients?
2701 throw new BadRequestException('message id not in database');
2705 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2707 if ($verbose == "true") {
2710 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2711 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2713 $answer = ['result' => 'error', 'message' => 'unknown error'];
2714 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2717 /// @todo return JSON data like Twitter API not yet implemented
2720 /// @TODO move to top of file or somewhere better
2721 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2726 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2727 * @return string|array
2728 * @throws HTTPException\BadRequestException
2729 * @throws HTTPException\ExpectationFailedException
2730 * @throws HTTPException\ForbiddenException
2731 * @throws HTTPException\InternalServerErrorException
2732 * @throws HTTPException\NotFoundException
2733 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2735 function api_friendships_destroy($type)
2737 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2738 $uid = BaseApi::getCurrentUserID();
2740 $owner = User::getOwnerDataById($uid);
2742 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2743 throw new HTTPException\NotFoundException('Error Processing Request');
2746 $contact_id = $_REQUEST['user_id'] ?? 0;
2748 if (empty($contact_id)) {
2749 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2750 throw new HTTPException\BadRequestException('no user_id specified');
2753 // Get Contact by given id
2754 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2756 if(!DBA::isResult($contact)) {
2757 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2758 throw new HTTPException\NotFoundException('no contact found to given ID');
2761 $url = $contact['url'];
2763 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2764 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2765 Strings::normaliseLink($url), $url];
2766 $contact = DBA::selectFirst('contact', [], $condition);
2768 if (!DBA::isResult($contact)) {
2769 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2770 throw new HTTPException\NotFoundException('Not following Contact');
2774 $result = Contact::terminateFriendship($owner, $contact);
2776 if ($result === null) {
2777 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2778 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2781 if ($result === false) {
2782 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2784 } catch (Exception $e) {
2785 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2786 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2789 // "uid" is only needed for some internal stuff, so remove it from here
2790 unset($contact['uid']);
2792 // Set screen_name since Twidere requests it
2793 $contact['screen_name'] = $contact['nick'];
2795 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2798 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2802 * @param string $type Return type (atom, rss, xml, json)
2803 * @param string $box
2804 * @param string $verbose
2806 * @return array|string
2807 * @throws BadRequestException
2808 * @throws ForbiddenException
2809 * @throws ImagickException
2810 * @throws InternalServerErrorException
2811 * @throws UnauthorizedException
2813 function api_direct_messages_box($type, $box, $verbose)
2815 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2816 $uid = BaseApi::getCurrentUserID();
2819 $count = $_GET['count'] ?? 20;
2820 $page = $_REQUEST['page'] ?? 1;
2822 $since_id = $_REQUEST['since_id'] ?? 0;
2823 $max_id = $_REQUEST['max_id'] ?? 0;
2825 $user_id = $_REQUEST['user_id'] ?? '';
2826 $screen_name = $_REQUEST['screen_name'] ?? '';
2829 unset($_REQUEST['user_id']);
2830 unset($_GET['user_id']);
2832 unset($_REQUEST['screen_name']);
2833 unset($_GET['screen_name']);
2835 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2837 $profile_url = $user_info["url"];
2840 $start = max(0, ($page - 1) * $count);
2845 if ($box=="sentbox") {
2846 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2847 } elseif ($box == "conversation") {
2848 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2849 } elseif ($box == "all") {
2850 $sql_extra = "true";
2851 } elseif ($box == "inbox") {
2852 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2856 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2859 if ($user_id != "") {
2860 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2861 } elseif ($screen_name !="") {
2862 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2865 $r = DBA::toArray(DBA::p(
2866 "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 ?,?",
2872 if ($verbose == "true" && !DBA::isResult($r)) {
2873 $answer = ['result' => 'error', 'message' => 'no mails available'];
2874 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2878 foreach ($r as $item) {
2879 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2880 $recipient = $user_info;
2881 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2882 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2883 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2884 $sender = $user_info;
2887 if (isset($recipient) && isset($sender)) {
2888 $ret[] = api_format_messages($item, $recipient, $sender);
2892 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2896 * Returns the most recent direct messages sent by the user.
2898 * @param string $type Return type (atom, rss, xml, json)
2900 * @return array|string
2901 * @throws BadRequestException
2902 * @throws ForbiddenException
2903 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2905 function api_direct_messages_sentbox($type)
2907 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2908 return api_direct_messages_box($type, "sentbox", $verbose);
2912 * Returns the most recent direct messages sent to the user.
2914 * @param string $type Return type (atom, rss, xml, json)
2916 * @return array|string
2917 * @throws BadRequestException
2918 * @throws ForbiddenException
2919 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2921 function api_direct_messages_inbox($type)
2923 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2924 return api_direct_messages_box($type, "inbox", $verbose);
2929 * @param string $type Return type (atom, rss, xml, json)
2931 * @return array|string
2932 * @throws BadRequestException
2933 * @throws ForbiddenException
2935 function api_direct_messages_all($type)
2937 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2938 return api_direct_messages_box($type, "all", $verbose);
2943 * @param string $type Return type (atom, rss, xml, json)
2945 * @return array|string
2946 * @throws BadRequestException
2947 * @throws ForbiddenException
2949 function api_direct_messages_conversation($type)
2951 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2952 return api_direct_messages_box($type, "conversation", $verbose);
2955 /// @TODO move to top of file or somewhere better
2956 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2957 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2958 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2959 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2962 * list all photos of the authenticated user
2964 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2965 * @return string|array
2966 * @throws ForbiddenException
2967 * @throws InternalServerErrorException
2969 function api_fr_photos_list($type)
2971 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2972 $uid = BaseApi::getCurrentUserID();
2974 $r = DBA::toArray(DBA::p(
2975 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2976 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2977 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2978 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2981 'image/jpeg' => 'jpg',
2982 'image/png' => 'png',
2983 'image/gif' => 'gif'
2985 $data = ['photo'=>[]];
2986 if (DBA::isResult($r)) {
2987 foreach ($r as $rr) {
2989 $photo['id'] = $rr['resource-id'];
2990 $photo['album'] = $rr['album'];
2991 $photo['filename'] = $rr['filename'];
2992 $photo['type'] = $rr['type'];
2993 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2994 $photo['created'] = $rr['created'];
2995 $photo['edited'] = $rr['edited'];
2996 $photo['desc'] = $rr['desc'];
2998 if ($type == "xml") {
2999 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3001 $photo['thumb'] = $thumb;
3002 $data['photo'][] = $photo;
3006 return DI::apiResponse()->formatData("photos", $type, $data);
3010 * upload a new photo or change an existing photo
3012 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3013 * @return string|array
3014 * @throws BadRequestException
3015 * @throws ForbiddenException
3016 * @throws ImagickException
3017 * @throws InternalServerErrorException
3018 * @throws NotFoundException
3020 function api_fr_photo_create_update($type)
3022 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3023 $uid = BaseApi::getCurrentUserID();
3026 $photo_id = $_REQUEST['photo_id'] ?? null;
3027 $desc = $_REQUEST['desc'] ?? null;
3028 $album = $_REQUEST['album'] ?? null;
3029 $album_new = $_REQUEST['album_new'] ?? null;
3030 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3031 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3032 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3033 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3034 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3036 // do several checks on input parameters
3037 // we do not allow calls without album string
3038 if ($album == null) {
3039 throw new BadRequestException("no albumname specified");
3041 // if photo_id == null --> we are uploading a new photo
3042 if ($photo_id == null) {
3045 // error if no media posted in create-mode
3046 if (empty($_FILES['media'])) {
3048 throw new BadRequestException("no media data submitted");
3051 // album_new will be ignored in create-mode
3056 // check if photo is existing in databasei
3057 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
3058 throw new BadRequestException("photo not available");
3062 // checks on acl strings provided by clients
3063 $acl_input_error = false;
3064 $acl_input_error |= check_acl_input($allow_cid, $uid);
3065 $acl_input_error |= check_acl_input($deny_cid, $uid);
3066 $acl_input_error |= check_acl_input($allow_gid, $uid);
3067 $acl_input_error |= check_acl_input($deny_gid, $uid);
3068 if ($acl_input_error) {
3069 throw new BadRequestException("acl data invalid");
3071 // now let's upload the new media in create-mode
3072 if ($mode == "create") {
3073 $media = $_FILES['media'];
3074 $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);
3076 // return success of updating or error message
3077 if (!is_null($data)) {
3078 return DI::apiResponse()->formatData("photo_create", $type, $data);
3080 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3084 // now let's do the changes in update-mode
3085 if ($mode == "update") {
3086 $updated_fields = [];
3088 if (!is_null($desc)) {
3089 $updated_fields['desc'] = $desc;
3092 if (!is_null($album_new)) {
3093 $updated_fields['album'] = $album_new;
3096 if (!is_null($allow_cid)) {
3097 $allow_cid = trim($allow_cid);
3098 $updated_fields['allow_cid'] = $allow_cid;
3101 if (!is_null($deny_cid)) {
3102 $deny_cid = trim($deny_cid);
3103 $updated_fields['deny_cid'] = $deny_cid;
3106 if (!is_null($allow_gid)) {
3107 $allow_gid = trim($allow_gid);
3108 $updated_fields['allow_gid'] = $allow_gid;
3111 if (!is_null($deny_gid)) {
3112 $deny_gid = trim($deny_gid);
3113 $updated_fields['deny_gid'] = $deny_gid;
3117 if (count($updated_fields) > 0) {
3118 $nothingtodo = false;
3119 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
3121 $nothingtodo = true;
3124 if (!empty($_FILES['media'])) {
3125 $nothingtodo = false;
3126 $media = $_FILES['media'];
3127 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
3128 if (!is_null($data)) {
3129 return DI::apiResponse()->formatData("photo_update", $type, $data);
3133 // return success of updating or error message
3135 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3136 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3139 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3140 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3142 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3145 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3149 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3151 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3152 * @return string|array
3153 * @throws BadRequestException
3154 * @throws ForbiddenException
3155 * @throws InternalServerErrorException
3156 * @throws NotFoundException
3158 function api_fr_photo_detail($type)
3160 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3162 if (empty($_REQUEST['photo_id'])) {
3163 throw new BadRequestException("No photo id.");
3166 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3167 $photo_id = $_REQUEST['photo_id'];
3169 // prepare json/xml output with data from database for the requested photo
3170 $data = prepare_photo_data($type, $scale, $photo_id);
3172 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3177 * updates the profile image for the user (either a specified profile or the default profile)
3179 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3181 * @return string|array
3182 * @throws BadRequestException
3183 * @throws ForbiddenException
3184 * @throws ImagickException
3185 * @throws InternalServerErrorException
3186 * @throws NotFoundException
3187 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3189 function api_account_update_profile_image($type)
3191 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3192 $uid = BaseApi::getCurrentUserID();
3195 $profile_id = $_REQUEST['profile_id'] ?? 0;
3197 // error if image data is missing
3198 if (empty($_FILES['image'])) {
3199 throw new BadRequestException("no media data submitted");
3202 // check if specified profile id is valid
3203 if ($profile_id != 0) {
3204 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
3205 // error message if specified profile id is not in database
3206 if (!DBA::isResult($profile)) {
3207 throw new BadRequestException("profile_id not available");
3209 $is_default_profile = $profile['is-default'];
3211 $is_default_profile = 1;
3214 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3216 if (!empty($_FILES['image'])) {
3217 $media = $_FILES['image'];
3218 } elseif (!empty($_FILES['media'])) {
3219 $media = $_FILES['media'];
3221 // save new profile image
3222 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
3225 if (is_array($media['type'])) {
3226 $filetype = $media['type'][0];
3228 $filetype = $media['type'];
3230 if ($filetype == "image/jpeg") {
3232 } elseif ($filetype == "image/png") {
3235 throw new InternalServerErrorException('Unsupported filetype');
3238 // change specified profile or all profiles to the new resource-id
3239 if ($is_default_profile) {
3240 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
3241 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3243 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3244 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3245 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
3248 Contact::updateSelfFromUserID($uid, true);
3250 // Update global directory in background
3251 Profile::publishUpdate($uid);
3253 // output for client
3255 return api_account_verify_credentials($type);
3257 // SaveMediaToDatabase failed for some reason
3258 throw new InternalServerErrorException("image upload failed");
3262 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3263 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3264 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3265 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3266 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3267 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3270 * Update user profile
3272 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3274 * @return array|string
3275 * @throws BadRequestException
3276 * @throws ForbiddenException
3277 * @throws ImagickException
3278 * @throws InternalServerErrorException
3279 * @throws UnauthorizedException
3281 function api_account_update_profile($type)
3283 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3284 $uid = BaseApi::getCurrentUserID();
3286 $api_user = DI::twitterUser()->createFromUserId($uid)->toArray();
3288 if (!empty($_POST['name'])) {
3289 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
3290 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
3291 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
3292 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3295 if (isset($_POST['description'])) {
3296 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3297 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3298 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3301 Profile::publishUpdate($uid);
3303 return api_account_verify_credentials($type);
3306 /// @TODO move to top of file or somewhere better
3307 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3311 * @param string $acl_string
3316 function check_acl_input($acl_string, $uid)
3318 if (empty($acl_string)) {
3322 $contact_not_found = false;
3324 // split <x><y><z> into array of cid's
3325 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3327 // check for each cid if it is available on server
3328 $cid_array = $array[0];
3329 foreach ($cid_array as $cid) {
3330 $cid = str_replace("<", "", $cid);
3331 $cid = str_replace(">", "", $cid);
3332 $condition = ['id' => $cid, 'uid' => $uid];
3333 $contact_not_found |= !DBA::exists('contact', $condition);
3335 return $contact_not_found;
3339 * @param string $mediatype
3340 * @param array $media
3341 * @param string $type
3342 * @param string $album
3343 * @param string $allow_cid
3344 * @param string $deny_cid
3345 * @param string $allow_gid
3346 * @param string $deny_gid
3347 * @param string $desc
3348 * @param integer $phototype
3349 * @param boolean $visibility
3350 * @param string $photo_id
3353 * @throws BadRequestException
3354 * @throws ForbiddenException
3355 * @throws ImagickException
3356 * @throws InternalServerErrorException
3357 * @throws NotFoundException
3358 * @throws UnauthorizedException
3360 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
3368 if (is_array($media)) {
3369 if (is_array($media['tmp_name'])) {
3370 $src = $media['tmp_name'][0];
3372 $src = $media['tmp_name'];
3374 if (is_array($media['name'])) {
3375 $filename = basename($media['name'][0]);
3377 $filename = basename($media['name']);
3379 if (is_array($media['size'])) {
3380 $filesize = intval($media['size'][0]);
3382 $filesize = intval($media['size']);
3384 if (is_array($media['type'])) {
3385 $filetype = $media['type'][0];
3387 $filetype = $media['type'];
3391 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3394 "File upload src: " . $src . " - filename: " . $filename .
3395 " - size: " . $filesize . " - type: " . $filetype);
3397 // check if there was a php upload error
3398 if ($filesize == 0 && $media['error'] == 1) {
3399 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3401 // check against max upload size within Friendica instance
3402 $maximagesize = DI::config()->get('system', 'maximagesize');
3403 if ($maximagesize && ($filesize > $maximagesize)) {
3404 $formattedBytes = Strings::formatBytes($maximagesize);
3405 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3408 // create Photo instance with the data of the image
3409 $imagedata = @file_get_contents($src);
3410 $Image = new Image($imagedata, $filetype);
3411 if (!$Image->isValid()) {
3412 throw new InternalServerErrorException("unable to process image data");
3415 // check orientation of image
3416 $Image->orient($src);
3419 // check max length of images on server
3420 $max_length = DI::config()->get('system', 'max_image_length');
3421 if ($max_length > 0) {
3422 $Image->scaleDown($max_length);
3423 logger::info("File upload: Scaling picture to new size " . $max_length);
3425 $width = $Image->getWidth();
3426 $height = $Image->getHeight();
3428 // create a new resource-id if not already provided
3429 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3431 if ($mediatype == "photo") {
3432 // upload normal image (scales 0, 1, 2)
3433 logger::info("photo upload: starting new photo upload");
3435 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3437 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3439 if ($width > 640 || $height > 640) {
3440 $Image->scaleDown(640);
3441 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3443 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3447 if ($width > 320 || $height > 320) {
3448 $Image->scaleDown(320);
3449 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3451 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3454 logger::info("photo upload: new photo upload ended");
3455 } elseif ($mediatype == "profileimage") {
3456 // upload profile image (scales 4, 5, 6)
3457 logger::info("photo upload: starting new profile image upload");
3459 if ($width > 300 || $height > 300) {
3460 $Image->scaleDown(300);
3461 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3463 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3467 if ($width > 80 || $height > 80) {
3468 $Image->scaleDown(80);
3469 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3471 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3475 if ($width > 48 || $height > 48) {
3476 $Image->scaleDown(48);
3477 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3479 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3482 $Image->__destruct();
3483 logger::info("photo upload: new profile image upload ended");
3487 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3488 if ($photo_id == null && $mediatype == "photo") {
3489 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
3491 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3492 return prepare_photo_data($type, false, $resource_id);
3494 throw new InternalServerErrorException("image upload failed");
3500 * @param string $hash
3501 * @param string $allow_cid
3502 * @param string $deny_cid
3503 * @param string $allow_gid
3504 * @param string $deny_gid
3505 * @param string $filetype
3506 * @param boolean $visibility
3508 * @throws InternalServerErrorException
3510 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
3512 // get data about the api authenticated user
3513 $uri = Item::newURI(intval($uid));
3514 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3517 $arr['guid'] = System::createUUID();
3518 $arr['uid'] = intval($uid);
3520 $arr['type'] = 'photo';
3522 $arr['resource-id'] = $hash;
3523 $arr['contact-id'] = $owner_record['id'];
3524 $arr['owner-name'] = $owner_record['name'];
3525 $arr['owner-link'] = $owner_record['url'];
3526 $arr['owner-avatar'] = $owner_record['thumb'];
3527 $arr['author-name'] = $owner_record['name'];
3528 $arr['author-link'] = $owner_record['url'];
3529 $arr['author-avatar'] = $owner_record['thumb'];
3531 $arr['allow_cid'] = $allow_cid;
3532 $arr['allow_gid'] = $allow_gid;
3533 $arr['deny_cid'] = $deny_cid;
3534 $arr['deny_gid'] = $deny_gid;
3535 $arr['visible'] = $visibility;
3539 'image/jpeg' => 'jpg',
3540 'image/png' => 'png',
3541 'image/gif' => 'gif'
3544 // adds link to the thumbnail scale photo
3545 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3546 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3549 // do the magic for storing the item in the database and trigger the federation to other contacts
3555 * @param string $type
3557 * @param string $photo_id
3560 * @throws BadRequestException
3561 * @throws ForbiddenException
3562 * @throws ImagickException
3563 * @throws InternalServerErrorException
3564 * @throws NotFoundException
3565 * @throws UnauthorizedException
3567 function prepare_photo_data($type, $scale, $photo_id)
3569 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3570 $uid = BaseApi::getCurrentUserID();
3572 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3573 $data_sql = ($scale === false ? "" : "data, ");
3575 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3576 // clients needs to convert this in their way for further processing
3577 $r = DBA::toArray(DBA::p(
3578 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3579 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3580 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3581 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
3582 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3583 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
3589 'image/jpeg' => 'jpg',
3590 'image/png' => 'png',
3591 'image/gif' => 'gif'
3594 // prepare output data for photo
3595 if (DBA::isResult($r)) {
3596 $data = ['photo' => $r[0]];
3597 $data['photo']['id'] = $data['photo']['resource-id'];
3598 if ($scale !== false) {
3599 $data['photo']['data'] = base64_encode($data['photo']['data']);
3601 unset($data['photo']['datasize']); //needed only with scale param
3603 if ($type == "xml") {
3604 $data['photo']['links'] = [];
3605 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3606 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
3608 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
3611 $data['photo']['link'] = [];
3612 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
3614 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3615 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3619 unset($data['photo']['resource-id']);
3620 unset($data['photo']['minscale']);
3621 unset($data['photo']['maxscale']);
3623 throw new NotFoundException();
3626 // retrieve item element for getting activities (like, dislike etc.) related to photo
3627 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
3628 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
3629 if (!DBA::isResult($item)) {
3630 throw new NotFoundException('Photo-related item not found.');
3633 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
3635 // retrieve comments on photo
3636 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
3637 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
3639 $statuses = Post::selectForUser($uid, [], $condition);
3641 // prepare output of comments
3643 while ($status = DBA::fetch($statuses)) {
3644 $commentData[] = api_format_item($status, $type);
3646 DBA::close($statuses);
3649 if ($type == "xml") {
3651 foreach ($commentData as $comment) {
3652 $comments[$k++ . ":comment"] = $comment;
3655 foreach ($commentData as $comment) {
3656 $comments[] = $comment;
3659 $data['photo']['friendica_comments'] = $comments;
3661 // include info if rights on photo and rights on item are mismatching
3662 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
3663 $data['photo']['deny_cid'] != $item['deny_cid'] ||
3664 $data['photo']['allow_gid'] != $item['allow_gid'] ||
3665 $data['photo']['deny_gid'] != $item['deny_gid'];
3666 $data['photo']['rights_mismatch'] = $rights_mismatch;
3672 * Return an item with announcer data if it had been announced
3674 * @param array $item Item array
3675 * @return array Item array with announce data
3677 function api_get_announce($item)
3679 // Quit if the item already has got a different owner and author
3680 if ($item['owner-id'] != $item['author-id']) {
3684 // Don't change original or Diaspora posts
3685 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
3689 // Quit if we do now the original author and it had been a post from a native network
3690 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
3694 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
3695 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
3696 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
3697 if (!DBA::isResult($announce)) {
3701 return array_merge($item, $announce);
3706 * @param array $item
3711 function api_in_reply_to($item)
3715 $in_reply_to['status_id'] = null;
3716 $in_reply_to['user_id'] = null;
3717 $in_reply_to['status_id_str'] = null;
3718 $in_reply_to['user_id_str'] = null;
3719 $in_reply_to['screen_name'] = null;
3721 if (!empty($item['thr-parent']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
3722 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
3723 if (DBA::isResult($parent)) {
3724 $in_reply_to['status_id'] = intval($parent['id']);
3726 $in_reply_to['status_id'] = intval($item['parent']);
3729 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3731 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
3732 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
3734 if (DBA::isResult($parent)) {
3735 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
3736 $in_reply_to['user_id'] = intval($parent['author-id']);
3737 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
3740 // There seems to be situation, where both fields are identical:
3741 // https://github.com/friendica/friendica/issues/1010
3742 // This is a bugfix for that.
3743 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3744 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']]);
3745 $in_reply_to['status_id'] = null;
3746 $in_reply_to['user_id'] = null;
3747 $in_reply_to['status_id_str'] = null;
3748 $in_reply_to['user_id_str'] = null;
3749 $in_reply_to['screen_name'] = null;
3753 return $in_reply_to;
3758 * @param string $text
3761 * @throws InternalServerErrorException
3763 function api_clean_plain_items($text)
3765 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
3767 $text = BBCode::cleanPictureLinks($text);
3768 $URLSearchString = "^\[\]";
3770 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
3772 if ($include_entities == "true") {
3773 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
3776 // Simplify "attachment" element
3777 $text = BBCode::removeAttachment($text);
3783 * Return all or a specified group of the user with the containing contacts.
3785 * @param string $type Return type (atom, rss, xml, json)
3787 * @return array|string
3788 * @throws BadRequestException
3789 * @throws ForbiddenException
3790 * @throws ImagickException
3791 * @throws InternalServerErrorException
3792 * @throws UnauthorizedException
3794 function api_friendica_group_show($type)
3796 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3797 $uid = BaseApi::getCurrentUserID();
3800 $gid = $_REQUEST['gid'] ?? 0;
3802 // get data of the specified group id or all groups if not specified
3804 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3806 // error message if specified gid is not in database
3807 if (!DBA::isResult($groups)) {
3808 throw new BadRequestException("gid not available");
3811 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3814 // loop through all groups and retrieve all members for adding data in the user array
3816 foreach ($groups as $rr) {
3817 $members = Contact\Group::getById($rr['id']);
3820 if ($type == "xml") {
3821 $user_element = "users";
3823 foreach ($members as $member) {
3824 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3825 $users[$k++.":user"] = $user;
3828 $user_element = "user";
3829 foreach ($members as $member) {
3830 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3834 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3836 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3839 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3844 * @param string $type Return type (atom, rss, xml, json)
3846 * @return array|string
3847 * @throws BadRequestException
3848 * @throws ForbiddenException
3849 * @throws ImagickException
3850 * @throws InternalServerErrorException
3851 * @throws UnauthorizedException
3852 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3854 function api_lists_destroy($type)
3856 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3857 $uid = BaseApi::getCurrentUserID();
3860 $gid = $_REQUEST['list_id'] ?? 0;
3862 // error if no gid specified
3864 throw new BadRequestException('gid not specified');
3867 // get data of the specified group id
3868 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3869 // error message if specified gid is not in database
3871 throw new BadRequestException('gid not available');
3874 if (Group::remove($gid)) {
3876 'name' => $group['name'],
3877 'id' => intval($gid),
3878 'id_str' => (string) $gid,
3879 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3882 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3886 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3889 * Add a new group to the database.
3891 * @param string $name Group name
3892 * @param int $uid User ID
3893 * @param array $users List of users to add to the group
3896 * @throws BadRequestException
3898 function group_create($name, $uid, $users = [])
3900 // error if no name specified
3902 throw new BadRequestException('group name not specified');
3905 // error message if specified group name already exists
3906 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
3907 throw new BadRequestException('group name already exists');
3910 // Check if the group needs to be reactivated
3911 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
3912 $reactivate_group = true;
3916 $ret = Group::create($uid, $name);
3918 $gid = Group::getIdByName($uid, $name);
3920 throw new BadRequestException('other API error');
3924 $erroraddinguser = false;
3926 foreach ($users as $user) {
3927 $cid = $user['cid'];
3928 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3929 Group::addMember($gid, $cid);
3931 $erroraddinguser = true;
3932 $errorusers[] = $cid;
3936 // return success message incl. missing users in array
3937 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
3939 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3943 * Create the specified group with the posted array of contacts.
3945 * @param string $type Return type (atom, rss, xml, json)
3947 * @return array|string
3948 * @throws BadRequestException
3949 * @throws ForbiddenException
3950 * @throws ImagickException
3951 * @throws InternalServerErrorException
3952 * @throws UnauthorizedException
3954 function api_friendica_group_create($type)
3956 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3957 $uid = BaseApi::getCurrentUserID();
3960 $name = $_REQUEST['name'] ?? '';
3961 $json = json_decode($_POST['json'], true);
3962 $users = $json['user'];
3964 $success = group_create($name, $uid, $users);
3966 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3969 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3972 * Create a new group.
3974 * @param string $type Return type (atom, rss, xml, json)
3976 * @return array|string
3977 * @throws BadRequestException
3978 * @throws ForbiddenException
3979 * @throws ImagickException
3980 * @throws InternalServerErrorException
3981 * @throws UnauthorizedException
3982 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3984 function api_lists_create($type)
3986 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3987 $uid = BaseApi::getCurrentUserID();
3990 $name = $_REQUEST['name'] ?? '';
3992 $success = group_create($name, $uid);
3993 if ($success['success']) {
3995 'name' => $success['name'],
3996 'id' => intval($success['gid']),
3997 'id_str' => (string) $success['gid'],
3998 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
4001 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4005 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4008 * Update the specified group with the posted array of contacts.
4010 * @param string $type Return type (atom, rss, xml, json)
4012 * @return array|string
4013 * @throws BadRequestException
4014 * @throws ForbiddenException
4015 * @throws ImagickException
4016 * @throws InternalServerErrorException
4017 * @throws UnauthorizedException
4019 function api_friendica_group_update($type)
4021 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4022 $uid = BaseApi::getCurrentUserID();
4025 $gid = $_REQUEST['gid'] ?? 0;
4026 $name = $_REQUEST['name'] ?? '';
4027 $json = json_decode($_POST['json'], true);
4028 $users = $json['user'];
4030 // error if no name specified
4032 throw new BadRequestException('group name not specified');
4035 // error if no gid specified
4037 throw new BadRequestException('gid not specified');
4041 $members = Contact\Group::getById($gid);
4042 foreach ($members as $member) {
4043 $cid = $member['id'];
4044 foreach ($users as $user) {
4045 $found = ($user['cid'] == $cid ? true : false);
4047 if (!isset($found) || !$found) {
4048 $gid = Group::getIdByName($uid, $name);
4049 Group::removeMember($gid, $cid);
4054 $erroraddinguser = false;
4056 foreach ($users as $user) {
4057 $cid = $user['cid'];
4059 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4060 Group::addMember($gid, $cid);
4062 $erroraddinguser = true;
4063 $errorusers[] = $cid;
4067 // return success message incl. missing users in array
4068 $status = ($erroraddinguser ? "missing user" : "ok");
4069 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4070 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4073 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4076 * Update information about a group.
4078 * @param string $type Return type (atom, rss, xml, json)
4080 * @return array|string
4081 * @throws BadRequestException
4082 * @throws ForbiddenException
4083 * @throws ImagickException
4084 * @throws InternalServerErrorException
4085 * @throws UnauthorizedException
4086 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4088 function api_lists_update($type)
4090 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4091 $uid = BaseApi::getCurrentUserID();
4094 $gid = $_REQUEST['list_id'] ?? 0;
4095 $name = $_REQUEST['name'] ?? '';
4097 // error if no gid specified
4099 throw new BadRequestException('gid not specified');
4102 // get data of the specified group id
4103 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4104 // error message if specified gid is not in database
4106 throw new BadRequestException('gid not available');
4109 if (Group::update($gid, $name)) {
4112 'id' => intval($gid),
4113 'id_str' => (string) $gid,
4114 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
4117 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4121 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4124 * Set notification as seen and returns associated item (if possible)
4126 * POST request with 'id' param as notification id
4128 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4129 * @return string|array
4130 * @throws BadRequestException
4131 * @throws ForbiddenException
4132 * @throws ImagickException
4133 * @throws InternalServerErrorException
4134 * @throws UnauthorizedException
4136 function api_friendica_notification_seen($type)
4138 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4139 $uid = BaseApi::getCurrentUserID();
4141 if (DI::args()->getArgc() !== 4) {
4142 throw new BadRequestException('Invalid argument count');
4145 $id = intval($_REQUEST['id'] ?? 0);
4148 $Notify = DI::notify()->selectOneById($id);
4149 if ($Notify->uid !== $uid) {
4150 throw new NotFoundException();
4153 if ($Notify->uriId) {
4154 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4158 DI::notify()->save($Notify);
4160 if ($Notify->otype === Notification\ObjectType::ITEM) {
4161 $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
4162 if (DBA::isResult($item)) {
4163 // we found the item, return it to the user
4164 $ret = [api_format_item($item, $type)];
4165 $data = ['status' => $ret];
4166 return DI::apiResponse()->formatData('status', $type, $data);
4168 // the item can't be found, but we set the notification as seen, so we count this as a success
4171 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4172 } catch (NotFoundException $e) {
4173 throw new BadRequestException('Invalid argument', $e);
4174 } catch (Exception $e) {
4175 throw new InternalServerErrorException('Internal Server exception', $e);
4179 /// @TODO move to top of file or somewhere better
4180 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4183 * search for direct_messages containing a searchstring through api
4185 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4186 * @param string $box
4187 * @return string|array (success: success=true if found and search_result contains found messages,
4188 * success=false if nothing was found, search_result='nothing found',
4189 * error: result=error with error message)
4190 * @throws BadRequestException
4191 * @throws ForbiddenException
4192 * @throws ImagickException
4193 * @throws InternalServerErrorException
4194 * @throws UnauthorizedException
4196 function api_friendica_direct_messages_search($type, $box = "")
4198 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4199 $uid = BaseApi::getCurrentUserID();
4202 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
4203 $searchstring = $_REQUEST['searchstring'] ?? '';
4205 // error if no searchstring specified
4206 if ($searchstring == "") {
4207 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4208 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4211 // get data for the specified searchstring
4212 $r = DBA::toArray(DBA::p(
4213 "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",
4215 '%'.$searchstring.'%'
4218 $profile_url = $user_info["url"];
4220 // message if nothing was found
4221 if (!DBA::isResult($r)) {
4222 $success = ['success' => false, 'search_results' => 'problem with query'];
4223 } elseif (count($r) == 0) {
4224 $success = ['success' => false, 'search_results' => 'nothing found'];
4227 foreach ($r as $item) {
4228 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4229 $recipient = $user_info;
4230 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
4231 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4232 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
4233 $sender = $user_info;
4236 if (isset($recipient) && isset($sender)) {
4237 $ret[] = api_format_messages($item, $recipient, $sender);
4240 $success = ['success' => true, 'search_results' => $ret];
4243 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4246 /// @TODO move to top of file or somewhere better
4247 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);