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 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
229 * Set values for RSS template
231 * @param array $arr Array to be passed to template
232 * @param array $user_info User info
234 * @throws BadRequestException
235 * @throws ImagickException
236 * @throws InternalServerErrorException
237 * @throws UnauthorizedException
238 * @todo find proper type-hints
240 function api_rss_extra($arr, $user_info)
242 if (is_null($user_info)) {
243 $uid = BaseApi::getCurrentUserID();
245 throw new ForbiddenException();
248 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
251 $arr['$user'] = $user_info;
253 'alternate' => $user_info['url'],
254 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
255 'base' => DI::baseUrl(),
256 'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
257 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
258 'language' => $user_info['lang'],
259 'logo' => DI::baseUrl() . "/images/friendica-32.png",
267 * Unique contact to contact url.
269 * @param int $id Contact id
270 * @return bool|string
271 * Contact url or False if contact id is unknown
274 function api_unique_id_to_nurl($id)
276 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
278 if (DBA::isResult($r)) {
286 * return api-formatted array for item's author and owner
289 * @param array $item item from db
290 * @return array(array:author, array:owner)
291 * @throws BadRequestException
292 * @throws ImagickException
293 * @throws InternalServerErrorException
294 * @throws UnauthorizedException
296 function api_item_get_user(App $a, $item)
298 if (empty($item['author-id'])) {
299 $item['author-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
301 $status_user = DI::twitterUser()->createFromContactId($item['author-id'], BaseApi::getCurrentUserID())->toArray();
303 $author_user = $status_user;
305 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
307 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
308 if (empty($item['owner-id'])) {
309 $item['owner-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
311 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], BaseApi::getCurrentUserID())->toArray();
313 $owner_user = $author_user;
316 return ([$status_user, $author_user, $owner_user]);
324 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
325 * returns a 401 status code and an error message if not.
327 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
329 * @param string $type Return type (atom, rss, xml, json)
330 * @return array|string
331 * @throws BadRequestException
332 * @throws ForbiddenException
333 * @throws ImagickException
334 * @throws InternalServerErrorException
335 * @throws UnauthorizedException
337 function api_account_verify_credentials($type)
339 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
341 unset($_REQUEST['user_id']);
342 unset($_GET['user_id']);
344 unset($_REQUEST['screen_name']);
345 unset($_GET['screen_name']);
347 $skip_status = $_REQUEST['skip_status'] ?? false;
349 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
351 // "verified" isn't used here in the standard
352 unset($user_info["verified"]);
354 // - Adding last status
356 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
358 $user_info['status'] = api_format_item($item, $type);
362 // "uid" and "self" are only needed for some internal stuff, so remove it from here
363 unset($user_info["uid"]);
364 unset($user_info["self"]);
366 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
369 /// @TODO move to top of file or somewhere better
370 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
373 * Get data from $_POST or $_GET
378 function requestdata($k)
380 if (!empty($_POST[$k])) {
383 if (!empty($_GET[$k])) {
390 * Deprecated function to upload media.
392 * @param string $type Return type (atom, rss, xml, json)
394 * @return array|string
395 * @throws BadRequestException
396 * @throws ForbiddenException
397 * @throws ImagickException
398 * @throws InternalServerErrorException
399 * @throws UnauthorizedException
401 function api_statuses_mediap($type)
405 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
407 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
409 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
410 $_REQUEST['api_source'] = true;
411 $txt = requestdata('status') ?? '';
412 /// @TODO old-lost code?
413 //$txt = urldecode(requestdata('status'));
415 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
416 $txt = HTML::toBBCodeVideo($txt);
417 $config = HTMLPurifier_Config::createDefault();
418 $config->set('Cache.DefinitionImpl', null);
419 $purifier = new HTMLPurifier($config);
420 $txt = $purifier->purify($txt);
422 $txt = HTML::toBBCode($txt);
424 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
426 $picture = wall_upload_post($a, false);
428 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
429 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
430 $item_id = item_post($a);
432 // output the post that we just posted.
433 return api_status_show($type, $item_id);
436 /// @TODO move this to top of file or somewhere better!
437 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
440 * Updates the user’s current status.
442 * @param string $type Return type (atom, rss, xml, json)
444 * @return array|string
445 * @throws BadRequestException
446 * @throws ForbiddenException
447 * @throws ImagickException
448 * @throws InternalServerErrorException
449 * @throws TooManyRequestsException
450 * @throws UnauthorizedException
451 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
453 function api_statuses_update($type)
457 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
459 // convert $_POST array items to the form we use for web posts.
460 if (requestdata('htmlstatus')) {
461 $txt = requestdata('htmlstatus') ?? '';
462 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
463 $txt = HTML::toBBCodeVideo($txt);
465 $config = HTMLPurifier_Config::createDefault();
466 $config->set('Cache.DefinitionImpl', null);
468 $purifier = new HTMLPurifier($config);
469 $txt = $purifier->purify($txt);
471 $_REQUEST['body'] = HTML::toBBCode($txt);
474 $_REQUEST['body'] = requestdata('status');
477 $_REQUEST['title'] = requestdata('title');
479 $parent = requestdata('in_reply_to_status_id');
481 // Twidere sends "-1" if it is no reply ...
486 if (ctype_digit($parent)) {
487 $_REQUEST['parent'] = $parent;
489 $_REQUEST['parent_uri'] = $parent;
492 if (requestdata('lat') && requestdata('long')) {
493 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
495 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
498 // Check for throttling (maximum posts per day, week and month)
499 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
500 if ($throttle_day > 0) {
501 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
503 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
504 $posts_day = Post::count($condition);
506 if ($posts_day > $throttle_day) {
507 logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
508 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
509 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));
513 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
514 if ($throttle_week > 0) {
515 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
517 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
518 $posts_week = Post::count($condition);
520 if ($posts_week > $throttle_week) {
521 logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
522 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
523 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));
527 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
528 if ($throttle_month > 0) {
529 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
531 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
532 $posts_month = Post::count($condition);
534 if ($posts_month > $throttle_month) {
535 logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
536 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
537 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));
542 if (requestdata('media_ids')) {
543 $ids = explode(',', requestdata('media_ids') ?? '');
544 } elseif (!empty($_FILES['media'])) {
545 // upload the image if we have one
546 $picture = wall_upload_post($a, false);
547 if (is_array($picture)) {
548 $ids[] = $picture['id'];
556 foreach ($ids as $id) {
557 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
558 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
559 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
560 ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
562 if (!empty($media)) {
563 $ressources[] = $media[0]['resource-id'];
564 $phototypes = Images::supportedTypes();
565 $ext = $phototypes[$media[0]['type']];
567 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
568 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
569 'size' => $media[0]['datasize'],
570 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
571 'description' => $media[0]['desc'] ?? '',
572 'width' => $media[0]['width'],
573 'height' => $media[0]['height']];
575 if (count($media) > 1) {
576 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
577 $attachment['preview-width'] = $media[1]['width'];
578 $attachment['preview-height'] = $media[1]['height'];
580 $attachments[] = $attachment;
584 // We have to avoid that the post is rejected because of an empty body
585 if (empty($_REQUEST['body'])) {
586 $_REQUEST['body'] = '[hr]';
590 if (!empty($attachments)) {
591 $_REQUEST['attachments'] = $attachments;
594 // set this so that the item_post() function is quiet and doesn't redirect or emit json
596 $_REQUEST['api_source'] = true;
598 if (empty($_REQUEST['source'])) {
599 $_REQUEST['source'] = api_source();
602 // call out normal post function
603 $item_id = item_post($a);
605 if (!empty($ressources) && !empty($item_id)) {
606 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
607 foreach ($ressources as $ressource) {
608 Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
612 // output the post that we just posted.
613 return api_status_show($type, $item_id);
616 /// @TODO move to top of file or somewhere better
617 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
618 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
621 * Uploads an image to Friendica.
624 * @throws BadRequestException
625 * @throws ForbiddenException
626 * @throws ImagickException
627 * @throws InternalServerErrorException
628 * @throws UnauthorizedException
629 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
631 function api_media_upload()
635 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
637 if (empty($_FILES['media'])) {
639 throw new BadRequestException("No media.");
642 $media = wall_upload_post($a, false);
645 throw new InternalServerErrorException();
649 $returndata["media_id"] = $media["id"];
650 $returndata["media_id_string"] = (string)$media["id"];
651 $returndata["size"] = $media["size"];
652 $returndata["image"] = ["w" => $media["width"],
653 "h" => $media["height"],
654 "image_type" => $media["type"],
655 "friendica_preview_url" => $media["preview"]];
657 Logger::info('Media uploaded', ['return' => $returndata]);
659 return ["media" => $returndata];
662 /// @TODO move to top of file or somewhere better
663 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
666 * Updates media meta data (picture descriptions)
668 * @param string $type Return type (atom, rss, xml, json)
670 * @return array|string
671 * @throws BadRequestException
672 * @throws ForbiddenException
673 * @throws ImagickException
674 * @throws InternalServerErrorException
675 * @throws TooManyRequestsException
676 * @throws UnauthorizedException
677 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
679 * @todo Compare the corresponding Twitter function for correct return values
681 function api_media_metadata_create($type)
683 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
685 $postdata = Network::postdata();
687 if (empty($postdata)) {
688 throw new BadRequestException("No post data");
691 $data = json_decode($postdata, true);
693 throw new BadRequestException("Invalid post data");
696 if (empty($data['media_id']) || empty($data['alt_text'])) {
697 throw new BadRequestException("Missing post data values");
700 if (empty($data['alt_text']['text'])) {
701 throw new BadRequestException("No alt text.");
704 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
706 $condition = ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
707 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
708 if (!DBA::isResult($photo)) {
709 throw new BadRequestException("Metadata not found.");
712 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
715 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
718 * @param string $type Return format (atom, rss, xml, json)
719 * @param int $item_id
720 * @return array|string
723 function api_status_show($type, $item_id)
725 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
729 $item = api_get_item(['id' => $item_id]);
731 $status_info = api_format_item($item, $type);
734 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
736 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
740 * Retrieves the last public status of the provided user info
742 * @param int $ownerId Public contact Id
743 * @param int $uid User Id
747 function api_get_last_status($ownerId, $uid)
750 'author-id'=> $ownerId,
752 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
753 'private' => [Item::PUBLIC, Item::UNLISTED]
756 $item = api_get_item($condition);
762 * Retrieves a single item record based on the provided condition and converts it for API use.
764 * @param array $condition Item table condition array
768 function api_get_item(array $condition)
770 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
776 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
777 * The author's most recent status will be returned inline.
779 * @param string $type Return type (atom, rss, xml, json)
780 * @return array|string
781 * @throws BadRequestException
782 * @throws ImagickException
783 * @throws InternalServerErrorException
784 * @throws UnauthorizedException
785 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
787 function api_users_show($type)
789 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
791 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
793 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
795 $user_info['status'] = api_format_item($item, $type);
798 // "uid" and "self" are only needed for some internal stuff, so remove it from here
799 unset($user_info['uid']);
800 unset($user_info['self']);
802 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
805 /// @TODO move to top of file or somewhere better
806 api_register_func('api/users/show', 'api_users_show');
807 api_register_func('api/externalprofile/show', 'api_users_show');
810 * Search a public user account.
812 * @param string $type Return type (atom, rss, xml, json)
814 * @return array|string
815 * @throws BadRequestException
816 * @throws ImagickException
817 * @throws InternalServerErrorException
818 * @throws UnauthorizedException
819 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
821 function api_users_search($type)
825 if (!empty($_GET['q'])) {
826 $contacts = Contact::selectToArray(
829 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
837 if (DBA::isResult($contacts)) {
839 foreach ($contacts as $contact) {
840 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
842 if ($type == 'xml') {
843 $userlist[$k++ . ':user'] = $user_info;
845 $userlist[] = $user_info;
848 $userlist = ['users' => $userlist];
850 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
853 throw new BadRequestException('No search term specified.');
856 return DI::apiResponse()->formatData('users', $type, $userlist);
859 /// @TODO move to top of file or somewhere better
860 api_register_func('api/users/search', 'api_users_search');
863 * Return user objects
865 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
867 * @param string $type Return format: json or xml
869 * @return array|string
870 * @throws BadRequestException
871 * @throws ImagickException
872 * @throws InternalServerErrorException
873 * @throws NotFoundException if the results are empty.
874 * @throws UnauthorizedException
876 function api_users_lookup($type)
880 if (!empty($_REQUEST['user_id'])) {
881 foreach (explode(',', $_REQUEST['user_id']) as $id) {
883 $cid = BaseApi::getContactIDForSearchterm($id);
885 $users[] = DI::twitterUser()->createFromContactId($cid, BaseApi::getCurrentUserID())->toArray();
892 throw new NotFoundException;
895 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
898 /// @TODO move to top of file or somewhere better
899 api_register_func('api/users/lookup', 'api_users_lookup', true);
902 * Returns statuses that match a specified query.
904 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
906 * @param string $type Return format: json, xml, atom, rss
908 * @return array|string
909 * @throws BadRequestException if the "q" parameter is missing.
910 * @throws ForbiddenException
911 * @throws ImagickException
912 * @throws InternalServerErrorException
913 * @throws UnauthorizedException
915 function api_search($type)
917 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
919 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
921 if (empty($_REQUEST['q'])) {
922 throw new BadRequestException('q parameter is required.');
925 $searchTerm = trim(rawurldecode($_REQUEST['q']));
928 $data['status'] = [];
930 $exclude_replies = !empty($_REQUEST['exclude_replies']);
931 if (!empty($_REQUEST['rpp'])) {
932 $count = $_REQUEST['rpp'];
933 } elseif (!empty($_REQUEST['count'])) {
934 $count = $_REQUEST['count'];
937 $since_id = $_REQUEST['since_id'] ?? 0;
938 $max_id = $_REQUEST['max_id'] ?? 0;
939 $page = $_REQUEST['page'] ?? 1;
941 $start = max(0, ($page - 1) * $count);
943 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
944 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
945 $searchTerm = $matches[1];
946 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, BaseApi::getCurrentUserID()];
947 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
949 while ($tag = DBA::fetch($tags)) {
950 $uriids[] = $tag['uri-id'];
954 if (empty($uriids)) {
955 return DI::apiResponse()->formatData('statuses', $type, $data);
958 $condition = ['uri-id' => $uriids];
959 if ($exclude_replies) {
960 $condition['gravity'] = GRAVITY_PARENT;
963 $params['group_by'] = ['uri-id'];
965 $condition = ["`id` > ?
966 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
967 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
968 AND `body` LIKE CONCAT('%',?,'%')",
969 $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
971 $condition[0] .= ' AND `id` <= ?';
972 $condition[] = $max_id;
978 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
979 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
982 $id = Item::fetchByLink($searchTerm);
986 $statuses = Post::select([], ['id' => $id]);
990 $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
992 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
994 bindComments($data['status']);
996 return DI::apiResponse()->formatData('statuses', $type, $data);
999 /// @TODO move to top of file or somewhere better
1000 api_register_func('api/search/tweets', 'api_search', true);
1001 api_register_func('api/search', 'api_search', true);
1004 * Returns the most recent statuses posted by the user and the users they follow.
1006 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1008 * @param string $type Return type (atom, rss, xml, json)
1010 * @return array|string
1011 * @throws BadRequestException
1012 * @throws ForbiddenException
1013 * @throws ImagickException
1014 * @throws InternalServerErrorException
1015 * @throws UnauthorizedException
1016 * @todo Optional parameters
1017 * @todo Add reply info
1019 function api_statuses_home_timeline($type)
1021 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1023 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1025 unset($_REQUEST['user_id']);
1026 unset($_GET['user_id']);
1028 unset($_REQUEST['screen_name']);
1029 unset($_GET['screen_name']);
1031 // get last network messages
1034 $count = $_REQUEST['count'] ?? 20;
1035 $page = $_REQUEST['page']?? 0;
1036 $since_id = $_REQUEST['since_id'] ?? 0;
1037 $max_id = $_REQUEST['max_id'] ?? 0;
1038 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1039 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1041 $start = max(0, ($page - 1) * $count);
1043 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1044 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1047 $condition[0] .= " AND `id` <= ?";
1048 $condition[] = $max_id;
1050 if ($exclude_replies) {
1051 $condition[0] .= ' AND `gravity` = ?';
1052 $condition[] = GRAVITY_PARENT;
1054 if ($conversation_id > 0) {
1055 $condition[0] .= " AND `parent` = ?";
1056 $condition[] = $conversation_id;
1059 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1060 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1062 $items = Post::toArray($statuses);
1064 $ret = api_format_items($items, $user_info, false, $type);
1066 // Set all posts from the query above to seen
1068 foreach ($items as $item) {
1069 $idarray[] = intval($item["id"]);
1072 if (!empty($idarray)) {
1073 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1075 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1081 $data = ['status' => $ret];
1086 $data = api_rss_extra($data, $user_info);
1090 return DI::apiResponse()->formatData("statuses", $type, $data);
1094 /// @TODO move to top of file or somewhere better
1095 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1096 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1099 * Returns the most recent statuses from public users.
1101 * @param string $type Return type (atom, rss, xml, json)
1103 * @return array|string
1104 * @throws BadRequestException
1105 * @throws ForbiddenException
1106 * @throws ImagickException
1107 * @throws InternalServerErrorException
1108 * @throws UnauthorizedException
1110 function api_statuses_public_timeline($type)
1112 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1114 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1116 // get last network messages
1119 $count = $_REQUEST['count'] ?? 20;
1120 $page = $_REQUEST['page'] ?? 1;
1121 $since_id = $_REQUEST['since_id'] ?? 0;
1122 $max_id = $_REQUEST['max_id'] ?? 0;
1123 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1124 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1126 $start = max(0, ($page - 1) * $count);
1128 if ($exclude_replies && !$conversation_id) {
1129 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1130 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1133 $condition[0] .= " AND `id` <= ?";
1134 $condition[] = $max_id;
1137 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1138 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1140 $r = Post::toArray($statuses);
1142 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1143 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1146 $condition[0] .= " AND `id` <= ?";
1147 $condition[] = $max_id;
1149 if ($conversation_id > 0) {
1150 $condition[0] .= " AND `parent` = ?";
1151 $condition[] = $conversation_id;
1154 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1155 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1157 $r = Post::toArray($statuses);
1160 $ret = api_format_items($r, $user_info, false, $type);
1164 $data = ['status' => $ret];
1169 $data = api_rss_extra($data, $user_info);
1173 return DI::apiResponse()->formatData("statuses", $type, $data);
1176 /// @TODO move to top of file or somewhere better
1177 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1180 * Returns the most recent statuses posted by users this node knows about.
1182 * @param string $type Return format: json, xml, atom, rss
1183 * @return array|string
1184 * @throws BadRequestException
1185 * @throws ForbiddenException
1186 * @throws ImagickException
1187 * @throws InternalServerErrorException
1188 * @throws UnauthorizedException
1190 function api_statuses_networkpublic_timeline($type)
1192 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1194 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1196 $since_id = $_REQUEST['since_id'] ?? 0;
1197 $max_id = $_REQUEST['max_id'] ?? 0;
1200 $count = $_REQUEST['count'] ?? 20;
1201 $page = $_REQUEST['page'] ?? 1;
1203 $start = max(0, ($page - 1) * $count);
1205 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1206 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1209 $condition[0] .= " AND `id` <= ?";
1210 $condition[] = $max_id;
1213 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1214 $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1216 $ret = api_format_items($statuses, $user_info, false, $type);
1220 $data = ['status' => $ret];
1225 $data = api_rss_extra($data, $user_info);
1229 return DI::apiResponse()->formatData("statuses", $type, $data);
1232 /// @TODO move to top of file or somewhere better
1233 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1236 * Returns a single status.
1238 * @param string $type Return type (atom, rss, xml, json)
1240 * @return array|string
1241 * @throws BadRequestException
1242 * @throws ForbiddenException
1243 * @throws ImagickException
1244 * @throws InternalServerErrorException
1245 * @throws UnauthorizedException
1246 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1248 function api_statuses_show($type)
1250 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1252 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1255 $id = intval(DI::args()->getArgv()[3] ?? 0);
1258 $id = intval($_REQUEST['id'] ?? 0);
1263 $id = intval(DI::args()->getArgv()[4] ?? 0);
1266 logger::notice('API: api_statuses_show: ' . $id);
1268 $conversation = !empty($_REQUEST['conversation']);
1270 // try to fetch the item for the local user - or the public item, if there is no local one
1271 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1272 if (!DBA::isResult($uri_item)) {
1273 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1276 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1277 if (!DBA::isResult($item)) {
1278 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1283 if ($conversation) {
1284 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1285 $params = ['order' => ['id' => true]];
1287 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1291 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1293 /// @TODO How about copying this to above methods which don't check $r ?
1294 if (!DBA::isResult($statuses)) {
1295 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1298 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1300 if ($conversation) {
1301 $data = ['status' => $ret];
1302 return DI::apiResponse()->formatData("statuses", $type, $data);
1304 $data = ['status' => $ret[0]];
1305 return DI::apiResponse()->formatData("status", $type, $data);
1309 /// @TODO move to top of file or somewhere better
1310 api_register_func('api/statuses/show', 'api_statuses_show', true);
1314 * @param string $type Return type (atom, rss, xml, json)
1316 * @return array|string
1317 * @throws BadRequestException
1318 * @throws ForbiddenException
1319 * @throws ImagickException
1320 * @throws InternalServerErrorException
1321 * @throws UnauthorizedException
1322 * @todo nothing to say?
1324 function api_conversation_show($type)
1326 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1328 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1331 $id = intval(DI::args()->getArgv()[3] ?? 0);
1332 $since_id = intval($_REQUEST['since_id'] ?? 0);
1333 $max_id = intval($_REQUEST['max_id'] ?? 0);
1334 $count = intval($_REQUEST['count'] ?? 20);
1335 $page = intval($_REQUEST['page'] ?? 1);
1337 $start = max(0, ($page - 1) * $count);
1340 $id = intval($_REQUEST['id'] ?? 0);
1345 $id = intval(DI::args()->getArgv()[4] ?? 0);
1348 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1350 // try to fetch the item for the local user - or the public item, if there is no local one
1351 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1352 if (!DBA::isResult($item)) {
1353 throw new BadRequestException("There is no status with the id $id.");
1356 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1357 if (!DBA::isResult($parent)) {
1358 throw new BadRequestException("There is no status with this id.");
1361 $id = $parent['id'];
1363 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1364 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1367 $condition[0] .= " AND `id` <= ?";
1368 $condition[] = $max_id;
1371 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1372 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1374 if (!DBA::isResult($statuses)) {
1375 throw new BadRequestException("There is no status with id $id.");
1378 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1380 $data = ['status' => $ret];
1381 return DI::apiResponse()->formatData("statuses", $type, $data);
1384 /// @TODO move to top of file or somewhere better
1385 api_register_func('api/conversation/show', 'api_conversation_show', true);
1386 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1391 * @param string $type Return type (atom, rss, xml, json)
1393 * @return array|string
1394 * @throws BadRequestException
1395 * @throws ForbiddenException
1396 * @throws ImagickException
1397 * @throws InternalServerErrorException
1398 * @throws UnauthorizedException
1399 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1401 function api_statuses_repeat($type)
1405 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1408 $id = intval(DI::args()->getArgv()[3] ?? 0);
1411 $id = intval($_REQUEST['id'] ?? 0);
1416 $id = intval(DI::args()->getArgv()[4] ?? 0);
1419 logger::notice('API: api_statuses_repeat: ' . $id);
1421 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1422 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1424 if (DBA::isResult($item) && !empty($item['body'])) {
1425 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1426 if (!Item::performActivity($id, 'announce', BaseApi::getCurrentUserID())) {
1427 throw new InternalServerErrorException();
1432 if (strpos($item['body'], "[/share]") !== false) {
1433 $pos = strpos($item['body'], "[share");
1434 $post = substr($item['body'], $pos);
1436 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1438 if (!empty($item['title'])) {
1439 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1442 $post .= $item['body'];
1443 $post .= "[/share]";
1445 $_REQUEST['body'] = $post;
1446 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1447 $_REQUEST['api_source'] = true;
1449 if (empty($_REQUEST['source'])) {
1450 $_REQUEST['source'] = api_source();
1453 $item_id = item_post($a);
1456 throw new ForbiddenException();
1459 // output the post that we just posted.
1460 return api_status_show($type, $item_id);
1463 /// @TODO move to top of file or somewhere better
1464 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1467 * Destroys a specific status.
1469 * @param string $type Return type (atom, rss, xml, json)
1471 * @return array|string
1472 * @throws BadRequestException
1473 * @throws ForbiddenException
1474 * @throws ImagickException
1475 * @throws InternalServerErrorException
1476 * @throws UnauthorizedException
1477 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1479 function api_statuses_destroy($type)
1481 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1484 $id = intval(DI::args()->getArgv()[3] ?? 0);
1487 $id = intval($_REQUEST['id'] ?? 0);
1492 $id = intval(DI::args()->getArgv()[4] ?? 0);
1495 logger::notice('API: api_statuses_destroy: ' . $id);
1497 $ret = api_statuses_show($type);
1499 Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1504 /// @TODO move to top of file or somewhere better
1505 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1508 * Returns the most recent mentions.
1510 * @param string $type Return type (atom, rss, xml, json)
1512 * @return array|string
1513 * @throws BadRequestException
1514 * @throws ForbiddenException
1515 * @throws ImagickException
1516 * @throws InternalServerErrorException
1517 * @throws UnauthorizedException
1518 * @see http://developer.twitter.com/doc/get/statuses/mentions
1520 function api_statuses_mentions($type)
1522 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1524 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1526 unset($_REQUEST['user_id']);
1527 unset($_GET['user_id']);
1529 unset($_REQUEST['screen_name']);
1530 unset($_GET['screen_name']);
1532 // get last network messages
1535 $since_id = intval($_REQUEST['since_id'] ?? 0);
1536 $max_id = intval($_REQUEST['max_id'] ?? 0);
1537 $count = intval($_REQUEST['count'] ?? 20);
1538 $page = intval($_REQUEST['page'] ?? 1);
1540 $start = max(0, ($page - 1) * $count);
1542 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1543 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1544 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1547 GRAVITY_PARENT, GRAVITY_COMMENT,
1548 BaseApi::getCurrentUserID(),
1549 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1550 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1551 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1552 BaseApi::getCurrentUserID(), $since_id,
1556 $query .= " AND `id` <= ?";
1557 $condition[] = $max_id;
1560 array_unshift($condition, $query);
1562 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1563 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1565 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1567 $data = ['status' => $ret];
1572 $data = api_rss_extra($data, $user_info);
1576 return DI::apiResponse()->formatData("statuses", $type, $data);
1579 /// @TODO move to top of file or somewhere better
1580 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1581 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1584 * Returns the most recent statuses posted by the user.
1586 * @param string $type Either "json" or "xml"
1587 * @return string|array
1588 * @throws BadRequestException
1589 * @throws ForbiddenException
1590 * @throws ImagickException
1591 * @throws InternalServerErrorException
1592 * @throws UnauthorizedException
1593 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1595 function api_statuses_user_timeline($type)
1597 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1599 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1601 Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1603 $since_id = $_REQUEST['since_id'] ?? 0;
1604 $max_id = $_REQUEST['max_id'] ?? 0;
1605 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1606 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1609 $count = $_REQUEST['count'] ?? 20;
1610 $page = $_REQUEST['page'] ?? 1;
1612 $start = max(0, ($page - 1) * $count);
1614 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1615 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1617 if ($user_info['self'] == 1) {
1618 $condition[0] .= ' AND `wall` ';
1621 if ($exclude_replies) {
1622 $condition[0] .= ' AND `gravity` = ?';
1623 $condition[] = GRAVITY_PARENT;
1626 if ($conversation_id > 0) {
1627 $condition[0] .= " AND `parent` = ?";
1628 $condition[] = $conversation_id;
1632 $condition[0] .= " AND `id` <= ?";
1633 $condition[] = $max_id;
1635 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1636 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1638 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1642 $data = ['status' => $ret];
1647 $data = api_rss_extra($data, $user_info);
1651 return DI::apiResponse()->formatData("statuses", $type, $data);
1654 /// @TODO move to top of file or somewhere better
1655 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1658 * Star/unstar an item.
1659 * param: id : id of the item
1661 * @param string $type Return type (atom, rss, xml, json)
1663 * @return array|string
1664 * @throws BadRequestException
1665 * @throws ForbiddenException
1666 * @throws ImagickException
1667 * @throws InternalServerErrorException
1668 * @throws UnauthorizedException
1669 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1671 function api_favorites_create_destroy($type)
1673 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1675 // for versioned api.
1676 /// @TODO We need a better global soluton
1677 $action_argv_id = 2;
1678 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1679 $action_argv_id = 3;
1682 if (DI::args()->getArgc() <= $action_argv_id) {
1683 throw new BadRequestException("Invalid request.");
1685 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1686 if (DI::args()->getArgc() == $action_argv_id + 2) {
1687 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1689 $itemid = intval($_REQUEST['id'] ?? 0);
1692 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1694 if (!DBA::isResult($item)) {
1695 throw new BadRequestException("Invalid item.");
1700 $item['starred'] = 1;
1703 $item['starred'] = 0;
1706 throw new BadRequestException("Invalid action ".$action);
1709 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1712 throw new InternalServerErrorException("DB error");
1715 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1716 $rets = api_format_items([$item], $user_info, false, $type);
1719 $data = ['status' => $ret];
1724 $data = api_rss_extra($data, $user_info);
1728 return DI::apiResponse()->formatData("status", $type, $data);
1731 /// @TODO move to top of file or somewhere better
1732 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1733 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1736 * Returns the most recent favorite statuses.
1738 * @param string $type Return type (atom, rss, xml, json)
1740 * @return string|array
1741 * @throws BadRequestException
1742 * @throws ForbiddenException
1743 * @throws ImagickException
1744 * @throws InternalServerErrorException
1745 * @throws UnauthorizedException
1747 function api_favorites($type)
1749 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1751 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1753 // in friendica starred item are private
1754 // return favorites only for self
1755 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1757 if ($user_info['self'] == 0) {
1761 $since_id = $_REQUEST['since_id'] ?? 0;
1762 $max_id = $_REQUEST['max_id'] ?? 0;
1763 $count = $_GET['count'] ?? 20;
1764 $page = $_REQUEST['page'] ?? 1;
1766 $start = max(0, ($page - 1) * $count);
1768 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1769 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1771 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1774 $condition[0] .= " AND `id` <= ?";
1775 $condition[] = $max_id;
1778 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1780 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1785 $data = ['status' => $ret];
1790 $data = api_rss_extra($data, $user_info);
1794 return DI::apiResponse()->formatData("statuses", $type, $data);
1797 /// @TODO move to top of file or somewhere better
1798 api_register_func('api/favorites', 'api_favorites', true);
1802 * @param array $item
1803 * @param array $recipient
1804 * @param array $sender
1807 * @throws InternalServerErrorException
1809 function api_format_messages($item, $recipient, $sender)
1811 // standard meta information
1813 'id' => $item['id'],
1814 'sender_id' => $sender['id'],
1816 'recipient_id' => $recipient['id'],
1817 'created_at' => DateTimeFormat::utc($item['created'] ?? 'now', DateTimeFormat::API),
1818 'sender_screen_name' => $sender['screen_name'],
1819 'recipient_screen_name' => $recipient['screen_name'],
1820 'sender' => $sender,
1821 'recipient' => $recipient,
1823 'friendica_seen' => $item['seen'] ?? 0,
1824 'friendica_parent_uri' => $item['parent-uri'] ?? '',
1827 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1828 if (isset($ret['sender']['uid'])) {
1829 unset($ret['sender']['uid']);
1831 if (isset($ret['sender']['self'])) {
1832 unset($ret['sender']['self']);
1834 if (isset($ret['recipient']['uid'])) {
1835 unset($ret['recipient']['uid']);
1837 if (isset($ret['recipient']['self'])) {
1838 unset($ret['recipient']['self']);
1841 //don't send title to regular StatusNET requests to avoid confusing these apps
1842 if (!empty($_GET['getText'])) {
1843 $ret['title'] = $item['title'];
1844 if ($_GET['getText'] == 'html') {
1845 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
1846 } elseif ($_GET['getText'] == 'plain') {
1847 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
1850 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
1852 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
1853 unset($ret['sender']);
1854 unset($ret['recipient']);
1862 * @param array $item
1865 * @throws InternalServerErrorException
1867 function api_convert_item($item)
1869 $body = api_add_attachments_to_body($item);
1871 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
1873 // Add pictures to the attachment array and remove them from the body
1874 $attachments = api_get_attachments($body, $item['uri-id']);
1876 // Workaround for ostatus messages where the title is identically to the body
1877 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
1878 $statusbody = trim(HTML::toPlaintext($html, 0));
1880 // handle data: images
1881 $statusbody = api_format_items_embeded_images($item, $statusbody);
1883 $statustitle = trim($item['title']);
1885 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
1886 $statustext = trim($statusbody);
1888 $statustext = trim($statustitle."\n\n".$statusbody);
1891 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
1892 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
1895 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
1897 // Workaround for clients with limited HTML parser functionality
1898 $search = ["<br>", "<blockquote>", "</blockquote>",
1899 "<h1>", "</h1>", "<h2>", "</h2>",
1900 "<h3>", "</h3>", "<h4>", "</h4>",
1901 "<h5>", "</h5>", "<h6>", "</h6>"];
1902 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
1903 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
1904 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
1905 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
1906 $statushtml = str_replace($search, $replace, $statushtml);
1908 if ($item['title'] != "") {
1909 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
1913 $oldtext = $statushtml;
1914 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
1915 } while ($oldtext != $statushtml);
1917 if (substr($statushtml, 0, 4) == '<br>') {
1918 $statushtml = substr($statushtml, 4);
1921 if (substr($statushtml, 0, -4) == '<br>') {
1922 $statushtml = substr($statushtml, -4);
1925 // feeds without body should contain the link
1926 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
1927 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
1931 "text" => $statustext,
1932 "html" => $statushtml,
1933 "attachments" => $attachments,
1934 "entities" => $entities
1939 * Add media attachments to the body
1941 * @param array $item
1942 * @return string body with added media
1944 function api_add_attachments_to_body(array $item)
1946 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1948 if (strpos($body, '[/img]') !== false) {
1952 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
1953 if (!empty($media['preview'])) {
1954 $description = $media['description'] ?: $media['name'];
1955 if (!empty($description)) {
1956 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
1958 $body .= "\n[img]" . $media['preview'] .'[/img]';
1968 * @param string $body
1972 * @throws InternalServerErrorException
1974 function api_get_attachments(&$body, $uriid)
1976 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1977 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1979 $URLSearchString = "^\[\]";
1980 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
1984 // Remove all embedded pictures, since they are added as attachments
1985 foreach ($images[0] as $orig) {
1986 $body = str_replace($orig, '', $body);
1991 foreach ($images[1] as $image) {
1992 $imagedata = Images::getInfoFromURLCached($image);
1995 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
1999 return $attachments;
2004 * @param string $text
2005 * @param string $bbcode
2008 * @throws InternalServerErrorException
2009 * @todo Links at the first character of the post
2011 function api_get_entitities(&$text, $bbcode, $uriid)
2013 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2015 if ($include_entities != "true") {
2016 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2018 foreach ($images[1] as $image) {
2019 $replace = Post\Link::getByLink($uriid, $image);
2020 $text = str_replace($image, $replace, $text);
2025 $bbcode = BBCode::cleanPictureLinks($bbcode);
2027 // Change pure links in text to bbcode uris
2028 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2031 $entities["hashtags"] = [];
2032 $entities["symbols"] = [];
2033 $entities["urls"] = [];
2034 $entities["user_mentions"] = [];
2036 $URLSearchString = "^\[\]";
2038 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2040 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2041 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2043 $bbcode = preg_replace(
2044 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2045 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2048 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2050 $bbcode = preg_replace(
2051 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2052 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2055 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2057 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2059 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2062 foreach ($urls[1] as $id => $url) {
2063 $start = iconv_strpos($text, $url, 0, "UTF-8");
2064 if (!($start === false)) {
2065 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2069 ksort($ordered_urls);
2073 foreach ($ordered_urls as $url) {
2074 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2075 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2077 $display_url = $url["title"];
2079 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2080 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2082 if (strlen($display_url) > 26) {
2083 $display_url = substr($display_url, 0, 25)."…";
2087 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2088 if (!($start === false)) {
2089 $entities["urls"][] = ["url" => $url["url"],
2090 "expanded_url" => $url["url"],
2091 "display_url" => $display_url,
2092 "indices" => [$start, $start+strlen($url["url"])]];
2093 $offset = $start + 1;
2097 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2098 $ordered_images = [];
2099 foreach ($images as $image) {
2100 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2101 if (!($start === false)) {
2102 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2106 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2107 foreach ($images[1] as $image) {
2108 $start = iconv_strpos($text, $image, 0, "UTF-8");
2109 if (!($start === false)) {
2110 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2116 foreach ($ordered_images as $image) {
2117 $url = $image['url'];
2118 $ext_alt_text = $image['alt'];
2120 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2121 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2123 if (strlen($display_url) > 26) {
2124 $display_url = substr($display_url, 0, 25)."…";
2127 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2128 if (!($start === false)) {
2129 $image = Images::getInfoFromURLCached($url);
2131 $media_url = Post\Link::getByLink($uriid, $url);
2132 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2134 $entities["media"][] = [
2136 "id_str" => (string) ($start + 1),
2137 "indices" => [$start, $start+strlen($url)],
2138 "media_url" => Strings::normaliseLink($media_url),
2139 "media_url_https" => $media_url,
2141 "display_url" => $display_url,
2142 "expanded_url" => $url,
2143 "ext_alt_text" => $ext_alt_text,
2147 $offset = $start + 1;
2156 * @param array $item
2157 * @param string $text
2161 function api_format_items_embeded_images($item, $text)
2163 $text = preg_replace_callback(
2164 '|data:image/([^;]+)[^=]+=*|m',
2165 function () use ($item) {
2166 return DI::baseUrl() . '/display/' . $item['guid'];
2174 * return <a href='url'>name</a> as array
2176 * @param string $txt text
2181 function api_contactlink_to_array($txt)
2184 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2185 if ($r && count($match)==3) {
2187 'name' => $match[2],
2201 * return likes, dislikes and attend status for item
2203 * @param array $item array
2204 * @param string $type Return type (atom, rss, xml, json)
2207 * likes => int count,
2208 * dislikes => int count
2209 * @throws BadRequestException
2210 * @throws ImagickException
2211 * @throws InternalServerErrorException
2212 * @throws UnauthorizedException
2214 function api_format_items_activities($item, $type = "json")
2221 'attendmaybe' => [],
2225 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2226 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2228 while ($parent_item = Post::fetch($ret)) {
2229 // not used as result should be structured like other user data
2230 //builtin_activity_puller($i, $activities);
2232 // get user data and add it to the array of the activity
2233 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2234 switch ($parent_item['verb']) {
2235 case Activity::LIKE:
2236 $activities['like'][] = $user;
2238 case Activity::DISLIKE:
2239 $activities['dislike'][] = $user;
2241 case Activity::ATTEND:
2242 $activities['attendyes'][] = $user;
2244 case Activity::ATTENDNO:
2245 $activities['attendno'][] = $user;
2247 case Activity::ATTENDMAYBE:
2248 $activities['attendmaybe'][] = $user;
2250 case Activity::ANNOUNCE:
2251 $activities['announce'][] = $user;
2260 if ($type == "xml") {
2261 $xml_activities = [];
2262 foreach ($activities as $k => $v) {
2263 // change xml element from "like" to "friendica:like"
2264 $xml_activities["friendica:".$k] = $v;
2265 // add user data into xml output
2267 foreach ($v as $user) {
2268 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2271 $activities = $xml_activities;
2278 * format items to be returned by api
2280 * @param array $items array of items
2281 * @param array $user_info
2282 * @param bool $filter_user filter items by $user_info
2283 * @param string $type Return type (atom, rss, xml, json)
2285 * @throws BadRequestException
2286 * @throws ImagickException
2287 * @throws InternalServerErrorException
2288 * @throws UnauthorizedException
2290 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2296 if (empty($items)) {
2300 foreach ((array)$items as $item) {
2301 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2303 // Look if the posts are matching if they should be filtered by user id
2304 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2308 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2317 * @param array $item Item record
2318 * @param string $type Return format (atom, rss, xml, json)
2319 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2320 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2321 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2322 * @return array API-formatted status
2323 * @throws BadRequestException
2324 * @throws ImagickException
2325 * @throws InternalServerErrorException
2326 * @throws UnauthorizedException
2328 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2332 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2333 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2336 DI::contentItem()->localize($item);
2338 $in_reply_to = api_in_reply_to($item);
2340 $converted = api_convert_item($item);
2342 if ($type == "xml") {
2343 $geo = "georss:point";
2349 'text' => $converted["text"],
2350 'truncated' => false,
2351 'created_at'=> DateTimeFormat::utc($item['created'], DateTimeFormat::API),
2352 'in_reply_to_status_id' => $in_reply_to['status_id'],
2353 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2354 'source' => (($item['app']) ? $item['app'] : 'web'),
2355 'id' => intval($item['id']),
2356 'id_str' => (string) intval($item['id']),
2357 'in_reply_to_user_id' => $in_reply_to['user_id'],
2358 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2359 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2361 'favorited' => $item['starred'] ? true : false,
2362 'user' => $status_user,
2363 'friendica_author' => $author_user,
2364 'friendica_owner' => $owner_user,
2365 'friendica_private' => $item['private'] == Item::PRIVATE,
2366 //'entities' => NULL,
2367 'statusnet_html' => $converted["html"],
2368 'statusnet_conversation_id' => $item['parent'],
2369 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2370 'friendica_activities' => api_format_items_activities($item, $type),
2371 'friendica_title' => $item['title'],
2372 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2375 if (count($converted["attachments"]) > 0) {
2376 $status["attachments"] = $converted["attachments"];
2379 if (count($converted["entities"]) > 0) {
2380 $status["entities"] = $converted["entities"];
2383 if ($status["source"] == 'web') {
2384 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2385 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2386 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2389 $retweeted_item = [];
2392 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2393 $announce = api_get_announce($item);
2394 if (!empty($announce)) {
2395 $retweeted_item = $item;
2397 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2401 if (!empty($quoted_item)) {
2402 if ($quoted_item['id'] != $item['id']) {
2403 $quoted_status = api_format_item($quoted_item);
2404 /// @todo Only remove the attachments that are also contained in the quotes status
2405 unset($status['attachments']);
2406 unset($status['entities']);
2408 $conv_quoted = api_convert_item($quoted_item);
2409 $quoted_status = $status;
2410 unset($quoted_status['attachments']);
2411 unset($quoted_status['entities']);
2412 unset($quoted_status['statusnet_conversation_id']);
2413 $quoted_status['text'] = $conv_quoted['text'];
2414 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2416 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2417 } catch (BadRequestException $e) {
2418 // user not found. should be found?
2419 /// @todo check if the user should be always found
2420 $quoted_status["user"] = [];
2423 unset($quoted_status['friendica_author']);
2424 unset($quoted_status['friendica_owner']);
2425 unset($quoted_status['friendica_activities']);
2426 unset($quoted_status['friendica_private']);
2429 if (!empty($retweeted_item)) {
2430 $retweeted_status = $status;
2431 unset($retweeted_status['friendica_author']);
2432 unset($retweeted_status['friendica_owner']);
2433 unset($retweeted_status['friendica_activities']);
2434 unset($retweeted_status['friendica_private']);
2435 unset($retweeted_status['statusnet_conversation_id']);
2436 $status['user'] = $status['friendica_owner'];
2438 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2439 } catch (BadRequestException $e) {
2440 // user not found. should be found?
2441 /// @todo check if the user should be always found
2442 $retweeted_status["user"] = [];
2445 $rt_converted = api_convert_item($retweeted_item);
2447 $retweeted_status['text'] = $rt_converted["text"];
2448 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2449 $retweeted_status['friendica_html'] = $rt_converted["html"];
2450 $retweeted_status['created_at'] = DateTimeFormat::utc($retweeted_item['created'], DateTimeFormat::API);
2452 if (!empty($quoted_status)) {
2453 $retweeted_status['quoted_status'] = $quoted_status;
2456 $status['friendica_author'] = $retweeted_status['user'];
2457 $status['retweeted_status'] = $retweeted_status;
2458 } elseif (!empty($quoted_status)) {
2459 $root_status = api_convert_item($item);
2461 $status['text'] = $root_status["text"];
2462 $status['statusnet_html'] = $root_status["html"];
2463 $status['quoted_status'] = $quoted_status;
2466 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2467 unset($status["user"]["uid"]);
2468 unset($status["user"]["self"]);
2470 if ($item["coord"] != "") {
2471 $coords = explode(' ', $item["coord"]);
2472 if (count($coords) == 2) {
2473 if ($type == "json") {
2474 $status["geo"] = ['type' => 'Point',
2475 'coordinates' => [(float) $coords[0],
2476 (float) $coords[1]]];
2477 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2478 $status["georss:point"] = $item["coord"];
2487 * Returns all lists the user subscribes to.
2489 * @param string $type Return type (atom, rss, xml, json)
2491 * @return array|string
2492 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2494 function api_lists_list($type)
2497 /// @TODO $ret is not filled here?
2498 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2501 /// @TODO move to top of file or somewhere better
2502 api_register_func('api/lists/list', 'api_lists_list', true);
2503 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2506 * Returns all groups the user owns.
2508 * @param string $type Return type (atom, rss, xml, json)
2510 * @return array|string
2511 * @throws BadRequestException
2512 * @throws ForbiddenException
2513 * @throws ImagickException
2514 * @throws InternalServerErrorException
2515 * @throws UnauthorizedException
2516 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2518 function api_lists_ownerships($type)
2520 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2523 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2524 $uid = $user_info['uid'];
2526 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2528 // loop through all groups
2530 foreach ($groups as $group) {
2531 if ($group['visible']) {
2537 'name' => $group['name'],
2538 'id' => intval($group['id']),
2539 'id_str' => (string) $group['id'],
2540 'user' => $user_info,
2544 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2547 /// @TODO move to top of file or somewhere better
2548 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2551 * Returns recent statuses from users in the specified group.
2553 * @param string $type Return type (atom, rss, xml, json)
2555 * @return array|string
2556 * @throws BadRequestException
2557 * @throws ForbiddenException
2558 * @throws ImagickException
2559 * @throws InternalServerErrorException
2560 * @throws UnauthorizedException
2561 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2563 function api_lists_statuses($type)
2565 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2567 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2569 unset($_REQUEST['user_id']);
2570 unset($_GET['user_id']);
2572 unset($_REQUEST['screen_name']);
2573 unset($_GET['screen_name']);
2575 if (empty($_REQUEST['list_id'])) {
2576 throw new BadRequestException('list_id not specified');
2580 $count = $_REQUEST['count'] ?? 20;
2581 $page = $_REQUEST['page'] ?? 1;
2582 $since_id = $_REQUEST['since_id'] ?? 0;
2583 $max_id = $_REQUEST['max_id'] ?? 0;
2584 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2585 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2587 $start = max(0, ($page - 1) * $count);
2589 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2590 $gids = array_column($groups, 'contact-id');
2591 $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2592 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2595 $condition[0] .= " AND `id` <= ?";
2596 $condition[] = $max_id;
2598 if ($exclude_replies > 0) {
2599 $condition[0] .= ' AND `gravity` = ?';
2600 $condition[] = GRAVITY_PARENT;
2602 if ($conversation_id > 0) {
2603 $condition[0] .= " AND `parent` = ?";
2604 $condition[] = $conversation_id;
2607 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2608 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2610 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2612 $data = ['status' => $items];
2617 $data = api_rss_extra($data, $user_info);
2621 return DI::apiResponse()->formatData("statuses", $type, $data);
2624 /// @TODO move to top of file or somewhere better
2625 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2628 * Returns either the friends of the follower list
2630 * Considers friends and followers lists to be private and won't return
2631 * anything if any user_id parameter is passed.
2633 * @param string $qtype Either "friends" or "followers"
2634 * @return boolean|array
2635 * @throws BadRequestException
2636 * @throws ForbiddenException
2637 * @throws ImagickException
2638 * @throws InternalServerErrorException
2639 * @throws UnauthorizedException
2641 function api_statuses_f($qtype)
2643 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2646 $count = $_GET['count'] ?? 20;
2647 $page = $_GET['page'] ?? 1;
2649 $start = max(0, ($page - 1) * $count);
2651 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2653 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2654 /* this is to stop Hotot to load friends multiple times
2655 * I'm not sure if I'm missing return something or
2656 * is a bug in hotot. Workaround, meantime
2660 return array('$users' => $ret);*/
2665 if ($qtype == 'friends') {
2666 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2667 } elseif ($qtype == 'followers') {
2668 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2671 // friends and followers only for self
2672 if ($user_info['self'] == 0) {
2673 $sql_extra = " AND false ";
2676 if ($qtype == 'blocks') {
2677 $sql_filter = 'AND `blocked` AND NOT `pending`';
2678 } elseif ($qtype == 'incoming') {
2679 $sql_filter = 'AND `pending`';
2681 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2684 // @todo This query most likely can be replaced with a Contact::select...
2685 $r = DBA::toArray(DBA::p(
2694 BaseApi::getCurrentUserID(),
2700 foreach ($r as $cid) {
2701 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2702 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2703 unset($user["uid"]);
2704 unset($user["self"]);
2711 return ['user' => $ret];
2716 * Returns the list of friends of the provided user
2718 * @deprecated By Twitter API in favor of friends/list
2720 * @param string $type Either "json" or "xml"
2721 * @return boolean|string|array
2722 * @throws BadRequestException
2723 * @throws ForbiddenException
2725 function api_statuses_friends($type)
2727 $data = api_statuses_f("friends");
2728 if ($data === false) {
2731 return DI::apiResponse()->formatData("users", $type, $data);
2735 * Returns the list of followers of the provided user
2737 * @deprecated By Twitter API in favor of friends/list
2739 * @param string $type Either "json" or "xml"
2740 * @return boolean|string|array
2741 * @throws BadRequestException
2742 * @throws ForbiddenException
2744 function api_statuses_followers($type)
2746 $data = api_statuses_f("followers");
2747 if ($data === false) {
2750 return DI::apiResponse()->formatData("users", $type, $data);
2753 /// @TODO move to top of file or somewhere better
2754 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2755 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2758 * Returns the list of blocked users
2760 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2762 * @param string $type Either "json" or "xml"
2764 * @return boolean|string|array
2765 * @throws BadRequestException
2766 * @throws ForbiddenException
2768 function api_blocks_list($type)
2770 $data = api_statuses_f('blocks');
2771 if ($data === false) {
2774 return DI::apiResponse()->formatData("users", $type, $data);
2777 /// @TODO move to top of file or somewhere better
2778 api_register_func('api/blocks/list', 'api_blocks_list', true);
2781 * Returns the list of pending users IDs
2783 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2785 * @param string $type Either "json" or "xml"
2787 * @return boolean|string|array
2788 * @throws BadRequestException
2789 * @throws ForbiddenException
2791 function api_friendships_incoming($type)
2793 $data = api_statuses_f('incoming');
2794 if ($data === false) {
2799 foreach ($data['user'] as $user) {
2800 $ids[] = $user['id'];
2803 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
2806 /// @TODO move to top of file or somewhere better
2807 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
2810 * Sends a new direct message.
2812 * @param string $type Return type (atom, rss, xml, json)
2814 * @return array|string
2815 * @throws BadRequestException
2816 * @throws ForbiddenException
2817 * @throws ImagickException
2818 * @throws InternalServerErrorException
2819 * @throws NotFoundException
2820 * @throws UnauthorizedException
2821 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
2823 function api_direct_messages_new($type)
2825 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2827 $uid = BaseApi::getCurrentUserID();
2829 if (empty($_POST["text"]) || empty($_POST['screen_name']) && empty($_POST['user_id'])) {
2833 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
2836 if (!empty($_POST['screen_name'])) {
2837 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
2838 if (DBA::isResult($contacts)) {
2839 // Selecting the id by priority, friendica first
2840 api_best_nickname($contacts);
2842 $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
2845 $cid = BaseApi::getContactIDForSearchterm($_POST['user_id']);
2847 $recipient = DI::twitterUser()->createFromContactId($cid, $uid)->toArray();
2851 if (empty($recipient)) {
2852 throw new NotFoundException('Recipient not found');
2856 if (!empty($_REQUEST['replyto'])) {
2857 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
2858 $replyto = $mail['parent-uri'];
2859 $sub = $mail['title'];
2861 if (!empty($_REQUEST['title'])) {
2862 $sub = $_REQUEST['title'];
2864 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
2868 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
2871 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
2872 $ret = api_format_messages($mail, $recipient, $sender);
2874 $ret = ["error" => $id];
2877 $data = ['direct_message'=>$ret];
2883 $data = api_rss_extra($data, $sender);
2887 return DI::apiResponse()->formatData("direct-messages", $type, $data);
2890 /// @TODO move to top of file or somewhere better
2891 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
2894 * delete a direct_message from mail table through api
2896 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2897 * @return string|array
2898 * @throws BadRequestException
2899 * @throws ForbiddenException
2900 * @throws ImagickException
2901 * @throws InternalServerErrorException
2902 * @throws UnauthorizedException
2903 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
2905 function api_direct_messages_destroy($type)
2907 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2910 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2912 $id = $_REQUEST['id'] ?? 0;
2914 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
2915 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
2916 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2918 $uid = $user_info['uid'];
2919 // error if no id or parenturi specified (for clients posting parent-uri as well)
2920 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
2921 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
2922 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2925 // BadRequestException if no id specified (for clients using Twitter API)
2927 throw new BadRequestException('Message id not specified');
2930 // add parent-uri to sql command if specified by calling app
2931 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
2933 // error message if specified id is not in database
2934 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
2935 if ($verbose == "true") {
2936 $answer = ['result' => 'error', 'message' => 'message id not in database'];
2937 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2939 /// @todo BadRequestException ok for Twitter API clients?
2940 throw new BadRequestException('message id not in database');
2944 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
2946 if ($verbose == "true") {
2949 $answer = ['result' => 'ok', 'message' => 'message deleted'];
2950 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
2952 $answer = ['result' => 'error', 'message' => 'unknown error'];
2953 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
2956 /// @todo return JSON data like Twitter API not yet implemented
2959 /// @TODO move to top of file or somewhere better
2960 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2965 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2966 * @return string|array
2967 * @throws HTTPException\BadRequestException
2968 * @throws HTTPException\ExpectationFailedException
2969 * @throws HTTPException\ForbiddenException
2970 * @throws HTTPException\InternalServerErrorException
2971 * @throws HTTPException\NotFoundException
2972 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
2974 function api_friendships_destroy($type)
2976 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
2977 $uid = BaseApi::getCurrentUserID();
2979 $owner = User::getOwnerDataById($uid);
2981 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
2982 throw new HTTPException\NotFoundException('Error Processing Request');
2985 $contact_id = $_REQUEST['user_id'] ?? 0;
2987 if (empty($contact_id)) {
2988 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
2989 throw new HTTPException\BadRequestException('no user_id specified');
2992 // Get Contact by given id
2993 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
2995 if(!DBA::isResult($contact)) {
2996 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
2997 throw new HTTPException\NotFoundException('no contact found to given ID');
3000 $url = $contact['url'];
3002 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3003 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3004 Strings::normaliseLink($url), $url];
3005 $contact = DBA::selectFirst('contact', [], $condition);
3007 if (!DBA::isResult($contact)) {
3008 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3009 throw new HTTPException\NotFoundException('Not following Contact');
3013 $result = Contact::terminateFriendship($owner, $contact);
3015 if ($result === null) {
3016 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3017 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3020 if ($result === false) {
3021 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3023 } catch (Exception $e) {
3024 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3025 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3028 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3029 unset($contact['uid']);
3030 unset($contact['self']);
3032 // Set screen_name since Twidere requests it
3033 $contact['screen_name'] = $contact['nick'];
3035 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3038 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3042 * @param string $type Return type (atom, rss, xml, json)
3043 * @param string $box
3044 * @param string $verbose
3046 * @return array|string
3047 * @throws BadRequestException
3048 * @throws ForbiddenException
3049 * @throws ImagickException
3050 * @throws InternalServerErrorException
3051 * @throws UnauthorizedException
3053 function api_direct_messages_box($type, $box, $verbose)
3055 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3058 $count = $_GET['count'] ?? 20;
3059 $page = $_REQUEST['page'] ?? 1;
3061 $since_id = $_REQUEST['since_id'] ?? 0;
3062 $max_id = $_REQUEST['max_id'] ?? 0;
3064 $user_id = $_REQUEST['user_id'] ?? '';
3065 $screen_name = $_REQUEST['screen_name'] ?? '';
3068 unset($_REQUEST['user_id']);
3069 unset($_GET['user_id']);
3071 unset($_REQUEST['screen_name']);
3072 unset($_GET['screen_name']);
3074 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3076 $profile_url = $user_info["url"];
3079 $start = max(0, ($page - 1) * $count);
3084 if ($box=="sentbox") {
3085 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3086 } elseif ($box == "conversation") {
3087 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3088 } elseif ($box == "all") {
3089 $sql_extra = "true";
3090 } elseif ($box == "inbox") {
3091 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3095 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3098 if ($user_id != "") {
3099 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3100 } elseif ($screen_name !="") {
3101 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3104 $r = DBA::toArray(DBA::p(
3105 "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 ?,?",
3106 BaseApi::getCurrentUserID(),
3111 if ($verbose == "true" && !DBA::isResult($r)) {
3112 $answer = ['result' => 'error', 'message' => 'no mails available'];
3113 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3117 foreach ($r as $item) {
3118 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3119 $recipient = $user_info;
3120 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3121 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3122 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3123 $sender = $user_info;
3126 if (isset($recipient) && isset($sender)) {
3127 $ret[] = api_format_messages($item, $recipient, $sender);
3132 $data = ['direct_message' => $ret];
3137 $data = api_rss_extra($data, $user_info);
3141 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3145 * Returns the most recent direct messages sent by the user.
3147 * @param string $type Return type (atom, rss, xml, json)
3149 * @return array|string
3150 * @throws BadRequestException
3151 * @throws ForbiddenException
3152 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3154 function api_direct_messages_sentbox($type)
3156 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3157 return api_direct_messages_box($type, "sentbox", $verbose);
3161 * Returns the most recent direct messages sent to the user.
3163 * @param string $type Return type (atom, rss, xml, json)
3165 * @return array|string
3166 * @throws BadRequestException
3167 * @throws ForbiddenException
3168 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3170 function api_direct_messages_inbox($type)
3172 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3173 return api_direct_messages_box($type, "inbox", $verbose);
3178 * @param string $type Return type (atom, rss, xml, json)
3180 * @return array|string
3181 * @throws BadRequestException
3182 * @throws ForbiddenException
3184 function api_direct_messages_all($type)
3186 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3187 return api_direct_messages_box($type, "all", $verbose);
3192 * @param string $type Return type (atom, rss, xml, json)
3194 * @return array|string
3195 * @throws BadRequestException
3196 * @throws ForbiddenException
3198 function api_direct_messages_conversation($type)
3200 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3201 return api_direct_messages_box($type, "conversation", $verbose);
3204 /// @TODO move to top of file or somewhere better
3205 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3206 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3207 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3208 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3211 * list all photos of the authenticated user
3213 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3214 * @return string|array
3215 * @throws ForbiddenException
3216 * @throws InternalServerErrorException
3218 function api_fr_photos_list($type)
3220 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3222 $r = DBA::toArray(DBA::p(
3223 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3224 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3225 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3226 BaseApi::getCurrentUserID(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3229 'image/jpeg' => 'jpg',
3230 'image/png' => 'png',
3231 'image/gif' => 'gif'
3233 $data = ['photo'=>[]];
3234 if (DBA::isResult($r)) {
3235 foreach ($r as $rr) {
3237 $photo['id'] = $rr['resource-id'];
3238 $photo['album'] = $rr['album'];
3239 $photo['filename'] = $rr['filename'];
3240 $photo['type'] = $rr['type'];
3241 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3242 $photo['created'] = $rr['created'];
3243 $photo['edited'] = $rr['edited'];
3244 $photo['desc'] = $rr['desc'];
3246 if ($type == "xml") {
3247 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3249 $photo['thumb'] = $thumb;
3250 $data['photo'][] = $photo;
3254 return DI::apiResponse()->formatData("photos", $type, $data);
3258 * upload a new photo or change an existing photo
3260 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3261 * @return string|array
3262 * @throws BadRequestException
3263 * @throws ForbiddenException
3264 * @throws ImagickException
3265 * @throws InternalServerErrorException
3266 * @throws NotFoundException
3268 function api_fr_photo_create_update($type)
3270 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3273 $photo_id = $_REQUEST['photo_id'] ?? null;
3274 $desc = $_REQUEST['desc'] ?? null;
3275 $album = $_REQUEST['album'] ?? null;
3276 $album_new = $_REQUEST['album_new'] ?? null;
3277 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3278 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3279 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3280 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3281 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3283 // do several checks on input parameters
3284 // we do not allow calls without album string
3285 if ($album == null) {
3286 throw new BadRequestException("no albumname specified");
3288 // if photo_id == null --> we are uploading a new photo
3289 if ($photo_id == null) {
3292 // error if no media posted in create-mode
3293 if (empty($_FILES['media'])) {
3295 throw new BadRequestException("no media data submitted");
3298 // album_new will be ignored in create-mode
3303 // check if photo is existing in databasei
3304 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3305 throw new BadRequestException("photo not available");
3309 // checks on acl strings provided by clients
3310 $acl_input_error = false;
3311 $acl_input_error |= check_acl_input($allow_cid);
3312 $acl_input_error |= check_acl_input($deny_cid);
3313 $acl_input_error |= check_acl_input($allow_gid);
3314 $acl_input_error |= check_acl_input($deny_gid);
3315 if ($acl_input_error) {
3316 throw new BadRequestException("acl data invalid");
3318 // now let's upload the new media in create-mode
3319 if ($mode == "create") {
3320 $media = $_FILES['media'];
3321 $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);
3323 // return success of updating or error message
3324 if (!is_null($data)) {
3325 return DI::apiResponse()->formatData("photo_create", $type, $data);
3327 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3331 // now let's do the changes in update-mode
3332 if ($mode == "update") {
3333 $updated_fields = [];
3335 if (!is_null($desc)) {
3336 $updated_fields['desc'] = $desc;
3339 if (!is_null($album_new)) {
3340 $updated_fields['album'] = $album_new;
3343 if (!is_null($allow_cid)) {
3344 $allow_cid = trim($allow_cid);
3345 $updated_fields['allow_cid'] = $allow_cid;
3348 if (!is_null($deny_cid)) {
3349 $deny_cid = trim($deny_cid);
3350 $updated_fields['deny_cid'] = $deny_cid;
3353 if (!is_null($allow_gid)) {
3354 $allow_gid = trim($allow_gid);
3355 $updated_fields['allow_gid'] = $allow_gid;
3358 if (!is_null($deny_gid)) {
3359 $deny_gid = trim($deny_gid);
3360 $updated_fields['deny_gid'] = $deny_gid;
3364 if (count($updated_fields) > 0) {
3365 $nothingtodo = false;
3366 $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3368 $nothingtodo = true;
3371 if (!empty($_FILES['media'])) {
3372 $nothingtodo = false;
3373 $media = $_FILES['media'];
3374 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3375 if (!is_null($data)) {
3376 return DI::apiResponse()->formatData("photo_update", $type, $data);
3380 // return success of updating or error message
3382 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3383 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3386 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3387 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3389 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3392 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3396 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3398 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3399 * @return string|array
3400 * @throws BadRequestException
3401 * @throws ForbiddenException
3402 * @throws InternalServerErrorException
3403 * @throws NotFoundException
3405 function api_fr_photo_detail($type)
3407 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3409 if (empty($_REQUEST['photo_id'])) {
3410 throw new BadRequestException("No photo id.");
3413 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3414 $photo_id = $_REQUEST['photo_id'];
3416 // prepare json/xml output with data from database for the requested photo
3417 $data = prepare_photo_data($type, $scale, $photo_id);
3419 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3424 * updates the profile image for the user (either a specified profile or the default profile)
3426 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3428 * @return string|array
3429 * @throws BadRequestException
3430 * @throws ForbiddenException
3431 * @throws ImagickException
3432 * @throws InternalServerErrorException
3433 * @throws NotFoundException
3434 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3436 function api_account_update_profile_image($type)
3438 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3441 $profile_id = $_REQUEST['profile_id'] ?? 0;
3443 // error if image data is missing
3444 if (empty($_FILES['image'])) {
3445 throw new BadRequestException("no media data submitted");
3448 // check if specified profile id is valid
3449 if ($profile_id != 0) {
3450 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3451 // error message if specified profile id is not in database
3452 if (!DBA::isResult($profile)) {
3453 throw new BadRequestException("profile_id not available");
3455 $is_default_profile = $profile['is-default'];
3457 $is_default_profile = 1;
3460 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3462 if (!empty($_FILES['image'])) {
3463 $media = $_FILES['image'];
3464 } elseif (!empty($_FILES['media'])) {
3465 $media = $_FILES['media'];
3467 // save new profile image
3468 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3471 if (is_array($media['type'])) {
3472 $filetype = $media['type'][0];
3474 $filetype = $media['type'];
3476 if ($filetype == "image/jpeg") {
3478 } elseif ($filetype == "image/png") {
3481 throw new InternalServerErrorException('Unsupported filetype');
3484 // change specified profile or all profiles to the new resource-id
3485 if ($is_default_profile) {
3486 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3487 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3489 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3490 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3491 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3494 Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3496 // Update global directory in background
3497 Profile::publishUpdate(BaseApi::getCurrentUserID());
3499 // output for client
3501 return api_account_verify_credentials($type);
3503 // SaveMediaToDatabase failed for some reason
3504 throw new InternalServerErrorException("image upload failed");
3508 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3509 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3510 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3511 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3512 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3513 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3516 * Update user profile
3518 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3520 * @return array|string
3521 * @throws BadRequestException
3522 * @throws ForbiddenException
3523 * @throws ImagickException
3524 * @throws InternalServerErrorException
3525 * @throws UnauthorizedException
3527 function api_account_update_profile($type)
3529 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3531 $local_user = BaseApi::getCurrentUserID();
3533 $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3535 if (!empty($_POST['name'])) {
3536 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3537 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3538 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3539 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3542 if (isset($_POST['description'])) {
3543 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3544 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3545 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3548 Profile::publishUpdate($local_user);
3550 return api_account_verify_credentials($type);
3553 /// @TODO move to top of file or somewhere better
3554 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3558 * @param string $acl_string
3562 function check_acl_input($acl_string)
3564 if (empty($acl_string)) {
3568 $contact_not_found = false;
3570 // split <x><y><z> into array of cid's
3571 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3573 // check for each cid if it is available on server
3574 $cid_array = $array[0];
3575 foreach ($cid_array as $cid) {
3576 $cid = str_replace("<", "", $cid);
3577 $cid = str_replace(">", "", $cid);
3578 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3579 $contact_not_found |= !DBA::exists('contact', $condition);
3581 return $contact_not_found;
3585 * @param string $mediatype
3586 * @param array $media
3587 * @param string $type
3588 * @param string $album
3589 * @param string $allow_cid
3590 * @param string $deny_cid
3591 * @param string $allow_gid
3592 * @param string $deny_gid
3593 * @param string $desc
3594 * @param integer $phototype
3595 * @param boolean $visibility
3596 * @param string $photo_id
3598 * @throws BadRequestException
3599 * @throws ForbiddenException
3600 * @throws ImagickException
3601 * @throws InternalServerErrorException
3602 * @throws NotFoundException
3603 * @throws UnauthorizedException
3605 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)
3613 if (is_array($media)) {
3614 if (is_array($media['tmp_name'])) {
3615 $src = $media['tmp_name'][0];
3617 $src = $media['tmp_name'];
3619 if (is_array($media['name'])) {
3620 $filename = basename($media['name'][0]);
3622 $filename = basename($media['name']);
3624 if (is_array($media['size'])) {
3625 $filesize = intval($media['size'][0]);
3627 $filesize = intval($media['size']);
3629 if (is_array($media['type'])) {
3630 $filetype = $media['type'][0];
3632 $filetype = $media['type'];
3636 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3639 "File upload src: " . $src . " - filename: " . $filename .
3640 " - size: " . $filesize . " - type: " . $filetype);
3642 // check if there was a php upload error
3643 if ($filesize == 0 && $media['error'] == 1) {
3644 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3646 // check against max upload size within Friendica instance
3647 $maximagesize = DI::config()->get('system', 'maximagesize');
3648 if ($maximagesize && ($filesize > $maximagesize)) {
3649 $formattedBytes = Strings::formatBytes($maximagesize);
3650 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3653 // create Photo instance with the data of the image
3654 $imagedata = @file_get_contents($src);
3655 $Image = new Image($imagedata, $filetype);
3656 if (!$Image->isValid()) {
3657 throw new InternalServerErrorException("unable to process image data");
3660 // check orientation of image
3661 $Image->orient($src);
3664 // check max length of images on server
3665 $max_length = DI::config()->get('system', 'max_image_length');
3666 if ($max_length > 0) {
3667 $Image->scaleDown($max_length);
3668 logger::info("File upload: Scaling picture to new size " . $max_length);
3670 $width = $Image->getWidth();
3671 $height = $Image->getHeight();
3673 // create a new resource-id if not already provided
3674 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3676 if ($mediatype == "photo") {
3677 // upload normal image (scales 0, 1, 2)
3678 logger::info("photo upload: starting new photo upload");
3680 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3682 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3684 if ($width > 640 || $height > 640) {
3685 $Image->scaleDown(640);
3686 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3688 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3692 if ($width > 320 || $height > 320) {
3693 $Image->scaleDown(320);
3694 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3696 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3699 logger::info("photo upload: new photo upload ended");
3700 } elseif ($mediatype == "profileimage") {
3701 // upload profile image (scales 4, 5, 6)
3702 logger::info("photo upload: starting new profile image upload");
3704 if ($width > 300 || $height > 300) {
3705 $Image->scaleDown(300);
3706 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3708 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3712 if ($width > 80 || $height > 80) {
3713 $Image->scaleDown(80);
3714 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3716 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3720 if ($width > 48 || $height > 48) {
3721 $Image->scaleDown(48);
3722 $r = Photo::store($Image, BaseApi::getCurrentUserID(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3724 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3727 $Image->__destruct();
3728 logger::info("photo upload: new profile image upload ended");
3732 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3733 if ($photo_id == null && $mediatype == "photo") {
3734 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3736 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3737 return prepare_photo_data($type, false, $resource_id);
3739 throw new InternalServerErrorException("image upload failed");
3745 * @param string $hash
3746 * @param string $allow_cid
3747 * @param string $deny_cid
3748 * @param string $allow_gid
3749 * @param string $deny_gid
3750 * @param string $filetype
3751 * @param boolean $visibility
3752 * @throws InternalServerErrorException
3754 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
3756 // get data about the api authenticated user
3757 $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
3758 $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
3761 $arr['guid'] = System::createUUID();
3762 $arr['uid'] = intval(BaseApi::getCurrentUserID());
3764 $arr['type'] = 'photo';
3766 $arr['resource-id'] = $hash;
3767 $arr['contact-id'] = $owner_record['id'];
3768 $arr['owner-name'] = $owner_record['name'];
3769 $arr['owner-link'] = $owner_record['url'];
3770 $arr['owner-avatar'] = $owner_record['thumb'];
3771 $arr['author-name'] = $owner_record['name'];
3772 $arr['author-link'] = $owner_record['url'];
3773 $arr['author-avatar'] = $owner_record['thumb'];
3775 $arr['allow_cid'] = $allow_cid;
3776 $arr['allow_gid'] = $allow_gid;
3777 $arr['deny_cid'] = $deny_cid;
3778 $arr['deny_gid'] = $deny_gid;
3779 $arr['visible'] = $visibility;
3783 'image/jpeg' => 'jpg',
3784 'image/png' => 'png',
3785 'image/gif' => 'gif'
3788 // adds link to the thumbnail scale photo
3789 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
3790 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
3793 // do the magic for storing the item in the database and trigger the federation to other contacts
3799 * @param string $type
3801 * @param string $photo_id
3804 * @throws BadRequestException
3805 * @throws ForbiddenException
3806 * @throws ImagickException
3807 * @throws InternalServerErrorException
3808 * @throws NotFoundException
3809 * @throws UnauthorizedException
3811 function prepare_photo_data($type, $scale, $photo_id)
3813 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3815 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3817 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
3818 $data_sql = ($scale === false ? "" : "data, ");
3820 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
3821 // clients needs to convert this in their way for further processing
3822 $r = DBA::toArray(DBA::p(
3823 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3824 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
3825 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
3826 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
3827 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3828 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
3829 BaseApi::getCurrentUserID(),
3834 'image/jpeg' => 'jpg',
3835 'image/png' => 'png',
3836 'image/gif' => 'gif'
3839 // prepare output data for photo
3840 if (DBA::isResult($r)) {
3841 $data = ['photo' => $r[0]];
3842 $data['photo']['id'] = $data['photo']['resource-id'];
3843 if ($scale !== false) {
3844 $data['photo']['data'] = base64_encode($data['photo']['data']);
3846 unset($data['photo']['datasize']); //needed only with scale param
3848 if ($type == "xml") {
3849 $data['photo']['links'] = [];
3850 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3851 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
3853 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
3856 $data['photo']['link'] = [];
3857 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
3859 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
3860 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
3864 unset($data['photo']['resource-id']);
3865 unset($data['photo']['minscale']);
3866 unset($data['photo']['maxscale']);
3868 throw new NotFoundException();
3871 // retrieve item element for getting activities (like, dislike etc.) related to photo
3872 $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
3873 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
3874 if (!DBA::isResult($item)) {
3875 throw new NotFoundException('Photo-related item not found.');
3878 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
3880 // retrieve comments on photo
3881 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
3882 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
3884 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
3886 // prepare output of comments
3887 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
3889 if ($type == "xml") {
3891 foreach ($commentData as $comment) {
3892 $comments[$k++ . ":comment"] = $comment;
3895 foreach ($commentData as $comment) {
3896 $comments[] = $comment;
3899 $data['photo']['friendica_comments'] = $comments;
3901 // include info if rights on photo and rights on item are mismatching
3902 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
3903 $data['photo']['deny_cid'] != $item['deny_cid'] ||
3904 $data['photo']['allow_gid'] != $item['allow_gid'] ||
3905 $data['photo']['deny_gid'] != $item['deny_gid'];
3906 $data['photo']['rights_mismatch'] = $rights_mismatch;
3912 * Return an item with announcer data if it had been announced
3914 * @param array $item Item array
3915 * @return array Item array with announce data
3917 function api_get_announce($item)
3919 // Quit if the item already has got a different owner and author
3920 if ($item['owner-id'] != $item['author-id']) {
3924 // Don't change original or Diaspora posts
3925 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
3929 // Quit if we do now the original author and it had been a post from a native network
3930 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
3934 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
3935 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
3936 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
3937 if (!DBA::isResult($announce)) {
3941 return array_merge($item, $announce);
3946 * @param array $item
3951 function api_in_reply_to($item)
3955 $in_reply_to['status_id'] = null;
3956 $in_reply_to['user_id'] = null;
3957 $in_reply_to['status_id_str'] = null;
3958 $in_reply_to['user_id_str'] = null;
3959 $in_reply_to['screen_name'] = null;
3961 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
3962 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
3963 if (DBA::isResult($parent)) {
3964 $in_reply_to['status_id'] = intval($parent['id']);
3966 $in_reply_to['status_id'] = intval($item['parent']);
3969 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3971 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
3972 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
3974 if (DBA::isResult($parent)) {
3975 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
3976 $in_reply_to['user_id'] = intval($parent['author-id']);
3977 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
3980 // There seems to be situation, where both fields are identical:
3981 // https://github.com/friendica/friendica/issues/1010
3982 // This is a bugfix for that.
3983 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3984 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']]);
3985 $in_reply_to['status_id'] = null;
3986 $in_reply_to['user_id'] = null;
3987 $in_reply_to['status_id_str'] = null;
3988 $in_reply_to['user_id_str'] = null;
3989 $in_reply_to['screen_name'] = null;
3993 return $in_reply_to;
3998 * @param string $text
4001 * @throws InternalServerErrorException
4003 function api_clean_plain_items($text)
4005 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4007 $text = BBCode::cleanPictureLinks($text);
4008 $URLSearchString = "^\[\]";
4010 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4012 if ($include_entities == "true") {
4013 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4016 // Simplify "attachment" element
4017 $text = BBCode::removeAttachment($text);
4024 * @param array $contacts
4028 function api_best_nickname(&$contacts)
4032 if (count($contacts) == 0) {
4036 foreach ($contacts as $contact) {
4037 if ($contact["network"] == "") {
4038 $contact["network"] = "dfrn";
4039 $best_contact = [$contact];
4043 if (sizeof($best_contact) == 0) {
4044 foreach ($contacts as $contact) {
4045 if ($contact["network"] == "dfrn") {
4046 $best_contact = [$contact];
4051 if (sizeof($best_contact) == 0) {
4052 foreach ($contacts as $contact) {
4053 if ($contact["network"] == "dspr") {
4054 $best_contact = [$contact];
4059 if (sizeof($best_contact) == 0) {
4060 foreach ($contacts as $contact) {
4061 if ($contact["network"] == "stat") {
4062 $best_contact = [$contact];
4067 if (sizeof($best_contact) == 0) {
4068 foreach ($contacts as $contact) {
4069 if ($contact["network"] == "pump") {
4070 $best_contact = [$contact];
4075 if (sizeof($best_contact) == 0) {
4076 foreach ($contacts as $contact) {
4077 if ($contact["network"] == "twit") {
4078 $best_contact = [$contact];
4083 if (sizeof($best_contact) == 1) {
4084 $contacts = $best_contact;
4086 $contacts = [$contacts[0]];
4091 * Return all or a specified group of the user with the containing contacts.
4093 * @param string $type Return type (atom, rss, xml, json)
4095 * @return array|string
4096 * @throws BadRequestException
4097 * @throws ForbiddenException
4098 * @throws ImagickException
4099 * @throws InternalServerErrorException
4100 * @throws UnauthorizedException
4102 function api_friendica_group_show($type)
4104 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4107 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4108 $gid = $_REQUEST['gid'] ?? 0;
4109 $uid = $user_info['uid'];
4111 // get data of the specified group id or all groups if not specified
4113 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4115 // error message if specified gid is not in database
4116 if (!DBA::isResult($groups)) {
4117 throw new BadRequestException("gid not available");
4120 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4123 // loop through all groups and retrieve all members for adding data in the user array
4125 foreach ($groups as $rr) {
4126 $members = Contact\Group::getById($rr['id']);
4129 if ($type == "xml") {
4130 $user_element = "users";
4132 foreach ($members as $member) {
4133 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4134 $users[$k++.":user"] = $user;
4137 $user_element = "user";
4138 foreach ($members as $member) {
4139 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4143 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4145 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4148 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4153 * @param string $type Return type (atom, rss, xml, json)
4155 * @return array|string
4156 * @throws BadRequestException
4157 * @throws ForbiddenException
4158 * @throws ImagickException
4159 * @throws InternalServerErrorException
4160 * @throws UnauthorizedException
4161 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4163 function api_lists_destroy($type)
4165 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4168 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4169 $gid = $_REQUEST['list_id'] ?? 0;
4170 $uid = $user_info['uid'];
4172 // error if no gid specified
4174 throw new BadRequestException('gid not specified');
4177 // get data of the specified group id
4178 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4179 // error message if specified gid is not in database
4181 throw new BadRequestException('gid not available');
4184 if (Group::remove($gid)) {
4186 'name' => $group['name'],
4187 'id' => intval($gid),
4188 'id_str' => (string) $gid,
4189 'user' => $user_info
4192 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4196 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4199 * Add a new group to the database.
4201 * @param string $name Group name
4202 * @param int $uid User ID
4203 * @param array $users List of users to add to the group
4206 * @throws BadRequestException
4208 function group_create($name, $uid, $users = [])
4210 // error if no name specified
4212 throw new BadRequestException('group name not specified');
4215 // error message if specified group name already exists
4216 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4217 throw new BadRequestException('group name already exists');
4220 // Check if the group needs to be reactivated
4221 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4222 $reactivate_group = true;
4226 $ret = Group::create($uid, $name);
4228 $gid = Group::getIdByName($uid, $name);
4230 throw new BadRequestException('other API error');
4234 $erroraddinguser = false;
4236 foreach ($users as $user) {
4237 $cid = $user['cid'];
4238 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4239 Group::addMember($gid, $cid);
4241 $erroraddinguser = true;
4242 $errorusers[] = $cid;
4246 // return success message incl. missing users in array
4247 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4249 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4253 * Create the specified group with the posted array of contacts.
4255 * @param string $type Return type (atom, rss, xml, json)
4257 * @return array|string
4258 * @throws BadRequestException
4259 * @throws ForbiddenException
4260 * @throws ImagickException
4261 * @throws InternalServerErrorException
4262 * @throws UnauthorizedException
4264 function api_friendica_group_create($type)
4266 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4269 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4270 $name = $_REQUEST['name'] ?? '';
4271 $uid = $user_info['uid'];
4272 $json = json_decode($_POST['json'], true);
4273 $users = $json['user'];
4275 $success = group_create($name, $uid, $users);
4277 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4280 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4283 * Create a new group.
4285 * @param string $type Return type (atom, rss, xml, json)
4287 * @return array|string
4288 * @throws BadRequestException
4289 * @throws ForbiddenException
4290 * @throws ImagickException
4291 * @throws InternalServerErrorException
4292 * @throws UnauthorizedException
4293 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4295 function api_lists_create($type)
4297 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4300 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4301 $name = $_REQUEST['name'] ?? '';
4302 $uid = $user_info['uid'];
4304 $success = group_create($name, $uid);
4305 if ($success['success']) {
4307 'name' => $success['name'],
4308 'id' => intval($success['gid']),
4309 'id_str' => (string) $success['gid'],
4310 'user' => $user_info
4313 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4317 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4320 * Update the specified group with the posted array of contacts.
4322 * @param string $type Return type (atom, rss, xml, json)
4324 * @return array|string
4325 * @throws BadRequestException
4326 * @throws ForbiddenException
4327 * @throws ImagickException
4328 * @throws InternalServerErrorException
4329 * @throws UnauthorizedException
4331 function api_friendica_group_update($type)
4333 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4336 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4337 $uid = $user_info['uid'];
4338 $gid = $_REQUEST['gid'] ?? 0;
4339 $name = $_REQUEST['name'] ?? '';
4340 $json = json_decode($_POST['json'], true);
4341 $users = $json['user'];
4343 // error if no name specified
4345 throw new BadRequestException('group name not specified');
4348 // error if no gid specified
4350 throw new BadRequestException('gid not specified');
4354 $members = Contact\Group::getById($gid);
4355 foreach ($members as $member) {
4356 $cid = $member['id'];
4357 foreach ($users as $user) {
4358 $found = ($user['cid'] == $cid ? true : false);
4360 if (!isset($found) || !$found) {
4361 $gid = Group::getIdByName($uid, $name);
4362 Group::removeMember($gid, $cid);
4367 $erroraddinguser = false;
4369 foreach ($users as $user) {
4370 $cid = $user['cid'];
4372 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4373 Group::addMember($gid, $cid);
4375 $erroraddinguser = true;
4376 $errorusers[] = $cid;
4380 // return success message incl. missing users in array
4381 $status = ($erroraddinguser ? "missing user" : "ok");
4382 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4383 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4386 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4389 * Update information about a group.
4391 * @param string $type Return type (atom, rss, xml, json)
4393 * @return array|string
4394 * @throws BadRequestException
4395 * @throws ForbiddenException
4396 * @throws ImagickException
4397 * @throws InternalServerErrorException
4398 * @throws UnauthorizedException
4399 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4401 function api_lists_update($type)
4403 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4406 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4407 $gid = $_REQUEST['list_id'] ?? 0;
4408 $name = $_REQUEST['name'] ?? '';
4409 $uid = $user_info['uid'];
4411 // error if no gid specified
4413 throw new BadRequestException('gid not specified');
4416 // get data of the specified group id
4417 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4418 // error message if specified gid is not in database
4420 throw new BadRequestException('gid not available');
4423 if (Group::update($gid, $name)) {
4426 'id' => intval($gid),
4427 'id_str' => (string) $gid,
4428 'user' => $user_info
4431 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4435 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4438 * Set notification as seen and returns associated item (if possible)
4440 * POST request with 'id' param as notification id
4442 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4443 * @return string|array
4444 * @throws BadRequestException
4445 * @throws ForbiddenException
4446 * @throws ImagickException
4447 * @throws InternalServerErrorException
4448 * @throws UnauthorizedException
4450 function api_friendica_notification_seen($type)
4452 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4454 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4456 if (DI::args()->getArgc() !== 4) {
4457 throw new BadRequestException('Invalid argument count');
4460 $id = intval($_REQUEST['id'] ?? 0);
4463 $Notify = DI::notify()->selectOneById($id);
4464 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4465 throw new NotFoundException();
4468 if ($Notify->uriId) {
4469 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4473 DI::notify()->save($Notify);
4475 if ($Notify->otype === Notification\ObjectType::ITEM) {
4476 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4477 if (DBA::isResult($item)) {
4478 // we found the item, return it to the user
4479 $ret = api_format_items([$item], $user_info, false, $type);
4480 $data = ['status' => $ret];
4481 return DI::apiResponse()->formatData('status', $type, $data);
4483 // the item can't be found, but we set the notification as seen, so we count this as a success
4486 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4487 } catch (NotFoundException $e) {
4488 throw new BadRequestException('Invalid argument', $e);
4489 } catch (Exception $e) {
4490 throw new InternalServerErrorException('Internal Server exception', $e);
4494 /// @TODO move to top of file or somewhere better
4495 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4498 * search for direct_messages containing a searchstring through api
4500 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4501 * @param string $box
4502 * @return string|array (success: success=true if found and search_result contains found messages,
4503 * success=false if nothing was found, search_result='nothing found',
4504 * error: result=error with error message)
4505 * @throws BadRequestException
4506 * @throws ForbiddenException
4507 * @throws ImagickException
4508 * @throws InternalServerErrorException
4509 * @throws UnauthorizedException
4511 function api_friendica_direct_messages_search($type, $box = "")
4513 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4516 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4517 $searchstring = $_REQUEST['searchstring'] ?? '';
4518 $uid = $user_info['uid'];
4520 // error if no searchstring specified
4521 if ($searchstring == "") {
4522 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4523 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4526 // get data for the specified searchstring
4527 $r = DBA::toArray(DBA::p(
4528 "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",
4530 '%'.$searchstring.'%'
4533 $profile_url = $user_info["url"];
4535 // message if nothing was found
4536 if (!DBA::isResult($r)) {
4537 $success = ['success' => false, 'search_results' => 'problem with query'];
4538 } elseif (count($r) == 0) {
4539 $success = ['success' => false, 'search_results' => 'nothing found'];
4542 foreach ($r as $item) {
4543 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4544 $recipient = $user_info;
4545 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4546 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4547 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4548 $sender = $user_info;
4551 if (isset($recipient) && isset($sender)) {
4552 $ret[] = api_format_messages($item, $recipient, $sender);
4555 $success = ['success' => true, 'search_results' => $ret];
4558 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4561 /// @TODO move to top of file or somewhere better
4562 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4565 * Number of comments
4567 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4569 * @param object $data [Status, Status]
4573 function bindComments(&$data)
4575 if (count($data) == 0) {
4581 foreach ($data as $item) {
4582 $ids[] = $item['id'];
4585 $idStr = DBA::escape(implode(', ', $ids));
4586 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4587 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4588 $itemsData = DBA::toArray($items);
4590 foreach ($itemsData as $item) {
4591 $comments[$item['parent']] = $item['comments'];
4594 foreach ($data as $idx => $item) {
4596 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4601 @TODO Maybe open to implement?
4603 [pagename] => api/1.1/statuses/lookup.json
4604 [id] => 605138389168451584
4605 [include_cards] => true
4606 [cards_platform] => Android-12
4607 [include_entities] => true
4608 [include_my_retweet] => 1
4610 [include_reply_count] => true
4611 [include_descendent_reply_count] => true
4615 Not implemented by now:
4616 statuses/retweets_of_me
4621 account/update_location
4622 account/update_profile_background_image
4625 friendica/profile/update
4626 friendica/profile/create
4627 friendica/profile/delete
4629 Not implemented in status.net:
4630 statuses/retweeted_to_me
4631 statuses/retweeted_by_me
4632 direct_messages/destroy
4634 account/update_delivery_device
4635 notifications/follow