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);
230 * Set values for RSS template
232 * @param array $arr Array to be passed to template
233 * @param array $user_info User info
235 * @throws BadRequestException
236 * @throws ImagickException
237 * @throws InternalServerErrorException
238 * @throws UnauthorizedException
239 * @todo find proper type-hints
241 function api_rss_extra($arr, $user_info)
243 if (is_null($user_info)) {
244 $uid = BaseApi::getCurrentUserID();
246 throw new ForbiddenException();
249 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
252 $arr['$user'] = $user_info;
254 'alternate' => $user_info['url'],
255 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
256 'base' => DI::baseUrl(),
257 'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
258 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
259 'language' => $user_info['lang'],
260 'logo' => DI::baseUrl() . "/images/friendica-32.png",
271 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
272 * returns a 401 status code and an error message if not.
274 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
276 * @param string $type Return type (atom, rss, xml, json)
277 * @return array|string
278 * @throws BadRequestException
279 * @throws ForbiddenException
280 * @throws ImagickException
281 * @throws InternalServerErrorException
282 * @throws UnauthorizedException
284 function api_account_verify_credentials($type)
286 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
288 unset($_REQUEST['user_id']);
289 unset($_GET['user_id']);
291 unset($_REQUEST['screen_name']);
292 unset($_GET['screen_name']);
294 $skip_status = $_REQUEST['skip_status'] ?? false;
296 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
298 // "verified" isn't used here in the standard
299 unset($user_info["verified"]);
301 // - Adding last status
303 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
305 $user_info['status'] = api_format_item($item, $type);
309 // "uid" and "self" are only needed for some internal stuff, so remove it from here
310 unset($user_info["uid"]);
311 unset($user_info["self"]);
313 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
316 /// @TODO move to top of file or somewhere better
317 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
320 * Get data from $_POST or $_GET
325 function requestdata($k)
327 if (!empty($_POST[$k])) {
330 if (!empty($_GET[$k])) {
337 * Deprecated function to upload media.
339 * @param string $type Return type (atom, rss, xml, json)
341 * @return array|string
342 * @throws BadRequestException
343 * @throws ForbiddenException
344 * @throws ImagickException
345 * @throws InternalServerErrorException
346 * @throws UnauthorizedException
348 function api_statuses_mediap($type)
352 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
354 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
355 $_REQUEST['api_source'] = true;
356 $txt = requestdata('status') ?? '';
358 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
359 $txt = HTML::toBBCodeVideo($txt);
360 $config = HTMLPurifier_Config::createDefault();
361 $config->set('Cache.DefinitionImpl', null);
362 $purifier = new HTMLPurifier($config);
363 $txt = $purifier->purify($txt);
365 $txt = HTML::toBBCode($txt);
367 $picture = wall_upload_post($a, false);
369 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
370 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
371 $item_id = item_post($a);
373 // output the post that we just posted.
374 return api_status_show($type, $item_id);
377 /// @TODO move this to top of file or somewhere better!
378 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
381 * Updates the user’s current status.
383 * @param string $type Return type (atom, rss, xml, json)
385 * @return array|string
386 * @throws BadRequestException
387 * @throws ForbiddenException
388 * @throws ImagickException
389 * @throws InternalServerErrorException
390 * @throws TooManyRequestsException
391 * @throws UnauthorizedException
392 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
394 function api_statuses_update($type)
398 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
400 // convert $_POST array items to the form we use for web posts.
401 if (requestdata('htmlstatus')) {
402 $txt = requestdata('htmlstatus') ?? '';
403 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
404 $txt = HTML::toBBCodeVideo($txt);
406 $config = HTMLPurifier_Config::createDefault();
407 $config->set('Cache.DefinitionImpl', null);
409 $purifier = new HTMLPurifier($config);
410 $txt = $purifier->purify($txt);
412 $_REQUEST['body'] = HTML::toBBCode($txt);
415 $_REQUEST['body'] = requestdata('status');
418 $_REQUEST['title'] = requestdata('title');
420 $parent = requestdata('in_reply_to_status_id');
422 // Twidere sends "-1" if it is no reply ...
427 if (ctype_digit($parent)) {
428 $_REQUEST['parent'] = $parent;
430 $_REQUEST['parent_uri'] = $parent;
433 if (requestdata('lat') && requestdata('long')) {
434 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
436 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
439 // Check for throttling (maximum posts per day, week and month)
440 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
441 if ($throttle_day > 0) {
442 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
444 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
445 $posts_day = Post::count($condition);
447 if ($posts_day > $throttle_day) {
448 logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
449 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
450 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));
454 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
455 if ($throttle_week > 0) {
456 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
458 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
459 $posts_week = Post::count($condition);
461 if ($posts_week > $throttle_week) {
462 logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
463 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
464 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));
468 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
469 if ($throttle_month > 0) {
470 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
472 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
473 $posts_month = Post::count($condition);
475 if ($posts_month > $throttle_month) {
476 logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
477 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
478 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));
483 if (requestdata('media_ids')) {
484 $ids = explode(',', requestdata('media_ids') ?? '');
485 } elseif (!empty($_FILES['media'])) {
486 // upload the image if we have one
487 $picture = wall_upload_post($a, false);
488 if (is_array($picture)) {
489 $ids[] = $picture['id'];
497 foreach ($ids as $id) {
498 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
499 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
500 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
501 ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
503 if (!empty($media)) {
504 $ressources[] = $media[0]['resource-id'];
505 $phototypes = Images::supportedTypes();
506 $ext = $phototypes[$media[0]['type']];
508 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
509 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
510 'size' => $media[0]['datasize'],
511 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
512 'description' => $media[0]['desc'] ?? '',
513 'width' => $media[0]['width'],
514 'height' => $media[0]['height']];
516 if (count($media) > 1) {
517 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
518 $attachment['preview-width'] = $media[1]['width'];
519 $attachment['preview-height'] = $media[1]['height'];
521 $attachments[] = $attachment;
525 // We have to avoid that the post is rejected because of an empty body
526 if (empty($_REQUEST['body'])) {
527 $_REQUEST['body'] = '[hr]';
531 if (!empty($attachments)) {
532 $_REQUEST['attachments'] = $attachments;
535 // set this so that the item_post() function is quiet and doesn't redirect or emit json
537 $_REQUEST['api_source'] = true;
539 if (empty($_REQUEST['source'])) {
540 $_REQUEST['source'] = api_source();
543 // call out normal post function
544 $item_id = item_post($a);
546 if (!empty($ressources) && !empty($item_id)) {
547 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
548 foreach ($ressources as $ressource) {
549 Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
553 // output the post that we just posted.
554 return api_status_show($type, $item_id);
557 /// @TODO move to top of file or somewhere better
558 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
559 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
562 * Uploads an image to Friendica.
565 * @throws BadRequestException
566 * @throws ForbiddenException
567 * @throws ImagickException
568 * @throws InternalServerErrorException
569 * @throws UnauthorizedException
570 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
572 function api_media_upload()
574 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
576 if (empty($_FILES['media'])) {
578 throw new BadRequestException("No media.");
581 $media = wall_upload_post(DI::app(), false);
584 throw new InternalServerErrorException();
588 $returndata["media_id"] = $media["id"];
589 $returndata["media_id_string"] = (string)$media["id"];
590 $returndata["size"] = $media["size"];
591 $returndata["image"] = ["w" => $media["width"],
592 "h" => $media["height"],
593 "image_type" => $media["type"],
594 "friendica_preview_url" => $media["preview"]];
596 Logger::info('Media uploaded', ['return' => $returndata]);
598 return ["media" => $returndata];
601 /// @TODO move to top of file or somewhere better
602 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
605 * Updates media meta data (picture descriptions)
607 * @param string $type Return type (atom, rss, xml, json)
609 * @return array|string
610 * @throws BadRequestException
611 * @throws ForbiddenException
612 * @throws ImagickException
613 * @throws InternalServerErrorException
614 * @throws TooManyRequestsException
615 * @throws UnauthorizedException
616 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
618 * @todo Compare the corresponding Twitter function for correct return values
620 function api_media_metadata_create($type)
622 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
624 $postdata = Network::postdata();
626 if (empty($postdata)) {
627 throw new BadRequestException("No post data");
630 $data = json_decode($postdata, true);
632 throw new BadRequestException("Invalid post data");
635 if (empty($data['media_id']) || empty($data['alt_text'])) {
636 throw new BadRequestException("Missing post data values");
639 if (empty($data['alt_text']['text'])) {
640 throw new BadRequestException("No alt text.");
643 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
645 $condition = ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
646 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
647 if (!DBA::isResult($photo)) {
648 throw new BadRequestException("Metadata not found.");
651 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
654 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
657 * @param string $type Return format (atom, rss, xml, json)
658 * @param int $item_id
659 * @return array|string
662 function api_status_show($type, $item_id)
664 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
668 $item = api_get_item(['id' => $item_id]);
670 $status_info = api_format_item($item, $type);
673 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
675 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
679 * Retrieves the last public status of the provided user info
681 * @param int $ownerId Public contact Id
682 * @param int $uid User Id
686 function api_get_last_status($ownerId, $uid)
689 'author-id'=> $ownerId,
691 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
692 'private' => [Item::PUBLIC, Item::UNLISTED]
695 $item = api_get_item($condition);
701 * Retrieves a single item record based on the provided condition and converts it for API use.
703 * @param array $condition Item table condition array
707 function api_get_item(array $condition)
709 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
715 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
716 * The author's most recent status will be returned inline.
718 * @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-show
726 function api_users_show($type)
728 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
730 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
732 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
734 $user_info['status'] = api_format_item($item, $type);
737 // "uid" and "self" are only needed for some internal stuff, so remove it from here
738 unset($user_info['uid']);
739 unset($user_info['self']);
741 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
744 /// @TODO move to top of file or somewhere better
745 api_register_func('api/users/show', 'api_users_show');
746 api_register_func('api/externalprofile/show', 'api_users_show');
749 * Search a public user account.
751 * @param string $type Return type (atom, rss, xml, json)
753 * @return array|string
754 * @throws BadRequestException
755 * @throws ImagickException
756 * @throws InternalServerErrorException
757 * @throws UnauthorizedException
758 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
760 function api_users_search($type)
764 if (!empty($_GET['q'])) {
765 $contacts = Contact::selectToArray(
768 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
776 if (DBA::isResult($contacts)) {
778 foreach ($contacts as $contact) {
779 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
781 if ($type == 'xml') {
782 $userlist[$k++ . ':user'] = $user_info;
784 $userlist[] = $user_info;
787 $userlist = ['users' => $userlist];
789 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
792 throw new BadRequestException('No search term specified.');
795 return DI::apiResponse()->formatData('users', $type, $userlist);
798 /// @TODO move to top of file or somewhere better
799 api_register_func('api/users/search', 'api_users_search');
802 * Return user objects
804 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
806 * @param string $type Return format: json or xml
808 * @return array|string
809 * @throws BadRequestException
810 * @throws ImagickException
811 * @throws InternalServerErrorException
812 * @throws NotFoundException if the results are empty.
813 * @throws UnauthorizedException
815 function api_users_lookup($type)
819 if (!empty($_REQUEST['user_id'])) {
820 foreach (explode(',', $_REQUEST['user_id']) as $cid) {
821 if (!empty($cid) && is_numeric($cid)) {
822 $users[] = DI::twitterUser()->createFromContactId((int)$cid, BaseApi::getCurrentUserID())->toArray();
828 throw new NotFoundException;
831 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
834 /// @TODO move to top of file or somewhere better
835 api_register_func('api/users/lookup', 'api_users_lookup', true);
838 * Returns statuses that match a specified query.
840 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
842 * @param string $type Return format: json, xml, atom, rss
844 * @return array|string
845 * @throws BadRequestException if the "q" parameter is missing.
846 * @throws ForbiddenException
847 * @throws ImagickException
848 * @throws InternalServerErrorException
849 * @throws UnauthorizedException
851 function api_search($type)
853 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
855 if (empty($_REQUEST['q'])) {
856 throw new BadRequestException('q parameter is required.');
859 $searchTerm = trim(rawurldecode($_REQUEST['q']));
862 $data['status'] = [];
864 $exclude_replies = !empty($_REQUEST['exclude_replies']);
865 if (!empty($_REQUEST['rpp'])) {
866 $count = $_REQUEST['rpp'];
867 } elseif (!empty($_REQUEST['count'])) {
868 $count = $_REQUEST['count'];
871 $since_id = $_REQUEST['since_id'] ?? 0;
872 $max_id = $_REQUEST['max_id'] ?? 0;
873 $page = $_REQUEST['page'] ?? 1;
875 $start = max(0, ($page - 1) * $count);
877 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
878 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
879 $searchTerm = $matches[1];
880 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, BaseApi::getCurrentUserID()];
881 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
883 while ($tag = DBA::fetch($tags)) {
884 $uriids[] = $tag['uri-id'];
888 if (empty($uriids)) {
889 return DI::apiResponse()->formatData('statuses', $type, $data);
892 $condition = ['uri-id' => $uriids];
893 if ($exclude_replies) {
894 $condition['gravity'] = GRAVITY_PARENT;
897 $params['group_by'] = ['uri-id'];
899 $condition = ["`id` > ?
900 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
901 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
902 AND `body` LIKE CONCAT('%',?,'%')",
903 $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
905 $condition[0] .= ' AND `id` <= ?';
906 $condition[] = $max_id;
912 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
913 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
916 $id = Item::fetchByLink($searchTerm);
920 $statuses = Post::select([], ['id' => $id]);
924 $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
926 $data['status'] = api_format_items(Post::toArray($statuses), $type);
928 bindComments($data['status']);
930 return DI::apiResponse()->formatData('statuses', $type, $data);
933 /// @TODO move to top of file or somewhere better
934 api_register_func('api/search/tweets', 'api_search', true);
935 api_register_func('api/search', 'api_search', true);
938 * Returns the most recent statuses posted by the user and the users they follow.
940 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
942 * @param string $type Return type (atom, rss, xml, json)
944 * @return array|string
945 * @throws BadRequestException
946 * @throws ForbiddenException
947 * @throws ImagickException
948 * @throws InternalServerErrorException
949 * @throws UnauthorizedException
950 * @todo Optional parameters
951 * @todo Add reply info
953 function api_statuses_home_timeline($type)
955 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
957 unset($_REQUEST['user_id']);
958 unset($_GET['user_id']);
960 unset($_REQUEST['screen_name']);
961 unset($_GET['screen_name']);
963 // get last network messages
966 $count = $_REQUEST['count'] ?? 20;
967 $page = $_REQUEST['page']?? 0;
968 $since_id = $_REQUEST['since_id'] ?? 0;
969 $max_id = $_REQUEST['max_id'] ?? 0;
970 $exclude_replies = !empty($_REQUEST['exclude_replies']);
971 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
973 $start = max(0, ($page - 1) * $count);
975 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
976 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
979 $condition[0] .= " AND `id` <= ?";
980 $condition[] = $max_id;
982 if ($exclude_replies) {
983 $condition[0] .= ' AND `gravity` = ?';
984 $condition[] = GRAVITY_PARENT;
986 if ($conversation_id > 0) {
987 $condition[0] .= " AND `parent` = ?";
988 $condition[] = $conversation_id;
991 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
992 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
994 $items = Post::toArray($statuses);
996 $ret = api_format_items($items, $type);
998 // Set all posts from the query above to seen
1000 foreach ($items as $item) {
1001 $idarray[] = intval($item["id"]);
1004 if (!empty($idarray)) {
1005 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1007 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1013 $data = ['status' => $ret];
1018 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
1022 return DI::apiResponse()->formatData("statuses", $type, $data);
1026 /// @TODO move to top of file or somewhere better
1027 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1028 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1031 * Returns the most recent statuses from public users.
1033 * @param string $type Return type (atom, rss, xml, json)
1035 * @return array|string
1036 * @throws BadRequestException
1037 * @throws ForbiddenException
1038 * @throws ImagickException
1039 * @throws InternalServerErrorException
1040 * @throws UnauthorizedException
1042 function api_statuses_public_timeline($type)
1044 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1046 // get last network messages
1049 $count = $_REQUEST['count'] ?? 20;
1050 $page = $_REQUEST['page'] ?? 1;
1051 $since_id = $_REQUEST['since_id'] ?? 0;
1052 $max_id = $_REQUEST['max_id'] ?? 0;
1053 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1054 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1056 $start = max(0, ($page - 1) * $count);
1058 if ($exclude_replies && !$conversation_id) {
1059 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1060 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1063 $condition[0] .= " AND `id` <= ?";
1064 $condition[] = $max_id;
1067 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1068 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1070 $r = Post::toArray($statuses);
1072 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1073 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1076 $condition[0] .= " AND `id` <= ?";
1077 $condition[] = $max_id;
1079 if ($conversation_id > 0) {
1080 $condition[0] .= " AND `parent` = ?";
1081 $condition[] = $conversation_id;
1084 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1085 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1087 $r = Post::toArray($statuses);
1090 $ret = api_format_items($r, $type);
1094 $data = ['status' => $ret];
1099 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
1103 return DI::apiResponse()->formatData("statuses", $type, $data);
1106 /// @TODO move to top of file or somewhere better
1107 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1110 * Returns the most recent statuses posted by users this node knows about.
1112 * @param string $type Return format: json, xml, atom, rss
1113 * @return array|string
1114 * @throws BadRequestException
1115 * @throws ForbiddenException
1116 * @throws ImagickException
1117 * @throws InternalServerErrorException
1118 * @throws UnauthorizedException
1120 function api_statuses_networkpublic_timeline($type)
1122 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1124 $since_id = $_REQUEST['since_id'] ?? 0;
1125 $max_id = $_REQUEST['max_id'] ?? 0;
1128 $count = $_REQUEST['count'] ?? 20;
1129 $page = $_REQUEST['page'] ?? 1;
1131 $start = max(0, ($page - 1) * $count);
1133 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1134 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1137 $condition[0] .= " AND `id` <= ?";
1138 $condition[] = $max_id;
1141 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1142 $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1144 $ret = api_format_items($statuses, $type);
1148 $data = ['status' => $ret];
1153 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
1157 return DI::apiResponse()->formatData("statuses", $type, $data);
1160 /// @TODO move to top of file or somewhere better
1161 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1164 * Returns a single status.
1166 * @param string $type Return type (atom, rss, xml, json)
1168 * @return array|string
1169 * @throws BadRequestException
1170 * @throws ForbiddenException
1171 * @throws ImagickException
1172 * @throws InternalServerErrorException
1173 * @throws UnauthorizedException
1174 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1176 function api_statuses_show($type)
1178 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1180 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1183 $id = intval(DI::args()->getArgv()[3] ?? 0);
1186 $id = intval($_REQUEST['id'] ?? 0);
1191 $id = intval(DI::args()->getArgv()[4] ?? 0);
1194 logger::notice('API: api_statuses_show: ' . $id);
1196 $conversation = !empty($_REQUEST['conversation']);
1198 // try to fetch the item for the local user - or the public item, if there is no local one
1199 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1200 if (!DBA::isResult($uri_item)) {
1201 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1204 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1205 if (!DBA::isResult($item)) {
1206 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1211 if ($conversation) {
1212 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1213 $params = ['order' => ['id' => true]];
1215 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1219 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1221 /// @TODO How about copying this to above methods which don't check $r ?
1222 if (!DBA::isResult($statuses)) {
1223 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1226 $ret = api_format_items(Post::toArray($statuses), $type);
1228 if ($conversation) {
1229 $data = ['status' => $ret];
1230 return DI::apiResponse()->formatData("statuses", $type, $data);
1232 $data = ['status' => $ret[0]];
1233 return DI::apiResponse()->formatData("status", $type, $data);
1237 /// @TODO move to top of file or somewhere better
1238 api_register_func('api/statuses/show', 'api_statuses_show', true);
1242 * @param string $type Return type (atom, rss, xml, json)
1244 * @return array|string
1245 * @throws BadRequestException
1246 * @throws ForbiddenException
1247 * @throws ImagickException
1248 * @throws InternalServerErrorException
1249 * @throws UnauthorizedException
1250 * @todo nothing to say?
1252 function api_conversation_show($type)
1254 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1256 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1259 $id = intval(DI::args()->getArgv()[3] ?? 0);
1260 $since_id = intval($_REQUEST['since_id'] ?? 0);
1261 $max_id = intval($_REQUEST['max_id'] ?? 0);
1262 $count = intval($_REQUEST['count'] ?? 20);
1263 $page = intval($_REQUEST['page'] ?? 1);
1265 $start = max(0, ($page - 1) * $count);
1268 $id = intval($_REQUEST['id'] ?? 0);
1273 $id = intval(DI::args()->getArgv()[4] ?? 0);
1276 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1278 // try to fetch the item for the local user - or the public item, if there is no local one
1279 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1280 if (!DBA::isResult($item)) {
1281 throw new BadRequestException("There is no status with the id $id.");
1284 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1285 if (!DBA::isResult($parent)) {
1286 throw new BadRequestException("There is no status with this id.");
1289 $id = $parent['id'];
1291 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1292 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1295 $condition[0] .= " AND `id` <= ?";
1296 $condition[] = $max_id;
1299 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1300 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1302 if (!DBA::isResult($statuses)) {
1303 throw new BadRequestException("There is no status with id $id.");
1306 $ret = api_format_items(Post::toArray($statuses), $type);
1308 $data = ['status' => $ret];
1309 return DI::apiResponse()->formatData("statuses", $type, $data);
1312 /// @TODO move to top of file or somewhere better
1313 api_register_func('api/conversation/show', 'api_conversation_show', true);
1314 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1319 * @param string $type Return type (atom, rss, xml, json)
1321 * @return array|string
1322 * @throws BadRequestException
1323 * @throws ForbiddenException
1324 * @throws ImagickException
1325 * @throws InternalServerErrorException
1326 * @throws UnauthorizedException
1327 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1329 function api_statuses_repeat($type)
1331 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1334 $id = intval(DI::args()->getArgv()[3] ?? 0);
1337 $id = intval($_REQUEST['id'] ?? 0);
1342 $id = intval(DI::args()->getArgv()[4] ?? 0);
1345 logger::notice('API: api_statuses_repeat: ' . $id);
1347 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1348 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1350 if (DBA::isResult($item) && !empty($item['body'])) {
1351 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1352 if (!Item::performActivity($id, 'announce', BaseApi::getCurrentUserID())) {
1353 throw new InternalServerErrorException();
1358 if (strpos($item['body'], "[/share]") !== false) {
1359 $pos = strpos($item['body'], "[share");
1360 $post = substr($item['body'], $pos);
1362 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1364 if (!empty($item['title'])) {
1365 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1368 $post .= $item['body'];
1369 $post .= "[/share]";
1371 $_REQUEST['body'] = $post;
1372 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1373 $_REQUEST['api_source'] = true;
1375 if (empty($_REQUEST['source'])) {
1376 $_REQUEST['source'] = api_source();
1379 $item_id = item_post(DI::app());
1382 throw new ForbiddenException();
1385 // output the post that we just posted.
1386 return api_status_show($type, $item_id);
1389 /// @TODO move to top of file or somewhere better
1390 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1393 * Destroys a specific status.
1395 * @param string $type Return type (atom, rss, xml, json)
1397 * @return array|string
1398 * @throws BadRequestException
1399 * @throws ForbiddenException
1400 * @throws ImagickException
1401 * @throws InternalServerErrorException
1402 * @throws UnauthorizedException
1403 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1405 function api_statuses_destroy($type)
1407 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1410 $id = intval(DI::args()->getArgv()[3] ?? 0);
1413 $id = intval($_REQUEST['id'] ?? 0);
1418 $id = intval(DI::args()->getArgv()[4] ?? 0);
1421 logger::notice('API: api_statuses_destroy: ' . $id);
1423 $ret = api_statuses_show($type);
1425 Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1430 /// @TODO move to top of file or somewhere better
1431 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1434 * Returns the most recent mentions.
1436 * @param string $type Return type (atom, rss, xml, json)
1438 * @return array|string
1439 * @throws BadRequestException
1440 * @throws ForbiddenException
1441 * @throws ImagickException
1442 * @throws InternalServerErrorException
1443 * @throws UnauthorizedException
1444 * @see http://developer.twitter.com/doc/get/statuses/mentions
1446 function api_statuses_mentions($type)
1448 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1450 unset($_REQUEST['user_id']);
1451 unset($_GET['user_id']);
1453 unset($_REQUEST['screen_name']);
1454 unset($_GET['screen_name']);
1456 // get last network messages
1459 $since_id = intval($_REQUEST['since_id'] ?? 0);
1460 $max_id = intval($_REQUEST['max_id'] ?? 0);
1461 $count = intval($_REQUEST['count'] ?? 20);
1462 $page = intval($_REQUEST['page'] ?? 1);
1464 $start = max(0, ($page - 1) * $count);
1466 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1467 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1468 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1471 GRAVITY_PARENT, GRAVITY_COMMENT,
1472 BaseApi::getCurrentUserID(),
1473 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1474 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1475 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1476 BaseApi::getCurrentUserID(), $since_id,
1480 $query .= " AND `id` <= ?";
1481 $condition[] = $max_id;
1484 array_unshift($condition, $query);
1486 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1487 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1489 $ret = api_format_items(Post::toArray($statuses), $type);
1491 $data = ['status' => $ret];
1496 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
1500 return DI::apiResponse()->formatData("statuses", $type, $data);
1503 /// @TODO move to top of file or somewhere better
1504 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1505 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1508 * Returns the most recent statuses posted by the user.
1510 * @param string $type Either "json" or "xml"
1511 * @return string|array
1512 * @throws BadRequestException
1513 * @throws ForbiddenException
1514 * @throws ImagickException
1515 * @throws InternalServerErrorException
1516 * @throws UnauthorizedException
1517 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1519 function api_statuses_user_timeline($type)
1521 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1523 $uid = BaseApi::getCurrentUserID();
1525 Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $_REQUEST]);
1527 $cid = BaseApi::getContactIDForSearchterm($_REQUEST['screen_name'] ?? '', $_REQUEST['user_id'] ?? 0, $uid);
1528 $since_id = $_REQUEST['since_id'] ?? 0;
1529 $max_id = $_REQUEST['max_id'] ?? 0;
1530 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1531 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1534 $count = $_REQUEST['count'] ?? 20;
1535 $page = $_REQUEST['page'] ?? 1;
1537 $start = max(0, ($page - 1) * $count);
1539 $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`)) AND `gravity` IN (?, ?) AND `id` > ? AND `author-id` = ?",
1540 0, $uid, GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $cid];
1542 if ($exclude_replies) {
1543 $condition[0] .= ' AND `gravity` = ?';
1544 $condition[] = GRAVITY_PARENT;
1547 if ($conversation_id > 0) {
1548 $condition[0] .= " AND `parent` = ?";
1549 $condition[] = $conversation_id;
1553 $condition[0] .= " AND `id` <= ?";
1554 $condition[] = $max_id;
1556 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1557 $statuses = Post::selectForUser($uid, [], $condition, $params);
1559 $ret = api_format_items(Post::toArray($statuses), $type);
1563 $data = ['status' => $ret];
1568 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId($uid)->toArray());
1572 return DI::apiResponse()->formatData("statuses", $type, $data);
1575 /// @TODO move to top of file or somewhere better
1576 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1579 * Star/unstar an item.
1580 * param: id : id of the item
1582 * @param string $type Return type (atom, rss, xml, json)
1584 * @return array|string
1585 * @throws BadRequestException
1586 * @throws ForbiddenException
1587 * @throws ImagickException
1588 * @throws InternalServerErrorException
1589 * @throws UnauthorizedException
1590 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1592 function api_favorites_create_destroy($type)
1594 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1596 // for versioned api.
1597 /// @TODO We need a better global soluton
1598 $action_argv_id = 2;
1599 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1600 $action_argv_id = 3;
1603 if (DI::args()->getArgc() <= $action_argv_id) {
1604 throw new BadRequestException("Invalid request.");
1606 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1607 if (DI::args()->getArgc() == $action_argv_id + 2) {
1608 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1610 $itemid = intval($_REQUEST['id'] ?? 0);
1613 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1615 if (!DBA::isResult($item)) {
1616 throw new BadRequestException("Invalid item.");
1621 $item['starred'] = 1;
1624 $item['starred'] = 0;
1627 throw new BadRequestException("Invalid action ".$action);
1630 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1633 throw new InternalServerErrorException("DB error");
1636 $ret = api_format_item($item, $type);
1638 $data = ['status' => $ret];
1643 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
1647 return DI::apiResponse()->formatData("status", $type, $data);
1650 /// @TODO move to top of file or somewhere better
1651 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1652 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1655 * Returns the most recent favorite statuses.
1657 * @param string $type Return type (atom, rss, xml, json)
1659 * @return string|array
1660 * @throws BadRequestException
1661 * @throws ForbiddenException
1662 * @throws ImagickException
1663 * @throws InternalServerErrorException
1664 * @throws UnauthorizedException
1666 function api_favorites($type)
1668 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1670 // in friendica starred item are private
1671 // return favorites only for self
1672 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
1675 $since_id = $_REQUEST['since_id'] ?? 0;
1676 $max_id = $_REQUEST['max_id'] ?? 0;
1677 $count = $_GET['count'] ?? 20;
1678 $page = $_REQUEST['page'] ?? 1;
1680 $start = max(0, ($page - 1) * $count);
1682 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1683 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1685 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1688 $condition[0] .= " AND `id` <= ?";
1689 $condition[] = $max_id;
1692 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1694 $ret = api_format_items(Post::toArray($statuses), $type);
1698 $data = ['status' => $ret];
1703 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
1707 return DI::apiResponse()->formatData("statuses", $type, $data);
1710 /// @TODO move to top of file or somewhere better
1711 api_register_func('api/favorites', 'api_favorites', true);
1715 * @param array $item
1716 * @param array $recipient
1717 * @param array $sender
1720 * @throws InternalServerErrorException
1722 function api_format_messages($item, $recipient, $sender)
1724 // standard meta information
1726 'id' => $item['id'],
1727 'sender_id' => $sender['id'],
1729 'recipient_id' => $recipient['id'],
1730 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
1731 'sender_screen_name' => $sender['screen_name'],
1732 'recipient_screen_name' => $recipient['screen_name'],
1733 'sender' => $sender,
1734 'recipient' => $recipient,
1736 'friendica_seen' => $item['seen'] ?? 0,
1737 'friendica_parent_uri' => $item['parent-uri'] ?? '',
1740 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1741 if (isset($ret['sender']['uid'])) {
1742 unset($ret['sender']['uid']);
1744 if (isset($ret['sender']['self'])) {
1745 unset($ret['sender']['self']);
1747 if (isset($ret['recipient']['uid'])) {
1748 unset($ret['recipient']['uid']);
1750 if (isset($ret['recipient']['self'])) {
1751 unset($ret['recipient']['self']);
1754 //don't send title to regular StatusNET requests to avoid confusing these apps
1755 if (!empty($_GET['getText'])) {
1756 $ret['title'] = $item['title'];
1757 if ($_GET['getText'] == 'html') {
1758 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
1759 } elseif ($_GET['getText'] == 'plain') {
1760 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
1763 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
1765 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
1766 unset($ret['sender']);
1767 unset($ret['recipient']);
1775 * @param array $item
1778 * @throws InternalServerErrorException
1780 function api_convert_item($item)
1782 $body = api_add_attachments_to_body($item);
1784 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
1786 // Add pictures to the attachment array and remove them from the body
1787 $attachments = api_get_attachments($body, $item['uri-id']);
1789 // Workaround for ostatus messages where the title is identically to the body
1790 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
1791 $statusbody = trim(HTML::toPlaintext($html, 0));
1793 // handle data: images
1794 $statusbody = api_format_items_embeded_images($item, $statusbody);
1796 $statustitle = trim($item['title']);
1798 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
1799 $statustext = trim($statusbody);
1801 $statustext = trim($statustitle."\n\n".$statusbody);
1804 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
1805 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
1808 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
1810 // Workaround for clients with limited HTML parser functionality
1811 $search = ["<br>", "<blockquote>", "</blockquote>",
1812 "<h1>", "</h1>", "<h2>", "</h2>",
1813 "<h3>", "</h3>", "<h4>", "</h4>",
1814 "<h5>", "</h5>", "<h6>", "</h6>"];
1815 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
1816 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
1817 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
1818 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
1819 $statushtml = str_replace($search, $replace, $statushtml);
1821 if ($item['title'] != "") {
1822 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
1826 $oldtext = $statushtml;
1827 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
1828 } while ($oldtext != $statushtml);
1830 if (substr($statushtml, 0, 4) == '<br>') {
1831 $statushtml = substr($statushtml, 4);
1834 if (substr($statushtml, 0, -4) == '<br>') {
1835 $statushtml = substr($statushtml, -4);
1838 // feeds without body should contain the link
1839 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
1840 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
1844 "text" => $statustext,
1845 "html" => $statushtml,
1846 "attachments" => $attachments,
1847 "entities" => $entities
1852 * Add media attachments to the body
1854 * @param array $item
1855 * @return string body with added media
1857 function api_add_attachments_to_body(array $item)
1859 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1861 if (strpos($body, '[/img]') !== false) {
1865 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
1866 if (!empty($media['preview'])) {
1867 $description = $media['description'] ?: $media['name'];
1868 if (!empty($description)) {
1869 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
1871 $body .= "\n[img]" . $media['preview'] .'[/img]';
1881 * @param string $body
1885 * @throws InternalServerErrorException
1887 function api_get_attachments(&$body, $uriid)
1889 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1890 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1892 $URLSearchString = "^\[\]";
1893 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
1897 // Remove all embedded pictures, since they are added as attachments
1898 foreach ($images[0] as $orig) {
1899 $body = str_replace($orig, '', $body);
1904 foreach ($images[1] as $image) {
1905 $imagedata = Images::getInfoFromURLCached($image);
1908 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
1912 return $attachments;
1917 * @param string $text
1918 * @param string $bbcode
1921 * @throws InternalServerErrorException
1922 * @todo Links at the first character of the post
1924 function api_get_entitities(&$text, $bbcode, $uriid)
1926 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
1928 if ($include_entities != "true") {
1929 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1931 foreach ($images[1] as $image) {
1932 $replace = Post\Link::getByLink($uriid, $image);
1933 $text = str_replace($image, $replace, $text);
1938 $bbcode = BBCode::cleanPictureLinks($bbcode);
1940 // Change pure links in text to bbcode uris
1941 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1944 $entities["hashtags"] = [];
1945 $entities["symbols"] = [];
1946 $entities["urls"] = [];
1947 $entities["user_mentions"] = [];
1949 $URLSearchString = "^\[\]";
1951 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
1953 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
1954 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
1956 $bbcode = preg_replace(
1957 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1958 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
1961 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
1963 $bbcode = preg_replace(
1964 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1965 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
1968 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
1970 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1972 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1975 foreach ($urls[1] as $id => $url) {
1976 $start = iconv_strpos($text, $url, 0, "UTF-8");
1977 if (!($start === false)) {
1978 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
1982 ksort($ordered_urls);
1986 foreach ($ordered_urls as $url) {
1987 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
1988 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
1990 $display_url = $url["title"];
1992 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
1993 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
1995 if (strlen($display_url) > 26) {
1996 $display_url = substr($display_url, 0, 25)."…";
2000 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2001 if (!($start === false)) {
2002 $entities["urls"][] = ["url" => $url["url"],
2003 "expanded_url" => $url["url"],
2004 "display_url" => $display_url,
2005 "indices" => [$start, $start+strlen($url["url"])]];
2006 $offset = $start + 1;
2010 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2011 $ordered_images = [];
2012 foreach ($images as $image) {
2013 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2014 if (!($start === false)) {
2015 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2019 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2020 foreach ($images[1] as $image) {
2021 $start = iconv_strpos($text, $image, 0, "UTF-8");
2022 if (!($start === false)) {
2023 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2029 foreach ($ordered_images as $image) {
2030 $url = $image['url'];
2031 $ext_alt_text = $image['alt'];
2033 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2034 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2036 if (strlen($display_url) > 26) {
2037 $display_url = substr($display_url, 0, 25)."…";
2040 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2041 if (!($start === false)) {
2042 $image = Images::getInfoFromURLCached($url);
2044 $media_url = Post\Link::getByLink($uriid, $url);
2045 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2047 $entities["media"][] = [
2049 "id_str" => (string) ($start + 1),
2050 "indices" => [$start, $start+strlen($url)],
2051 "media_url" => Strings::normaliseLink($media_url),
2052 "media_url_https" => $media_url,
2054 "display_url" => $display_url,
2055 "expanded_url" => $url,
2056 "ext_alt_text" => $ext_alt_text,
2060 $offset = $start + 1;
2069 * @param array $item
2070 * @param string $text
2074 function api_format_items_embeded_images($item, $text)
2076 $text = preg_replace_callback(
2077 '|data:image/([^;]+)[^=]+=*|m',
2078 function () use ($item) {
2079 return DI::baseUrl() . '/display/' . $item['guid'];
2087 * return <a href='url'>name</a> as array
2089 * @param string $txt text
2094 function api_contactlink_to_array($txt)
2097 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2098 if ($r && count($match)==3) {
2100 'name' => $match[2],
2114 * return likes, dislikes and attend status for item
2116 * @param array $item array
2117 * @param string $type Return type (atom, rss, xml, json)
2120 * likes => int count,
2121 * dislikes => int count
2122 * @throws BadRequestException
2123 * @throws ImagickException
2124 * @throws InternalServerErrorException
2125 * @throws UnauthorizedException
2127 function api_format_items_activities($item, $type = "json")
2134 'attendmaybe' => [],
2138 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2139 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2141 while ($parent_item = Post::fetch($ret)) {
2142 // not used as result should be structured like other user data
2143 //builtin_activity_puller($i, $activities);
2145 // get user data and add it to the array of the activity
2146 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2147 switch ($parent_item['verb']) {
2148 case Activity::LIKE:
2149 $activities['like'][] = $user;
2151 case Activity::DISLIKE:
2152 $activities['dislike'][] = $user;
2154 case Activity::ATTEND:
2155 $activities['attendyes'][] = $user;
2157 case Activity::ATTENDNO:
2158 $activities['attendno'][] = $user;
2160 case Activity::ATTENDMAYBE:
2161 $activities['attendmaybe'][] = $user;
2163 case Activity::ANNOUNCE:
2164 $activities['announce'][] = $user;
2173 if ($type == "xml") {
2174 $xml_activities = [];
2175 foreach ($activities as $k => $v) {
2176 // change xml element from "like" to "friendica:like"
2177 $xml_activities["friendica:".$k] = $v;
2178 // add user data into xml output
2180 foreach ($v as $user) {
2181 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2184 $activities = $xml_activities;
2191 * format items to be returned by api
2193 * @param array $items array of items
2194 * @param string $type Return type (atom, rss, xml, json)
2196 * @throws BadRequestException
2197 * @throws ImagickException
2198 * @throws InternalServerErrorException
2199 * @throws UnauthorizedException
2201 function api_format_items($items, $type = "json")
2204 foreach ($items as $item) {
2205 $ret[] = api_format_item($item, $type);
2212 * @param array $item Item record
2213 * @param string $type Return format (atom, rss, xml, json)
2214 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2215 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2216 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2217 * @return array API-formatted status
2218 * @throws BadRequestException
2219 * @throws ImagickException
2220 * @throws InternalServerErrorException
2221 * @throws UnauthorizedException
2223 function api_format_item($item, $type = "json")
2225 $author_user = DI::twitterUser()->createFromContactId($item['author-id'], BaseApi::getCurrentUserID())->toArray();
2226 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], BaseApi::getCurrentUserID())->toArray();
2228 DI::contentItem()->localize($item);
2230 $in_reply_to = api_in_reply_to($item);
2232 $converted = api_convert_item($item);
2234 if ($type == "xml") {
2235 $geo = "georss:point";
2241 'text' => $converted["text"],
2242 'truncated' => false,
2243 'created_at'=> DateTimeFormat::utc($item['created'], DateTimeFormat::API),
2244 'in_reply_to_status_id' => $in_reply_to['status_id'],
2245 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2246 'source' => (($item['app']) ? $item['app'] : 'web'),
2247 'id' => intval($item['id']),
2248 'id_str' => (string) intval($item['id']),
2249 'in_reply_to_user_id' => $in_reply_to['user_id'],
2250 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2251 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2253 'favorited' => $item['starred'] ? true : false,
2254 'user' => $author_user,
2255 'friendica_author' => $author_user,
2256 'friendica_owner' => $owner_user,
2257 'friendica_private' => $item['private'] == Item::PRIVATE,
2258 //'entities' => NULL,
2259 'statusnet_html' => $converted["html"],
2260 'statusnet_conversation_id' => $item['parent'],
2261 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2262 'friendica_activities' => api_format_items_activities($item, $type),
2263 'friendica_title' => $item['title'],
2264 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2267 if (count($converted["attachments"]) > 0) {
2268 $status["attachments"] = $converted["attachments"];
2271 if (count($converted["entities"]) > 0) {
2272 $status["entities"] = $converted["entities"];
2275 if ($status["source"] == 'web') {
2276 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2277 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2278 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2281 $retweeted_item = [];
2284 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2285 $announce = api_get_announce($item);
2286 if (!empty($announce)) {
2287 $retweeted_item = $item;
2289 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2293 if (!empty($quoted_item)) {
2294 if ($quoted_item['id'] != $item['id']) {
2295 $quoted_status = api_format_item($quoted_item);
2296 /// @todo Only remove the attachments that are also contained in the quotes status
2297 unset($status['attachments']);
2298 unset($status['entities']);
2300 $conv_quoted = api_convert_item($quoted_item);
2301 $quoted_status = $status;
2302 unset($quoted_status['attachments']);
2303 unset($quoted_status['entities']);
2304 unset($quoted_status['statusnet_conversation_id']);
2305 $quoted_status['text'] = $conv_quoted['text'];
2306 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2308 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2309 } catch (BadRequestException $e) {
2310 // user not found. should be found?
2311 /// @todo check if the user should be always found
2312 $quoted_status["user"] = [];
2315 unset($quoted_status['friendica_author']);
2316 unset($quoted_status['friendica_owner']);
2317 unset($quoted_status['friendica_activities']);
2318 unset($quoted_status['friendica_private']);
2321 if (!empty($retweeted_item)) {
2322 $retweeted_status = $status;
2323 unset($retweeted_status['friendica_author']);
2324 unset($retweeted_status['friendica_owner']);
2325 unset($retweeted_status['friendica_activities']);
2326 unset($retweeted_status['friendica_private']);
2327 unset($retweeted_status['statusnet_conversation_id']);
2328 $status['user'] = $status['friendica_owner'];
2330 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2331 } catch (BadRequestException $e) {
2332 // user not found. should be found?
2333 /// @todo check if the user should be always found
2334 $retweeted_status["user"] = [];
2337 $rt_converted = api_convert_item($retweeted_item);
2339 $retweeted_status['text'] = $rt_converted["text"];
2340 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2341 $retweeted_status['friendica_html'] = $rt_converted["html"];
2342 $retweeted_status['created_at'] = DateTimeFormat::utc($retweeted_item['created'], DateTimeFormat::API);
2344 if (!empty($quoted_status)) {
2345 $retweeted_status['quoted_status'] = $quoted_status;
2348 $status['friendica_author'] = $retweeted_status['user'];
2349 $status['retweeted_status'] = $retweeted_status;
2350 } elseif (!empty($quoted_status)) {
2351 $root_status = api_convert_item($item);
2353 $status['text'] = $root_status["text"];
2354 $status['statusnet_html'] = $root_status["html"];
2355 $status['quoted_status'] = $quoted_status;
2358 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2359 unset($status["user"]["uid"]);
2360 unset($status["user"]["self"]);
2362 if ($item["coord"] != "") {
2363 $coords = explode(' ', $item["coord"]);
2364 if (count($coords) == 2) {
2365 if ($type == "json") {
2366 $status["geo"] = ['type' => 'Point',
2367 'coordinates' => [(float) $coords[0],
2368 (float) $coords[1]]];
2369 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2370 $status["georss:point"] = $item["coord"];
2379 * Returns all lists the user subscribes to.
2381 * @param string $type Return type (atom, rss, xml, json)
2383 * @return array|string
2384 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2386 function api_lists_list($type)
2389 /// @TODO $ret is not filled here?
2390 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2393 /// @TODO move to top of file or somewhere better
2394 api_register_func('api/lists/list', 'api_lists_list', true);
2395 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2398 * Returns all groups the user owns.
2400 * @param string $type Return type (atom, rss, xml, json)
2402 * @return array|string
2403 * @throws BadRequestException
2404 * @throws ForbiddenException
2405 * @throws ImagickException
2406 * @throws InternalServerErrorException
2407 * @throws UnauthorizedException
2408 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2410 function api_lists_ownerships($type)
2412 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2415 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2416 $uid = $user_info['uid'];
2418 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2420 // loop through all groups
2422 foreach ($groups as $group) {
2423 if ($group['visible']) {
2429 'name' => $group['name'],
2430 'id' => intval($group['id']),
2431 'id_str' => (string) $group['id'],
2432 'user' => $user_info,
2436 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2439 /// @TODO move to top of file or somewhere better
2440 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2443 * Returns recent statuses from users in the specified group.
2445 * @param string $type Return type (atom, rss, xml, json)
2447 * @return array|string
2448 * @throws BadRequestException
2449 * @throws ForbiddenException
2450 * @throws ImagickException
2451 * @throws InternalServerErrorException
2452 * @throws UnauthorizedException
2453 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2455 function api_lists_statuses($type)
2457 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2459 unset($_REQUEST['user_id']);
2460 unset($_GET['user_id']);
2462 unset($_REQUEST['screen_name']);
2463 unset($_GET['screen_name']);
2465 if (empty($_REQUEST['list_id'])) {
2466 throw new BadRequestException('list_id not specified');
2470 $count = $_REQUEST['count'] ?? 20;
2471 $page = $_REQUEST['page'] ?? 1;
2472 $since_id = $_REQUEST['since_id'] ?? 0;
2473 $max_id = $_REQUEST['max_id'] ?? 0;
2474 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2475 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2477 $start = max(0, ($page - 1) * $count);
2479 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2480 $gids = array_column($groups, 'contact-id');
2481 $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2482 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2485 $condition[0] .= " AND `id` <= ?";
2486 $condition[] = $max_id;
2488 if ($exclude_replies > 0) {
2489 $condition[0] .= ' AND `gravity` = ?';
2490 $condition[] = GRAVITY_PARENT;
2492 if ($conversation_id > 0) {
2493 $condition[0] .= " AND `parent` = ?";
2494 $condition[] = $conversation_id;
2497 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2498 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2500 $items = api_format_items(Post::toArray($statuses), $type);
2502 $data = ['status' => $items];
2507 $data = api_rss_extra($data, DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray());
2511 return DI::apiResponse()->formatData("statuses", $type, $data);
2514 /// @TODO move to top of file or somewhere better
2515 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2518 * Returns either the friends of the follower list
2520 * Considers friends and followers lists to be private and won't return
2521 * anything if any user_id parameter is passed.
2523 * @param string $qtype Either "friends" or "followers"
2524 * @return boolean|array
2525 * @throws BadRequestException
2526 * @throws ForbiddenException
2527 * @throws ImagickException
2528 * @throws InternalServerErrorException
2529 * @throws UnauthorizedException
2531 function api_statuses_f($qtype)
2533 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2536 $count = $_GET['count'] ?? 20;
2537 $page = $_GET['page'] ?? 1;
2539 $start = max(0, ($page - 1) * $count);
2541 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2543 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2544 /* this is to stop Hotot to load friends multiple times
2545 * I'm not sure if I'm missing return something or
2546 * is a bug in hotot. Workaround, meantime
2550 return array('$users' => $ret);*/
2555 if ($qtype == 'friends') {
2556 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2557 } elseif ($qtype == 'followers') {
2558 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2561 // friends and followers only for self
2562 if ($user_info['self'] == 0) {
2563 $sql_extra = " AND false ";
2566 if ($qtype == 'blocks') {
2567 $sql_filter = 'AND `blocked` AND NOT `pending`';
2568 } elseif ($qtype == 'incoming') {
2569 $sql_filter = 'AND `pending`';
2571 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2574 // @todo This query most likely can be replaced with a Contact::select...
2575 $r = DBA::toArray(DBA::p(
2584 BaseApi::getCurrentUserID(),
2590 foreach ($r as $cid) {
2591 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2592 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2593 unset($user["uid"]);
2594 unset($user["self"]);
2601 return ['user' => $ret];
2606 * Returns the list of friends of the provided user
2608 * @deprecated By Twitter API in favor of friends/list
2610 * @param string $type Either "json" or "xml"
2611 * @return boolean|string|array
2612 * @throws BadRequestException
2613 * @throws ForbiddenException
2615 function api_statuses_friends($type)
2617 $data = api_statuses_f("friends");
2618 if ($data === false) {
2621 return DI::apiResponse()->formatData("users", $type, $data);
2625 * Returns the list of followers of the provided user
2627 * @deprecated By Twitter API in favor of friends/list
2629 * @param string $type Either "json" or "xml"
2630 * @return boolean|string|array
2631 * @throws BadRequestException
2632 * @throws ForbiddenException
2634 function api_statuses_followers($type)
2636 $data = api_statuses_f("followers");
2637 if ($data === false) {
2640 return DI::apiResponse()->formatData("users", $type, $data);
2643 /// @TODO move to top of file or somewhere better
2644 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2645 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2648 * Returns the list of blocked users
2650 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2652 * @param string $type Either "json" or "xml"
2654 * @return boolean|string|array
2655 * @throws BadRequestException
2656 * @throws ForbiddenException
2658 function api_blocks_list($type)
2660 $data = api_statuses_f('blocks');
2661 if ($data === false) {
2664 return DI::apiResponse()->formatData("users", $type, $data);
2667 /// @TODO move to top of file or somewhere better
2668 api_register_func('api/blocks/list', 'api_blocks_list', true);
2671 * Returns the list of pending users IDs
2673 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2675 * @param string $type Either "json" or "xml"
2677 * @return boolean|string|array
2678 * @throws BadRequestException
2679 * @throws ForbiddenException
2681 function api_friendships_incoming($type)
2683 $data = api_statuses_f('incoming');
2684 if ($data === false) {
2689 foreach ($data['user'] as $user) {
2690 $ids[] = $user['id'];
2693 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2696 /// @TODO move to top of file or somewhere better
2697 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2700 * Sends a new direct message.
2702 * @param string $type Return type (atom, rss, xml, json)
2704 * @return array|string
2705 * @throws BadRequestException
2706 * @throws ForbiddenException
2707 * @throws ImagickException
2708 * @throws InternalServerErrorException
2709 * @throws NotFoundException
2710 * @throws UnauthorizedException
2711 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2713 function api_direct_messages_new($type)
2715 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2717 $uid = BaseApi::getCurrentUserID();
2719 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2723 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2725 $cid = BaseApi::getContactIDForSearchterm($_POST['screen_name'] ?? '', $_POST['user_id'] ?? 0, $uid);
2727 throw new NotFoundException('Recipient not found');
2731 if (!empty($_REQUEST['replyto'])) {
2732 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
2733 $replyto = $mail['parent-uri'];
2734 $sub = $mail['title'];
2736 if (!empty($_REQUEST['title'])) {
2737 $sub = $_REQUEST['title'];
2739 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2743 $id = Mail::send($cid, $_POST['text'], $sub, $replyto);
2746 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2747 $ret = api_format_messages($mail, DI::twitterUser()->createFromContactId($cid, $uid)->toArray(), $sender);
2749 $ret = ["error" => $id];
2752 $data = ['direct_message'=>$ret];
2758 $data = api_rss_extra($data, $sender);
2762 return DI::apiResponse()->formatData("direct-messages", $type, $data);
2765 /// @TODO move to top of file or somewhere better
2766 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2769 * delete a direct_message from mail table through api
2771 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2772 * @return string|array
2773 * @throws BadRequestException
2774 * @throws ForbiddenException
2775 * @throws ImagickException
2776 * @throws InternalServerErrorException
2777 * @throws UnauthorizedException
2778 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2780 function api_direct_messages_destroy($type)
2782 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2785 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2787 $id = $_REQUEST['id'] ?? 0;
2789 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2790 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2791 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2793 $uid = $user_info['uid'];
2794 // error if no id or parenturi specified (for clients posting parent-uri as well)
2795 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2796 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2797 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2800 // BadRequestException if no id specified (for clients using Twitter API)
2802 throw new BadRequestException('Message id not specified');
2805 // add parent-uri to sql command if specified by calling app
2806 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2808 // error message if specified id is not in database
2809 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2810 if ($verbose == "true") {
2811 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2812 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2814 /// @todo BadRequestException ok for Twitter API clients?
2815 throw new BadRequestException('message id not in database');
2819 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2821 if ($verbose == "true") {
2824 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2825 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2827 $answer = ['result' => 'error', 'message' => 'unknown error'];
2828 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2831 /// @todo return JSON data like Twitter API not yet implemented
2834 /// @TODO move to top of file or somewhere better
2835 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2840 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2841 * @return string|array
2842 * @throws HTTPException\BadRequestException
2843 * @throws HTTPException\ExpectationFailedException
2844 * @throws HTTPException\ForbiddenException
2845 * @throws HTTPException\InternalServerErrorException
2846 * @throws HTTPException\NotFoundException
2847 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2849 function api_friendships_destroy($type)
2851 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2852 $uid = BaseApi::getCurrentUserID();
2854 $owner = User::getOwnerDataById($uid);
2856 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2857 throw new HTTPException\NotFoundException('Error Processing Request');
2860 $contact_id = $_REQUEST['user_id'] ?? 0;
2862 if (empty($contact_id)) {
2863 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2864 throw new HTTPException\BadRequestException('no user_id specified');
2867 // Get Contact by given id
2868 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2870 if(!DBA::isResult($contact)) {
2871 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2872 throw new HTTPException\NotFoundException('no contact found to given ID');
2875 $url = $contact['url'];
2877 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
2878 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
2879 Strings::normaliseLink($url), $url];
2880 $contact = DBA::selectFirst('contact', [], $condition);
2882 if (!DBA::isResult($contact)) {
2883 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
2884 throw new HTTPException\NotFoundException('Not following Contact');
2888 $result = Contact::terminateFriendship($owner, $contact);
2890 if ($result === null) {
2891 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
2892 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
2895 if ($result === false) {
2896 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
2898 } catch (Exception $e) {
2899 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
2900 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
2903 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2904 unset($contact['uid']);
2905 unset($contact['self']);
2907 // Set screen_name since Twidere requests it
2908 $contact['screen_name'] = $contact['nick'];
2910 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
2913 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
2917 * @param string $type Return type (atom, rss, xml, json)
2918 * @param string $box
2919 * @param string $verbose
2921 * @return array|string
2922 * @throws BadRequestException
2923 * @throws ForbiddenException
2924 * @throws ImagickException
2925 * @throws InternalServerErrorException
2926 * @throws UnauthorizedException
2928 function api_direct_messages_box($type, $box, $verbose)
2930 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2933 $count = $_GET['count'] ?? 20;
2934 $page = $_REQUEST['page'] ?? 1;
2936 $since_id = $_REQUEST['since_id'] ?? 0;
2937 $max_id = $_REQUEST['max_id'] ?? 0;
2939 $user_id = $_REQUEST['user_id'] ?? '';
2940 $screen_name = $_REQUEST['screen_name'] ?? '';
2943 unset($_REQUEST['user_id']);
2944 unset($_GET['user_id']);
2946 unset($_REQUEST['screen_name']);
2947 unset($_GET['screen_name']);
2949 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2951 $profile_url = $user_info["url"];
2954 $start = max(0, ($page - 1) * $count);
2959 if ($box=="sentbox") {
2960 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
2961 } elseif ($box == "conversation") {
2962 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
2963 } elseif ($box == "all") {
2964 $sql_extra = "true";
2965 } elseif ($box == "inbox") {
2966 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
2970 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
2973 if ($user_id != "") {
2974 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2975 } elseif ($screen_name !="") {
2976 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
2979 $r = DBA::toArray(DBA::p(
2980 "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 ?,?",
2981 BaseApi::getCurrentUserID(),
2986 if ($verbose == "true" && !DBA::isResult($r)) {
2987 $answer = ['result' => 'error', 'message' => 'no mails available'];
2988 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
2992 foreach ($r as $item) {
2993 if ($box == "inbox" || $item['from-url'] != $profile_url) {
2994 $recipient = $user_info;
2995 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
2996 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
2997 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
2998 $sender = $user_info;
3001 if (isset($recipient) && isset($sender)) {
3002 $ret[] = api_format_messages($item, $recipient, $sender);
3007 $data = ['direct_message' => $ret];
3012 $data = api_rss_extra($data, $user_info);
3016 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3020 * Returns the most recent direct messages sent by the user.
3022 * @param string $type Return type (atom, rss, xml, json)
3024 * @return array|string
3025 * @throws BadRequestException
3026 * @throws ForbiddenException
3027 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3029 function api_direct_messages_sentbox($type)
3031 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3032 return api_direct_messages_box($type, "sentbox", $verbose);
3036 * Returns the most recent direct messages sent to the user.
3038 * @param string $type Return type (atom, rss, xml, json)
3040 * @return array|string
3041 * @throws BadRequestException
3042 * @throws ForbiddenException
3043 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3045 function api_direct_messages_inbox($type)
3047 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3048 return api_direct_messages_box($type, "inbox", $verbose);
3053 * @param string $type Return type (atom, rss, xml, json)
3055 * @return array|string
3056 * @throws BadRequestException
3057 * @throws ForbiddenException
3059 function api_direct_messages_all($type)
3061 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3062 return api_direct_messages_box($type, "all", $verbose);
3067 * @param string $type Return type (atom, rss, xml, json)
3069 * @return array|string
3070 * @throws BadRequestException
3071 * @throws ForbiddenException
3073 function api_direct_messages_conversation($type)
3075 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3076 return api_direct_messages_box($type, "conversation", $verbose);
3079 /// @TODO move to top of file or somewhere better
3080 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3081 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3082 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3083 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3086 * list all photos of the authenticated user
3088 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3089 * @return string|array
3090 * @throws ForbiddenException
3091 * @throws InternalServerErrorException
3093 function api_fr_photos_list($type)
3095 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3097 $r = DBA::toArray(DBA::p(
3098 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3099 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3100 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3101 BaseApi::getCurrentUserID(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3104 'image/jpeg' => 'jpg',
3105 'image/png' => 'png',
3106 'image/gif' => 'gif'
3108 $data = ['photo'=>[]];
3109 if (DBA::isResult($r)) {
3110 foreach ($r as $rr) {
3112 $photo['id'] = $rr['resource-id'];
3113 $photo['album'] = $rr['album'];
3114 $photo['filename'] = $rr['filename'];
3115 $photo['type'] = $rr['type'];
3116 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3117 $photo['created'] = $rr['created'];
3118 $photo['edited'] = $rr['edited'];
3119 $photo['desc'] = $rr['desc'];
3121 if ($type == "xml") {
3122 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3124 $photo['thumb'] = $thumb;
3125 $data['photo'][] = $photo;
3129 return DI::apiResponse()->formatData("photos", $type, $data);
3133 * upload a new photo or change an existing photo
3135 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3136 * @return string|array
3137 * @throws BadRequestException
3138 * @throws ForbiddenException
3139 * @throws ImagickException
3140 * @throws InternalServerErrorException
3141 * @throws NotFoundException
3143 function api_fr_photo_create_update($type)
3145 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3148 $photo_id = $_REQUEST['photo_id'] ?? null;
3149 $desc = $_REQUEST['desc'] ?? null;
3150 $album = $_REQUEST['album'] ?? null;
3151 $album_new = $_REQUEST['album_new'] ?? null;
3152 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3153 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3154 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3155 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3156 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3158 // do several checks on input parameters
3159 // we do not allow calls without album string
3160 if ($album == null) {
3161 throw new BadRequestException("no albumname specified");
3163 // if photo_id == null --> we are uploading a new photo
3164 if ($photo_id == null) {
3167 // error if no media posted in create-mode
3168 if (empty($_FILES['media'])) {
3170 throw new BadRequestException("no media data submitted");
3173 // album_new will be ignored in create-mode
3178 // check if photo is existing in databasei
3179 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3180 throw new BadRequestException("photo not available");
3184 // checks on acl strings provided by clients
3185 $acl_input_error = false;
3186 $acl_input_error |= check_acl_input($allow_cid);
3187 $acl_input_error |= check_acl_input($deny_cid);
3188 $acl_input_error |= check_acl_input($allow_gid);
3189 $acl_input_error |= check_acl_input($deny_gid);
3190 if ($acl_input_error) {
3191 throw new BadRequestException("acl data invalid");
3193 // now let's upload the new media in create-mode
3194 if ($mode == "create") {
3195 $media = $_FILES['media'];
3196 $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);
3198 // return success of updating or error message
3199 if (!is_null($data)) {
3200 return DI::apiResponse()->formatData("photo_create", $type, $data);
3202 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3206 // now let's do the changes in update-mode
3207 if ($mode == "update") {
3208 $updated_fields = [];
3210 if (!is_null($desc)) {
3211 $updated_fields['desc'] = $desc;
3214 if (!is_null($album_new)) {
3215 $updated_fields['album'] = $album_new;
3218 if (!is_null($allow_cid)) {
3219 $allow_cid = trim($allow_cid);
3220 $updated_fields['allow_cid'] = $allow_cid;
3223 if (!is_null($deny_cid)) {
3224 $deny_cid = trim($deny_cid);
3225 $updated_fields['deny_cid'] = $deny_cid;
3228 if (!is_null($allow_gid)) {
3229 $allow_gid = trim($allow_gid);
3230 $updated_fields['allow_gid'] = $allow_gid;
3233 if (!is_null($deny_gid)) {
3234 $deny_gid = trim($deny_gid);
3235 $updated_fields['deny_gid'] = $deny_gid;
3239 if (count($updated_fields) > 0) {
3240 $nothingtodo = false;
3241 $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3243 $nothingtodo = true;
3246 if (!empty($_FILES['media'])) {
3247 $nothingtodo = false;
3248 $media = $_FILES['media'];
3249 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3250 if (!is_null($data)) {
3251 return DI::apiResponse()->formatData("photo_update", $type, $data);
3255 // return success of updating or error message
3257 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3258 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3261 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3262 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3264 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3267 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3271 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3273 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3274 * @return string|array
3275 * @throws BadRequestException
3276 * @throws ForbiddenException
3277 * @throws InternalServerErrorException
3278 * @throws NotFoundException
3280 function api_fr_photo_detail($type)
3282 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3284 if (empty($_REQUEST['photo_id'])) {
3285 throw new BadRequestException("No photo id.");
3288 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3289 $photo_id = $_REQUEST['photo_id'];
3291 // prepare json/xml output with data from database for the requested photo
3292 $data = prepare_photo_data($type, $scale, $photo_id);
3294 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3299 * updates the profile image for the user (either a specified profile or the default profile)
3301 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3303 * @return string|array
3304 * @throws BadRequestException
3305 * @throws ForbiddenException
3306 * @throws ImagickException
3307 * @throws InternalServerErrorException
3308 * @throws NotFoundException
3309 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3311 function api_account_update_profile_image($type)
3313 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3316 $profile_id = $_REQUEST['profile_id'] ?? 0;
3318 // error if image data is missing
3319 if (empty($_FILES['image'])) {
3320 throw new BadRequestException("no media data submitted");
3323 // check if specified profile id is valid
3324 if ($profile_id != 0) {
3325 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3326 // error message if specified profile id is not in database
3327 if (!DBA::isResult($profile)) {
3328 throw new BadRequestException("profile_id not available");
3330 $is_default_profile = $profile['is-default'];
3332 $is_default_profile = 1;
3335 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3337 if (!empty($_FILES['image'])) {
3338 $media = $_FILES['image'];
3339 } elseif (!empty($_FILES['media'])) {
3340 $media = $_FILES['media'];
3342 // save new profile image
3343 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3346 if (is_array($media['type'])) {
3347 $filetype = $media['type'][0];
3349 $filetype = $media['type'];
3351 if ($filetype == "image/jpeg") {
3353 } elseif ($filetype == "image/png") {
3356 throw new InternalServerErrorException('Unsupported filetype');
3359 // change specified profile or all profiles to the new resource-id
3360 if ($is_default_profile) {
3361 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3362 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3364 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3365 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3366 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3369 Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3371 // Update global directory in background
3372 Profile::publishUpdate(BaseApi::getCurrentUserID());
3374 // output for client
3376 return api_account_verify_credentials($type);
3378 // SaveMediaToDatabase failed for some reason
3379 throw new InternalServerErrorException("image upload failed");
3383 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3384 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3385 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3386 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3387 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3388 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3391 * Update user profile
3393 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3395 * @return array|string
3396 * @throws BadRequestException
3397 * @throws ForbiddenException
3398 * @throws ImagickException
3399 * @throws InternalServerErrorException
3400 * @throws UnauthorizedException
3402 function api_account_update_profile($type)
3404 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3406 $local_user = BaseApi::getCurrentUserID();
3408 $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3410 if (!empty($_POST['name'])) {
3411 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3412 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3413 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3414 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3417 if (isset($_POST['description'])) {
3418 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3419 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3420 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3423 Profile::publishUpdate($local_user);
3425 return api_account_verify_credentials($type);
3428 /// @TODO move to top of file or somewhere better
3429 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3433 * @param string $acl_string
3437 function check_acl_input($acl_string)
3439 if (empty($acl_string)) {
3443 $contact_not_found = false;
3445 // split <x><y><z> into array of cid's
3446 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3448 // check for each cid if it is available on server
3449 $cid_array = $array[0];
3450 foreach ($cid_array as $cid) {
3451 $cid = str_replace("<", "", $cid);
3452 $cid = str_replace(">", "", $cid);
3453 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3454 $contact_not_found |= !DBA::exists('contact', $condition);
3456 return $contact_not_found;
3460 * @param string $mediatype
3461 * @param array $media
3462 * @param string $type
3463 * @param string $album
3464 * @param string $allow_cid
3465 * @param string $deny_cid
3466 * @param string $allow_gid
3467 * @param string $deny_gid
3468 * @param string $desc
3469 * @param integer $phototype
3470 * @param boolean $visibility
3471 * @param string $photo_id
3473 * @throws BadRequestException
3474 * @throws ForbiddenException
3475 * @throws ImagickException
3476 * @throws InternalServerErrorException
3477 * @throws NotFoundException
3478 * @throws UnauthorizedException
3480 function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, $phototype = 0, $visibility = false, $photo_id = null)
3488 if (is_array($media)) {
3489 if (is_array($media['tmp_name'])) {
3490 $src = $media['tmp_name'][0];
3492 $src = $media['tmp_name'];
3494 if (is_array($media['name'])) {
3495 $filename = basename($media['name'][0]);
3497 $filename = basename($media['name']);
3499 if (is_array($media['size'])) {
3500 $filesize = intval($media['size'][0]);
3502 $filesize = intval($media['size']);
3504 if (is_array($media['type'])) {
3505 $filetype = $media['type'][0];
3507 $filetype = $media['type'];
3511 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3514 "File upload src: " . $src . " - filename: " . $filename .
3515 " - size: " . $filesize . " - type: " . $filetype);
3517 // check if there was a php upload error
3518 if ($filesize == 0 && $media['error'] == 1) {
3519 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3521 // check against max upload size within Friendica instance
3522 $maximagesize = DI::config()->get('system', 'maximagesize');
3523 if ($maximagesize && ($filesize > $maximagesize)) {
3524 $formattedBytes = Strings::formatBytes($maximagesize);
3525 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3528 // create Photo instance with the data of the image
3529 $imagedata = @file_get_contents($src);
3530 $Image = new Image($imagedata, $filetype);
3531 if (!$Image->isValid()) {
3532 throw new InternalServerErrorException("unable to process image data");
3535 // check orientation of image
3536 $Image->orient($src);
3539 // check max length of images on server
3540 $max_length = DI::config()->get('system', 'max_image_length');
3541 if ($max_length > 0) {
3542 $Image->scaleDown($max_length);
3543 logger::info("File upload: Scaling picture to new size " . $max_length);
3545 $width = $Image->getWidth();
3546 $height = $Image->getHeight();
3548 // create a new resource-id if not already provided
3549 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3551 if ($mediatype == "photo") {
3552 // upload normal image (scales 0, 1, 2)
3553 logger::info("photo upload: starting new photo upload");
3555 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3557 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3559 if ($width > 640 || $height > 640) {
3560 $Image->scaleDown(640);
3561 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3563 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3567 if ($width > 320 || $height > 320) {
3568 $Image->scaleDown(320);
3569 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3571 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3574 logger::info("photo upload: new photo upload ended");
3575 } elseif ($mediatype == "profileimage") {
3576 // upload profile image (scales 4, 5, 6)
3577 logger::info("photo upload: starting new profile image upload");
3579 if ($width > 300 || $height > 300) {
3580 $Image->scaleDown(300);
3581 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3583 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3587 if ($width > 80 || $height > 80) {
3588 $Image->scaleDown(80);
3589 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3591 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3595 if ($width > 48 || $height > 48) {
3596 $Image->scaleDown(48);
3597 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3599 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3602 $Image->__destruct();
3603 logger::info("photo upload: new profile image upload ended");
3607 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3608 if ($photo_id == null && $mediatype == "photo") {
3609 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3611 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3612 return prepare_photo_data($type, false, $resource_id);
3614 throw new InternalServerErrorException("image upload failed");
3620 * @param string $hash
3621 * @param string $allow_cid
3622 * @param string $deny_cid
3623 * @param string $allow_gid
3624 * @param string $deny_gid
3625 * @param string $filetype
3626 * @param boolean $visibility
3627 * @throws InternalServerErrorException
3629 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
3631 // get data about the api authenticated user
3632 $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
3633 $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
3636 $arr['guid'] = System::createUUID();
3637 $arr['uid'] = intval(BaseApi::getCurrentUserID());
3639 $arr['type'] = 'photo';
3641 $arr['resource-id'] = $hash;
3642 $arr['contact-id'] = $owner_record['id'];
3643 $arr['owner-name'] = $owner_record['name'];
3644 $arr['owner-link'] = $owner_record['url'];
3645 $arr['owner-avatar'] = $owner_record['thumb'];
3646 $arr['author-name'] = $owner_record['name'];
3647 $arr['author-link'] = $owner_record['url'];
3648 $arr['author-avatar'] = $owner_record['thumb'];
3650 $arr['allow_cid'] = $allow_cid;
3651 $arr['allow_gid'] = $allow_gid;
3652 $arr['deny_cid'] = $deny_cid;
3653 $arr['deny_gid'] = $deny_gid;
3654 $arr['visible'] = $visibility;
3658 'image/jpeg' => 'jpg',
3659 'image/png' => 'png',
3660 'image/gif' => 'gif'
3663 // adds link to the thumbnail scale photo
3664 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3665 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3668 // do the magic for storing the item in the database and trigger the federation to other contacts
3674 * @param string $type
3676 * @param string $photo_id
3679 * @throws BadRequestException
3680 * @throws ForbiddenException
3681 * @throws ImagickException
3682 * @throws InternalServerErrorException
3683 * @throws NotFoundException
3684 * @throws UnauthorizedException
3686 function prepare_photo_data($type, $scale, $photo_id)
3688 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3690 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3692 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3693 $data_sql = ($scale === false ? "" : "data, ");
3695 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3696 // clients needs to convert this in their way for further processing
3697 $r = DBA::toArray(DBA::p(
3698 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3699 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3700 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3701 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
3702 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3703 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
3704 BaseApi::getCurrentUserID(),
3709 'image/jpeg' => 'jpg',
3710 'image/png' => 'png',
3711 'image/gif' => 'gif'
3714 // prepare output data for photo
3715 if (DBA::isResult($r)) {
3716 $data = ['photo' => $r[0]];
3717 $data['photo']['id'] = $data['photo']['resource-id'];
3718 if ($scale !== false) {
3719 $data['photo']['data'] = base64_encode($data['photo']['data']);
3721 unset($data['photo']['datasize']); //needed only with scale param
3723 if ($type == "xml") {
3724 $data['photo']['links'] = [];
3725 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3726 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
3728 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
3731 $data['photo']['link'] = [];
3732 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
3734 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3735 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3739 unset($data['photo']['resource-id']);
3740 unset($data['photo']['minscale']);
3741 unset($data['photo']['maxscale']);
3743 throw new NotFoundException();
3746 // retrieve item element for getting activities (like, dislike etc.) related to photo
3747 $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
3748 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
3749 if (!DBA::isResult($item)) {
3750 throw new NotFoundException('Photo-related item not found.');
3753 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
3755 // retrieve comments on photo
3756 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
3757 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
3759 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
3761 // prepare output of comments
3762 $commentData = api_format_items(Post::toArray($statuses), $type);
3764 if ($type == "xml") {
3766 foreach ($commentData as $comment) {
3767 $comments[$k++ . ":comment"] = $comment;
3770 foreach ($commentData as $comment) {
3771 $comments[] = $comment;
3774 $data['photo']['friendica_comments'] = $comments;
3776 // include info if rights on photo and rights on item are mismatching
3777 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
3778 $data['photo']['deny_cid'] != $item['deny_cid'] ||
3779 $data['photo']['allow_gid'] != $item['allow_gid'] ||
3780 $data['photo']['deny_gid'] != $item['deny_gid'];
3781 $data['photo']['rights_mismatch'] = $rights_mismatch;
3787 * Return an item with announcer data if it had been announced
3789 * @param array $item Item array
3790 * @return array Item array with announce data
3792 function api_get_announce($item)
3794 // Quit if the item already has got a different owner and author
3795 if ($item['owner-id'] != $item['author-id']) {
3799 // Don't change original or Diaspora posts
3800 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
3804 // Quit if we do now the original author and it had been a post from a native network
3805 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
3809 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
3810 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
3811 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
3812 if (!DBA::isResult($announce)) {
3816 return array_merge($item, $announce);
3821 * @param array $item
3826 function api_in_reply_to($item)
3830 $in_reply_to['status_id'] = null;
3831 $in_reply_to['user_id'] = null;
3832 $in_reply_to['status_id_str'] = null;
3833 $in_reply_to['user_id_str'] = null;
3834 $in_reply_to['screen_name'] = null;
3836 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
3837 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
3838 if (DBA::isResult($parent)) {
3839 $in_reply_to['status_id'] = intval($parent['id']);
3841 $in_reply_to['status_id'] = intval($item['parent']);
3844 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3846 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
3847 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
3849 if (DBA::isResult($parent)) {
3850 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
3851 $in_reply_to['user_id'] = intval($parent['author-id']);
3852 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
3855 // There seems to be situation, where both fields are identical:
3856 // https://github.com/friendica/friendica/issues/1010
3857 // This is a bugfix for that.
3858 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3859 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']]);
3860 $in_reply_to['status_id'] = null;
3861 $in_reply_to['user_id'] = null;
3862 $in_reply_to['status_id_str'] = null;
3863 $in_reply_to['user_id_str'] = null;
3864 $in_reply_to['screen_name'] = null;
3868 return $in_reply_to;
3873 * @param string $text
3876 * @throws InternalServerErrorException
3878 function api_clean_plain_items($text)
3880 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
3882 $text = BBCode::cleanPictureLinks($text);
3883 $URLSearchString = "^\[\]";
3885 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
3887 if ($include_entities == "true") {
3888 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
3891 // Simplify "attachment" element
3892 $text = BBCode::removeAttachment($text);
3898 * Return all or a specified group of the user with the containing contacts.
3900 * @param string $type Return type (atom, rss, xml, json)
3902 * @return array|string
3903 * @throws BadRequestException
3904 * @throws ForbiddenException
3905 * @throws ImagickException
3906 * @throws InternalServerErrorException
3907 * @throws UnauthorizedException
3909 function api_friendica_group_show($type)
3911 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3914 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3915 $gid = $_REQUEST['gid'] ?? 0;
3916 $uid = $user_info['uid'];
3918 // get data of the specified group id or all groups if not specified
3920 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
3922 // error message if specified gid is not in database
3923 if (!DBA::isResult($groups)) {
3924 throw new BadRequestException("gid not available");
3927 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
3930 // loop through all groups and retrieve all members for adding data in the user array
3932 foreach ($groups as $rr) {
3933 $members = Contact\Group::getById($rr['id']);
3936 if ($type == "xml") {
3937 $user_element = "users";
3939 foreach ($members as $member) {
3940 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
3941 $users[$k++.":user"] = $user;
3944 $user_element = "user";
3945 foreach ($members as $member) {
3946 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
3950 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
3952 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
3955 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3960 * @param string $type Return type (atom, rss, xml, json)
3962 * @return array|string
3963 * @throws BadRequestException
3964 * @throws ForbiddenException
3965 * @throws ImagickException
3966 * @throws InternalServerErrorException
3967 * @throws UnauthorizedException
3968 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
3970 function api_lists_destroy($type)
3972 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3975 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3976 $gid = $_REQUEST['list_id'] ?? 0;
3977 $uid = $user_info['uid'];
3979 // error if no gid specified
3981 throw new BadRequestException('gid not specified');
3984 // get data of the specified group id
3985 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
3986 // error message if specified gid is not in database
3988 throw new BadRequestException('gid not available');
3991 if (Group::remove($gid)) {
3993 'name' => $group['name'],
3994 'id' => intval($gid),
3995 'id_str' => (string) $gid,
3996 'user' => $user_info
3999 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4003 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4006 * Add a new group to the database.
4008 * @param string $name Group name
4009 * @param int $uid User ID
4010 * @param array $users List of users to add to the group
4013 * @throws BadRequestException
4015 function group_create($name, $uid, $users = [])
4017 // error if no name specified
4019 throw new BadRequestException('group name not specified');
4022 // error message if specified group name already exists
4023 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4024 throw new BadRequestException('group name already exists');
4027 // Check if the group needs to be reactivated
4028 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4029 $reactivate_group = true;
4033 $ret = Group::create($uid, $name);
4035 $gid = Group::getIdByName($uid, $name);
4037 throw new BadRequestException('other API error');
4041 $erroraddinguser = false;
4043 foreach ($users as $user) {
4044 $cid = $user['cid'];
4045 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4046 Group::addMember($gid, $cid);
4048 $erroraddinguser = true;
4049 $errorusers[] = $cid;
4053 // return success message incl. missing users in array
4054 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4056 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4060 * Create the specified group with the posted array of contacts.
4062 * @param string $type Return type (atom, rss, xml, json)
4064 * @return array|string
4065 * @throws BadRequestException
4066 * @throws ForbiddenException
4067 * @throws ImagickException
4068 * @throws InternalServerErrorException
4069 * @throws UnauthorizedException
4071 function api_friendica_group_create($type)
4073 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4076 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4077 $name = $_REQUEST['name'] ?? '';
4078 $uid = $user_info['uid'];
4079 $json = json_decode($_POST['json'], true);
4080 $users = $json['user'];
4082 $success = group_create($name, $uid, $users);
4084 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4087 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4090 * Create a new group.
4092 * @param string $type Return type (atom, rss, xml, json)
4094 * @return array|string
4095 * @throws BadRequestException
4096 * @throws ForbiddenException
4097 * @throws ImagickException
4098 * @throws InternalServerErrorException
4099 * @throws UnauthorizedException
4100 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4102 function api_lists_create($type)
4104 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4107 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4108 $name = $_REQUEST['name'] ?? '';
4109 $uid = $user_info['uid'];
4111 $success = group_create($name, $uid);
4112 if ($success['success']) {
4114 'name' => $success['name'],
4115 'id' => intval($success['gid']),
4116 'id_str' => (string) $success['gid'],
4117 'user' => $user_info
4120 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4124 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4127 * Update the specified group with the posted array of contacts.
4129 * @param string $type Return type (atom, rss, xml, json)
4131 * @return array|string
4132 * @throws BadRequestException
4133 * @throws ForbiddenException
4134 * @throws ImagickException
4135 * @throws InternalServerErrorException
4136 * @throws UnauthorizedException
4138 function api_friendica_group_update($type)
4140 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4143 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4144 $uid = $user_info['uid'];
4145 $gid = $_REQUEST['gid'] ?? 0;
4146 $name = $_REQUEST['name'] ?? '';
4147 $json = json_decode($_POST['json'], true);
4148 $users = $json['user'];
4150 // error if no name specified
4152 throw new BadRequestException('group name not specified');
4155 // error if no gid specified
4157 throw new BadRequestException('gid not specified');
4161 $members = Contact\Group::getById($gid);
4162 foreach ($members as $member) {
4163 $cid = $member['id'];
4164 foreach ($users as $user) {
4165 $found = ($user['cid'] == $cid ? true : false);
4167 if (!isset($found) || !$found) {
4168 $gid = Group::getIdByName($uid, $name);
4169 Group::removeMember($gid, $cid);
4174 $erroraddinguser = false;
4176 foreach ($users as $user) {
4177 $cid = $user['cid'];
4179 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4180 Group::addMember($gid, $cid);
4182 $erroraddinguser = true;
4183 $errorusers[] = $cid;
4187 // return success message incl. missing users in array
4188 $status = ($erroraddinguser ? "missing user" : "ok");
4189 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4190 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4193 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4196 * Update information about a group.
4198 * @param string $type Return type (atom, rss, xml, json)
4200 * @return array|string
4201 * @throws BadRequestException
4202 * @throws ForbiddenException
4203 * @throws ImagickException
4204 * @throws InternalServerErrorException
4205 * @throws UnauthorizedException
4206 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4208 function api_lists_update($type)
4210 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4213 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4214 $gid = $_REQUEST['list_id'] ?? 0;
4215 $name = $_REQUEST['name'] ?? '';
4216 $uid = $user_info['uid'];
4218 // error if no gid specified
4220 throw new BadRequestException('gid not specified');
4223 // get data of the specified group id
4224 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4225 // error message if specified gid is not in database
4227 throw new BadRequestException('gid not available');
4230 if (Group::update($gid, $name)) {
4233 'id' => intval($gid),
4234 'id_str' => (string) $gid,
4235 'user' => $user_info
4238 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4242 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4245 * Set notification as seen and returns associated item (if possible)
4247 * POST request with 'id' param as notification id
4249 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4250 * @return string|array
4251 * @throws BadRequestException
4252 * @throws ForbiddenException
4253 * @throws ImagickException
4254 * @throws InternalServerErrorException
4255 * @throws UnauthorizedException
4257 function api_friendica_notification_seen($type)
4259 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4261 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4263 if (DI::args()->getArgc() !== 4) {
4264 throw new BadRequestException('Invalid argument count');
4267 $id = intval($_REQUEST['id'] ?? 0);
4270 $Notify = DI::notify()->selectOneById($id);
4271 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4272 throw new NotFoundException();
4275 if ($Notify->uriId) {
4276 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4280 DI::notify()->save($Notify);
4282 if ($Notify->otype === Notification\ObjectType::ITEM) {
4283 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4284 if (DBA::isResult($item)) {
4285 // we found the item, return it to the user
4286 $ret = api_format_items([$item], $type);
4287 $data = ['status' => $ret];
4288 return DI::apiResponse()->formatData('status', $type, $data);
4290 // the item can't be found, but we set the notification as seen, so we count this as a success
4293 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4294 } catch (NotFoundException $e) {
4295 throw new BadRequestException('Invalid argument', $e);
4296 } catch (Exception $e) {
4297 throw new InternalServerErrorException('Internal Server exception', $e);
4301 /// @TODO move to top of file or somewhere better
4302 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4305 * search for direct_messages containing a searchstring through api
4307 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4308 * @param string $box
4309 * @return string|array (success: success=true if found and search_result contains found messages,
4310 * success=false if nothing was found, search_result='nothing found',
4311 * error: result=error with error message)
4312 * @throws BadRequestException
4313 * @throws ForbiddenException
4314 * @throws ImagickException
4315 * @throws InternalServerErrorException
4316 * @throws UnauthorizedException
4318 function api_friendica_direct_messages_search($type, $box = "")
4320 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4323 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4324 $searchstring = $_REQUEST['searchstring'] ?? '';
4325 $uid = $user_info['uid'];
4327 // error if no searchstring specified
4328 if ($searchstring == "") {
4329 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4330 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4333 // get data for the specified searchstring
4334 $r = DBA::toArray(DBA::p(
4335 "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",
4337 '%'.$searchstring.'%'
4340 $profile_url = $user_info["url"];
4342 // message if nothing was found
4343 if (!DBA::isResult($r)) {
4344 $success = ['success' => false, 'search_results' => 'problem with query'];
4345 } elseif (count($r) == 0) {
4346 $success = ['success' => false, 'search_results' => 'nothing found'];
4349 foreach ($r as $item) {
4350 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4351 $recipient = $user_info;
4352 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4353 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4354 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4355 $sender = $user_info;
4358 if (isset($recipient) && isset($sender)) {
4359 $ret[] = api_format_messages($item, $recipient, $sender);
4362 $success = ['success' => true, 'search_results' => $ret];
4365 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4368 /// @TODO move to top of file or somewhere better
4369 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4372 * Number of comments
4374 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4376 * @param object $data [Status, Status]
4380 function bindComments(&$data)
4382 if (count($data) == 0) {
4388 foreach ($data as $item) {
4389 $ids[] = $item['id'];
4392 $idStr = DBA::escape(implode(', ', $ids));
4393 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4394 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4395 $itemsData = DBA::toArray($items);
4397 foreach ($itemsData as $item) {
4398 $comments[$item['parent']] = $item['comments'];
4401 foreach ($data as $idx => $item) {
4403 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4408 @TODO Maybe open to implement?
4410 [pagename] => api/1.1/statuses/lookup.json
4411 [id] => 605138389168451584
4412 [include_cards] => true
4413 [cards_platform] => Android-12
4414 [include_entities] => true
4415 [include_my_retweet] => 1
4417 [include_reply_count] => true
4418 [include_descendent_reply_count] => true
4422 Not implemented by now:
4423 statuses/retweets_of_me
4428 account/update_location
4429 account/update_profile_background_image
4432 friendica/profile/update
4433 friendica/profile/create
4434 friendica/profile/delete
4436 Not implemented in status.net:
4437 statuses/retweeted_to_me
4438 statuses/retweeted_by_me
4439 direct_messages/destroy
4441 account/update_delivery_device
4442 notifications/follow