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\Security\OAuth;
58 use Friendica\Util\DateTimeFormat;
59 use Friendica\Util\Images;
60 use Friendica\Util\Network;
61 use Friendica\Util\Strings;
63 require_once __DIR__ . '/../mod/item.php';
64 require_once __DIR__ . '/../mod/wall_upload.php';
66 define('API_METHOD_ANY', '*');
67 define('API_METHOD_GET', 'GET');
68 define('API_METHOD_POST', 'POST,PUT');
69 define('API_METHOD_DELETE', 'POST,DELETE');
71 define('API_LOG_PREFIX', 'API {action} - ');
77 * Get source name from API client
79 * Clients can send 'source' parameter to be show in post metadata
80 * as "sent via <source>".
81 * Some clients doesn't send a source param, we support ones we know
85 * Client source name, default to "api" if unset/unknown
90 if (requestdata('source')) {
91 return requestdata('source');
94 // Support for known clients that doesn't send a source name
95 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
96 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
100 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
102 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
109 * Format date for API
111 * @param string $str Source date, as UTC
112 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
115 function api_date($str)
117 // Wed May 23 06:01:13 +0000 2007
118 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
122 * Register a function to be the endpoint for defined API path.
124 * @param string $path API URL path, relative to DI::baseUrl()
125 * @param string $func Function name to call on path request
126 * @param bool $auth API need logged user
127 * @param string $method HTTP method reqiured to call this endpoint.
128 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
129 * Default to API_METHOD_ANY
131 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
141 // Workaround for hotot
142 $path = str_replace("api/", "api/1.1/", $path);
152 * Check HTTP method of called API
154 * API endpoints can define which HTTP method to accept when called.
155 * This function check the current HTTP method agains endpoint
158 * @param string $method Required methods, uppercase, separated by comma
161 function api_check_method($method)
163 if ($method == "*") {
166 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
170 * Main API entry point
172 * Authenticate user, call registered API function, set HTTP headers
175 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
176 * @return string|array API call result
179 function api_call(App $a, App\Arguments $args = null)
181 global $API, $called_api;
188 if (strpos($args->getCommand(), ".xml") > 0) {
191 if (strpos($args->getCommand(), ".json") > 0) {
194 if (strpos($args->getCommand(), ".rss") > 0) {
197 if (strpos($args->getCommand(), ".atom") > 0) {
202 foreach ($API as $p => $info) {
203 if (strpos($args->getCommand(), $p) === 0) {
204 if (!api_check_method($info['method'])) {
205 throw new MethodNotAllowedException();
208 $called_api = explode("/", $p);
210 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
211 BasicAuth::getCurrentUserID(true);
212 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
215 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
217 $stamp = microtime(true);
218 $return = call_user_func($info['func'], $type);
219 $duration = floatval(microtime(true) - $stamp);
221 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
223 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
225 if (false === $return) {
227 * api function returned false withour throw an
228 * exception. This should not happend, throw a 500
230 throw new InternalServerErrorException();
235 header("Content-Type: text/xml");
238 header("Content-Type: application/json");
239 if (!empty($return)) {
240 $json = json_encode(end($return));
241 if (!empty($_GET['callback'])) {
242 $json = $_GET['callback'] . "(" . $json . ")";
248 header("Content-Type: application/rss+xml");
249 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
252 header("Content-Type: application/atom+xml");
253 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
260 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
261 throw new NotFoundException();
262 } catch (HTTPException $e) {
263 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
268 * Set values for RSS template
270 * @param array $arr Array to be passed to template
271 * @param array $user_info User info
273 * @throws BadRequestException
274 * @throws ImagickException
275 * @throws InternalServerErrorException
276 * @throws UnauthorizedException
277 * @todo find proper type-hints
279 function api_rss_extra($arr, $user_info)
281 if (is_null($user_info)) {
282 $uid = BaseApi::getCurrentUserID();
284 throw new ForbiddenException();
287 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
290 $arr['$user'] = $user_info;
292 'alternate' => $user_info['url'],
293 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
294 'base' => DI::baseUrl(),
295 'updated' => api_date(null),
296 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
297 'language' => $user_info['lang'],
298 'logo' => DI::baseUrl() . "/images/friendica-32.png",
306 * Unique contact to contact url.
308 * @param int $id Contact id
309 * @return bool|string
310 * Contact url or False if contact id is unknown
313 function api_unique_id_to_nurl($id)
315 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
317 if (DBA::isResult($r)) {
325 * Get user info array.
328 * @param int|string $contact_id Contact ID or URL
330 * @throws BadRequestException
331 * @throws ImagickException
332 * @throws InternalServerErrorException
333 * @throws UnauthorizedException
335 function api_get_user($contact_id = null)
343 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
345 // Searching for contact URL
346 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
347 $user = Strings::normaliseLink($contact_id);
349 $extra_query = "AND `contact`.`nurl` = ? ";
350 if (BaseApi::getCurrentUserID() !== false) {
351 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
355 // Searching for contact id with uid = 0
356 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
357 $user = api_unique_id_to_nurl(intval($contact_id));
360 throw new BadRequestException("User ID ".$contact_id." not found.");
364 $extra_query = "AND `contact`.`nurl` = ? ";
365 if (BaseApi::getCurrentUserID() !== false) {
366 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
370 if (is_null($user) && !empty($_GET['user_id'])) {
371 $user = api_unique_id_to_nurl($_GET['user_id']);
374 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
378 $extra_query = "AND `contact`.`nurl` = ? ";
379 if (BaseApi::getCurrentUserID() !== false) {
380 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
383 if (is_null($user) && !empty($_GET['screen_name'])) {
384 $user = $_GET['screen_name'];
385 $extra_query = "AND `contact`.`nick` = ? ";
386 if (BaseApi::getCurrentUserID() !== false) {
387 $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
391 if (is_null($user) && !empty($_GET['profileurl'])) {
392 $user = Strings::normaliseLink($_GET['profileurl']);
393 $extra_query = "AND `contact`.`nurl` = ? ";
394 if (BaseApi::getCurrentUserID() !== false) {
395 $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
399 // $called_api is the API path exploded on / and is expected to have at least 2 elements
400 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
401 $argid = count($called_api);
402 if (!empty(DI::args()->getArgv()[$argid])) {
403 $data = explode(".", DI::args()->getArgv()[$argid]);
404 if (count($data) > 1) {
405 [$user, $null] = $data;
408 if (is_numeric($user)) {
409 $user = api_unique_id_to_nurl(intval($user));
413 $extra_query = "AND `contact`.`nurl` = ? ";
414 if (BaseApi::getCurrentUserID() !== false) {
415 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
419 $extra_query = "AND `contact`.`nick` = ? ";
420 if (BaseApi::getCurrentUserID() !== false) {
421 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
426 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
429 if (empty(BaseApi::getCurrentUserID())) {
430 BasicAuth::getCurrentUserID(true);
433 $user = BaseApi::getCurrentUserID();
434 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
438 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
441 $uinfo = DBA::toArray(DBA::p(
442 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
448 if (DBA::isResult($uinfo)) {
449 // Selecting the id by priority, friendica first
450 api_best_nickname($uinfo);
451 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
455 throw new BadRequestException("User not found.");
458 $cid = Contact::getIdForURL($url, 0, false);
461 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
463 throw new BadRequestException("User ".$url." not found.");
468 * return api-formatted array for item's author and owner
471 * @param array $item item from db
472 * @return array(array:author, array:owner)
473 * @throws BadRequestException
474 * @throws ImagickException
475 * @throws InternalServerErrorException
476 * @throws UnauthorizedException
478 function api_item_get_user(App $a, $item)
480 if (empty($item['author-id'])) {
481 $item['author-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
483 $status_user = DI::twitterUser()->createFromContactId($item['author-id'], BaseApi::getCurrentUserID())->toArray();
485 $author_user = $status_user;
487 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
489 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
490 if (empty($item['owner-id'])) {
491 $item['owner-id'] = Contact::getPublicIdByUserId(BaseApi::getCurrentUserID());
493 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'], BaseApi::getCurrentUserID())->toArray();
495 $owner_user = $author_user;
498 return ([$status_user, $author_user, $owner_user]);
506 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
507 * returns a 401 status code and an error message if not.
509 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
511 * @param string $type Return type (atom, rss, xml, json)
512 * @return array|string
513 * @throws BadRequestException
514 * @throws ForbiddenException
515 * @throws ImagickException
516 * @throws InternalServerErrorException
517 * @throws UnauthorizedException
519 function api_account_verify_credentials($type)
521 if (empty(BaseApi::getCurrentUserID())) {
522 throw new ForbiddenException();
524 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
526 unset($_REQUEST["user_id"]);
527 unset($_GET["user_id"]);
529 unset($_REQUEST["screen_name"]);
530 unset($_GET["screen_name"]);
532 $skip_status = $_REQUEST['skip_status'] ?? false;
534 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
536 // "verified" isn't used here in the standard
537 unset($user_info["verified"]);
539 // - Adding last status
541 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
543 $user_info['status'] = api_format_item($item, $type);
547 // "uid" and "self" are only needed for some internal stuff, so remove it from here
548 unset($user_info["uid"]);
549 unset($user_info["self"]);
551 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
554 /// @TODO move to top of file or somewhere better
555 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
558 * Get data from $_POST or $_GET
563 function requestdata($k)
565 if (!empty($_POST[$k])) {
568 if (!empty($_GET[$k])) {
575 * Deprecated function to upload media.
577 * @param string $type Return type (atom, rss, xml, json)
579 * @return array|string
580 * @throws BadRequestException
581 * @throws ForbiddenException
582 * @throws ImagickException
583 * @throws InternalServerErrorException
584 * @throws UnauthorizedException
586 function api_statuses_mediap($type)
590 if (empty(BaseApi::getCurrentUserID())) {
591 throw new ForbiddenException();
594 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
596 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
598 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
599 $_REQUEST['api_source'] = true;
600 $txt = requestdata('status') ?? '';
601 /// @TODO old-lost code?
602 //$txt = urldecode(requestdata('status'));
604 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
605 $txt = HTML::toBBCodeVideo($txt);
606 $config = HTMLPurifier_Config::createDefault();
607 $config->set('Cache.DefinitionImpl', null);
608 $purifier = new HTMLPurifier($config);
609 $txt = $purifier->purify($txt);
611 $txt = HTML::toBBCode($txt);
613 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
615 $picture = wall_upload_post($a, false);
617 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
618 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
619 $item_id = item_post($a);
621 // output the post that we just posted.
622 return api_status_show($type, $item_id);
625 /// @TODO move this to top of file or somewhere better!
626 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
629 * Updates the user’s current status.
631 * @param string $type Return type (atom, rss, xml, json)
633 * @return array|string
634 * @throws BadRequestException
635 * @throws ForbiddenException
636 * @throws ImagickException
637 * @throws InternalServerErrorException
638 * @throws TooManyRequestsException
639 * @throws UnauthorizedException
640 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
642 function api_statuses_update($type)
646 if (empty(BaseApi::getCurrentUserID())) {
647 throw new ForbiddenException();
650 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
652 // convert $_POST array items to the form we use for web posts.
653 if (requestdata('htmlstatus')) {
654 $txt = requestdata('htmlstatus') ?? '';
655 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
656 $txt = HTML::toBBCodeVideo($txt);
658 $config = HTMLPurifier_Config::createDefault();
659 $config->set('Cache.DefinitionImpl', null);
661 $purifier = new HTMLPurifier($config);
662 $txt = $purifier->purify($txt);
664 $_REQUEST['body'] = HTML::toBBCode($txt);
667 $_REQUEST['body'] = requestdata('status');
670 $_REQUEST['title'] = requestdata('title');
672 $parent = requestdata('in_reply_to_status_id');
674 // Twidere sends "-1" if it is no reply ...
679 if (ctype_digit($parent)) {
680 $_REQUEST['parent'] = $parent;
682 $_REQUEST['parent_uri'] = $parent;
685 if (requestdata('lat') && requestdata('long')) {
686 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
688 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
691 // Check for throttling (maximum posts per day, week and month)
692 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
693 if ($throttle_day > 0) {
694 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
696 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
697 $posts_day = Post::count($condition);
699 if ($posts_day > $throttle_day) {
700 logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
701 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
702 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));
706 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
707 if ($throttle_week > 0) {
708 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
710 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
711 $posts_week = Post::count($condition);
713 if ($posts_week > $throttle_week) {
714 logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
715 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
716 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));
720 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
721 if ($throttle_month > 0) {
722 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
724 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
725 $posts_month = Post::count($condition);
727 if ($posts_month > $throttle_month) {
728 logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
729 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
730 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));
735 if (requestdata('media_ids')) {
736 $ids = explode(',', requestdata('media_ids') ?? '');
737 } elseif (!empty($_FILES['media'])) {
738 // upload the image if we have one
739 $picture = wall_upload_post($a, false);
740 if (is_array($picture)) {
741 $ids[] = $picture['id'];
749 foreach ($ids as $id) {
750 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
751 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
752 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
753 ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
755 if (!empty($media)) {
756 $ressources[] = $media[0]['resource-id'];
757 $phototypes = Images::supportedTypes();
758 $ext = $phototypes[$media[0]['type']];
760 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
761 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
762 'size' => $media[0]['datasize'],
763 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
764 'description' => $media[0]['desc'] ?? '',
765 'width' => $media[0]['width'],
766 'height' => $media[0]['height']];
768 if (count($media) > 1) {
769 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
770 $attachment['preview-width'] = $media[1]['width'];
771 $attachment['preview-height'] = $media[1]['height'];
773 $attachments[] = $attachment;
777 // We have to avoid that the post is rejected because of an empty body
778 if (empty($_REQUEST['body'])) {
779 $_REQUEST['body'] = '[hr]';
783 if (!empty($attachments)) {
784 $_REQUEST['attachments'] = $attachments;
787 // set this so that the item_post() function is quiet and doesn't redirect or emit json
789 $_REQUEST['api_source'] = true;
791 if (empty($_REQUEST['source'])) {
792 $_REQUEST["source"] = api_source();
795 // call out normal post function
796 $item_id = item_post($a);
798 if (!empty($ressources) && !empty($item_id)) {
799 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
800 foreach ($ressources as $ressource) {
801 Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
805 // output the post that we just posted.
806 return api_status_show($type, $item_id);
809 /// @TODO move to top of file or somewhere better
810 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
811 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
814 * Uploads an image to Friendica.
817 * @throws BadRequestException
818 * @throws ForbiddenException
819 * @throws ImagickException
820 * @throws InternalServerErrorException
821 * @throws UnauthorizedException
822 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
824 function api_media_upload()
828 if (empty(BaseApi::getCurrentUserID())) {
829 throw new ForbiddenException();
832 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
834 if (empty($_FILES['media'])) {
836 throw new BadRequestException("No media.");
839 $media = wall_upload_post($a, false);
842 throw new InternalServerErrorException();
846 $returndata["media_id"] = $media["id"];
847 $returndata["media_id_string"] = (string)$media["id"];
848 $returndata["size"] = $media["size"];
849 $returndata["image"] = ["w" => $media["width"],
850 "h" => $media["height"],
851 "image_type" => $media["type"],
852 "friendica_preview_url" => $media["preview"]];
854 Logger::info('Media uploaded', ['return' => $returndata]);
856 return ["media" => $returndata];
859 /// @TODO move to top of file or somewhere better
860 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
863 * Updates media meta data (picture descriptions)
865 * @param string $type Return type (atom, rss, xml, json)
867 * @return array|string
868 * @throws BadRequestException
869 * @throws ForbiddenException
870 * @throws ImagickException
871 * @throws InternalServerErrorException
872 * @throws TooManyRequestsException
873 * @throws UnauthorizedException
874 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
876 * @todo Compare the corresponding Twitter function for correct return values
878 function api_media_metadata_create($type)
880 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
882 $postdata = Network::postdata();
884 if (empty($postdata)) {
885 throw new BadRequestException("No post data");
888 $data = json_decode($postdata, true);
890 throw new BadRequestException("Invalid post data");
893 if (empty($data['media_id']) || empty($data['alt_text'])) {
894 throw new BadRequestException("Missing post data values");
897 if (empty($data['alt_text']['text'])) {
898 throw new BadRequestException("No alt text.");
901 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
903 $condition = ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
904 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
905 if (!DBA::isResult($photo)) {
906 throw new BadRequestException("Metadata not found.");
909 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
912 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
915 * @param string $type Return format (atom, rss, xml, json)
916 * @param int $item_id
917 * @return array|string
920 function api_status_show($type, $item_id)
922 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
926 $item = api_get_item(['id' => $item_id]);
928 $status_info = api_format_item($item, $type);
931 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
933 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
937 * Retrieves the last public status of the provided user info
939 * @param int $ownerId Public contact Id
940 * @param int $uid User Id
944 function api_get_last_status($ownerId, $uid)
947 'author-id'=> $ownerId,
949 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
950 'private' => [Item::PUBLIC, Item::UNLISTED]
953 $item = api_get_item($condition);
959 * Retrieves a single item record based on the provided condition and converts it for API use.
961 * @param array $condition Item table condition array
965 function api_get_item(array $condition)
967 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
973 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
974 * The author's most recent status will be returned inline.
976 * @param string $type Return type (atom, rss, xml, json)
977 * @return array|string
978 * @throws BadRequestException
979 * @throws ImagickException
980 * @throws InternalServerErrorException
981 * @throws UnauthorizedException
982 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
984 function api_users_show($type)
986 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
988 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
990 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
992 $user_info['status'] = api_format_item($item, $type);
995 // "uid" and "self" are only needed for some internal stuff, so remove it from here
996 unset($user_info['uid']);
997 unset($user_info['self']);
999 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1002 /// @TODO move to top of file or somewhere better
1003 api_register_func('api/users/show', 'api_users_show');
1004 api_register_func('api/externalprofile/show', 'api_users_show');
1007 * Search a public user account.
1009 * @param string $type Return type (atom, rss, xml, json)
1011 * @return array|string
1012 * @throws BadRequestException
1013 * @throws ImagickException
1014 * @throws InternalServerErrorException
1015 * @throws UnauthorizedException
1016 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1018 function api_users_search($type)
1022 if (!empty($_GET['q'])) {
1023 $contacts = Contact::selectToArray(
1026 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1034 if (DBA::isResult($contacts)) {
1036 foreach ($contacts as $contact) {
1037 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
1039 if ($type == 'xml') {
1040 $userlist[$k++ . ':user'] = $user_info;
1042 $userlist[] = $user_info;
1045 $userlist = ['users' => $userlist];
1047 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1050 throw new BadRequestException('No search term specified.');
1053 return DI::apiResponse()->formatData('users', $type, $userlist);
1056 /// @TODO move to top of file or somewhere better
1057 api_register_func('api/users/search', 'api_users_search');
1060 * Return user objects
1062 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1064 * @param string $type Return format: json or xml
1066 * @return array|string
1067 * @throws BadRequestException
1068 * @throws ImagickException
1069 * @throws InternalServerErrorException
1070 * @throws NotFoundException if the results are empty.
1071 * @throws UnauthorizedException
1073 function api_users_lookup($type)
1077 if (!empty($_REQUEST['user_id'])) {
1078 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1080 $users[] = api_get_user($id);
1085 if (empty($users)) {
1086 throw new NotFoundException;
1089 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1092 /// @TODO move to top of file or somewhere better
1093 api_register_func('api/users/lookup', 'api_users_lookup', true);
1096 * Returns statuses that match a specified query.
1098 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1100 * @param string $type Return format: json, xml, atom, rss
1102 * @return array|string
1103 * @throws BadRequestException if the "q" parameter is missing.
1104 * @throws ForbiddenException
1105 * @throws ImagickException
1106 * @throws InternalServerErrorException
1107 * @throws UnauthorizedException
1109 function api_search($type)
1111 if (empty(BaseApi::getCurrentUserID())) {
1112 throw new ForbiddenException();
1114 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1116 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1118 if (empty($_REQUEST['q'])) {
1119 throw new BadRequestException('q parameter is required.');
1122 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1125 $data['status'] = [];
1127 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1128 if (!empty($_REQUEST['rpp'])) {
1129 $count = $_REQUEST['rpp'];
1130 } elseif (!empty($_REQUEST['count'])) {
1131 $count = $_REQUEST['count'];
1134 $since_id = $_REQUEST['since_id'] ?? 0;
1135 $max_id = $_REQUEST['max_id'] ?? 0;
1136 $page = $_REQUEST['page'] ?? 1;
1138 $start = max(0, ($page - 1) * $count);
1140 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1141 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1142 $searchTerm = $matches[1];
1143 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1144 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1146 while ($tag = DBA::fetch($tags)) {
1147 $uriids[] = $tag['uri-id'];
1151 if (empty($uriids)) {
1152 return DI::apiResponse()->formatData('statuses', $type, $data);
1155 $condition = ['uri-id' => $uriids];
1156 if ($exclude_replies) {
1157 $condition['gravity'] = GRAVITY_PARENT;
1160 $params['group_by'] = ['uri-id'];
1162 $condition = ["`id` > ?
1163 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1164 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1165 AND `body` LIKE CONCAT('%',?,'%')",
1166 $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
1168 $condition[0] .= ' AND `id` <= ?';
1169 $condition[] = $max_id;
1175 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1176 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
1179 $id = Item::fetchByLink($searchTerm);
1183 $statuses = Post::select([], ['id' => $id]);
1187 $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1189 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1191 bindComments($data['status']);
1193 return DI::apiResponse()->formatData('statuses', $type, $data);
1196 /// @TODO move to top of file or somewhere better
1197 api_register_func('api/search/tweets', 'api_search', true);
1198 api_register_func('api/search', 'api_search', true);
1201 * Returns the most recent statuses posted by the user and the users they follow.
1203 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1205 * @param string $type Return type (atom, rss, xml, json)
1207 * @return array|string
1208 * @throws BadRequestException
1209 * @throws ForbiddenException
1210 * @throws ImagickException
1211 * @throws InternalServerErrorException
1212 * @throws UnauthorizedException
1213 * @todo Optional parameters
1214 * @todo Add reply info
1216 function api_statuses_home_timeline($type)
1218 if (empty(BaseApi::getCurrentUserID())) {
1219 throw new ForbiddenException();
1221 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1223 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1225 unset($_REQUEST["user_id"]);
1226 unset($_GET["user_id"]);
1228 unset($_REQUEST["screen_name"]);
1229 unset($_GET["screen_name"]);
1231 // get last network messages
1234 $count = $_REQUEST['count'] ?? 20;
1235 $page = $_REQUEST['page']?? 0;
1236 $since_id = $_REQUEST['since_id'] ?? 0;
1237 $max_id = $_REQUEST['max_id'] ?? 0;
1238 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1239 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1241 $start = max(0, ($page - 1) * $count);
1243 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1244 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1247 $condition[0] .= " AND `id` <= ?";
1248 $condition[] = $max_id;
1250 if ($exclude_replies) {
1251 $condition[0] .= ' AND `gravity` = ?';
1252 $condition[] = GRAVITY_PARENT;
1254 if ($conversation_id > 0) {
1255 $condition[0] .= " AND `parent` = ?";
1256 $condition[] = $conversation_id;
1259 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1260 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1262 $items = Post::toArray($statuses);
1264 $ret = api_format_items($items, $user_info, false, $type);
1266 // Set all posts from the query above to seen
1268 foreach ($items as $item) {
1269 $idarray[] = intval($item["id"]);
1272 if (!empty($idarray)) {
1273 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1275 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1281 $data = ['status' => $ret];
1286 $data = api_rss_extra($data, $user_info);
1290 return DI::apiResponse()->formatData("statuses", $type, $data);
1294 /// @TODO move to top of file or somewhere better
1295 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1296 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1299 * Returns the most recent statuses from public users.
1301 * @param string $type Return type (atom, rss, xml, json)
1303 * @return array|string
1304 * @throws BadRequestException
1305 * @throws ForbiddenException
1306 * @throws ImagickException
1307 * @throws InternalServerErrorException
1308 * @throws UnauthorizedException
1310 function api_statuses_public_timeline($type)
1312 if (empty(BaseApi::getCurrentUserID())) {
1313 throw new ForbiddenException();
1315 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1317 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1319 // get last network messages
1322 $count = $_REQUEST['count'] ?? 20;
1323 $page = $_REQUEST['page'] ?? 1;
1324 $since_id = $_REQUEST['since_id'] ?? 0;
1325 $max_id = $_REQUEST['max_id'] ?? 0;
1326 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1327 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1329 $start = max(0, ($page - 1) * $count);
1331 if ($exclude_replies && !$conversation_id) {
1332 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1333 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1336 $condition[0] .= " AND `id` <= ?";
1337 $condition[] = $max_id;
1340 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1341 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1343 $r = Post::toArray($statuses);
1345 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1346 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1349 $condition[0] .= " AND `id` <= ?";
1350 $condition[] = $max_id;
1352 if ($conversation_id > 0) {
1353 $condition[0] .= " AND `parent` = ?";
1354 $condition[] = $conversation_id;
1357 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1358 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1360 $r = Post::toArray($statuses);
1363 $ret = api_format_items($r, $user_info, false, $type);
1367 $data = ['status' => $ret];
1372 $data = api_rss_extra($data, $user_info);
1376 return DI::apiResponse()->formatData("statuses", $type, $data);
1379 /// @TODO move to top of file or somewhere better
1380 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1383 * Returns the most recent statuses posted by users this node knows about.
1385 * @param string $type Return format: json, xml, atom, rss
1386 * @return array|string
1387 * @throws BadRequestException
1388 * @throws ForbiddenException
1389 * @throws ImagickException
1390 * @throws InternalServerErrorException
1391 * @throws UnauthorizedException
1393 function api_statuses_networkpublic_timeline($type)
1395 if (empty(BaseApi::getCurrentUserID())) {
1396 throw new ForbiddenException();
1398 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1400 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1402 $since_id = $_REQUEST['since_id'] ?? 0;
1403 $max_id = $_REQUEST['max_id'] ?? 0;
1406 $count = $_REQUEST['count'] ?? 20;
1407 $page = $_REQUEST['page'] ?? 1;
1409 $start = max(0, ($page - 1) * $count);
1411 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1412 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1415 $condition[0] .= " AND `id` <= ?";
1416 $condition[] = $max_id;
1419 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1420 $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1422 $ret = api_format_items($statuses, $user_info, false, $type);
1426 $data = ['status' => $ret];
1431 $data = api_rss_extra($data, $user_info);
1435 return DI::apiResponse()->formatData("statuses", $type, $data);
1438 /// @TODO move to top of file or somewhere better
1439 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1442 * Returns a single status.
1444 * @param string $type Return type (atom, rss, xml, json)
1446 * @return array|string
1447 * @throws BadRequestException
1448 * @throws ForbiddenException
1449 * @throws ImagickException
1450 * @throws InternalServerErrorException
1451 * @throws UnauthorizedException
1452 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1454 function api_statuses_show($type)
1456 if (empty(BaseApi::getCurrentUserID())) {
1457 throw new ForbiddenException();
1459 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1461 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1464 $id = intval(DI::args()->getArgv()[3] ?? 0);
1467 $id = intval($_REQUEST['id'] ?? 0);
1472 $id = intval(DI::args()->getArgv()[4] ?? 0);
1475 logger::notice('API: api_statuses_show: ' . $id);
1477 $conversation = !empty($_REQUEST['conversation']);
1479 // try to fetch the item for the local user - or the public item, if there is no local one
1480 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1481 if (!DBA::isResult($uri_item)) {
1482 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1485 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1486 if (!DBA::isResult($item)) {
1487 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1492 if ($conversation) {
1493 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1494 $params = ['order' => ['id' => true]];
1496 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1500 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1502 /// @TODO How about copying this to above methods which don't check $r ?
1503 if (!DBA::isResult($statuses)) {
1504 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1507 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1509 if ($conversation) {
1510 $data = ['status' => $ret];
1511 return DI::apiResponse()->formatData("statuses", $type, $data);
1513 $data = ['status' => $ret[0]];
1514 return DI::apiResponse()->formatData("status", $type, $data);
1518 /// @TODO move to top of file or somewhere better
1519 api_register_func('api/statuses/show', 'api_statuses_show', true);
1523 * @param string $type Return type (atom, rss, xml, json)
1525 * @return array|string
1526 * @throws BadRequestException
1527 * @throws ForbiddenException
1528 * @throws ImagickException
1529 * @throws InternalServerErrorException
1530 * @throws UnauthorizedException
1531 * @todo nothing to say?
1533 function api_conversation_show($type)
1535 if (empty(BaseApi::getCurrentUserID())) {
1536 throw new ForbiddenException();
1538 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1540 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1543 $id = intval(DI::args()->getArgv()[3] ?? 0);
1544 $since_id = intval($_REQUEST['since_id'] ?? 0);
1545 $max_id = intval($_REQUEST['max_id'] ?? 0);
1546 $count = intval($_REQUEST['count'] ?? 20);
1547 $page = intval($_REQUEST['page'] ?? 1);
1549 $start = max(0, ($page - 1) * $count);
1552 $id = intval($_REQUEST['id'] ?? 0);
1557 $id = intval(DI::args()->getArgv()[4] ?? 0);
1560 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1562 // try to fetch the item for the local user - or the public item, if there is no local one
1563 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1564 if (!DBA::isResult($item)) {
1565 throw new BadRequestException("There is no status with the id $id.");
1568 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1569 if (!DBA::isResult($parent)) {
1570 throw new BadRequestException("There is no status with this id.");
1573 $id = $parent['id'];
1575 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1576 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1579 $condition[0] .= " AND `id` <= ?";
1580 $condition[] = $max_id;
1583 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1584 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1586 if (!DBA::isResult($statuses)) {
1587 throw new BadRequestException("There is no status with id $id.");
1590 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1592 $data = ['status' => $ret];
1593 return DI::apiResponse()->formatData("statuses", $type, $data);
1596 /// @TODO move to top of file or somewhere better
1597 api_register_func('api/conversation/show', 'api_conversation_show', true);
1598 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1603 * @param string $type Return type (atom, rss, xml, json)
1605 * @return array|string
1606 * @throws BadRequestException
1607 * @throws ForbiddenException
1608 * @throws ImagickException
1609 * @throws InternalServerErrorException
1610 * @throws UnauthorizedException
1611 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1613 function api_statuses_repeat($type)
1619 if (empty(BaseApi::getCurrentUserID())) {
1620 throw new ForbiddenException();
1623 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1626 $id = intval(DI::args()->getArgv()[3] ?? 0);
1629 $id = intval($_REQUEST['id'] ?? 0);
1634 $id = intval(DI::args()->getArgv()[4] ?? 0);
1637 logger::notice('API: api_statuses_repeat: ' . $id);
1639 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1640 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1642 if (DBA::isResult($item) && !empty($item['body'])) {
1643 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1644 if (!Item::performActivity($id, 'announce', local_user())) {
1645 throw new InternalServerErrorException();
1650 if (strpos($item['body'], "[/share]") !== false) {
1651 $pos = strpos($item['body'], "[share");
1652 $post = substr($item['body'], $pos);
1654 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1656 if (!empty($item['title'])) {
1657 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1660 $post .= $item['body'];
1661 $post .= "[/share]";
1663 $_REQUEST['body'] = $post;
1664 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1665 $_REQUEST['api_source'] = true;
1667 if (empty($_REQUEST['source'])) {
1668 $_REQUEST["source"] = api_source();
1671 $item_id = item_post($a);
1674 throw new ForbiddenException();
1677 // output the post that we just posted.
1679 return api_status_show($type, $item_id);
1682 /// @TODO move to top of file or somewhere better
1683 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1686 * Destroys a specific status.
1688 * @param string $type Return type (atom, rss, xml, json)
1690 * @return array|string
1691 * @throws BadRequestException
1692 * @throws ForbiddenException
1693 * @throws ImagickException
1694 * @throws InternalServerErrorException
1695 * @throws UnauthorizedException
1696 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1698 function api_statuses_destroy($type)
1700 if (empty(BaseApi::getCurrentUserID())) {
1701 throw new ForbiddenException();
1704 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1707 $id = intval(DI::args()->getArgv()[3] ?? 0);
1710 $id = intval($_REQUEST['id'] ?? 0);
1715 $id = intval(DI::args()->getArgv()[4] ?? 0);
1718 logger::notice('API: api_statuses_destroy: ' . $id);
1720 $ret = api_statuses_show($type);
1722 Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1727 /// @TODO move to top of file or somewhere better
1728 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1731 * Returns the most recent mentions.
1733 * @param string $type Return type (atom, rss, xml, json)
1735 * @return array|string
1736 * @throws BadRequestException
1737 * @throws ForbiddenException
1738 * @throws ImagickException
1739 * @throws InternalServerErrorException
1740 * @throws UnauthorizedException
1741 * @see http://developer.twitter.com/doc/get/statuses/mentions
1743 function api_statuses_mentions($type)
1745 if (empty(BaseApi::getCurrentUserID())) {
1746 throw new ForbiddenException();
1748 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1750 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1752 unset($_REQUEST["user_id"]);
1753 unset($_GET["user_id"]);
1755 unset($_REQUEST["screen_name"]);
1756 unset($_GET["screen_name"]);
1758 // get last network messages
1761 $since_id = intval($_REQUEST['since_id'] ?? 0);
1762 $max_id = intval($_REQUEST['max_id'] ?? 0);
1763 $count = intval($_REQUEST['count'] ?? 20);
1764 $page = intval($_REQUEST['page'] ?? 1);
1766 $start = max(0, ($page - 1) * $count);
1768 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1769 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1770 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1773 GRAVITY_PARENT, GRAVITY_COMMENT,
1774 BaseApi::getCurrentUserID(),
1775 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1776 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1777 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1778 BaseApi::getCurrentUserID(), $since_id,
1782 $query .= " AND `id` <= ?";
1783 $condition[] = $max_id;
1786 array_unshift($condition, $query);
1788 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1789 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1791 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1793 $data = ['status' => $ret];
1798 $data = api_rss_extra($data, $user_info);
1802 return DI::apiResponse()->formatData("statuses", $type, $data);
1805 /// @TODO move to top of file or somewhere better
1806 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1807 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1810 * Returns the most recent statuses posted by the user.
1812 * @param string $type Either "json" or "xml"
1813 * @return string|array
1814 * @throws BadRequestException
1815 * @throws ForbiddenException
1816 * @throws ImagickException
1817 * @throws InternalServerErrorException
1818 * @throws UnauthorizedException
1819 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1821 function api_statuses_user_timeline($type)
1823 if (empty(BaseApi::getCurrentUserID())) {
1824 throw new ForbiddenException();
1826 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1828 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1830 Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1832 $since_id = $_REQUEST['since_id'] ?? 0;
1833 $max_id = $_REQUEST['max_id'] ?? 0;
1834 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1835 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1838 $count = $_REQUEST['count'] ?? 20;
1839 $page = $_REQUEST['page'] ?? 1;
1841 $start = max(0, ($page - 1) * $count);
1843 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1844 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1846 if ($user_info['self'] == 1) {
1847 $condition[0] .= ' AND `wall` ';
1850 if ($exclude_replies) {
1851 $condition[0] .= ' AND `gravity` = ?';
1852 $condition[] = GRAVITY_PARENT;
1855 if ($conversation_id > 0) {
1856 $condition[0] .= " AND `parent` = ?";
1857 $condition[] = $conversation_id;
1861 $condition[0] .= " AND `id` <= ?";
1862 $condition[] = $max_id;
1864 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1865 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1867 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1871 $data = ['status' => $ret];
1876 $data = api_rss_extra($data, $user_info);
1880 return DI::apiResponse()->formatData("statuses", $type, $data);
1883 /// @TODO move to top of file or somewhere better
1884 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1887 * Star/unstar an item.
1888 * param: id : id of the item
1890 * @param string $type Return type (atom, rss, xml, json)
1892 * @return array|string
1893 * @throws BadRequestException
1894 * @throws ForbiddenException
1895 * @throws ImagickException
1896 * @throws InternalServerErrorException
1897 * @throws UnauthorizedException
1898 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1900 function api_favorites_create_destroy($type)
1902 if (empty(BaseApi::getCurrentUserID())) {
1903 throw new ForbiddenException();
1906 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1908 // for versioned api.
1909 /// @TODO We need a better global soluton
1910 $action_argv_id = 2;
1911 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1912 $action_argv_id = 3;
1915 if (DI::args()->getArgc() <= $action_argv_id) {
1916 throw new BadRequestException("Invalid request.");
1918 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1919 if (DI::args()->getArgc() == $action_argv_id + 2) {
1920 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1922 $itemid = intval($_REQUEST['id'] ?? 0);
1925 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1927 if (!DBA::isResult($item)) {
1928 throw new BadRequestException("Invalid item.");
1933 $item['starred'] = 1;
1936 $item['starred'] = 0;
1939 throw new BadRequestException("Invalid action ".$action);
1942 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1945 throw new InternalServerErrorException("DB error");
1948 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1949 $rets = api_format_items([$item], $user_info, false, $type);
1952 $data = ['status' => $ret];
1957 $data = api_rss_extra($data, $user_info);
1961 return DI::apiResponse()->formatData("status", $type, $data);
1964 /// @TODO move to top of file or somewhere better
1965 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1966 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1969 * Returns the most recent favorite statuses.
1971 * @param string $type Return type (atom, rss, xml, json)
1973 * @return string|array
1974 * @throws BadRequestException
1975 * @throws ForbiddenException
1976 * @throws ImagickException
1977 * @throws InternalServerErrorException
1978 * @throws UnauthorizedException
1980 function api_favorites($type)
1984 if (empty(BaseApi::getCurrentUserID())) {
1985 throw new ForbiddenException();
1987 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1989 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1993 // in friendica starred item are private
1994 // return favorites only for self
1995 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1997 if ($user_info['self'] == 0) {
2001 $since_id = $_REQUEST['since_id'] ?? 0;
2002 $max_id = $_REQUEST['max_id'] ?? 0;
2003 $count = $_GET['count'] ?? 20;
2004 $page = $_REQUEST['page'] ?? 1;
2006 $start = max(0, ($page - 1) * $count);
2008 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2009 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2011 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2014 $condition[0] .= " AND `id` <= ?";
2015 $condition[] = $max_id;
2018 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2020 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2025 $data = ['status' => $ret];
2030 $data = api_rss_extra($data, $user_info);
2034 return DI::apiResponse()->formatData("statuses", $type, $data);
2037 /// @TODO move to top of file or somewhere better
2038 api_register_func('api/favorites', 'api_favorites', true);
2042 * @param array $item
2043 * @param array $recipient
2044 * @param array $sender
2047 * @throws InternalServerErrorException
2049 function api_format_messages($item, $recipient, $sender)
2051 // standard meta information
2053 'id' => $item['id'],
2054 'sender_id' => $sender['id'],
2056 'recipient_id' => $recipient['id'],
2057 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2058 'sender_screen_name' => $sender['screen_name'],
2059 'recipient_screen_name' => $recipient['screen_name'],
2060 'sender' => $sender,
2061 'recipient' => $recipient,
2063 'friendica_seen' => $item['seen'] ?? 0,
2064 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2067 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2068 if (isset($ret['sender']['uid'])) {
2069 unset($ret['sender']['uid']);
2071 if (isset($ret['sender']['self'])) {
2072 unset($ret['sender']['self']);
2074 if (isset($ret['recipient']['uid'])) {
2075 unset($ret['recipient']['uid']);
2077 if (isset($ret['recipient']['self'])) {
2078 unset($ret['recipient']['self']);
2081 //don't send title to regular StatusNET requests to avoid confusing these apps
2082 if (!empty($_GET['getText'])) {
2083 $ret['title'] = $item['title'];
2084 if ($_GET['getText'] == 'html') {
2085 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2086 } elseif ($_GET['getText'] == 'plain') {
2087 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2090 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2092 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2093 unset($ret['sender']);
2094 unset($ret['recipient']);
2102 * @param array $item
2105 * @throws InternalServerErrorException
2107 function api_convert_item($item)
2109 $body = api_add_attachments_to_body($item);
2111 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2113 // Add pictures to the attachment array and remove them from the body
2114 $attachments = api_get_attachments($body, $item['uri-id']);
2116 // Workaround for ostatus messages where the title is identically to the body
2117 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2118 $statusbody = trim(HTML::toPlaintext($html, 0));
2120 // handle data: images
2121 $statusbody = api_format_items_embeded_images($item, $statusbody);
2123 $statustitle = trim($item['title']);
2125 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2126 $statustext = trim($statusbody);
2128 $statustext = trim($statustitle."\n\n".$statusbody);
2131 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2132 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2135 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2137 // Workaround for clients with limited HTML parser functionality
2138 $search = ["<br>", "<blockquote>", "</blockquote>",
2139 "<h1>", "</h1>", "<h2>", "</h2>",
2140 "<h3>", "</h3>", "<h4>", "</h4>",
2141 "<h5>", "</h5>", "<h6>", "</h6>"];
2142 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2143 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2144 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2145 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2146 $statushtml = str_replace($search, $replace, $statushtml);
2148 if ($item['title'] != "") {
2149 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2153 $oldtext = $statushtml;
2154 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2155 } while ($oldtext != $statushtml);
2157 if (substr($statushtml, 0, 4) == '<br>') {
2158 $statushtml = substr($statushtml, 4);
2161 if (substr($statushtml, 0, -4) == '<br>') {
2162 $statushtml = substr($statushtml, -4);
2165 // feeds without body should contain the link
2166 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2167 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2171 "text" => $statustext,
2172 "html" => $statushtml,
2173 "attachments" => $attachments,
2174 "entities" => $entities
2179 * Add media attachments to the body
2181 * @param array $item
2182 * @return string body with added media
2184 function api_add_attachments_to_body(array $item)
2186 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2188 if (strpos($body, '[/img]') !== false) {
2192 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2193 if (!empty($media['preview'])) {
2194 $description = $media['description'] ?: $media['name'];
2195 if (!empty($description)) {
2196 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2198 $body .= "\n[img]" . $media['preview'] .'[/img]';
2208 * @param string $body
2212 * @throws InternalServerErrorException
2214 function api_get_attachments(&$body, $uriid)
2216 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2217 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2219 $URLSearchString = "^\[\]";
2220 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2224 // Remove all embedded pictures, since they are added as attachments
2225 foreach ($images[0] as $orig) {
2226 $body = str_replace($orig, '', $body);
2231 foreach ($images[1] as $image) {
2232 $imagedata = Images::getInfoFromURLCached($image);
2235 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2239 return $attachments;
2244 * @param string $text
2245 * @param string $bbcode
2248 * @throws InternalServerErrorException
2249 * @todo Links at the first character of the post
2251 function api_get_entitities(&$text, $bbcode, $uriid)
2253 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2255 if ($include_entities != "true") {
2256 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2258 foreach ($images[1] as $image) {
2259 $replace = Post\Link::getByLink($uriid, $image);
2260 $text = str_replace($image, $replace, $text);
2265 $bbcode = BBCode::cleanPictureLinks($bbcode);
2267 // Change pure links in text to bbcode uris
2268 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2271 $entities["hashtags"] = [];
2272 $entities["symbols"] = [];
2273 $entities["urls"] = [];
2274 $entities["user_mentions"] = [];
2276 $URLSearchString = "^\[\]";
2278 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2280 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2281 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2283 $bbcode = preg_replace(
2284 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2285 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2288 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2290 $bbcode = preg_replace(
2291 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2292 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2295 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2297 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2299 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2302 foreach ($urls[1] as $id => $url) {
2303 $start = iconv_strpos($text, $url, 0, "UTF-8");
2304 if (!($start === false)) {
2305 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2309 ksort($ordered_urls);
2313 foreach ($ordered_urls as $url) {
2314 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2315 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2317 $display_url = $url["title"];
2319 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2320 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2322 if (strlen($display_url) > 26) {
2323 $display_url = substr($display_url, 0, 25)."…";
2327 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2328 if (!($start === false)) {
2329 $entities["urls"][] = ["url" => $url["url"],
2330 "expanded_url" => $url["url"],
2331 "display_url" => $display_url,
2332 "indices" => [$start, $start+strlen($url["url"])]];
2333 $offset = $start + 1;
2337 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2338 $ordered_images = [];
2339 foreach ($images as $image) {
2340 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2341 if (!($start === false)) {
2342 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2346 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2347 foreach ($images[1] as $image) {
2348 $start = iconv_strpos($text, $image, 0, "UTF-8");
2349 if (!($start === false)) {
2350 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2356 foreach ($ordered_images as $image) {
2357 $url = $image['url'];
2358 $ext_alt_text = $image['alt'];
2360 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2361 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2363 if (strlen($display_url) > 26) {
2364 $display_url = substr($display_url, 0, 25)."…";
2367 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2368 if (!($start === false)) {
2369 $image = Images::getInfoFromURLCached($url);
2371 $media_url = Post\Link::getByLink($uriid, $url);
2372 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2374 $entities["media"][] = [
2376 "id_str" => (string) ($start + 1),
2377 "indices" => [$start, $start+strlen($url)],
2378 "media_url" => Strings::normaliseLink($media_url),
2379 "media_url_https" => $media_url,
2381 "display_url" => $display_url,
2382 "expanded_url" => $url,
2383 "ext_alt_text" => $ext_alt_text,
2387 $offset = $start + 1;
2396 * @param array $item
2397 * @param string $text
2401 function api_format_items_embeded_images($item, $text)
2403 $text = preg_replace_callback(
2404 '|data:image/([^;]+)[^=]+=*|m',
2405 function () use ($item) {
2406 return DI::baseUrl() . '/display/' . $item['guid'];
2414 * return <a href='url'>name</a> as array
2416 * @param string $txt text
2421 function api_contactlink_to_array($txt)
2424 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2425 if ($r && count($match)==3) {
2427 'name' => $match[2],
2441 * return likes, dislikes and attend status for item
2443 * @param array $item array
2444 * @param string $type Return type (atom, rss, xml, json)
2447 * likes => int count,
2448 * dislikes => int count
2449 * @throws BadRequestException
2450 * @throws ImagickException
2451 * @throws InternalServerErrorException
2452 * @throws UnauthorizedException
2454 function api_format_items_activities($item, $type = "json")
2461 'attendmaybe' => [],
2465 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2466 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2468 while ($parent_item = Post::fetch($ret)) {
2469 // not used as result should be structured like other user data
2470 //builtin_activity_puller($i, $activities);
2472 // get user data and add it to the array of the activity
2473 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2474 switch ($parent_item['verb']) {
2475 case Activity::LIKE:
2476 $activities['like'][] = $user;
2478 case Activity::DISLIKE:
2479 $activities['dislike'][] = $user;
2481 case Activity::ATTEND:
2482 $activities['attendyes'][] = $user;
2484 case Activity::ATTENDNO:
2485 $activities['attendno'][] = $user;
2487 case Activity::ATTENDMAYBE:
2488 $activities['attendmaybe'][] = $user;
2490 case Activity::ANNOUNCE:
2491 $activities['announce'][] = $user;
2500 if ($type == "xml") {
2501 $xml_activities = [];
2502 foreach ($activities as $k => $v) {
2503 // change xml element from "like" to "friendica:like"
2504 $xml_activities["friendica:".$k] = $v;
2505 // add user data into xml output
2507 foreach ($v as $user) {
2508 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2511 $activities = $xml_activities;
2518 * format items to be returned by api
2520 * @param array $items array of items
2521 * @param array $user_info
2522 * @param bool $filter_user filter items by $user_info
2523 * @param string $type Return type (atom, rss, xml, json)
2525 * @throws BadRequestException
2526 * @throws ImagickException
2527 * @throws InternalServerErrorException
2528 * @throws UnauthorizedException
2530 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2536 if (empty($items)) {
2540 foreach ((array)$items as $item) {
2541 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2543 // Look if the posts are matching if they should be filtered by user id
2544 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2548 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2557 * @param array $item Item record
2558 * @param string $type Return format (atom, rss, xml, json)
2559 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2560 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2561 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2562 * @return array API-formatted status
2563 * @throws BadRequestException
2564 * @throws ImagickException
2565 * @throws InternalServerErrorException
2566 * @throws UnauthorizedException
2568 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2572 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2573 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2576 DI::contentItem()->localize($item);
2578 $in_reply_to = api_in_reply_to($item);
2580 $converted = api_convert_item($item);
2582 if ($type == "xml") {
2583 $geo = "georss:point";
2589 'text' => $converted["text"],
2590 'truncated' => false,
2591 'created_at'=> api_date($item['created']),
2592 'in_reply_to_status_id' => $in_reply_to['status_id'],
2593 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2594 'source' => (($item['app']) ? $item['app'] : 'web'),
2595 'id' => intval($item['id']),
2596 'id_str' => (string) intval($item['id']),
2597 'in_reply_to_user_id' => $in_reply_to['user_id'],
2598 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2599 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2601 'favorited' => $item['starred'] ? true : false,
2602 'user' => $status_user,
2603 'friendica_author' => $author_user,
2604 'friendica_owner' => $owner_user,
2605 'friendica_private' => $item['private'] == Item::PRIVATE,
2606 //'entities' => NULL,
2607 'statusnet_html' => $converted["html"],
2608 'statusnet_conversation_id' => $item['parent'],
2609 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2610 'friendica_activities' => api_format_items_activities($item, $type),
2611 'friendica_title' => $item['title'],
2612 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2615 if (count($converted["attachments"]) > 0) {
2616 $status["attachments"] = $converted["attachments"];
2619 if (count($converted["entities"]) > 0) {
2620 $status["entities"] = $converted["entities"];
2623 if ($status["source"] == 'web') {
2624 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2625 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2626 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2629 $retweeted_item = [];
2632 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2633 $announce = api_get_announce($item);
2634 if (!empty($announce)) {
2635 $retweeted_item = $item;
2637 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2641 if (!empty($quoted_item)) {
2642 if ($quoted_item['id'] != $item['id']) {
2643 $quoted_status = api_format_item($quoted_item);
2644 /// @todo Only remove the attachments that are also contained in the quotes status
2645 unset($status['attachments']);
2646 unset($status['entities']);
2648 $conv_quoted = api_convert_item($quoted_item);
2649 $quoted_status = $status;
2650 unset($quoted_status['attachments']);
2651 unset($quoted_status['entities']);
2652 unset($quoted_status['statusnet_conversation_id']);
2653 $quoted_status['text'] = $conv_quoted['text'];
2654 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2656 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2657 } catch (BadRequestException $e) {
2658 // user not found. should be found?
2659 /// @todo check if the user should be always found
2660 $quoted_status["user"] = [];
2663 unset($quoted_status['friendica_author']);
2664 unset($quoted_status['friendica_owner']);
2665 unset($quoted_status['friendica_activities']);
2666 unset($quoted_status['friendica_private']);
2669 if (!empty($retweeted_item)) {
2670 $retweeted_status = $status;
2671 unset($retweeted_status['friendica_author']);
2672 unset($retweeted_status['friendica_owner']);
2673 unset($retweeted_status['friendica_activities']);
2674 unset($retweeted_status['friendica_private']);
2675 unset($retweeted_status['statusnet_conversation_id']);
2676 $status['user'] = $status['friendica_owner'];
2678 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2679 } catch (BadRequestException $e) {
2680 // user not found. should be found?
2681 /// @todo check if the user should be always found
2682 $retweeted_status["user"] = [];
2685 $rt_converted = api_convert_item($retweeted_item);
2687 $retweeted_status['text'] = $rt_converted["text"];
2688 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2689 $retweeted_status['friendica_html'] = $rt_converted["html"];
2690 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2692 if (!empty($quoted_status)) {
2693 $retweeted_status['quoted_status'] = $quoted_status;
2696 $status['friendica_author'] = $retweeted_status['user'];
2697 $status['retweeted_status'] = $retweeted_status;
2698 } elseif (!empty($quoted_status)) {
2699 $root_status = api_convert_item($item);
2701 $status['text'] = $root_status["text"];
2702 $status['statusnet_html'] = $root_status["html"];
2703 $status['quoted_status'] = $quoted_status;
2706 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2707 unset($status["user"]["uid"]);
2708 unset($status["user"]["self"]);
2710 if ($item["coord"] != "") {
2711 $coords = explode(' ', $item["coord"]);
2712 if (count($coords) == 2) {
2713 if ($type == "json") {
2714 $status["geo"] = ['type' => 'Point',
2715 'coordinates' => [(float) $coords[0],
2716 (float) $coords[1]]];
2717 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2718 $status["georss:point"] = $item["coord"];
2727 * Returns all lists the user subscribes to.
2729 * @param string $type Return type (atom, rss, xml, json)
2731 * @return array|string
2732 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2734 function api_lists_list($type)
2737 /// @TODO $ret is not filled here?
2738 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2741 /// @TODO move to top of file or somewhere better
2742 api_register_func('api/lists/list', 'api_lists_list', true);
2743 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2746 * Returns all groups the user owns.
2748 * @param string $type Return type (atom, rss, xml, json)
2750 * @return array|string
2751 * @throws BadRequestException
2752 * @throws ForbiddenException
2753 * @throws ImagickException
2754 * @throws InternalServerErrorException
2755 * @throws UnauthorizedException
2756 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2758 function api_lists_ownerships($type)
2760 if (empty(BaseApi::getCurrentUserID())) {
2761 throw new ForbiddenException();
2763 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2766 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2767 $uid = $user_info['uid'];
2769 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2771 // loop through all groups
2773 foreach ($groups as $group) {
2774 if ($group['visible']) {
2780 'name' => $group['name'],
2781 'id' => intval($group['id']),
2782 'id_str' => (string) $group['id'],
2783 'user' => $user_info,
2787 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2790 /// @TODO move to top of file or somewhere better
2791 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2794 * Returns recent statuses from users in the specified group.
2796 * @param string $type Return type (atom, rss, xml, json)
2798 * @return array|string
2799 * @throws BadRequestException
2800 * @throws ForbiddenException
2801 * @throws ImagickException
2802 * @throws InternalServerErrorException
2803 * @throws UnauthorizedException
2804 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2806 function api_lists_statuses($type)
2808 if (empty(BaseApi::getCurrentUserID())) {
2809 throw new ForbiddenException();
2811 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2813 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2815 unset($_REQUEST["user_id"]);
2816 unset($_GET["user_id"]);
2818 unset($_REQUEST["screen_name"]);
2819 unset($_GET["screen_name"]);
2821 if (empty($_REQUEST['list_id'])) {
2822 throw new BadRequestException('list_id not specified');
2826 $count = $_REQUEST['count'] ?? 20;
2827 $page = $_REQUEST['page'] ?? 1;
2828 $since_id = $_REQUEST['since_id'] ?? 0;
2829 $max_id = $_REQUEST['max_id'] ?? 0;
2830 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2831 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2833 $start = max(0, ($page - 1) * $count);
2835 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2836 $gids = array_column($groups, 'contact-id');
2837 $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2838 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2841 $condition[0] .= " AND `id` <= ?";
2842 $condition[] = $max_id;
2844 if ($exclude_replies > 0) {
2845 $condition[0] .= ' AND `gravity` = ?';
2846 $condition[] = GRAVITY_PARENT;
2848 if ($conversation_id > 0) {
2849 $condition[0] .= " AND `parent` = ?";
2850 $condition[] = $conversation_id;
2853 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2854 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2856 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2858 $data = ['status' => $items];
2863 $data = api_rss_extra($data, $user_info);
2867 return DI::apiResponse()->formatData("statuses", $type, $data);
2870 /// @TODO move to top of file or somewhere better
2871 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2874 * Returns either the friends of the follower list
2876 * Considers friends and followers lists to be private and won't return
2877 * anything if any user_id parameter is passed.
2879 * @param string $qtype Either "friends" or "followers"
2880 * @return boolean|array
2881 * @throws BadRequestException
2882 * @throws ForbiddenException
2883 * @throws ImagickException
2884 * @throws InternalServerErrorException
2885 * @throws UnauthorizedException
2887 function api_statuses_f($qtype)
2889 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2892 $count = $_GET['count'] ?? 20;
2893 $page = $_GET['page'] ?? 1;
2895 $start = max(0, ($page - 1) * $count);
2897 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2899 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2900 /* this is to stop Hotot to load friends multiple times
2901 * I'm not sure if I'm missing return something or
2902 * is a bug in hotot. Workaround, meantime
2906 return array('$users' => $ret);*/
2911 if ($qtype == 'friends') {
2912 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2913 } elseif ($qtype == 'followers') {
2914 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2917 // friends and followers only for self
2918 if ($user_info['self'] == 0) {
2919 $sql_extra = " AND false ";
2922 if ($qtype == 'blocks') {
2923 $sql_filter = 'AND `blocked` AND NOT `pending`';
2924 } elseif ($qtype == 'incoming') {
2925 $sql_filter = 'AND `pending`';
2927 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2930 // @todo This query most likely can be replaced with a Contact::select...
2931 $r = DBA::toArray(DBA::p(
2940 BaseApi::getCurrentUserID(),
2946 foreach ($r as $cid) {
2947 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2948 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2949 unset($user["uid"]);
2950 unset($user["self"]);
2957 return ['user' => $ret];
2962 * Returns the list of friends of the provided user
2964 * @deprecated By Twitter API in favor of friends/list
2966 * @param string $type Either "json" or "xml"
2967 * @return boolean|string|array
2968 * @throws BadRequestException
2969 * @throws ForbiddenException
2971 function api_statuses_friends($type)
2973 $data = api_statuses_f("friends");
2974 if ($data === false) {
2977 return DI::apiResponse()->formatData("users", $type, $data);
2981 * Returns the list of followers of the provided user
2983 * @deprecated By Twitter API in favor of friends/list
2985 * @param string $type Either "json" or "xml"
2986 * @return boolean|string|array
2987 * @throws BadRequestException
2988 * @throws ForbiddenException
2990 function api_statuses_followers($type)
2992 $data = api_statuses_f("followers");
2993 if ($data === false) {
2996 return DI::apiResponse()->formatData("users", $type, $data);
2999 /// @TODO move to top of file or somewhere better
3000 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3001 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3004 * Returns the list of blocked users
3006 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3008 * @param string $type Either "json" or "xml"
3010 * @return boolean|string|array
3011 * @throws BadRequestException
3012 * @throws ForbiddenException
3014 function api_blocks_list($type)
3016 $data = api_statuses_f('blocks');
3017 if ($data === false) {
3020 return DI::apiResponse()->formatData("users", $type, $data);
3023 /// @TODO move to top of file or somewhere better
3024 api_register_func('api/blocks/list', 'api_blocks_list', true);
3027 * Returns the list of pending users IDs
3029 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3031 * @param string $type Either "json" or "xml"
3033 * @return boolean|string|array
3034 * @throws BadRequestException
3035 * @throws ForbiddenException
3037 function api_friendships_incoming($type)
3039 $data = api_statuses_f('incoming');
3040 if ($data === false) {
3045 foreach ($data['user'] as $user) {
3046 $ids[] = $user['id'];
3049 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3052 /// @TODO move to top of file or somewhere better
3053 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3056 * Sends a new direct message.
3058 * @param string $type Return type (atom, rss, xml, json)
3060 * @return array|string
3061 * @throws BadRequestException
3062 * @throws ForbiddenException
3063 * @throws ImagickException
3064 * @throws InternalServerErrorException
3065 * @throws NotFoundException
3066 * @throws UnauthorizedException
3067 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3069 function api_direct_messages_new($type)
3071 if (empty(BaseApi::getCurrentUserID())) {
3072 throw new ForbiddenException();
3075 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3077 $uid = BaseApi::getCurrentUserID();
3079 throw new ForbiddenException();
3082 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3086 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
3089 if (!empty($_POST['screen_name'])) {
3090 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
3091 if (DBA::isResult($contacts)) {
3092 // Selecting the id by priority, friendica first
3093 api_best_nickname($contacts);
3095 $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
3098 $recipient = api_get_user($_POST['user_id']);
3101 if (empty($recipient)) {
3102 throw new NotFoundException('Recipient not found');
3106 if (!empty($_REQUEST['replyto'])) {
3107 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
3108 $replyto = $mail['parent-uri'];
3109 $sub = $mail['title'];
3111 if (!empty($_REQUEST['title'])) {
3112 $sub = $_REQUEST['title'];
3114 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3118 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3121 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3122 $ret = api_format_messages($mail, $recipient, $sender);
3124 $ret = ["error" => $id];
3127 $data = ['direct_message'=>$ret];
3133 $data = api_rss_extra($data, $sender);
3137 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3140 /// @TODO move to top of file or somewhere better
3141 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3144 * delete a direct_message from mail table through api
3146 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3147 * @return string|array
3148 * @throws BadRequestException
3149 * @throws ForbiddenException
3150 * @throws ImagickException
3151 * @throws InternalServerErrorException
3152 * @throws UnauthorizedException
3153 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3155 function api_direct_messages_destroy($type)
3157 if (empty(BaseApi::getCurrentUserID())) {
3158 throw new ForbiddenException();
3161 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3164 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3166 $id = $_REQUEST['id'] ?? 0;
3168 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3169 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3170 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3172 $uid = $user_info['uid'];
3173 // error if no id or parenturi specified (for clients posting parent-uri as well)
3174 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3175 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3176 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3179 // BadRequestException if no id specified (for clients using Twitter API)
3181 throw new BadRequestException('Message id not specified');
3184 // add parent-uri to sql command if specified by calling app
3185 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3187 // error message if specified id is not in database
3188 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3189 if ($verbose == "true") {
3190 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3191 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3193 /// @todo BadRequestException ok for Twitter API clients?
3194 throw new BadRequestException('message id not in database');
3198 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3200 if ($verbose == "true") {
3203 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3204 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3206 $answer = ['result' => 'error', 'message' => 'unknown error'];
3207 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3210 /// @todo return JSON data like Twitter API not yet implemented
3213 /// @TODO move to top of file or somewhere better
3214 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3219 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3220 * @return string|array
3221 * @throws HTTPException\BadRequestException
3222 * @throws HTTPException\ExpectationFailedException
3223 * @throws HTTPException\ForbiddenException
3224 * @throws HTTPException\InternalServerErrorException
3225 * @throws HTTPException\NotFoundException
3226 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3228 function api_friendships_destroy($type)
3230 $uid = BaseApi::getCurrentUserID();
3232 if ($uid === false) {
3233 throw new HTTPException\ForbiddenException();
3236 $owner = User::getOwnerDataById($uid);
3238 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3239 throw new HTTPException\NotFoundException('Error Processing Request');
3242 $contact_id = $_REQUEST['user_id'] ?? 0;
3244 if (empty($contact_id)) {
3245 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3246 throw new HTTPException\BadRequestException('no user_id specified');
3249 // Get Contact by given id
3250 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3252 if(!DBA::isResult($contact)) {
3253 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3254 throw new HTTPException\NotFoundException('no contact found to given ID');
3257 $url = $contact['url'];
3259 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3260 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3261 Strings::normaliseLink($url), $url];
3262 $contact = DBA::selectFirst('contact', [], $condition);
3264 if (!DBA::isResult($contact)) {
3265 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3266 throw new HTTPException\NotFoundException('Not following Contact');
3270 $result = Contact::terminateFriendship($owner, $contact);
3272 if ($result === null) {
3273 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3274 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3277 if ($result === false) {
3278 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3280 } catch (Exception $e) {
3281 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3282 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3285 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3286 unset($contact['uid']);
3287 unset($contact['self']);
3289 // Set screen_name since Twidere requests it
3290 $contact['screen_name'] = $contact['nick'];
3292 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3295 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3299 * @param string $type Return type (atom, rss, xml, json)
3300 * @param string $box
3301 * @param string $verbose
3303 * @return array|string
3304 * @throws BadRequestException
3305 * @throws ForbiddenException
3306 * @throws ImagickException
3307 * @throws InternalServerErrorException
3308 * @throws UnauthorizedException
3310 function api_direct_messages_box($type, $box, $verbose)
3312 if (empty(BaseApi::getCurrentUserID())) {
3313 throw new ForbiddenException();
3315 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3318 $count = $_GET['count'] ?? 20;
3319 $page = $_REQUEST['page'] ?? 1;
3321 $since_id = $_REQUEST['since_id'] ?? 0;
3322 $max_id = $_REQUEST['max_id'] ?? 0;
3324 $user_id = $_REQUEST['user_id'] ?? '';
3325 $screen_name = $_REQUEST['screen_name'] ?? '';
3328 unset($_REQUEST["user_id"]);
3329 unset($_GET["user_id"]);
3331 unset($_REQUEST["screen_name"]);
3332 unset($_GET["screen_name"]);
3334 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3336 $profile_url = $user_info["url"];
3339 $start = max(0, ($page - 1) * $count);
3344 if ($box=="sentbox") {
3345 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3346 } elseif ($box == "conversation") {
3347 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3348 } elseif ($box == "all") {
3349 $sql_extra = "true";
3350 } elseif ($box == "inbox") {
3351 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3355 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3358 if ($user_id != "") {
3359 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3360 } elseif ($screen_name !="") {
3361 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3364 $r = DBA::toArray(DBA::p(
3365 "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 ?,?",
3366 BaseApi::getCurrentUserID(),
3371 if ($verbose == "true" && !DBA::isResult($r)) {
3372 $answer = ['result' => 'error', 'message' => 'no mails available'];
3373 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3377 foreach ($r as $item) {
3378 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3379 $recipient = $user_info;
3380 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3381 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3382 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3383 $sender = $user_info;
3386 if (isset($recipient) && isset($sender)) {
3387 $ret[] = api_format_messages($item, $recipient, $sender);
3392 $data = ['direct_message' => $ret];
3397 $data = api_rss_extra($data, $user_info);
3401 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3405 * Returns the most recent direct messages sent by the user.
3407 * @param string $type Return type (atom, rss, xml, json)
3409 * @return array|string
3410 * @throws BadRequestException
3411 * @throws ForbiddenException
3412 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3414 function api_direct_messages_sentbox($type)
3416 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3417 return api_direct_messages_box($type, "sentbox", $verbose);
3421 * Returns the most recent direct messages sent to the user.
3423 * @param string $type Return type (atom, rss, xml, json)
3425 * @return array|string
3426 * @throws BadRequestException
3427 * @throws ForbiddenException
3428 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3430 function api_direct_messages_inbox($type)
3432 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3433 return api_direct_messages_box($type, "inbox", $verbose);
3438 * @param string $type Return type (atom, rss, xml, json)
3440 * @return array|string
3441 * @throws BadRequestException
3442 * @throws ForbiddenException
3444 function api_direct_messages_all($type)
3446 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3447 return api_direct_messages_box($type, "all", $verbose);
3452 * @param string $type Return type (atom, rss, xml, json)
3454 * @return array|string
3455 * @throws BadRequestException
3456 * @throws ForbiddenException
3458 function api_direct_messages_conversation($type)
3460 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3461 return api_direct_messages_box($type, "conversation", $verbose);
3464 /// @TODO move to top of file or somewhere better
3465 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3466 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3467 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3468 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3471 * list all photos of the authenticated user
3473 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3474 * @return string|array
3475 * @throws ForbiddenException
3476 * @throws InternalServerErrorException
3478 function api_fr_photos_list($type)
3480 if (empty(BaseApi::getCurrentUserID())) {
3481 throw new ForbiddenException();
3483 $r = DBA::toArray(DBA::p(
3484 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3485 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3486 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3487 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3490 'image/jpeg' => 'jpg',
3491 'image/png' => 'png',
3492 'image/gif' => 'gif'
3494 $data = ['photo'=>[]];
3495 if (DBA::isResult($r)) {
3496 foreach ($r as $rr) {
3498 $photo['id'] = $rr['resource-id'];
3499 $photo['album'] = $rr['album'];
3500 $photo['filename'] = $rr['filename'];
3501 $photo['type'] = $rr['type'];
3502 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3503 $photo['created'] = $rr['created'];
3504 $photo['edited'] = $rr['edited'];
3505 $photo['desc'] = $rr['desc'];
3507 if ($type == "xml") {
3508 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3510 $photo['thumb'] = $thumb;
3511 $data['photo'][] = $photo;
3515 return DI::apiResponse()->formatData("photos", $type, $data);
3519 * upload a new photo or change an existing photo
3521 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3522 * @return string|array
3523 * @throws BadRequestException
3524 * @throws ForbiddenException
3525 * @throws ImagickException
3526 * @throws InternalServerErrorException
3527 * @throws NotFoundException
3529 function api_fr_photo_create_update($type)
3531 if (empty(BaseApi::getCurrentUserID())) {
3532 throw new ForbiddenException();
3535 $photo_id = $_REQUEST['photo_id'] ?? null;
3536 $desc = $_REQUEST['desc'] ?? null;
3537 $album = $_REQUEST['album'] ?? null;
3538 $album_new = $_REQUEST['album_new'] ?? null;
3539 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3540 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3541 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3542 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3543 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3545 // do several checks on input parameters
3546 // we do not allow calls without album string
3547 if ($album == null) {
3548 throw new BadRequestException("no albumname specified");
3550 // if photo_id == null --> we are uploading a new photo
3551 if ($photo_id == null) {
3554 // error if no media posted in create-mode
3555 if (empty($_FILES['media'])) {
3557 throw new BadRequestException("no media data submitted");
3560 // album_new will be ignored in create-mode
3565 // check if photo is existing in databasei
3566 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3567 throw new BadRequestException("photo not available");
3571 // checks on acl strings provided by clients
3572 $acl_input_error = false;
3573 $acl_input_error |= check_acl_input($allow_cid);
3574 $acl_input_error |= check_acl_input($deny_cid);
3575 $acl_input_error |= check_acl_input($allow_gid);
3576 $acl_input_error |= check_acl_input($deny_gid);
3577 if ($acl_input_error) {
3578 throw new BadRequestException("acl data invalid");
3580 // now let's upload the new media in create-mode
3581 if ($mode == "create") {
3582 $media = $_FILES['media'];
3583 $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);
3585 // return success of updating or error message
3586 if (!is_null($data)) {
3587 return DI::apiResponse()->formatData("photo_create", $type, $data);
3589 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3593 // now let's do the changes in update-mode
3594 if ($mode == "update") {
3595 $updated_fields = [];
3597 if (!is_null($desc)) {
3598 $updated_fields['desc'] = $desc;
3601 if (!is_null($album_new)) {
3602 $updated_fields['album'] = $album_new;
3605 if (!is_null($allow_cid)) {
3606 $allow_cid = trim($allow_cid);
3607 $updated_fields['allow_cid'] = $allow_cid;
3610 if (!is_null($deny_cid)) {
3611 $deny_cid = trim($deny_cid);
3612 $updated_fields['deny_cid'] = $deny_cid;
3615 if (!is_null($allow_gid)) {
3616 $allow_gid = trim($allow_gid);
3617 $updated_fields['allow_gid'] = $allow_gid;
3620 if (!is_null($deny_gid)) {
3621 $deny_gid = trim($deny_gid);
3622 $updated_fields['deny_gid'] = $deny_gid;
3626 if (count($updated_fields) > 0) {
3627 $nothingtodo = false;
3628 $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3630 $nothingtodo = true;
3633 if (!empty($_FILES['media'])) {
3634 $nothingtodo = false;
3635 $media = $_FILES['media'];
3636 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3637 if (!is_null($data)) {
3638 return DI::apiResponse()->formatData("photo_update", $type, $data);
3642 // return success of updating or error message
3644 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3645 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3648 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3649 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3651 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3654 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3658 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3660 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3661 * @return string|array
3662 * @throws BadRequestException
3663 * @throws ForbiddenException
3664 * @throws InternalServerErrorException
3665 * @throws NotFoundException
3667 function api_fr_photo_detail($type)
3669 if (empty(BaseApi::getCurrentUserID())) {
3670 throw new ForbiddenException();
3672 if (empty($_REQUEST['photo_id'])) {
3673 throw new BadRequestException("No photo id.");
3676 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3677 $photo_id = $_REQUEST['photo_id'];
3679 // prepare json/xml output with data from database for the requested photo
3680 $data = prepare_photo_data($type, $scale, $photo_id);
3682 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3687 * updates the profile image for the user (either a specified profile or the default profile)
3689 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3691 * @return string|array
3692 * @throws BadRequestException
3693 * @throws ForbiddenException
3694 * @throws ImagickException
3695 * @throws InternalServerErrorException
3696 * @throws NotFoundException
3697 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3699 function api_account_update_profile_image($type)
3701 if (empty(BaseApi::getCurrentUserID())) {
3702 throw new ForbiddenException();
3705 $profile_id = $_REQUEST['profile_id'] ?? 0;
3707 // error if image data is missing
3708 if (empty($_FILES['image'])) {
3709 throw new BadRequestException("no media data submitted");
3712 // check if specified profile id is valid
3713 if ($profile_id != 0) {
3714 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3715 // error message if specified profile id is not in database
3716 if (!DBA::isResult($profile)) {
3717 throw new BadRequestException("profile_id not available");
3719 $is_default_profile = $profile['is-default'];
3721 $is_default_profile = 1;
3724 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3726 if (!empty($_FILES['image'])) {
3727 $media = $_FILES['image'];
3728 } elseif (!empty($_FILES['media'])) {
3729 $media = $_FILES['media'];
3731 // save new profile image
3732 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3735 if (is_array($media['type'])) {
3736 $filetype = $media['type'][0];
3738 $filetype = $media['type'];
3740 if ($filetype == "image/jpeg") {
3742 } elseif ($filetype == "image/png") {
3745 throw new InternalServerErrorException('Unsupported filetype');
3748 // change specified profile or all profiles to the new resource-id
3749 if ($is_default_profile) {
3750 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3751 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3753 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3754 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3755 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3758 Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3760 // Update global directory in background
3761 Profile::publishUpdate(BaseApi::getCurrentUserID());
3763 // output for client
3765 return api_account_verify_credentials($type);
3767 // SaveMediaToDatabase failed for some reason
3768 throw new InternalServerErrorException("image upload failed");
3772 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3773 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3774 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3775 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3776 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3777 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3780 * Update user profile
3782 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3784 * @return array|string
3785 * @throws BadRequestException
3786 * @throws ForbiddenException
3787 * @throws ImagickException
3788 * @throws InternalServerErrorException
3789 * @throws UnauthorizedException
3791 function api_account_update_profile($type)
3793 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3795 $local_user = BaseApi::getCurrentUserID();
3797 $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3799 if (!empty($_POST['name'])) {
3800 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3801 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3802 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3803 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3806 if (isset($_POST['description'])) {
3807 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3808 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3809 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3812 Profile::publishUpdate($local_user);
3814 return api_account_verify_credentials($type);
3817 /// @TODO move to top of file or somewhere better
3818 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3822 * @param string $acl_string
3826 function check_acl_input($acl_string)
3828 if (empty($acl_string)) {
3832 $contact_not_found = false;
3834 // split <x><y><z> into array of cid's
3835 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3837 // check for each cid if it is available on server
3838 $cid_array = $array[0];
3839 foreach ($cid_array as $cid) {
3840 $cid = str_replace("<", "", $cid);
3841 $cid = str_replace(">", "", $cid);
3842 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3843 $contact_not_found |= !DBA::exists('contact', $condition);
3845 return $contact_not_found;
3849 * @param string $mediatype
3850 * @param array $media
3851 * @param string $type
3852 * @param string $album
3853 * @param string $allow_cid
3854 * @param string $deny_cid
3855 * @param string $allow_gid
3856 * @param string $deny_gid
3857 * @param string $desc
3858 * @param integer $phototype
3859 * @param boolean $visibility
3860 * @param string $photo_id
3862 * @throws BadRequestException
3863 * @throws ForbiddenException
3864 * @throws ImagickException
3865 * @throws InternalServerErrorException
3866 * @throws NotFoundException
3867 * @throws UnauthorizedException
3869 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)
3877 if (is_array($media)) {
3878 if (is_array($media['tmp_name'])) {
3879 $src = $media['tmp_name'][0];
3881 $src = $media['tmp_name'];
3883 if (is_array($media['name'])) {
3884 $filename = basename($media['name'][0]);
3886 $filename = basename($media['name']);
3888 if (is_array($media['size'])) {
3889 $filesize = intval($media['size'][0]);
3891 $filesize = intval($media['size']);
3893 if (is_array($media['type'])) {
3894 $filetype = $media['type'][0];
3896 $filetype = $media['type'];
3900 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3903 "File upload src: " . $src . " - filename: " . $filename .
3904 " - size: " . $filesize . " - type: " . $filetype);
3906 // check if there was a php upload error
3907 if ($filesize == 0 && $media['error'] == 1) {
3908 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3910 // check against max upload size within Friendica instance
3911 $maximagesize = DI::config()->get('system', 'maximagesize');
3912 if ($maximagesize && ($filesize > $maximagesize)) {
3913 $formattedBytes = Strings::formatBytes($maximagesize);
3914 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3917 // create Photo instance with the data of the image
3918 $imagedata = @file_get_contents($src);
3919 $Image = new Image($imagedata, $filetype);
3920 if (!$Image->isValid()) {
3921 throw new InternalServerErrorException("unable to process image data");
3924 // check orientation of image
3925 $Image->orient($src);
3928 // check max length of images on server
3929 $max_length = DI::config()->get('system', 'max_image_length');
3930 if ($max_length > 0) {
3931 $Image->scaleDown($max_length);
3932 logger::info("File upload: Scaling picture to new size " . $max_length);
3934 $width = $Image->getWidth();
3935 $height = $Image->getHeight();
3937 // create a new resource-id if not already provided
3938 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3940 if ($mediatype == "photo") {
3941 // upload normal image (scales 0, 1, 2)
3942 logger::info("photo upload: starting new photo upload");
3944 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3946 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3948 if ($width > 640 || $height > 640) {
3949 $Image->scaleDown(640);
3950 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3952 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3956 if ($width > 320 || $height > 320) {
3957 $Image->scaleDown(320);
3958 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3960 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3963 logger::info("photo upload: new photo upload ended");
3964 } elseif ($mediatype == "profileimage") {
3965 // upload profile image (scales 4, 5, 6)
3966 logger::info("photo upload: starting new profile image upload");
3968 if ($width > 300 || $height > 300) {
3969 $Image->scaleDown(300);
3970 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3972 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3976 if ($width > 80 || $height > 80) {
3977 $Image->scaleDown(80);
3978 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3980 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3984 if ($width > 48 || $height > 48) {
3985 $Image->scaleDown(48);
3986 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3988 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3991 $Image->__destruct();
3992 logger::info("photo upload: new profile image upload ended");
3996 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3997 if ($photo_id == null && $mediatype == "photo") {
3998 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4000 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4001 return prepare_photo_data($type, false, $resource_id);
4003 throw new InternalServerErrorException("image upload failed");
4009 * @param string $hash
4010 * @param string $allow_cid
4011 * @param string $deny_cid
4012 * @param string $allow_gid
4013 * @param string $deny_gid
4014 * @param string $filetype
4015 * @param boolean $visibility
4016 * @throws InternalServerErrorException
4018 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4020 // get data about the api authenticated user
4021 $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
4022 $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
4025 $arr['guid'] = System::createUUID();
4026 $arr['uid'] = intval(BaseApi::getCurrentUserID());
4028 $arr['type'] = 'photo';
4030 $arr['resource-id'] = $hash;
4031 $arr['contact-id'] = $owner_record['id'];
4032 $arr['owner-name'] = $owner_record['name'];
4033 $arr['owner-link'] = $owner_record['url'];
4034 $arr['owner-avatar'] = $owner_record['thumb'];
4035 $arr['author-name'] = $owner_record['name'];
4036 $arr['author-link'] = $owner_record['url'];
4037 $arr['author-avatar'] = $owner_record['thumb'];
4039 $arr['allow_cid'] = $allow_cid;
4040 $arr['allow_gid'] = $allow_gid;
4041 $arr['deny_cid'] = $deny_cid;
4042 $arr['deny_gid'] = $deny_gid;
4043 $arr['visible'] = $visibility;
4047 'image/jpeg' => 'jpg',
4048 'image/png' => 'png',
4049 'image/gif' => 'gif'
4052 // adds link to the thumbnail scale photo
4053 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4054 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4057 // do the magic for storing the item in the database and trigger the federation to other contacts
4063 * @param string $type
4065 * @param string $photo_id
4068 * @throws BadRequestException
4069 * @throws ForbiddenException
4070 * @throws ImagickException
4071 * @throws InternalServerErrorException
4072 * @throws NotFoundException
4073 * @throws UnauthorizedException
4075 function prepare_photo_data($type, $scale, $photo_id)
4077 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4079 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4081 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4082 $data_sql = ($scale === false ? "" : "data, ");
4084 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4085 // clients needs to convert this in their way for further processing
4086 $r = DBA::toArray(DBA::p(
4087 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4088 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4089 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4090 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4091 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4092 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4098 'image/jpeg' => 'jpg',
4099 'image/png' => 'png',
4100 'image/gif' => 'gif'
4103 // prepare output data for photo
4104 if (DBA::isResult($r)) {
4105 $data = ['photo' => $r[0]];
4106 $data['photo']['id'] = $data['photo']['resource-id'];
4107 if ($scale !== false) {
4108 $data['photo']['data'] = base64_encode($data['photo']['data']);
4110 unset($data['photo']['datasize']); //needed only with scale param
4112 if ($type == "xml") {
4113 $data['photo']['links'] = [];
4114 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4115 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4117 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4120 $data['photo']['link'] = [];
4121 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4123 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4124 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4128 unset($data['photo']['resource-id']);
4129 unset($data['photo']['minscale']);
4130 unset($data['photo']['maxscale']);
4132 throw new NotFoundException();
4135 // retrieve item element for getting activities (like, dislike etc.) related to photo
4136 $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
4137 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4138 if (!DBA::isResult($item)) {
4139 throw new NotFoundException('Photo-related item not found.');
4142 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4144 // retrieve comments on photo
4145 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4146 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
4148 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
4150 // prepare output of comments
4151 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4153 if ($type == "xml") {
4155 foreach ($commentData as $comment) {
4156 $comments[$k++ . ":comment"] = $comment;
4159 foreach ($commentData as $comment) {
4160 $comments[] = $comment;
4163 $data['photo']['friendica_comments'] = $comments;
4165 // include info if rights on photo and rights on item are mismatching
4166 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4167 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4168 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4169 $data['photo']['deny_gid'] != $item['deny_gid'];
4170 $data['photo']['rights_mismatch'] = $rights_mismatch;
4176 * Return an item with announcer data if it had been announced
4178 * @param array $item Item array
4179 * @return array Item array with announce data
4181 function api_get_announce($item)
4183 // Quit if the item already has got a different owner and author
4184 if ($item['owner-id'] != $item['author-id']) {
4188 // Don't change original or Diaspora posts
4189 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4193 // Quit if we do now the original author and it had been a post from a native network
4194 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4198 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4199 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4200 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4201 if (!DBA::isResult($announce)) {
4205 return array_merge($item, $announce);
4210 * @param array $item
4215 function api_in_reply_to($item)
4219 $in_reply_to['status_id'] = null;
4220 $in_reply_to['user_id'] = null;
4221 $in_reply_to['status_id_str'] = null;
4222 $in_reply_to['user_id_str'] = null;
4223 $in_reply_to['screen_name'] = null;
4225 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4226 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4227 if (DBA::isResult($parent)) {
4228 $in_reply_to['status_id'] = intval($parent['id']);
4230 $in_reply_to['status_id'] = intval($item['parent']);
4233 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4235 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4236 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4238 if (DBA::isResult($parent)) {
4239 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4240 $in_reply_to['user_id'] = intval($parent['author-id']);
4241 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4244 // There seems to be situation, where both fields are identical:
4245 // https://github.com/friendica/friendica/issues/1010
4246 // This is a bugfix for that.
4247 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4248 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']]);
4249 $in_reply_to['status_id'] = null;
4250 $in_reply_to['user_id'] = null;
4251 $in_reply_to['status_id_str'] = null;
4252 $in_reply_to['user_id_str'] = null;
4253 $in_reply_to['screen_name'] = null;
4257 return $in_reply_to;
4262 * @param string $text
4265 * @throws InternalServerErrorException
4267 function api_clean_plain_items($text)
4269 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4271 $text = BBCode::cleanPictureLinks($text);
4272 $URLSearchString = "^\[\]";
4274 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4276 if ($include_entities == "true") {
4277 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4280 // Simplify "attachment" element
4281 $text = BBCode::removeAttachment($text);
4288 * @param array $contacts
4292 function api_best_nickname(&$contacts)
4296 if (count($contacts) == 0) {
4300 foreach ($contacts as $contact) {
4301 if ($contact["network"] == "") {
4302 $contact["network"] = "dfrn";
4303 $best_contact = [$contact];
4307 if (sizeof($best_contact) == 0) {
4308 foreach ($contacts as $contact) {
4309 if ($contact["network"] == "dfrn") {
4310 $best_contact = [$contact];
4315 if (sizeof($best_contact) == 0) {
4316 foreach ($contacts as $contact) {
4317 if ($contact["network"] == "dspr") {
4318 $best_contact = [$contact];
4323 if (sizeof($best_contact) == 0) {
4324 foreach ($contacts as $contact) {
4325 if ($contact["network"] == "stat") {
4326 $best_contact = [$contact];
4331 if (sizeof($best_contact) == 0) {
4332 foreach ($contacts as $contact) {
4333 if ($contact["network"] == "pump") {
4334 $best_contact = [$contact];
4339 if (sizeof($best_contact) == 0) {
4340 foreach ($contacts as $contact) {
4341 if ($contact["network"] == "twit") {
4342 $best_contact = [$contact];
4347 if (sizeof($best_contact) == 1) {
4348 $contacts = $best_contact;
4350 $contacts = [$contacts[0]];
4355 * Return all or a specified group of the user with the containing contacts.
4357 * @param string $type Return type (atom, rss, xml, json)
4359 * @return array|string
4360 * @throws BadRequestException
4361 * @throws ForbiddenException
4362 * @throws ImagickException
4363 * @throws InternalServerErrorException
4364 * @throws UnauthorizedException
4366 function api_friendica_group_show($type)
4368 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4371 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4372 $gid = $_REQUEST['gid'] ?? 0;
4373 $uid = $user_info['uid'];
4375 // get data of the specified group id or all groups if not specified
4377 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4379 // error message if specified gid is not in database
4380 if (!DBA::isResult($groups)) {
4381 throw new BadRequestException("gid not available");
4384 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4387 // loop through all groups and retrieve all members for adding data in the user array
4389 foreach ($groups as $rr) {
4390 $members = Contact\Group::getById($rr['id']);
4393 if ($type == "xml") {
4394 $user_element = "users";
4396 foreach ($members as $member) {
4397 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4398 $users[$k++.":user"] = $user;
4401 $user_element = "user";
4402 foreach ($members as $member) {
4403 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4407 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4409 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4412 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4417 * @param string $type Return type (atom, rss, xml, json)
4419 * @return array|string
4420 * @throws BadRequestException
4421 * @throws ForbiddenException
4422 * @throws ImagickException
4423 * @throws InternalServerErrorException
4424 * @throws UnauthorizedException
4425 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4427 function api_lists_destroy($type)
4429 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4432 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4433 $gid = $_REQUEST['list_id'] ?? 0;
4434 $uid = $user_info['uid'];
4436 // error if no gid specified
4438 throw new BadRequestException('gid not specified');
4441 // get data of the specified group id
4442 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4443 // error message if specified gid is not in database
4445 throw new BadRequestException('gid not available');
4448 if (Group::remove($gid)) {
4450 'name' => $group['name'],
4451 'id' => intval($gid),
4452 'id_str' => (string) $gid,
4453 'user' => $user_info
4456 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4460 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4463 * Add a new group to the database.
4465 * @param string $name Group name
4466 * @param int $uid User ID
4467 * @param array $users List of users to add to the group
4470 * @throws BadRequestException
4472 function group_create($name, $uid, $users = [])
4474 // error if no name specified
4476 throw new BadRequestException('group name not specified');
4479 // error message if specified group name already exists
4480 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4481 throw new BadRequestException('group name already exists');
4484 // Check if the group needs to be reactivated
4485 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4486 $reactivate_group = true;
4490 $ret = Group::create($uid, $name);
4492 $gid = Group::getIdByName($uid, $name);
4494 throw new BadRequestException('other API error');
4498 $erroraddinguser = false;
4500 foreach ($users as $user) {
4501 $cid = $user['cid'];
4502 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4503 Group::addMember($gid, $cid);
4505 $erroraddinguser = true;
4506 $errorusers[] = $cid;
4510 // return success message incl. missing users in array
4511 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4513 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4517 * Create the specified group with the posted array of contacts.
4519 * @param string $type Return type (atom, rss, xml, json)
4521 * @return array|string
4522 * @throws BadRequestException
4523 * @throws ForbiddenException
4524 * @throws ImagickException
4525 * @throws InternalServerErrorException
4526 * @throws UnauthorizedException
4528 function api_friendica_group_create($type)
4530 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4533 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4534 $name = $_REQUEST['name'] ?? '';
4535 $uid = $user_info['uid'];
4536 $json = json_decode($_POST['json'], true);
4537 $users = $json['user'];
4539 $success = group_create($name, $uid, $users);
4541 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4544 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4547 * Create a new group.
4549 * @param string $type Return type (atom, rss, xml, json)
4551 * @return array|string
4552 * @throws BadRequestException
4553 * @throws ForbiddenException
4554 * @throws ImagickException
4555 * @throws InternalServerErrorException
4556 * @throws UnauthorizedException
4557 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4559 function api_lists_create($type)
4561 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4564 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4565 $name = $_REQUEST['name'] ?? '';
4566 $uid = $user_info['uid'];
4568 $success = group_create($name, $uid);
4569 if ($success['success']) {
4571 'name' => $success['name'],
4572 'id' => intval($success['gid']),
4573 'id_str' => (string) $success['gid'],
4574 'user' => $user_info
4577 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4581 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4584 * Update the specified group with the posted array of contacts.
4586 * @param string $type Return type (atom, rss, xml, json)
4588 * @return array|string
4589 * @throws BadRequestException
4590 * @throws ForbiddenException
4591 * @throws ImagickException
4592 * @throws InternalServerErrorException
4593 * @throws UnauthorizedException
4595 function api_friendica_group_update($type)
4597 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4600 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4601 $uid = $user_info['uid'];
4602 $gid = $_REQUEST['gid'] ?? 0;
4603 $name = $_REQUEST['name'] ?? '';
4604 $json = json_decode($_POST['json'], true);
4605 $users = $json['user'];
4607 // error if no name specified
4609 throw new BadRequestException('group name not specified');
4612 // error if no gid specified
4614 throw new BadRequestException('gid not specified');
4618 $members = Contact\Group::getById($gid);
4619 foreach ($members as $member) {
4620 $cid = $member['id'];
4621 foreach ($users as $user) {
4622 $found = ($user['cid'] == $cid ? true : false);
4624 if (!isset($found) || !$found) {
4625 $gid = Group::getIdByName($uid, $name);
4626 Group::removeMember($gid, $cid);
4631 $erroraddinguser = false;
4633 foreach ($users as $user) {
4634 $cid = $user['cid'];
4636 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4637 Group::addMember($gid, $cid);
4639 $erroraddinguser = true;
4640 $errorusers[] = $cid;
4644 // return success message incl. missing users in array
4645 $status = ($erroraddinguser ? "missing user" : "ok");
4646 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4647 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4650 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4653 * Update information about a group.
4655 * @param string $type Return type (atom, rss, xml, json)
4657 * @return array|string
4658 * @throws BadRequestException
4659 * @throws ForbiddenException
4660 * @throws ImagickException
4661 * @throws InternalServerErrorException
4662 * @throws UnauthorizedException
4663 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4665 function api_lists_update($type)
4667 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4670 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4671 $gid = $_REQUEST['list_id'] ?? 0;
4672 $name = $_REQUEST['name'] ?? '';
4673 $uid = $user_info['uid'];
4675 // error if no gid specified
4677 throw new BadRequestException('gid not specified');
4680 // get data of the specified group id
4681 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4682 // error message if specified gid is not in database
4684 throw new BadRequestException('gid not available');
4687 if (Group::update($gid, $name)) {
4690 'id' => intval($gid),
4691 'id_str' => (string) $gid,
4692 'user' => $user_info
4695 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4699 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4702 * Set notification as seen and returns associated item (if possible)
4704 * POST request with 'id' param as notification id
4706 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4707 * @return string|array
4708 * @throws BadRequestException
4709 * @throws ForbiddenException
4710 * @throws ImagickException
4711 * @throws InternalServerErrorException
4712 * @throws UnauthorizedException
4714 function api_friendica_notification_seen($type)
4716 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4718 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4720 if (DI::args()->getArgc() !== 4) {
4721 throw new BadRequestException('Invalid argument count');
4724 $id = intval($_REQUEST['id'] ?? 0);
4727 $Notify = DI::notify()->selectOneById($id);
4728 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4729 throw new NotFoundException();
4732 if ($Notify->uriId) {
4733 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4737 DI::notify()->save($Notify);
4739 if ($Notify->otype === Notification\ObjectType::ITEM) {
4740 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4741 if (DBA::isResult($item)) {
4742 // we found the item, return it to the user
4743 $ret = api_format_items([$item], $user_info, false, $type);
4744 $data = ['status' => $ret];
4745 return DI::apiResponse()->formatData('status', $type, $data);
4747 // the item can't be found, but we set the notification as seen, so we count this as a success
4750 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4751 } catch (NotFoundException $e) {
4752 throw new BadRequestException('Invalid argument', $e);
4753 } catch (Exception $e) {
4754 throw new InternalServerErrorException('Internal Server exception', $e);
4758 /// @TODO move to top of file or somewhere better
4759 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4762 * search for direct_messages containing a searchstring through api
4764 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4765 * @param string $box
4766 * @return string|array (success: success=true if found and search_result contains found messages,
4767 * success=false if nothing was found, search_result='nothing found',
4768 * error: result=error with error message)
4769 * @throws BadRequestException
4770 * @throws ForbiddenException
4771 * @throws ImagickException
4772 * @throws InternalServerErrorException
4773 * @throws UnauthorizedException
4775 function api_friendica_direct_messages_search($type, $box = "")
4777 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4780 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4781 $searchstring = $_REQUEST['searchstring'] ?? '';
4782 $uid = $user_info['uid'];
4784 // error if no searchstring specified
4785 if ($searchstring == "") {
4786 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4787 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4790 // get data for the specified searchstring
4791 $r = DBA::toArray(DBA::p(
4792 "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",
4794 '%'.$searchstring.'%'
4797 $profile_url = $user_info["url"];
4799 // message if nothing was found
4800 if (!DBA::isResult($r)) {
4801 $success = ['success' => false, 'search_results' => 'problem with query'];
4802 } elseif (count($r) == 0) {
4803 $success = ['success' => false, 'search_results' => 'nothing found'];
4806 foreach ($r as $item) {
4807 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4808 $recipient = $user_info;
4809 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4810 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4811 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4812 $sender = $user_info;
4815 if (isset($recipient) && isset($sender)) {
4816 $ret[] = api_format_messages($item, $recipient, $sender);
4819 $success = ['success' => true, 'search_results' => $ret];
4822 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4825 /// @TODO move to top of file or somewhere better
4826 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4829 * Number of comments
4831 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4833 * @param object $data [Status, Status]
4837 function bindComments(&$data)
4839 if (count($data) == 0) {
4845 foreach ($data as $item) {
4846 $ids[] = $item['id'];
4849 $idStr = DBA::escape(implode(', ', $ids));
4850 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4851 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4852 $itemsData = DBA::toArray($items);
4854 foreach ($itemsData as $item) {
4855 $comments[$item['parent']] = $item['comments'];
4858 foreach ($data as $idx => $item) {
4860 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4865 @TODO Maybe open to implement?
4867 [pagename] => api/1.1/statuses/lookup.json
4868 [id] => 605138389168451584
4869 [include_cards] => true
4870 [cards_platform] => Android-12
4871 [include_entities] => true
4872 [include_my_retweet] => 1
4874 [include_reply_count] => true
4875 [include_descendent_reply_count] => true
4879 Not implemented by now:
4880 statuses/retweets_of_me
4885 account/update_location
4886 account/update_profile_background_image
4889 friendica/profile/update
4890 friendica/profile/create
4891 friendica/profile/delete
4893 Not implemented in status.net:
4894 statuses/retweeted_to_me
4895 statuses/retweeted_by_me
4896 direct_messages/destroy
4898 account/update_delivery_device
4899 notifications/follow