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 $author_user = DI::twitterUser()->createFromContactId($item['author-id'], $item['uid'])->toArray();
2130 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], $item['uid'])->toArray();
2132 DI::contentItem()->localize($item);
2134 $in_reply_to = api_in_reply_to($item);
2136 $converted = api_convert_item($item);
2138 if ($type == "xml") {
2139 $geo = "georss:point";
2145 'text' => $converted["text"],
2146 'truncated' => false,
2147 'created_at'=> DateTimeFormat::utc($item['created'], DateTimeFormat::API),
2148 'in_reply_to_status_id' => $in_reply_to['status_id'],
2149 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2150 'source' => (($item['app']) ? $item['app'] : 'web'),
2151 'id' => intval($item['id']),
2152 'id_str' => (string) intval($item['id']),
2153 'in_reply_to_user_id' => $in_reply_to['user_id'],
2154 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2155 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2157 'favorited' => $item['starred'] ? true : false,
2158 'user' => $author_user,
2159 'friendica_author' => $author_user,
2160 'friendica_owner' => $owner_user,
2161 'friendica_private' => $item['private'] == Item::PRIVATE,
2162 //'entities' => NULL,
2163 'statusnet_html' => $converted["html"],
2164 'statusnet_conversation_id' => $item['parent'],
2165 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2166 'friendica_activities' => api_format_items_activities($item, $type),
2167 'friendica_title' => $item['title'],
2168 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL),
2169 'friendica_comments' => Post::countPosts(['thr-parent-id' => $item['uri-id'], 'deleted' => false, 'gravity' => GRAVITY_COMMENT])
2172 if (count($converted["attachments"]) > 0) {
2173 $status["attachments"] = $converted["attachments"];
2176 if (count($converted["entities"]) > 0) {
2177 $status["entities"] = $converted["entities"];
2180 if ($status["source"] == 'web') {
2181 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2182 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2183 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2186 $retweeted_item = [];
2189 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2190 $announce = api_get_announce($item);
2191 if (!empty($announce)) {
2192 $retweeted_item = $item;
2194 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], $item['uid'])->toArray();
2198 if (!empty($quoted_item)) {
2199 if ($quoted_item['id'] != $item['id']) {
2200 $quoted_status = api_format_item($quoted_item);
2201 /// @todo Only remove the attachments that are also contained in the quotes status
2202 unset($status['attachments']);
2203 unset($status['entities']);
2205 $conv_quoted = api_convert_item($quoted_item);
2206 $quoted_status = $status;
2207 unset($quoted_status['attachments']);
2208 unset($quoted_status['entities']);
2209 unset($quoted_status['statusnet_conversation_id']);
2210 $quoted_status['text'] = $conv_quoted['text'];
2211 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2213 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], $item['uid'])->toArray();
2214 } catch (BadRequestException $e) {
2215 // user not found. should be found?
2216 /// @todo check if the user should be always found
2217 $quoted_status["user"] = [];
2220 unset($quoted_status['friendica_author']);
2221 unset($quoted_status['friendica_owner']);
2222 unset($quoted_status['friendica_activities']);
2223 unset($quoted_status['friendica_private']);
2226 if (!empty($retweeted_item)) {
2227 $retweeted_status = $status;
2228 unset($retweeted_status['friendica_author']);
2229 unset($retweeted_status['friendica_owner']);
2230 unset($retweeted_status['friendica_activities']);
2231 unset($retweeted_status['friendica_private']);
2232 unset($retweeted_status['statusnet_conversation_id']);
2233 $status['user'] = $status['friendica_owner'];
2235 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], $item['uid'])->toArray();
2236 } catch (BadRequestException $e) {
2237 // user not found. should be found?
2238 /// @todo check if the user should be always found
2239 $retweeted_status["user"] = [];
2242 $rt_converted = api_convert_item($retweeted_item);
2244 $retweeted_status['text'] = $rt_converted["text"];
2245 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2246 $retweeted_status['friendica_html'] = $rt_converted["html"];
2247 $retweeted_status['created_at'] = DateTimeFormat::utc($retweeted_item['created'], DateTimeFormat::API);
2249 if (!empty($quoted_status)) {
2250 $retweeted_status['quoted_status'] = $quoted_status;
2253 $status['friendica_author'] = $retweeted_status['user'];
2254 $status['retweeted_status'] = $retweeted_status;
2255 } elseif (!empty($quoted_status)) {
2256 $root_status = api_convert_item($item);
2258 $status['text'] = $root_status["text"];
2259 $status['statusnet_html'] = $root_status["html"];
2260 $status['quoted_status'] = $quoted_status;
2263 // "uid" is only needed for some internal stuff, so remove it from here
2264 unset($status["user"]['uid']);
2266 if ($item["coord"] != "") {
2267 $coords = explode(' ', $item["coord"]);
2268 if (count($coords) == 2) {
2269 if ($type == "json") {
2270 $status["geo"] = ['type' => 'Point',
2271 'coordinates' => [(float) $coords[0],
2272 (float) $coords[1]]];
2273 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2274 $status["georss:point"] = $item["coord"];
2283 * Returns all lists the user subscribes to.
2285 * @param string $type Return type (atom, rss, xml, json)
2287 * @return array|string
2288 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2290 function api_lists_list($type)
2293 /// @TODO $ret is not filled here?
2294 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2297 /// @TODO move to top of file or somewhere better
2298 api_register_func('api/lists/list', 'api_lists_list', true);
2299 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2302 * Returns all groups the user owns.
2304 * @param string $type Return type (atom, rss, xml, json)
2306 * @return array|string
2307 * @throws BadRequestException
2308 * @throws ForbiddenException
2309 * @throws ImagickException
2310 * @throws InternalServerErrorException
2311 * @throws UnauthorizedException
2312 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2314 function api_lists_ownerships($type)
2316 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2317 $uid = BaseApi::getCurrentUserID();
2320 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2322 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2324 // loop through all groups
2326 foreach ($groups as $group) {
2327 if ($group['visible']) {
2333 'name' => $group['name'],
2334 'id' => intval($group['id']),
2335 'id_str' => (string) $group['id'],
2336 'user' => $user_info,
2340 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2343 /// @TODO move to top of file or somewhere better
2344 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2347 * Returns recent statuses from users in the specified group.
2349 * @param string $type Return type (atom, rss, xml, json)
2351 * @return array|string
2352 * @throws BadRequestException
2353 * @throws ForbiddenException
2354 * @throws ImagickException
2355 * @throws InternalServerErrorException
2356 * @throws UnauthorizedException
2357 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2359 function api_lists_statuses($type)
2361 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2362 $uid = BaseApi::getCurrentUserID();
2364 unset($_REQUEST['user_id']);
2365 unset($_GET['user_id']);
2367 unset($_REQUEST['screen_name']);
2368 unset($_GET['screen_name']);
2370 if (empty($_REQUEST['list_id'])) {
2371 throw new BadRequestException('list_id not specified');
2375 $count = $_REQUEST['count'] ?? 20;
2376 $page = $_REQUEST['page'] ?? 1;
2377 $since_id = $_REQUEST['since_id'] ?? 0;
2378 $max_id = $_REQUEST['max_id'] ?? 0;
2379 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2380 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2382 $start = max(0, ($page - 1) * $count);
2384 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2385 $gids = array_column($groups, 'contact-id');
2386 $condition = ['uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2387 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2390 $condition[0] .= " AND `id` <= ?";
2391 $condition[] = $max_id;
2393 if ($exclude_replies > 0) {
2394 $condition[0] .= ' AND `gravity` = ?';
2395 $condition[] = GRAVITY_PARENT;
2397 if ($conversation_id > 0) {
2398 $condition[0] .= " AND `parent` = ?";
2399 $condition[] = $conversation_id;
2402 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2403 $statuses = Post::selectForUser($uid, [], $condition, $params);
2406 while ($status = DBA::fetch($statuses)) {
2407 $items[] = api_format_item($status, $type);
2409 DBA::close($statuses);
2411 return DI::apiResponse()->formatData("statuses", $type, ['status' => $items], Contact::getPublicIdByUserId($uid));
2414 /// @TODO move to top of file or somewhere better
2415 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2418 * Returns either the friends of the follower list
2420 * Considers friends and followers lists to be private and won't return
2421 * anything if any user_id parameter is passed.
2423 * @param string $qtype Either "friends" or "followers"
2424 * @return boolean|array
2425 * @throws BadRequestException
2426 * @throws ForbiddenException
2427 * @throws ImagickException
2428 * @throws InternalServerErrorException
2429 * @throws UnauthorizedException
2431 function api_statuses_f($qtype)
2433 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2434 $uid = BaseApi::getCurrentUserID();
2437 $count = $_GET['count'] ?? 20;
2438 $page = $_GET['page'] ?? 1;
2440 $start = max(0, ($page - 1) * $count);
2442 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2444 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2445 /* this is to stop Hotot to load friends multiple times
2446 * I'm not sure if I'm missing return something or
2447 * is a bug in hotot. Workaround, meantime
2451 return array('$users' => $ret);*/
2456 if ($qtype == 'friends') {
2457 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2458 } elseif ($qtype == 'followers') {
2459 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2462 if ($qtype == 'blocks') {
2463 $sql_filter = 'AND `blocked` AND NOT `pending`';
2464 } elseif ($qtype == 'incoming') {
2465 $sql_filter = 'AND `pending`';
2467 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2470 // @todo This query most likely can be replaced with a Contact::select...
2471 $r = DBA::toArray(DBA::p(
2486 foreach ($r as $cid) {
2487 $user = DI::twitterUser()->createFromContactId($cid['id'], $uid)->toArray();
2488 // "uid" is only needed for some internal stuff, so remove it from here
2489 unset($user['uid']);
2496 return ['user' => $ret];
2501 * Returns the list of friends of the provided user
2503 * @deprecated By Twitter API in favor of friends/list
2505 * @param string $type Either "json" or "xml"
2506 * @return boolean|string|array
2507 * @throws BadRequestException
2508 * @throws ForbiddenException
2510 function api_statuses_friends($type)
2512 $data = api_statuses_f("friends");
2513 if ($data === false) {
2516 return DI::apiResponse()->formatData("users", $type, $data);
2520 * Returns the list of followers of the provided user
2522 * @deprecated By Twitter API in favor of friends/list
2524 * @param string $type Either "json" or "xml"
2525 * @return boolean|string|array
2526 * @throws BadRequestException
2527 * @throws ForbiddenException
2529 function api_statuses_followers($type)
2531 $data = api_statuses_f("followers");
2532 if ($data === false) {
2535 return DI::apiResponse()->formatData("users", $type, $data);
2538 /// @TODO move to top of file or somewhere better
2539 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2540 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2543 * Returns the list of blocked users
2545 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2547 * @param string $type Either "json" or "xml"
2549 * @return boolean|string|array
2550 * @throws BadRequestException
2551 * @throws ForbiddenException
2553 function api_blocks_list($type)
2555 $data = api_statuses_f('blocks');
2556 if ($data === false) {
2559 return DI::apiResponse()->formatData("users", $type, $data);
2562 /// @TODO move to top of file or somewhere better
2563 api_register_func('api/blocks/list', 'api_blocks_list', true);
2566 * Returns the list of pending users IDs
2568 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2570 * @param string $type Either "json" or "xml"
2572 * @return boolean|string|array
2573 * @throws BadRequestException
2574 * @throws ForbiddenException
2576 function api_friendships_incoming($type)
2578 $data = api_statuses_f('incoming');
2579 if ($data === false) {
2584 foreach ($data['user'] as $user) {
2585 $ids[] = $user['id'];
2588 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2591 /// @TODO move to top of file or somewhere better
2592 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2595 * Sends a new direct message.
2597 * @param string $type Return type (atom, rss, xml, json)
2599 * @return array|string
2600 * @throws BadRequestException
2601 * @throws ForbiddenException
2602 * @throws ImagickException
2603 * @throws InternalServerErrorException
2604 * @throws NotFoundException
2605 * @throws UnauthorizedException
2606 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2608 function api_direct_messages_new($type)
2610 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2611 $uid = BaseApi::getCurrentUserID();
2613 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2617 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2619 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2621 throw new NotFoundException('Recipient not found');
2625 if (!empty($_REQUEST['replyto'])) {
2626 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => $uid, 'id' => $_REQUEST['replyto']]);
2627 $replyto = $mail['parent-uri'];
2628 $sub = $mail['title'];
2630 if (!empty($_REQUEST['title'])) {
2631 $sub = $_REQUEST['title'];
2633 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2637 $cdata = Contact::getPublicAndUserContactID($cid, $uid);
2639 $id = Mail::send($cdata['user'], $_POST['text'], $sub, $replyto);
2642 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2643 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid)->toArray(), $sender);
2645 $ret = ["error" => $id];
2648 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2651 /// @TODO move to top of file or somewhere better
2652 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2655 * delete a direct_message from mail table through api
2657 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2658 * @return string|array
2659 * @throws BadRequestException
2660 * @throws ForbiddenException
2661 * @throws ImagickException
2662 * @throws InternalServerErrorException
2663 * @throws UnauthorizedException
2664 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2666 function api_direct_messages_destroy($type)
2668 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2669 $uid = BaseApi::getCurrentUserID();
2672 $id = $_REQUEST['id'] ?? 0;
2674 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2675 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2676 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2678 // error if no id or parenturi specified (for clients posting parent-uri as well)
2679 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2680 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2681 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2684 // BadRequestException if no id specified (for clients using Twitter API)
2686 throw new BadRequestException('Message id not specified');
2689 // add parent-uri to sql command if specified by calling app
2690 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2692 // error message if specified id is not in database
2693 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2694 if ($verbose == "true") {
2695 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2696 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2698 /// @todo BadRequestException ok for Twitter API clients?
2699 throw new BadRequestException('message id not in database');
2703 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2705 if ($verbose == "true") {
2708 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2709 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2711 $answer = ['result' => 'error', 'message' => 'unknown error'];
2712 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2715 /// @todo return JSON data like Twitter API not yet implemented
2718 /// @TODO move to top of file or somewhere better
2719 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2724 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2725 * @return string|array
2726 * @throws HTTPException\BadRequestException
2727 * @throws HTTPException\ExpectationFailedException
2728 * @throws HTTPException\ForbiddenException
2729 * @throws HTTPException\InternalServerErrorException
2730 * @throws HTTPException\NotFoundException
2731 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2733 function api_friendships_destroy($type)
2735 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2736 $uid = BaseApi::getCurrentUserID();
2738 $owner = User::getOwnerDataById($uid);
2740 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2741 throw new HTTPException\NotFoundException('Error Processing Request');
2744 $contact_id = $_REQUEST['user_id'] ?? 0;
2746 if (empty($contact_id)) {
2747 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2748 throw new HTTPException\BadRequestException('no user_id specified');
2751 // Get Contact by given id
2752 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2754 if(!DBA::isResult($contact)) {
2755 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2756 throw new HTTPException\NotFoundException('no contact found to given ID');
2759 $url = $contact['url'];
2761 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2762 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2763 Strings::normaliseLink($url), $url];
2764 $contact = DBA::selectFirst('contact', [], $condition);
2766 if (!DBA::isResult($contact)) {
2767 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2768 throw new HTTPException\NotFoundException('Not following Contact');
2772 $result = Contact::terminateFriendship($owner, $contact);
2774 if ($result === null) {
2775 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2776 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2779 if ($result === false) {
2780 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2782 } catch (Exception $e) {
2783 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2784 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2787 // "uid" is only needed for some internal stuff, so remove it from here
2788 unset($contact['uid']);
2790 // Set screen_name since Twidere requests it
2791 $contact['screen_name'] = $contact['nick'];
2793 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2796 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2800 * @param string $type Return type (atom, rss, xml, json)
2801 * @param string $box
2802 * @param string $verbose
2804 * @return array|string
2805 * @throws BadRequestException
2806 * @throws ForbiddenException
2807 * @throws ImagickException
2808 * @throws InternalServerErrorException
2809 * @throws UnauthorizedException
2811 function api_direct_messages_box($type, $box, $verbose)
2813 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2814 $uid = BaseApi::getCurrentUserID();
2817 $count = $_GET['count'] ?? 20;
2818 $page = $_REQUEST['page'] ?? 1;
2820 $since_id = $_REQUEST['since_id'] ?? 0;
2821 $max_id = $_REQUEST['max_id'] ?? 0;
2823 $user_id = $_REQUEST['user_id'] ?? '';
2824 $screen_name = $_REQUEST['screen_name'] ?? '';
2827 unset($_REQUEST['user_id']);
2828 unset($_GET['user_id']);
2830 unset($_REQUEST['screen_name']);
2831 unset($_GET['screen_name']);
2833 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
2835 $profile_url = $user_info["url"];
2838 $start = max(0, ($page - 1) * $count);
2843 if ($box=="sentbox") {
2844 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2845 } elseif ($box == "conversation") {
2846 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2847 } elseif ($box == "all") {
2848 $sql_extra = "true";
2849 } elseif ($box == "inbox") {
2850 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2854 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2857 if ($user_id != "") {
2858 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2859 } elseif ($screen_name !="") {
2860 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2863 $r = DBA::toArray(DBA::p(
2864 "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 ?,?",
2870 if ($verbose == "true" && !DBA::isResult($r)) {
2871 $answer = ['result' => 'error', 'message' => 'no mails available'];
2872 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2876 foreach ($r as $item) {
2877 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2878 $recipient = $user_info;
2879 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2880 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2881 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
2882 $sender = $user_info;
2885 if (isset($recipient) && isset($sender)) {
2886 $ret[] = api_format_messages($item, $recipient, $sender);
2890 return DI::apiResponse()->formatData("direct-messages", $type, ['direct_message' => $ret], Contact::getPublicIdByUserId($uid));
2894 * Returns the most recent direct messages sent by the user.
2896 * @param string $type Return type (atom, rss, xml, json)
2898 * @return array|string
2899 * @throws BadRequestException
2900 * @throws ForbiddenException
2901 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
2903 function api_direct_messages_sentbox($type)
2905 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2906 return api_direct_messages_box($type, "sentbox", $verbose);
2910 * Returns the most recent direct messages sent to the user.
2912 * @param string $type Return type (atom, rss, xml, json)
2914 * @return array|string
2915 * @throws BadRequestException
2916 * @throws ForbiddenException
2917 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
2919 function api_direct_messages_inbox($type)
2921 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2922 return api_direct_messages_box($type, "inbox", $verbose);
2927 * @param string $type Return type (atom, rss, xml, json)
2929 * @return array|string
2930 * @throws BadRequestException
2931 * @throws ForbiddenException
2933 function api_direct_messages_all($type)
2935 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2936 return api_direct_messages_box($type, "all", $verbose);
2941 * @param string $type Return type (atom, rss, xml, json)
2943 * @return array|string
2944 * @throws BadRequestException
2945 * @throws ForbiddenException
2947 function api_direct_messages_conversation($type)
2949 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
2950 return api_direct_messages_box($type, "conversation", $verbose);
2953 /// @TODO move to top of file or somewhere better
2954 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
2955 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
2956 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
2957 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
2960 * list all photos of the authenticated user
2962 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2963 * @return string|array
2964 * @throws ForbiddenException
2965 * @throws InternalServerErrorException
2967 function api_fr_photos_list($type)
2969 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2970 $uid = BaseApi::getCurrentUserID();
2972 $r = DBA::toArray(DBA::p(
2973 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
2974 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
2975 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
2976 $uid, Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
2979 'image/jpeg' => 'jpg',
2980 'image/png' => 'png',
2981 'image/gif' => 'gif'
2983 $data = ['photo'=>[]];
2984 if (DBA::isResult($r)) {
2985 foreach ($r as $rr) {
2987 $photo['id'] = $rr['resource-id'];
2988 $photo['album'] = $rr['album'];
2989 $photo['filename'] = $rr['filename'];
2990 $photo['type'] = $rr['type'];
2991 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
2992 $photo['created'] = $rr['created'];
2993 $photo['edited'] = $rr['edited'];
2994 $photo['desc'] = $rr['desc'];
2996 if ($type == "xml") {
2997 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
2999 $photo['thumb'] = $thumb;
3000 $data['photo'][] = $photo;
3004 return DI::apiResponse()->formatData("photos", $type, $data);
3008 * upload a new photo or change an existing photo
3010 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3011 * @return string|array
3012 * @throws BadRequestException
3013 * @throws ForbiddenException
3014 * @throws ImagickException
3015 * @throws InternalServerErrorException
3016 * @throws NotFoundException
3018 function api_fr_photo_create_update($type)
3020 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3021 $uid = BaseApi::getCurrentUserID();
3024 $photo_id = $_REQUEST['photo_id'] ?? null;
3025 $desc = $_REQUEST['desc'] ?? null;
3026 $album = $_REQUEST['album'] ?? null;
3027 $album_new = $_REQUEST['album_new'] ?? null;
3028 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3029 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3030 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3031 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3032 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3034 // do several checks on input parameters
3035 // we do not allow calls without album string
3036 if ($album == null) {
3037 throw new BadRequestException("no albumname specified");
3039 // if photo_id == null --> we are uploading a new photo
3040 if ($photo_id == null) {
3043 // error if no media posted in create-mode
3044 if (empty($_FILES['media'])) {
3046 throw new BadRequestException("no media data submitted");
3049 // album_new will be ignored in create-mode
3054 // check if photo is existing in databasei
3055 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => $uid, 'album' => $album])) {
3056 throw new BadRequestException("photo not available");
3060 // checks on acl strings provided by clients
3061 $acl_input_error = false;
3062 $acl_input_error |= check_acl_input($allow_cid, $uid);
3063 $acl_input_error |= check_acl_input($deny_cid, $uid);
3064 $acl_input_error |= check_acl_input($allow_gid, $uid);
3065 $acl_input_error |= check_acl_input($deny_gid, $uid);
3066 if ($acl_input_error) {
3067 throw new BadRequestException("acl data invalid");
3069 // now let's upload the new media in create-mode
3070 if ($mode == "create") {
3071 $media = $_FILES['media'];
3072 $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);
3074 // return success of updating or error message
3075 if (!is_null($data)) {
3076 return DI::apiResponse()->formatData("photo_create", $type, $data);
3078 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3082 // now let's do the changes in update-mode
3083 if ($mode == "update") {
3084 $updated_fields = [];
3086 if (!is_null($desc)) {
3087 $updated_fields['desc'] = $desc;
3090 if (!is_null($album_new)) {
3091 $updated_fields['album'] = $album_new;
3094 if (!is_null($allow_cid)) {
3095 $allow_cid = trim($allow_cid);
3096 $updated_fields['allow_cid'] = $allow_cid;
3099 if (!is_null($deny_cid)) {
3100 $deny_cid = trim($deny_cid);
3101 $updated_fields['deny_cid'] = $deny_cid;
3104 if (!is_null($allow_gid)) {
3105 $allow_gid = trim($allow_gid);
3106 $updated_fields['allow_gid'] = $allow_gid;
3109 if (!is_null($deny_gid)) {
3110 $deny_gid = trim($deny_gid);
3111 $updated_fields['deny_gid'] = $deny_gid;
3115 if (count($updated_fields) > 0) {
3116 $nothingtodo = false;
3117 $result = Photo::update($updated_fields, ['uid' => $uid, 'resource-id' => $photo_id, 'album' => $album]);
3119 $nothingtodo = true;
3122 if (!empty($_FILES['media'])) {
3123 $nothingtodo = false;
3124 $media = $_FILES['media'];
3125 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id, $uid);
3126 if (!is_null($data)) {
3127 return DI::apiResponse()->formatData("photo_update", $type, $data);
3131 // return success of updating or error message
3133 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3134 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3137 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3138 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3140 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3143 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3147 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3149 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3150 * @return string|array
3151 * @throws BadRequestException
3152 * @throws ForbiddenException
3153 * @throws InternalServerErrorException
3154 * @throws NotFoundException
3156 function api_fr_photo_detail($type)
3158 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3160 if (empty($_REQUEST['photo_id'])) {
3161 throw new BadRequestException("No photo id.");
3164 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3165 $photo_id = $_REQUEST['photo_id'];
3167 // prepare json/xml output with data from database for the requested photo
3168 $data = prepare_photo_data($type, $scale, $photo_id);
3170 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3175 * updates the profile image for the user (either a specified profile or the default profile)
3177 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3179 * @return string|array
3180 * @throws BadRequestException
3181 * @throws ForbiddenException
3182 * @throws ImagickException
3183 * @throws InternalServerErrorException
3184 * @throws NotFoundException
3185 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3187 function api_account_update_profile_image($type)
3189 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3190 $uid = BaseApi::getCurrentUserID();
3193 $profile_id = $_REQUEST['profile_id'] ?? 0;
3195 // error if image data is missing
3196 if (empty($_FILES['image'])) {
3197 throw new BadRequestException("no media data submitted");
3200 // check if specified profile id is valid
3201 if ($profile_id != 0) {
3202 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => $uid, 'id' => $profile_id]);
3203 // error message if specified profile id is not in database
3204 if (!DBA::isResult($profile)) {
3205 throw new BadRequestException("profile_id not available");
3207 $is_default_profile = $profile['is-default'];
3209 $is_default_profile = 1;
3212 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3214 if (!empty($_FILES['image'])) {
3215 $media = $_FILES['image'];
3216 } elseif (!empty($_FILES['media'])) {
3217 $media = $_FILES['media'];
3219 // save new profile image
3220 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR, false, null, $uid);
3223 if (is_array($media['type'])) {
3224 $filetype = $media['type'][0];
3226 $filetype = $media['type'];
3228 if ($filetype == "image/jpeg") {
3230 } elseif ($filetype == "image/png") {
3233 throw new InternalServerErrorException('Unsupported filetype');
3236 // change specified profile or all profiles to the new resource-id
3237 if ($is_default_profile) {
3238 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], $uid];
3239 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3241 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3242 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3243 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => $uid]);
3246 Contact::updateSelfFromUserID($uid, true);
3248 // Update global directory in background
3249 Profile::publishUpdate($uid);
3251 // output for client
3253 return api_account_verify_credentials($type);
3255 // SaveMediaToDatabase failed for some reason
3256 throw new InternalServerErrorException("image upload failed");
3260 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3261 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3262 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3263 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3264 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3265 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3268 * Update user profile
3270 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3272 * @return array|string
3273 * @throws BadRequestException
3274 * @throws ForbiddenException
3275 * @throws ImagickException
3276 * @throws InternalServerErrorException
3277 * @throws UnauthorizedException
3279 function api_account_update_profile($type)
3281 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3282 $uid = BaseApi::getCurrentUserID();
3284 $api_user = DI::twitterUser()->createFromUserId($uid)->toArray();
3286 if (!empty($_POST['name'])) {
3287 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $uid]);
3288 DBA::update('user', ['username' => $_POST['name']], ['uid' => $uid]);
3289 Contact::update(['name' => $_POST['name']], ['uid' => $uid, 'self' => 1]);
3290 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3293 if (isset($_POST['description'])) {
3294 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $uid]);
3295 Contact::update(['about' => $_POST['description']], ['uid' => $uid, 'self' => 1]);
3296 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3299 Profile::publishUpdate($uid);
3301 return api_account_verify_credentials($type);
3304 /// @TODO move to top of file or somewhere better
3305 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3309 * @param string $acl_string
3314 function check_acl_input($acl_string, $uid)
3316 if (empty($acl_string)) {
3320 $contact_not_found = false;
3322 // split <x><y><z> into array of cid's
3323 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3325 // check for each cid if it is available on server
3326 $cid_array = $array[0];
3327 foreach ($cid_array as $cid) {
3328 $cid = str_replace("<", "", $cid);
3329 $cid = str_replace(">", "", $cid);
3330 $condition = ['id' => $cid, 'uid' => $uid];
3331 $contact_not_found |= !DBA::exists('contact', $condition);
3333 return $contact_not_found;
3337 * @param string $mediatype
3338 * @param array $media
3339 * @param string $type
3340 * @param string $album
3341 * @param string $allow_cid
3342 * @param string $deny_cid
3343 * @param string $allow_gid
3344 * @param string $deny_gid
3345 * @param string $desc
3346 * @param integer $phototype
3347 * @param boolean $visibility
3348 * @param string $photo_id
3351 * @throws BadRequestException
3352 * @throws ForbiddenException
3353 * @throws ImagickException
3354 * @throws InternalServerErrorException
3355 * @throws NotFoundException
3356 * @throws UnauthorizedException
3358 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype, $visibility, $photo_id, $uid)
3366 if (is_array($media)) {
3367 if (is_array($media['tmp_name'])) {
3368 $src = $media['tmp_name'][0];
3370 $src = $media['tmp_name'];
3372 if (is_array($media['name'])) {
3373 $filename = basename($media['name'][0]);
3375 $filename = basename($media['name']);
3377 if (is_array($media['size'])) {
3378 $filesize = intval($media['size'][0]);
3380 $filesize = intval($media['size']);
3382 if (is_array($media['type'])) {
3383 $filetype = $media['type'][0];
3385 $filetype = $media['type'];
3389 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3392 "File upload src: " . $src . " - filename: " . $filename .
3393 " - size: " . $filesize . " - type: " . $filetype);
3395 // check if there was a php upload error
3396 if ($filesize == 0 && $media['error'] == 1) {
3397 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3399 // check against max upload size within Friendica instance
3400 $maximagesize = DI::config()->get('system', 'maximagesize');
3401 if ($maximagesize && ($filesize > $maximagesize)) {
3402 $formattedBytes = Strings::formatBytes($maximagesize);
3403 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3406 // create Photo instance with the data of the image
3407 $imagedata = @file_get_contents($src);
3408 $Image = new Image($imagedata, $filetype);
3409 if (!$Image->isValid()) {
3410 throw new InternalServerErrorException("unable to process image data");
3413 // check orientation of image
3414 $Image->orient($src);
3417 // check max length of images on server
3418 $max_length = DI::config()->get('system', 'max_image_length');
3419 if ($max_length > 0) {
3420 $Image->scaleDown($max_length);
3421 logger::info("File upload: Scaling picture to new size " . $max_length);
3423 $width = $Image->getWidth();
3424 $height = $Image->getHeight();
3426 // create a new resource-id if not already provided
3427 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3429 if ($mediatype == "photo") {
3430 // upload normal image (scales 0, 1, 2)
3431 logger::info("photo upload: starting new photo upload");
3433 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3435 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3437 if ($width > 640 || $height > 640) {
3438 $Image->scaleDown(640);
3439 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3441 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3445 if ($width > 320 || $height > 320) {
3446 $Image->scaleDown(320);
3447 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3449 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3452 logger::info("photo upload: new photo upload ended");
3453 } elseif ($mediatype == "profileimage") {
3454 // upload profile image (scales 4, 5, 6)
3455 logger::info("photo upload: starting new profile image upload");
3457 if ($width > 300 || $height > 300) {
3458 $Image->scaleDown(300);
3459 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3461 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3465 if ($width > 80 || $height > 80) {
3466 $Image->scaleDown(80);
3467 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3469 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3473 if ($width > 48 || $height > 48) {
3474 $Image->scaleDown(48);
3475 $r = Photo::store($Image, $uid, $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3477 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3480 $Image->__destruct();
3481 logger::info("photo upload: new profile image upload ended");
3485 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3486 if ($photo_id == null && $mediatype == "photo") {
3487 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid);
3489 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3490 return prepare_photo_data($type, false, $resource_id);
3492 throw new InternalServerErrorException("image upload failed");
3498 * @param string $hash
3499 * @param string $allow_cid
3500 * @param string $deny_cid
3501 * @param string $allow_gid
3502 * @param string $deny_gid
3503 * @param string $filetype
3504 * @param boolean $visibility
3506 * @throws InternalServerErrorException
3508 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility, $uid)
3510 // get data about the api authenticated user
3511 $uri = Item::newURI(intval($uid));
3512 $owner_record = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3515 $arr['guid'] = System::createUUID();
3516 $arr['uid'] = intval($uid);
3518 $arr['type'] = 'photo';
3520 $arr['resource-id'] = $hash;
3521 $arr['contact-id'] = $owner_record['id'];
3522 $arr['owner-name'] = $owner_record['name'];
3523 $arr['owner-link'] = $owner_record['url'];
3524 $arr['owner-avatar'] = $owner_record['thumb'];
3525 $arr['author-name'] = $owner_record['name'];
3526 $arr['author-link'] = $owner_record['url'];
3527 $arr['author-avatar'] = $owner_record['thumb'];
3529 $arr['allow_cid'] = $allow_cid;
3530 $arr['allow_gid'] = $allow_gid;
3531 $arr['deny_cid'] = $deny_cid;
3532 $arr['deny_gid'] = $deny_gid;
3533 $arr['visible'] = $visibility;
3537 'image/jpeg' => 'jpg',
3538 'image/png' => 'png',
3539 'image/gif' => 'gif'
3542 // adds link to the thumbnail scale photo
3543 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3544 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3547 // do the magic for storing the item in the database and trigger the federation to other contacts
3553 * @param string $type
3555 * @param string $photo_id
3558 * @throws BadRequestException
3559 * @throws ForbiddenException
3560 * @throws ImagickException
3561 * @throws InternalServerErrorException
3562 * @throws NotFoundException
3563 * @throws UnauthorizedException
3565 function prepare_photo_data($type, $scale, $photo_id)
3567 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3568 $uid = BaseApi::getCurrentUserID();
3570 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3571 $data_sql = ($scale === false ? "" : "data, ");
3573 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3574 // clients needs to convert this in their way for further processing
3575 $r = DBA::toArray(DBA::p(
3576 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3577 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3578 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3579 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
3580 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3581 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
3587 'image/jpeg' => 'jpg',
3588 'image/png' => 'png',
3589 'image/gif' => 'gif'
3592 // prepare output data for photo
3593 if (DBA::isResult($r)) {
3594 $data = ['photo' => $r[0]];
3595 $data['photo']['id'] = $data['photo']['resource-id'];
3596 if ($scale !== false) {
3597 $data['photo']['data'] = base64_encode($data['photo']['data']);
3599 unset($data['photo']['datasize']); //needed only with scale param
3601 if ($type == "xml") {
3602 $data['photo']['links'] = [];
3603 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3604 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
3606 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
3609 $data['photo']['link'] = [];
3610 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
3612 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3613 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3617 unset($data['photo']['resource-id']);
3618 unset($data['photo']['minscale']);
3619 unset($data['photo']['maxscale']);
3621 throw new NotFoundException();
3624 // retrieve item element for getting activities (like, dislike etc.) related to photo
3625 $condition = ['uid' => $uid, 'resource-id' => $photo_id];
3626 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
3627 if (!DBA::isResult($item)) {
3628 throw new NotFoundException('Photo-related item not found.');
3631 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
3633 // retrieve comments on photo
3634 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
3635 $item['parent'], $uid, GRAVITY_PARENT, GRAVITY_COMMENT];
3637 $statuses = Post::selectForUser($uid, [], $condition);
3639 // prepare output of comments
3641 while ($status = DBA::fetch($statuses)) {
3642 $commentData[] = api_format_item($status, $type);
3644 DBA::close($statuses);
3647 if ($type == "xml") {
3649 foreach ($commentData as $comment) {
3650 $comments[$k++ . ":comment"] = $comment;
3653 foreach ($commentData as $comment) {
3654 $comments[] = $comment;
3657 $data['photo']['friendica_comments'] = $comments;
3659 // include info if rights on photo and rights on item are mismatching
3660 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
3661 $data['photo']['deny_cid'] != $item['deny_cid'] ||
3662 $data['photo']['allow_gid'] != $item['allow_gid'] ||
3663 $data['photo']['deny_gid'] != $item['deny_gid'];
3664 $data['photo']['rights_mismatch'] = $rights_mismatch;
3670 * Return an item with announcer data if it had been announced
3672 * @param array $item Item array
3673 * @return array Item array with announce data
3675 function api_get_announce($item)
3677 // Quit if the item already has got a different owner and author
3678 if ($item['owner-id'] != $item['author-id']) {
3682 // Don't change original or Diaspora posts
3683 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
3687 // Quit if we do now the original author and it had been a post from a native network
3688 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
3692 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
3693 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
3694 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
3695 if (!DBA::isResult($announce)) {
3699 return array_merge($item, $announce);
3704 * @param array $item
3709 function api_in_reply_to($item)
3713 $in_reply_to['status_id'] = null;
3714 $in_reply_to['user_id'] = null;
3715 $in_reply_to['status_id_str'] = null;
3716 $in_reply_to['user_id_str'] = null;
3717 $in_reply_to['screen_name'] = null;
3719 if (!empty($item['thr-parent']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
3720 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
3721 if (DBA::isResult($parent)) {
3722 $in_reply_to['status_id'] = intval($parent['id']);
3724 $in_reply_to['status_id'] = intval($item['parent']);
3727 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3729 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
3730 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
3732 if (DBA::isResult($parent)) {
3733 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
3734 $in_reply_to['user_id'] = intval($parent['author-id']);
3735 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
3738 // There seems to be situation, where both fields are identical:
3739 // https://github.com/friendica/friendica/issues/1010
3740 // This is a bugfix for that.
3741 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3742 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']]);
3743 $in_reply_to['status_id'] = null;
3744 $in_reply_to['user_id'] = null;
3745 $in_reply_to['status_id_str'] = null;
3746 $in_reply_to['user_id_str'] = null;
3747 $in_reply_to['screen_name'] = null;
3751 return $in_reply_to;
3756 * @param string $text
3759 * @throws InternalServerErrorException
3761 function api_clean_plain_items($text)
3763 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
3765 $text = BBCode::cleanPictureLinks($text);
3766 $URLSearchString = "^\[\]";
3768 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
3770 if ($include_entities == "true") {
3771 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
3774 // Simplify "attachment" element
3775 $text = BBCode::removeAttachment($text);
3781 * Return all or a specified group of the user with the containing contacts.
3783 * @param string $type Return type (atom, rss, xml, json)
3785 * @return array|string
3786 * @throws BadRequestException
3787 * @throws ForbiddenException
3788 * @throws ImagickException
3789 * @throws InternalServerErrorException
3790 * @throws UnauthorizedException
3792 function api_friendica_group_show($type)
3794 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3795 $uid = BaseApi::getCurrentUserID();
3798 $gid = $_REQUEST['gid'] ?? 0;
3800 // get data of the specified group id or all groups if not specified
3802 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3804 // error message if specified gid is not in database
3805 if (!DBA::isResult($groups)) {
3806 throw new BadRequestException("gid not available");
3809 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3812 // loop through all groups and retrieve all members for adding data in the user array
3814 foreach ($groups as $rr) {
3815 $members = Contact\Group::getById($rr['id']);
3818 if ($type == "xml") {
3819 $user_element = "users";
3821 foreach ($members as $member) {
3822 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3823 $users[$k++.":user"] = $user;
3826 $user_element = "user";
3827 foreach ($members as $member) {
3828 $user = DI::twitterUser()->createFromContactId($member['contact-id'], $uid)->toArray();
3832 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3834 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3837 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3842 * @param string $type Return type (atom, rss, xml, json)
3844 * @return array|string
3845 * @throws BadRequestException
3846 * @throws ForbiddenException
3847 * @throws ImagickException
3848 * @throws InternalServerErrorException
3849 * @throws UnauthorizedException
3850 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3852 function api_lists_destroy($type)
3854 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3855 $uid = BaseApi::getCurrentUserID();
3858 $gid = $_REQUEST['list_id'] ?? 0;
3860 // error if no gid specified
3862 throw new BadRequestException('gid not specified');
3865 // get data of the specified group id
3866 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3867 // error message if specified gid is not in database
3869 throw new BadRequestException('gid not available');
3872 if (Group::remove($gid)) {
3874 'name' => $group['name'],
3875 'id' => intval($gid),
3876 'id_str' => (string) $gid,
3877 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3880 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
3884 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
3887 * Add a new group to the database.
3889 * @param string $name Group name
3890 * @param int $uid User ID
3891 * @param array $users List of users to add to the group
3894 * @throws BadRequestException
3896 function group_create($name, $uid, $users = [])
3898 // error if no name specified
3900 throw new BadRequestException('group name not specified');
3903 // error message if specified group name already exists
3904 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
3905 throw new BadRequestException('group name already exists');
3908 // Check if the group needs to be reactivated
3909 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
3910 $reactivate_group = true;
3914 $ret = Group::create($uid, $name);
3916 $gid = Group::getIdByName($uid, $name);
3918 throw new BadRequestException('other API error');
3922 $erroraddinguser = false;
3924 foreach ($users as $user) {
3925 $cid = $user['cid'];
3926 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
3927 Group::addMember($gid, $cid);
3929 $erroraddinguser = true;
3930 $errorusers[] = $cid;
3934 // return success message incl. missing users in array
3935 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
3937 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
3941 * Create the specified group with the posted array of contacts.
3943 * @param string $type Return type (atom, rss, xml, json)
3945 * @return array|string
3946 * @throws BadRequestException
3947 * @throws ForbiddenException
3948 * @throws ImagickException
3949 * @throws InternalServerErrorException
3950 * @throws UnauthorizedException
3952 function api_friendica_group_create($type)
3954 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3955 $uid = BaseApi::getCurrentUserID();
3958 $name = $_REQUEST['name'] ?? '';
3959 $json = json_decode($_POST['json'], true);
3960 $users = $json['user'];
3962 $success = group_create($name, $uid, $users);
3964 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
3967 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3970 * Create a new group.
3972 * @param string $type Return type (atom, rss, xml, json)
3974 * @return array|string
3975 * @throws BadRequestException
3976 * @throws ForbiddenException
3977 * @throws ImagickException
3978 * @throws InternalServerErrorException
3979 * @throws UnauthorizedException
3980 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
3982 function api_lists_create($type)
3984 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3985 $uid = BaseApi::getCurrentUserID();
3988 $name = $_REQUEST['name'] ?? '';
3990 $success = group_create($name, $uid);
3991 if ($success['success']) {
3993 'name' => $success['name'],
3994 'id' => intval($success['gid']),
3995 'id_str' => (string) $success['gid'],
3996 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
3999 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4003 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4006 * Update the specified group with the posted array of contacts.
4008 * @param string $type Return type (atom, rss, xml, json)
4010 * @return array|string
4011 * @throws BadRequestException
4012 * @throws ForbiddenException
4013 * @throws ImagickException
4014 * @throws InternalServerErrorException
4015 * @throws UnauthorizedException
4017 function api_friendica_group_update($type)
4019 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4020 $uid = BaseApi::getCurrentUserID();
4023 $gid = $_REQUEST['gid'] ?? 0;
4024 $name = $_REQUEST['name'] ?? '';
4025 $json = json_decode($_POST['json'], true);
4026 $users = $json['user'];
4028 // error if no name specified
4030 throw new BadRequestException('group name not specified');
4033 // error if no gid specified
4035 throw new BadRequestException('gid not specified');
4039 $members = Contact\Group::getById($gid);
4040 foreach ($members as $member) {
4041 $cid = $member['id'];
4042 foreach ($users as $user) {
4043 $found = ($user['cid'] == $cid ? true : false);
4045 if (!isset($found) || !$found) {
4046 $gid = Group::getIdByName($uid, $name);
4047 Group::removeMember($gid, $cid);
4052 $erroraddinguser = false;
4054 foreach ($users as $user) {
4055 $cid = $user['cid'];
4057 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4058 Group::addMember($gid, $cid);
4060 $erroraddinguser = true;
4061 $errorusers[] = $cid;
4065 // return success message incl. missing users in array
4066 $status = ($erroraddinguser ? "missing user" : "ok");
4067 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4068 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4071 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4074 * Update information about a group.
4076 * @param string $type Return type (atom, rss, xml, json)
4078 * @return array|string
4079 * @throws BadRequestException
4080 * @throws ForbiddenException
4081 * @throws ImagickException
4082 * @throws InternalServerErrorException
4083 * @throws UnauthorizedException
4084 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4086 function api_lists_update($type)
4088 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4089 $uid = BaseApi::getCurrentUserID();
4092 $gid = $_REQUEST['list_id'] ?? 0;
4093 $name = $_REQUEST['name'] ?? '';
4095 // error if no gid specified
4097 throw new BadRequestException('gid not specified');
4100 // get data of the specified group id
4101 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4102 // error message if specified gid is not in database
4104 throw new BadRequestException('gid not available');
4107 if (Group::update($gid, $name)) {
4110 'id' => intval($gid),
4111 'id_str' => (string) $gid,
4112 'user' => DI::twitterUser()->createFromUserId($uid)->toArray()
4115 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4119 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4122 * Set notification as seen and returns associated item (if possible)
4124 * POST request with 'id' param as notification id
4126 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4127 * @return string|array
4128 * @throws BadRequestException
4129 * @throws ForbiddenException
4130 * @throws ImagickException
4131 * @throws InternalServerErrorException
4132 * @throws UnauthorizedException
4134 function api_friendica_notification_seen($type)
4136 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4137 $uid = BaseApi::getCurrentUserID();
4139 if (DI::args()->getArgc() !== 4) {
4140 throw new BadRequestException('Invalid argument count');
4143 $id = intval($_REQUEST['id'] ?? 0);
4146 $Notify = DI::notify()->selectOneById($id);
4147 if ($Notify->uid !== $uid) {
4148 throw new NotFoundException();
4151 if ($Notify->uriId) {
4152 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4156 DI::notify()->save($Notify);
4158 if ($Notify->otype === Notification\ObjectType::ITEM) {
4159 $item = Post::selectFirstForUser($uid, [], ['id' => $Notify->iid, 'uid' => $uid]);
4160 if (DBA::isResult($item)) {
4161 // we found the item, return it to the user
4162 $ret = [api_format_item($item, $type)];
4163 $data = ['status' => $ret];
4164 return DI::apiResponse()->formatData('status', $type, $data);
4166 // the item can't be found, but we set the notification as seen, so we count this as a success
4169 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4170 } catch (NotFoundException $e) {
4171 throw new BadRequestException('Invalid argument', $e);
4172 } catch (Exception $e) {
4173 throw new InternalServerErrorException('Internal Server exception', $e);
4177 /// @TODO move to top of file or somewhere better
4178 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4181 * search for direct_messages containing a searchstring through api
4183 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4184 * @param string $box
4185 * @return string|array (success: success=true if found and search_result contains found messages,
4186 * success=false if nothing was found, search_result='nothing found',
4187 * error: result=error with error message)
4188 * @throws BadRequestException
4189 * @throws ForbiddenException
4190 * @throws ImagickException
4191 * @throws InternalServerErrorException
4192 * @throws UnauthorizedException
4194 function api_friendica_direct_messages_search($type, $box = "")
4196 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4197 $uid = BaseApi::getCurrentUserID();
4200 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
4201 $searchstring = $_REQUEST['searchstring'] ?? '';
4203 // error if no searchstring specified
4204 if ($searchstring == "") {
4205 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4206 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4209 // get data for the specified searchstring
4210 $r = DBA::toArray(DBA::p(
4211 "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",
4213 '%'.$searchstring.'%'
4216 $profile_url = $user_info["url"];
4218 // message if nothing was found
4219 if (!DBA::isResult($r)) {
4220 $success = ['success' => false, 'search_results' => 'problem with query'];
4221 } elseif (count($r) == 0) {
4222 $success = ['success' => false, 'search_results' => 'nothing found'];
4225 foreach ($r as $item) {
4226 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4227 $recipient = $user_info;
4228 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
4229 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4230 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], $uid)->toArray();
4231 $sender = $user_info;
4234 if (isset($recipient) && isset($sender)) {
4235 $ret[] = api_format_messages($item, $recipient, $sender);
4238 $success = ['success' => true, 'search_results' => $ret];
4241 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4244 /// @TODO move to top of file or somewhere better
4245 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);