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} - ');
79 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
80 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
81 * into a page, and visitors will post something without noticing it).
85 $user = OAuth::getCurrentUserID();
90 if (!empty($_SESSION['allow_api'])) {
98 * Get source name from API client
100 * Clients can send 'source' parameter to be show in post metadata
101 * as "sent via <source>".
102 * Some clients doesn't send a source param, we support ones we know
103 * (only Twidere, atm)
106 * Client source name, default to "api" if unset/unknown
109 function api_source()
111 if (requestdata('source')) {
112 return requestdata('source');
115 // Support for known clients that doesn't send a source name
116 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
117 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
121 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
123 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
130 * Format date for API
132 * @param string $str Source date, as UTC
133 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
136 function api_date($str)
138 // Wed May 23 06:01:13 +0000 2007
139 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
143 * Register a function to be the endpoint for defined API path.
145 * @param string $path API URL path, relative to DI::baseUrl()
146 * @param string $func Function name to call on path request
147 * @param bool $auth API need logged user
148 * @param string $method HTTP method reqiured to call this endpoint.
149 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
150 * Default to API_METHOD_ANY
152 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
162 // Workaround for hotot
163 $path = str_replace("api/", "api/1.1/", $path);
173 * Check HTTP method of called API
175 * API endpoints can define which HTTP method to accept when called.
176 * This function check the current HTTP method agains endpoint
179 * @param string $method Required methods, uppercase, separated by comma
182 function api_check_method($method)
184 if ($method == "*") {
187 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
191 * Main API entry point
193 * Authenticate user, call registered API function, set HTTP headers
196 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
197 * @return string|array API call result
200 function api_call(App $a, App\Arguments $args = null)
202 global $API, $called_api;
209 if (strpos($args->getCommand(), ".xml") > 0) {
212 if (strpos($args->getCommand(), ".json") > 0) {
215 if (strpos($args->getCommand(), ".rss") > 0) {
218 if (strpos($args->getCommand(), ".atom") > 0) {
223 foreach ($API as $p => $info) {
224 if (strpos($args->getCommand(), $p) === 0) {
225 if (!api_check_method($info['method'])) {
226 throw new MethodNotAllowedException();
229 $called_api = explode("/", $p);
231 if (!empty($info['auth']) && BaseApi::getCurrentUserID() === false) {
232 BasicAuth::getCurrentUserID(true);
233 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
236 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
238 $stamp = microtime(true);
239 $return = call_user_func($info['func'], $type);
240 $duration = floatval(microtime(true) - $stamp);
242 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
244 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
246 if (false === $return) {
248 * api function returned false withour throw an
249 * exception. This should not happend, throw a 500
251 throw new InternalServerErrorException();
256 header("Content-Type: text/xml");
259 header("Content-Type: application/json");
260 if (!empty($return)) {
261 $json = json_encode(end($return));
262 if (!empty($_GET['callback'])) {
263 $json = $_GET['callback'] . "(" . $json . ")";
269 header("Content-Type: application/rss+xml");
270 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
273 header("Content-Type: application/atom+xml");
274 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
281 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
282 throw new NotFoundException();
283 } catch (HTTPException $e) {
284 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
289 * Set values for RSS template
291 * @param array $arr Array to be passed to template
292 * @param array $user_info User info
294 * @throws BadRequestException
295 * @throws ImagickException
296 * @throws InternalServerErrorException
297 * @throws UnauthorizedException
298 * @todo find proper type-hints
300 function api_rss_extra($arr, $user_info)
302 if (is_null($user_info)) {
303 $uid = BaseApi::getCurrentUserID();
305 throw new ForbiddenException();
308 $user_info = DI::twitterUser()->createFromUserId($uid)->toArray();
311 $arr['$user'] = $user_info;
313 'alternate' => $user_info['url'],
314 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
315 'base' => DI::baseUrl(),
316 'updated' => api_date(null),
317 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
318 'language' => $user_info['lang'],
319 'logo' => DI::baseUrl() . "/images/friendica-32.png",
327 * Unique contact to contact url.
329 * @param int $id Contact id
330 * @return bool|string
331 * Contact url or False if contact id is unknown
334 function api_unique_id_to_nurl($id)
336 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
338 if (DBA::isResult($r)) {
346 * Get user info array.
349 * @param int|string $contact_id Contact ID or URL
351 * @throws BadRequestException
352 * @throws ImagickException
353 * @throws InternalServerErrorException
354 * @throws UnauthorizedException
356 function api_get_user($contact_id = null)
364 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
366 // Searching for contact URL
367 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
368 $user = Strings::normaliseLink($contact_id);
370 $extra_query = "AND `contact`.`nurl` = ? ";
371 if (BaseApi::getCurrentUserID() !== false) {
372 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
376 // Searching for contact id with uid = 0
377 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
378 $user = api_unique_id_to_nurl(intval($contact_id));
381 throw new BadRequestException("User ID ".$contact_id." not found.");
385 $extra_query = "AND `contact`.`nurl` = ? ";
386 if (BaseApi::getCurrentUserID() !== false) {
387 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
391 if (is_null($user) && !empty($_GET['user_id'])) {
392 $user = api_unique_id_to_nurl($_GET['user_id']);
395 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
399 $extra_query = "AND `contact`.`nurl` = ? ";
400 if (BaseApi::getCurrentUserID() !== false) {
401 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
404 if (is_null($user) && !empty($_GET['screen_name'])) {
405 $user = $_GET['screen_name'];
406 $extra_query = "AND `contact`.`nick` = ? ";
407 if (BaseApi::getCurrentUserID() !== false) {
408 $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
412 if (is_null($user) && !empty($_GET['profileurl'])) {
413 $user = Strings::normaliseLink($_GET['profileurl']);
414 $extra_query = "AND `contact`.`nurl` = ? ";
415 if (BaseApi::getCurrentUserID() !== false) {
416 $extra_query .= "AND `contact`.`uid`=".intval(BaseApi::getCurrentUserID());
420 // $called_api is the API path exploded on / and is expected to have at least 2 elements
421 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
422 $argid = count($called_api);
423 if (!empty(DI::args()->getArgv()[$argid])) {
424 $data = explode(".", DI::args()->getArgv()[$argid]);
425 if (count($data) > 1) {
426 [$user, $null] = $data;
429 if (is_numeric($user)) {
430 $user = api_unique_id_to_nurl(intval($user));
434 $extra_query = "AND `contact`.`nurl` = ? ";
435 if (BaseApi::getCurrentUserID() !== false) {
436 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
440 $extra_query = "AND `contact`.`nick` = ? ";
441 if (BaseApi::getCurrentUserID() !== false) {
442 $extra_query .= "AND `contact`.`uid`=" . intval(BaseApi::getCurrentUserID());
447 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
450 if (BaseApi::getCurrentUserID() === false) {
451 BasicAuth::getCurrentUserID(true);
454 $user = BaseApi::getCurrentUserID();
455 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
459 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
462 $uinfo = DBA::toArray(DBA::p(
463 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
469 if (DBA::isResult($uinfo)) {
470 // Selecting the id by priority, friendica first
471 api_best_nickname($uinfo);
472 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
476 throw new BadRequestException("User not found.");
479 $cid = Contact::getIdForURL($url, 0, false);
482 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
484 throw new BadRequestException("User ".$url." not found.");
489 * return api-formatted array for item's author and owner
492 * @param array $item item from db
493 * @return array(array:author, array:owner)
494 * @throws BadRequestException
495 * @throws ImagickException
496 * @throws InternalServerErrorException
497 * @throws UnauthorizedException
499 function api_item_get_user(App $a, $item)
501 $status_user = DI::twitterUser()->createFromContactId($item['author-id'] ?? 0, BaseApi::getCurrentUserID())->toArray();
503 $author_user = $status_user;
505 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
507 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
508 $owner_user = DI::twitterUser()->createFromContactId($item['owner-id'] ?? 0, BaseApi::getCurrentUserID())->toArray();
510 $owner_user = $author_user;
513 return ([$status_user, $author_user, $owner_user]);
521 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
522 * returns a 401 status code and an error message if not.
524 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
526 * @param string $type Return type (atom, rss, xml, json)
527 * @return array|string
528 * @throws BadRequestException
529 * @throws ForbiddenException
530 * @throws ImagickException
531 * @throws InternalServerErrorException
532 * @throws UnauthorizedException
534 function api_account_verify_credentials($type)
536 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
538 unset($_REQUEST["user_id"]);
539 unset($_GET["user_id"]);
541 unset($_REQUEST["screen_name"]);
542 unset($_GET["screen_name"]);
544 $skip_status = $_REQUEST['skip_status'] ?? false;
546 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
548 // "verified" isn't used here in the standard
549 unset($user_info["verified"]);
551 // - Adding last status
553 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
555 $user_info['status'] = api_format_item($item, $type);
559 // "uid" and "self" are only needed for some internal stuff, so remove it from here
560 unset($user_info["uid"]);
561 unset($user_info["self"]);
563 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
566 /// @TODO move to top of file or somewhere better
567 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
570 * Get data from $_POST or $_GET
575 function requestdata($k)
577 if (!empty($_POST[$k])) {
580 if (!empty($_GET[$k])) {
587 * Deprecated function to upload media.
589 * @param string $type Return type (atom, rss, xml, json)
591 * @return array|string
592 * @throws BadRequestException
593 * @throws ForbiddenException
594 * @throws ImagickException
595 * @throws InternalServerErrorException
596 * @throws UnauthorizedException
598 function api_statuses_mediap($type)
602 if (empty(BaseApi::getCurrentUserID())) {
603 throw new ForbiddenException();
606 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
608 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
610 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
611 $_REQUEST['api_source'] = true;
612 $txt = requestdata('status') ?? '';
613 /// @TODO old-lost code?
614 //$txt = urldecode(requestdata('status'));
616 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
617 $txt = HTML::toBBCodeVideo($txt);
618 $config = HTMLPurifier_Config::createDefault();
619 $config->set('Cache.DefinitionImpl', null);
620 $purifier = new HTMLPurifier($config);
621 $txt = $purifier->purify($txt);
623 $txt = HTML::toBBCode($txt);
625 DI::args()->getArgv()[1] = $user_info['screen_name']; //should be set to username?
627 $picture = wall_upload_post($a, false);
629 // now that we have the img url in bbcode we can add it to the status and insert the wall item.
630 $_REQUEST['body'] = $txt . "\n\n" . '[url=' . $picture["albumpage"] . '][img]' . $picture["preview"] . "[/img][/url]";
631 $item_id = item_post($a);
633 // output the post that we just posted.
634 return api_status_show($type, $item_id);
637 /// @TODO move this to top of file or somewhere better!
638 api_register_func('api/statuses/mediap', 'api_statuses_mediap', true, API_METHOD_POST);
641 * Updates the user’s current status.
643 * @param string $type Return type (atom, rss, xml, json)
645 * @return array|string
646 * @throws BadRequestException
647 * @throws ForbiddenException
648 * @throws ImagickException
649 * @throws InternalServerErrorException
650 * @throws TooManyRequestsException
651 * @throws UnauthorizedException
652 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
654 function api_statuses_update($type)
658 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
660 // convert $_POST array items to the form we use for web posts.
661 if (requestdata('htmlstatus')) {
662 $txt = requestdata('htmlstatus') ?? '';
663 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
664 $txt = HTML::toBBCodeVideo($txt);
666 $config = HTMLPurifier_Config::createDefault();
667 $config->set('Cache.DefinitionImpl', null);
669 $purifier = new HTMLPurifier($config);
670 $txt = $purifier->purify($txt);
672 $_REQUEST['body'] = HTML::toBBCode($txt);
675 $_REQUEST['body'] = requestdata('status');
678 $_REQUEST['title'] = requestdata('title');
680 $parent = requestdata('in_reply_to_status_id');
682 // Twidere sends "-1" if it is no reply ...
687 if (ctype_digit($parent)) {
688 $_REQUEST['parent'] = $parent;
690 $_REQUEST['parent_uri'] = $parent;
693 if (requestdata('lat') && requestdata('long')) {
694 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
696 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
699 // Check for throttling (maximum posts per day, week and month)
700 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
701 if ($throttle_day > 0) {
702 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
704 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
705 $posts_day = Post::count($condition);
707 if ($posts_day > $throttle_day) {
708 logger::info('Daily posting limit reached for user '.BaseApi::getCurrentUserID());
709 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
710 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));
714 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
715 if ($throttle_week > 0) {
716 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
718 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
719 $posts_week = Post::count($condition);
721 if ($posts_week > $throttle_week) {
722 logger::info('Weekly posting limit reached for user '.BaseApi::getCurrentUserID());
723 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
724 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));
728 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
729 if ($throttle_month > 0) {
730 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
732 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, BaseApi::getCurrentUserID(), $datefrom];
733 $posts_month = Post::count($condition);
735 if ($posts_month > $throttle_month) {
736 logger::info('Monthly posting limit reached for user '.BaseApi::getCurrentUserID());
737 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
738 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));
743 if (requestdata('media_ids')) {
744 $ids = explode(',', requestdata('media_ids') ?? '');
745 } elseif (!empty($_FILES['media'])) {
746 // upload the image if we have one
747 $picture = wall_upload_post($a, false);
748 if (is_array($picture)) {
749 $ids[] = $picture['id'];
757 foreach ($ids as $id) {
758 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
759 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
760 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
761 ORDER BY `photo`.`width` DESC LIMIT 2", $id, BaseApi::getCurrentUserID()));
763 if (!empty($media)) {
764 $ressources[] = $media[0]['resource-id'];
765 $phototypes = Images::supportedTypes();
766 $ext = $phototypes[$media[0]['type']];
768 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
769 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
770 'size' => $media[0]['datasize'],
771 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
772 'description' => $media[0]['desc'] ?? '',
773 'width' => $media[0]['width'],
774 'height' => $media[0]['height']];
776 if (count($media) > 1) {
777 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
778 $attachment['preview-width'] = $media[1]['width'];
779 $attachment['preview-height'] = $media[1]['height'];
781 $attachments[] = $attachment;
785 // We have to avoid that the post is rejected because of an empty body
786 if (empty($_REQUEST['body'])) {
787 $_REQUEST['body'] = '[hr]';
791 if (!empty($attachments)) {
792 $_REQUEST['attachments'] = $attachments;
795 // set this so that the item_post() function is quiet and doesn't redirect or emit json
797 $_REQUEST['api_source'] = true;
799 if (empty($_REQUEST['source'])) {
800 $_REQUEST["source"] = api_source();
803 // call out normal post function
804 $item_id = item_post($a);
806 if (!empty($ressources) && !empty($item_id)) {
807 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
808 foreach ($ressources as $ressource) {
809 Photo::setPermissionForRessource($ressource, BaseApi::getCurrentUserID(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
813 // output the post that we just posted.
814 return api_status_show($type, $item_id);
817 /// @TODO move to top of file or somewhere better
818 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
819 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
822 * Uploads an image to Friendica.
825 * @throws BadRequestException
826 * @throws ForbiddenException
827 * @throws ImagickException
828 * @throws InternalServerErrorException
829 * @throws UnauthorizedException
830 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
832 function api_media_upload()
836 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
838 if (empty($_FILES['media'])) {
840 throw new BadRequestException("No media.");
843 $media = wall_upload_post($a, false);
846 throw new InternalServerErrorException();
850 $returndata["media_id"] = $media["id"];
851 $returndata["media_id_string"] = (string)$media["id"];
852 $returndata["size"] = $media["size"];
853 $returndata["image"] = ["w" => $media["width"],
854 "h" => $media["height"],
855 "image_type" => $media["type"],
856 "friendica_preview_url" => $media["preview"]];
858 Logger::info('Media uploaded', ['return' => $returndata]);
860 return ["media" => $returndata];
863 /// @TODO move to top of file or somewhere better
864 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
867 * Updates media meta data (picture descriptions)
869 * @param string $type Return type (atom, rss, xml, json)
871 * @return array|string
872 * @throws BadRequestException
873 * @throws ForbiddenException
874 * @throws ImagickException
875 * @throws InternalServerErrorException
876 * @throws TooManyRequestsException
877 * @throws UnauthorizedException
878 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
880 * @todo Compare the corresponding Twitter function for correct return values
882 function api_media_metadata_create($type)
884 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
886 $postdata = Network::postdata();
888 if (empty($postdata)) {
889 throw new BadRequestException("No post data");
892 $data = json_decode($postdata, true);
894 throw new BadRequestException("Invalid post data");
897 if (empty($data['media_id']) || empty($data['alt_text'])) {
898 throw new BadRequestException("Missing post data values");
901 if (empty($data['alt_text']['text'])) {
902 throw new BadRequestException("No alt text.");
905 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
907 $condition = ['id' => $data['media_id'], 'uid' => BaseApi::getCurrentUserID()];
908 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
909 if (!DBA::isResult($photo)) {
910 throw new BadRequestException("Metadata not found.");
913 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
916 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
919 * @param string $type Return format (atom, rss, xml, json)
920 * @param int $item_id
921 * @return array|string
924 function api_status_show($type, $item_id)
926 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
930 $item = api_get_item(['id' => $item_id]);
932 $status_info = api_format_item($item, $type);
935 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
937 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
941 * Retrieves the last public status of the provided user info
943 * @param int $ownerId Public contact Id
944 * @param int $uid User Id
948 function api_get_last_status($ownerId, $uid)
951 'author-id'=> $ownerId,
953 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
954 'private' => [Item::PUBLIC, Item::UNLISTED]
957 $item = api_get_item($condition);
963 * Retrieves a single item record based on the provided condition and converts it for API use.
965 * @param array $condition Item table condition array
969 function api_get_item(array $condition)
971 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
977 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
978 * The author's most recent status will be returned inline.
980 * @param string $type Return type (atom, rss, xml, json)
981 * @return array|string
982 * @throws BadRequestException
983 * @throws ImagickException
984 * @throws InternalServerErrorException
985 * @throws UnauthorizedException
986 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
988 function api_users_show($type)
990 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
992 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
994 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
996 $user_info['status'] = api_format_item($item, $type);
999 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1000 unset($user_info['uid']);
1001 unset($user_info['self']);
1003 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1006 /// @TODO move to top of file or somewhere better
1007 api_register_func('api/users/show', 'api_users_show');
1008 api_register_func('api/externalprofile/show', 'api_users_show');
1011 * Search a public user account.
1013 * @param string $type Return type (atom, rss, xml, json)
1015 * @return array|string
1016 * @throws BadRequestException
1017 * @throws ImagickException
1018 * @throws InternalServerErrorException
1019 * @throws UnauthorizedException
1020 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1022 function api_users_search($type)
1026 if (!empty($_GET['q'])) {
1027 $contacts = Contact::selectToArray(
1030 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1038 if (DBA::isResult($contacts)) {
1040 foreach ($contacts as $contact) {
1041 $user_info = DI::twitterUser()->createFromContactId($contact['id'], BaseApi::getCurrentUserID())->toArray();
1043 if ($type == 'xml') {
1044 $userlist[$k++ . ':user'] = $user_info;
1046 $userlist[] = $user_info;
1049 $userlist = ['users' => $userlist];
1051 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1054 throw new BadRequestException('No search term specified.');
1057 return DI::apiResponse()->formatData('users', $type, $userlist);
1060 /// @TODO move to top of file or somewhere better
1061 api_register_func('api/users/search', 'api_users_search');
1064 * Return user objects
1066 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1068 * @param string $type Return format: json or xml
1070 * @return array|string
1071 * @throws BadRequestException
1072 * @throws ImagickException
1073 * @throws InternalServerErrorException
1074 * @throws NotFoundException if the results are empty.
1075 * @throws UnauthorizedException
1077 function api_users_lookup($type)
1081 if (!empty($_REQUEST['user_id'])) {
1082 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1084 $users[] = api_get_user($id);
1089 if (empty($users)) {
1090 throw new NotFoundException;
1093 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1096 /// @TODO move to top of file or somewhere better
1097 api_register_func('api/users/lookup', 'api_users_lookup', true);
1100 * Returns statuses that match a specified query.
1102 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1104 * @param string $type Return format: json, xml, atom, rss
1106 * @return array|string
1107 * @throws BadRequestException if the "q" parameter is missing.
1108 * @throws ForbiddenException
1109 * @throws ImagickException
1110 * @throws InternalServerErrorException
1111 * @throws UnauthorizedException
1113 function api_search($type)
1115 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1117 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1119 if (empty($_REQUEST['q'])) {
1120 throw new BadRequestException('q parameter is required.');
1123 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1126 $data['status'] = [];
1128 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1129 if (!empty($_REQUEST['rpp'])) {
1130 $count = $_REQUEST['rpp'];
1131 } elseif (!empty($_REQUEST['count'])) {
1132 $count = $_REQUEST['count'];
1135 $since_id = $_REQUEST['since_id'] ?? 0;
1136 $max_id = $_REQUEST['max_id'] ?? 0;
1137 $page = $_REQUEST['page'] ?? 1;
1139 $start = max(0, ($page - 1) * $count);
1141 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1142 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1143 $searchTerm = $matches[1];
1144 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1145 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1147 while ($tag = DBA::fetch($tags)) {
1148 $uriids[] = $tag['uri-id'];
1152 if (empty($uriids)) {
1153 return DI::apiResponse()->formatData('statuses', $type, $data);
1156 $condition = ['uri-id' => $uriids];
1157 if ($exclude_replies) {
1158 $condition['gravity'] = GRAVITY_PARENT;
1161 $params['group_by'] = ['uri-id'];
1163 $condition = ["`id` > ?
1164 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1165 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1166 AND `body` LIKE CONCAT('%',?,'%')",
1167 $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
1169 $condition[0] .= ' AND `id` <= ?';
1170 $condition[] = $max_id;
1176 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1177 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
1180 $id = Item::fetchByLink($searchTerm);
1184 $statuses = Post::select([], ['id' => $id]);
1188 $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1190 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1192 bindComments($data['status']);
1194 return DI::apiResponse()->formatData('statuses', $type, $data);
1197 /// @TODO move to top of file or somewhere better
1198 api_register_func('api/search/tweets', 'api_search', true);
1199 api_register_func('api/search', 'api_search', true);
1202 * Returns the most recent statuses posted by the user and the users they follow.
1204 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1206 * @param string $type Return type (atom, rss, xml, json)
1208 * @return array|string
1209 * @throws BadRequestException
1210 * @throws ForbiddenException
1211 * @throws ImagickException
1212 * @throws InternalServerErrorException
1213 * @throws UnauthorizedException
1214 * @todo Optional parameters
1215 * @todo Add reply info
1217 function api_statuses_home_timeline($type)
1219 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1221 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1223 unset($_REQUEST["user_id"]);
1224 unset($_GET["user_id"]);
1226 unset($_REQUEST["screen_name"]);
1227 unset($_GET["screen_name"]);
1229 // get last network messages
1232 $count = $_REQUEST['count'] ?? 20;
1233 $page = $_REQUEST['page']?? 0;
1234 $since_id = $_REQUEST['since_id'] ?? 0;
1235 $max_id = $_REQUEST['max_id'] ?? 0;
1236 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1237 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1239 $start = max(0, ($page - 1) * $count);
1241 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1242 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1245 $condition[0] .= " AND `id` <= ?";
1246 $condition[] = $max_id;
1248 if ($exclude_replies) {
1249 $condition[0] .= ' AND `gravity` = ?';
1250 $condition[] = GRAVITY_PARENT;
1252 if ($conversation_id > 0) {
1253 $condition[0] .= " AND `parent` = ?";
1254 $condition[] = $conversation_id;
1257 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1258 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1260 $items = Post::toArray($statuses);
1262 $ret = api_format_items($items, $user_info, false, $type);
1264 // Set all posts from the query above to seen
1266 foreach ($items as $item) {
1267 $idarray[] = intval($item["id"]);
1270 if (!empty($idarray)) {
1271 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1273 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1279 $data = ['status' => $ret];
1284 $data = api_rss_extra($data, $user_info);
1288 return DI::apiResponse()->formatData("statuses", $type, $data);
1292 /// @TODO move to top of file or somewhere better
1293 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1294 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1297 * Returns the most recent statuses from public users.
1299 * @param string $type Return type (atom, rss, xml, json)
1301 * @return array|string
1302 * @throws BadRequestException
1303 * @throws ForbiddenException
1304 * @throws ImagickException
1305 * @throws InternalServerErrorException
1306 * @throws UnauthorizedException
1308 function api_statuses_public_timeline($type)
1310 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1312 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1314 // get last network messages
1317 $count = $_REQUEST['count'] ?? 20;
1318 $page = $_REQUEST['page'] ?? 1;
1319 $since_id = $_REQUEST['since_id'] ?? 0;
1320 $max_id = $_REQUEST['max_id'] ?? 0;
1321 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1322 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1324 $start = max(0, ($page - 1) * $count);
1326 if ($exclude_replies && !$conversation_id) {
1327 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1328 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1331 $condition[0] .= " AND `id` <= ?";
1332 $condition[] = $max_id;
1335 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1336 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1338 $r = Post::toArray($statuses);
1340 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1341 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1344 $condition[0] .= " AND `id` <= ?";
1345 $condition[] = $max_id;
1347 if ($conversation_id > 0) {
1348 $condition[0] .= " AND `parent` = ?";
1349 $condition[] = $conversation_id;
1352 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1353 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1355 $r = Post::toArray($statuses);
1358 $ret = api_format_items($r, $user_info, false, $type);
1362 $data = ['status' => $ret];
1367 $data = api_rss_extra($data, $user_info);
1371 return DI::apiResponse()->formatData("statuses", $type, $data);
1374 /// @TODO move to top of file or somewhere better
1375 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1378 * Returns the most recent statuses posted by users this node knows about.
1380 * @param string $type Return format: json, xml, atom, rss
1381 * @return array|string
1382 * @throws BadRequestException
1383 * @throws ForbiddenException
1384 * @throws ImagickException
1385 * @throws InternalServerErrorException
1386 * @throws UnauthorizedException
1388 function api_statuses_networkpublic_timeline($type)
1390 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1392 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1394 $since_id = $_REQUEST['since_id'] ?? 0;
1395 $max_id = $_REQUEST['max_id'] ?? 0;
1398 $count = $_REQUEST['count'] ?? 20;
1399 $page = $_REQUEST['page'] ?? 1;
1401 $start = max(0, ($page - 1) * $count);
1403 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1404 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1407 $condition[0] .= " AND `id` <= ?";
1408 $condition[] = $max_id;
1411 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1412 $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1414 $ret = api_format_items($statuses, $user_info, false, $type);
1418 $data = ['status' => $ret];
1423 $data = api_rss_extra($data, $user_info);
1427 return DI::apiResponse()->formatData("statuses", $type, $data);
1430 /// @TODO move to top of file or somewhere better
1431 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1434 * Returns a single status.
1436 * @param string $type Return type (atom, rss, xml, json)
1438 * @return array|string
1439 * @throws BadRequestException
1440 * @throws ForbiddenException
1441 * @throws ImagickException
1442 * @throws InternalServerErrorException
1443 * @throws UnauthorizedException
1444 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1446 function api_statuses_show($type)
1448 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1450 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1453 $id = intval(DI::args()->getArgv()[3] ?? 0);
1456 $id = intval($_REQUEST['id'] ?? 0);
1461 $id = intval(DI::args()->getArgv()[4] ?? 0);
1464 logger::notice('API: api_statuses_show: ' . $id);
1466 $conversation = !empty($_REQUEST['conversation']);
1468 // try to fetch the item for the local user - or the public item, if there is no local one
1469 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1470 if (!DBA::isResult($uri_item)) {
1471 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1474 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1475 if (!DBA::isResult($item)) {
1476 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1481 if ($conversation) {
1482 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1483 $params = ['order' => ['id' => true]];
1485 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1489 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1491 /// @TODO How about copying this to above methods which don't check $r ?
1492 if (!DBA::isResult($statuses)) {
1493 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1496 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1498 if ($conversation) {
1499 $data = ['status' => $ret];
1500 return DI::apiResponse()->formatData("statuses", $type, $data);
1502 $data = ['status' => $ret[0]];
1503 return DI::apiResponse()->formatData("status", $type, $data);
1507 /// @TODO move to top of file or somewhere better
1508 api_register_func('api/statuses/show', 'api_statuses_show', true);
1512 * @param string $type Return type (atom, rss, xml, json)
1514 * @return array|string
1515 * @throws BadRequestException
1516 * @throws ForbiddenException
1517 * @throws ImagickException
1518 * @throws InternalServerErrorException
1519 * @throws UnauthorizedException
1520 * @todo nothing to say?
1522 function api_conversation_show($type)
1524 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1526 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1529 $id = intval(DI::args()->getArgv()[3] ?? 0);
1530 $since_id = intval($_REQUEST['since_id'] ?? 0);
1531 $max_id = intval($_REQUEST['max_id'] ?? 0);
1532 $count = intval($_REQUEST['count'] ?? 20);
1533 $page = intval($_REQUEST['page'] ?? 1);
1535 $start = max(0, ($page - 1) * $count);
1538 $id = intval($_REQUEST['id'] ?? 0);
1543 $id = intval(DI::args()->getArgv()[4] ?? 0);
1546 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1548 // try to fetch the item for the local user - or the public item, if there is no local one
1549 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1550 if (!DBA::isResult($item)) {
1551 throw new BadRequestException("There is no status with the id $id.");
1554 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1555 if (!DBA::isResult($parent)) {
1556 throw new BadRequestException("There is no status with this id.");
1559 $id = $parent['id'];
1561 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1562 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1565 $condition[0] .= " AND `id` <= ?";
1566 $condition[] = $max_id;
1569 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1570 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1572 if (!DBA::isResult($statuses)) {
1573 throw new BadRequestException("There is no status with id $id.");
1576 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1578 $data = ['status' => $ret];
1579 return DI::apiResponse()->formatData("statuses", $type, $data);
1582 /// @TODO move to top of file or somewhere better
1583 api_register_func('api/conversation/show', 'api_conversation_show', true);
1584 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1589 * @param string $type Return type (atom, rss, xml, json)
1591 * @return array|string
1592 * @throws BadRequestException
1593 * @throws ForbiddenException
1594 * @throws ImagickException
1595 * @throws InternalServerErrorException
1596 * @throws UnauthorizedException
1597 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1599 function api_statuses_repeat($type)
1605 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1608 $id = intval(DI::args()->getArgv()[3] ?? 0);
1611 $id = intval($_REQUEST['id'] ?? 0);
1616 $id = intval(DI::args()->getArgv()[4] ?? 0);
1619 logger::notice('API: api_statuses_repeat: ' . $id);
1621 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1622 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1624 if (DBA::isResult($item) && !empty($item['body'])) {
1625 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1626 if (!Item::performActivity($id, 'announce', local_user())) {
1627 throw new InternalServerErrorException();
1632 if (strpos($item['body'], "[/share]") !== false) {
1633 $pos = strpos($item['body'], "[share");
1634 $post = substr($item['body'], $pos);
1636 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1638 if (!empty($item['title'])) {
1639 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1642 $post .= $item['body'];
1643 $post .= "[/share]";
1645 $_REQUEST['body'] = $post;
1646 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1647 $_REQUEST['api_source'] = true;
1649 if (empty($_REQUEST['source'])) {
1650 $_REQUEST["source"] = api_source();
1653 $item_id = item_post($a);
1656 throw new ForbiddenException();
1659 // output the post that we just posted.
1661 return api_status_show($type, $item_id);
1664 /// @TODO move to top of file or somewhere better
1665 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1668 * Destroys a specific status.
1670 * @param string $type Return type (atom, rss, xml, json)
1672 * @return array|string
1673 * @throws BadRequestException
1674 * @throws ForbiddenException
1675 * @throws ImagickException
1676 * @throws InternalServerErrorException
1677 * @throws UnauthorizedException
1678 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1680 function api_statuses_destroy($type)
1682 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1685 $id = intval(DI::args()->getArgv()[3] ?? 0);
1688 $id = intval($_REQUEST['id'] ?? 0);
1693 $id = intval(DI::args()->getArgv()[4] ?? 0);
1696 logger::notice('API: api_statuses_destroy: ' . $id);
1698 $ret = api_statuses_show($type);
1700 Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1705 /// @TODO move to top of file or somewhere better
1706 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1709 * Returns the most recent mentions.
1711 * @param string $type Return type (atom, rss, xml, json)
1713 * @return array|string
1714 * @throws BadRequestException
1715 * @throws ForbiddenException
1716 * @throws ImagickException
1717 * @throws InternalServerErrorException
1718 * @throws UnauthorizedException
1719 * @see http://developer.twitter.com/doc/get/statuses/mentions
1721 function api_statuses_mentions($type)
1723 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1725 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1727 unset($_REQUEST["user_id"]);
1728 unset($_GET["user_id"]);
1730 unset($_REQUEST["screen_name"]);
1731 unset($_GET["screen_name"]);
1733 // get last network messages
1736 $since_id = intval($_REQUEST['since_id'] ?? 0);
1737 $max_id = intval($_REQUEST['max_id'] ?? 0);
1738 $count = intval($_REQUEST['count'] ?? 20);
1739 $page = intval($_REQUEST['page'] ?? 1);
1741 $start = max(0, ($page - 1) * $count);
1743 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1744 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1745 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1748 GRAVITY_PARENT, GRAVITY_COMMENT,
1749 BaseApi::getCurrentUserID(),
1750 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1751 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1752 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1753 BaseApi::getCurrentUserID(), $since_id,
1757 $query .= " AND `id` <= ?";
1758 $condition[] = $max_id;
1761 array_unshift($condition, $query);
1763 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1764 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1766 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1768 $data = ['status' => $ret];
1773 $data = api_rss_extra($data, $user_info);
1777 return DI::apiResponse()->formatData("statuses", $type, $data);
1780 /// @TODO move to top of file or somewhere better
1781 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1782 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1785 * Returns the most recent statuses posted by the user.
1787 * @param string $type Either "json" or "xml"
1788 * @return string|array
1789 * @throws BadRequestException
1790 * @throws ForbiddenException
1791 * @throws ImagickException
1792 * @throws InternalServerErrorException
1793 * @throws UnauthorizedException
1794 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1796 function api_statuses_user_timeline($type)
1798 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1800 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1802 Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1804 $since_id = $_REQUEST['since_id'] ?? 0;
1805 $max_id = $_REQUEST['max_id'] ?? 0;
1806 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1807 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1810 $count = $_REQUEST['count'] ?? 20;
1811 $page = $_REQUEST['page'] ?? 1;
1813 $start = max(0, ($page - 1) * $count);
1815 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1816 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1818 if ($user_info['self'] == 1) {
1819 $condition[0] .= ' AND `wall` ';
1822 if ($exclude_replies) {
1823 $condition[0] .= ' AND `gravity` = ?';
1824 $condition[] = GRAVITY_PARENT;
1827 if ($conversation_id > 0) {
1828 $condition[0] .= " AND `parent` = ?";
1829 $condition[] = $conversation_id;
1833 $condition[0] .= " AND `id` <= ?";
1834 $condition[] = $max_id;
1836 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1837 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1839 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1843 $data = ['status' => $ret];
1848 $data = api_rss_extra($data, $user_info);
1852 return DI::apiResponse()->formatData("statuses", $type, $data);
1855 /// @TODO move to top of file or somewhere better
1856 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1859 * Star/unstar an item.
1860 * param: id : id of the item
1862 * @param string $type Return type (atom, rss, xml, json)
1864 * @return array|string
1865 * @throws BadRequestException
1866 * @throws ForbiddenException
1867 * @throws ImagickException
1868 * @throws InternalServerErrorException
1869 * @throws UnauthorizedException
1870 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1872 function api_favorites_create_destroy($type)
1874 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1876 // for versioned api.
1877 /// @TODO We need a better global soluton
1878 $action_argv_id = 2;
1879 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1880 $action_argv_id = 3;
1883 if (DI::args()->getArgc() <= $action_argv_id) {
1884 throw new BadRequestException("Invalid request.");
1886 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1887 if (DI::args()->getArgc() == $action_argv_id + 2) {
1888 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1890 $itemid = intval($_REQUEST['id'] ?? 0);
1893 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1895 if (!DBA::isResult($item)) {
1896 throw new BadRequestException("Invalid item.");
1901 $item['starred'] = 1;
1904 $item['starred'] = 0;
1907 throw new BadRequestException("Invalid action ".$action);
1910 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1913 throw new InternalServerErrorException("DB error");
1916 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1917 $rets = api_format_items([$item], $user_info, false, $type);
1920 $data = ['status' => $ret];
1925 $data = api_rss_extra($data, $user_info);
1929 return DI::apiResponse()->formatData("status", $type, $data);
1932 /// @TODO move to top of file or somewhere better
1933 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1934 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1937 * Returns the most recent favorite statuses.
1939 * @param string $type Return type (atom, rss, xml, json)
1941 * @return string|array
1942 * @throws BadRequestException
1943 * @throws ForbiddenException
1944 * @throws ImagickException
1945 * @throws InternalServerErrorException
1946 * @throws UnauthorizedException
1948 function api_favorites($type)
1952 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1954 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1958 // in friendica starred item are private
1959 // return favorites only for self
1960 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1962 if ($user_info['self'] == 0) {
1966 $since_id = $_REQUEST['since_id'] ?? 0;
1967 $max_id = $_REQUEST['max_id'] ?? 0;
1968 $count = $_GET['count'] ?? 20;
1969 $page = $_REQUEST['page'] ?? 1;
1971 $start = max(0, ($page - 1) * $count);
1973 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
1974 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1976 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1979 $condition[0] .= " AND `id` <= ?";
1980 $condition[] = $max_id;
1983 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1985 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1990 $data = ['status' => $ret];
1995 $data = api_rss_extra($data, $user_info);
1999 return DI::apiResponse()->formatData("statuses", $type, $data);
2002 /// @TODO move to top of file or somewhere better
2003 api_register_func('api/favorites', 'api_favorites', true);
2007 * @param array $item
2008 * @param array $recipient
2009 * @param array $sender
2012 * @throws InternalServerErrorException
2014 function api_format_messages($item, $recipient, $sender)
2016 // standard meta information
2018 'id' => $item['id'],
2019 'sender_id' => $sender['id'],
2021 'recipient_id' => $recipient['id'],
2022 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2023 'sender_screen_name' => $sender['screen_name'],
2024 'recipient_screen_name' => $recipient['screen_name'],
2025 'sender' => $sender,
2026 'recipient' => $recipient,
2028 'friendica_seen' => $item['seen'] ?? 0,
2029 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2032 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2033 if (isset($ret['sender']['uid'])) {
2034 unset($ret['sender']['uid']);
2036 if (isset($ret['sender']['self'])) {
2037 unset($ret['sender']['self']);
2039 if (isset($ret['recipient']['uid'])) {
2040 unset($ret['recipient']['uid']);
2042 if (isset($ret['recipient']['self'])) {
2043 unset($ret['recipient']['self']);
2046 //don't send title to regular StatusNET requests to avoid confusing these apps
2047 if (!empty($_GET['getText'])) {
2048 $ret['title'] = $item['title'];
2049 if ($_GET['getText'] == 'html') {
2050 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2051 } elseif ($_GET['getText'] == 'plain') {
2052 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2055 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2057 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2058 unset($ret['sender']);
2059 unset($ret['recipient']);
2067 * @param array $item
2070 * @throws InternalServerErrorException
2072 function api_convert_item($item)
2074 $body = api_add_attachments_to_body($item);
2076 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2078 // Add pictures to the attachment array and remove them from the body
2079 $attachments = api_get_attachments($body, $item['uri-id']);
2081 // Workaround for ostatus messages where the title is identically to the body
2082 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2083 $statusbody = trim(HTML::toPlaintext($html, 0));
2085 // handle data: images
2086 $statusbody = api_format_items_embeded_images($item, $statusbody);
2088 $statustitle = trim($item['title']);
2090 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2091 $statustext = trim($statusbody);
2093 $statustext = trim($statustitle."\n\n".$statusbody);
2096 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2097 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2100 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2102 // Workaround for clients with limited HTML parser functionality
2103 $search = ["<br>", "<blockquote>", "</blockquote>",
2104 "<h1>", "</h1>", "<h2>", "</h2>",
2105 "<h3>", "</h3>", "<h4>", "</h4>",
2106 "<h5>", "</h5>", "<h6>", "</h6>"];
2107 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2108 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2109 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2110 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2111 $statushtml = str_replace($search, $replace, $statushtml);
2113 if ($item['title'] != "") {
2114 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2118 $oldtext = $statushtml;
2119 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2120 } while ($oldtext != $statushtml);
2122 if (substr($statushtml, 0, 4) == '<br>') {
2123 $statushtml = substr($statushtml, 4);
2126 if (substr($statushtml, 0, -4) == '<br>') {
2127 $statushtml = substr($statushtml, -4);
2130 // feeds without body should contain the link
2131 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2132 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2136 "text" => $statustext,
2137 "html" => $statushtml,
2138 "attachments" => $attachments,
2139 "entities" => $entities
2144 * Add media attachments to the body
2146 * @param array $item
2147 * @return string body with added media
2149 function api_add_attachments_to_body(array $item)
2151 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2153 if (strpos($body, '[/img]') !== false) {
2157 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2158 if (!empty($media['preview'])) {
2159 $description = $media['description'] ?: $media['name'];
2160 if (!empty($description)) {
2161 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2163 $body .= "\n[img]" . $media['preview'] .'[/img]';
2173 * @param string $body
2177 * @throws InternalServerErrorException
2179 function api_get_attachments(&$body, $uriid)
2181 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2182 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2184 $URLSearchString = "^\[\]";
2185 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2189 // Remove all embedded pictures, since they are added as attachments
2190 foreach ($images[0] as $orig) {
2191 $body = str_replace($orig, '', $body);
2196 foreach ($images[1] as $image) {
2197 $imagedata = Images::getInfoFromURLCached($image);
2200 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2204 return $attachments;
2209 * @param string $text
2210 * @param string $bbcode
2213 * @throws InternalServerErrorException
2214 * @todo Links at the first character of the post
2216 function api_get_entitities(&$text, $bbcode, $uriid)
2218 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2220 if ($include_entities != "true") {
2221 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2223 foreach ($images[1] as $image) {
2224 $replace = Post\Link::getByLink($uriid, $image);
2225 $text = str_replace($image, $replace, $text);
2230 $bbcode = BBCode::cleanPictureLinks($bbcode);
2232 // Change pure links in text to bbcode uris
2233 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2236 $entities["hashtags"] = [];
2237 $entities["symbols"] = [];
2238 $entities["urls"] = [];
2239 $entities["user_mentions"] = [];
2241 $URLSearchString = "^\[\]";
2243 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2245 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2246 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2248 $bbcode = preg_replace(
2249 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2250 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2253 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2255 $bbcode = preg_replace(
2256 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2257 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2260 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2262 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2264 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2267 foreach ($urls[1] as $id => $url) {
2268 $start = iconv_strpos($text, $url, 0, "UTF-8");
2269 if (!($start === false)) {
2270 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2274 ksort($ordered_urls);
2278 foreach ($ordered_urls as $url) {
2279 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2280 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2282 $display_url = $url["title"];
2284 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2285 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2287 if (strlen($display_url) > 26) {
2288 $display_url = substr($display_url, 0, 25)."…";
2292 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2293 if (!($start === false)) {
2294 $entities["urls"][] = ["url" => $url["url"],
2295 "expanded_url" => $url["url"],
2296 "display_url" => $display_url,
2297 "indices" => [$start, $start+strlen($url["url"])]];
2298 $offset = $start + 1;
2302 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2303 $ordered_images = [];
2304 foreach ($images as $image) {
2305 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2306 if (!($start === false)) {
2307 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2311 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2312 foreach ($images[1] as $image) {
2313 $start = iconv_strpos($text, $image, 0, "UTF-8");
2314 if (!($start === false)) {
2315 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2321 foreach ($ordered_images as $image) {
2322 $url = $image['url'];
2323 $ext_alt_text = $image['alt'];
2325 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2326 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2328 if (strlen($display_url) > 26) {
2329 $display_url = substr($display_url, 0, 25)."…";
2332 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2333 if (!($start === false)) {
2334 $image = Images::getInfoFromURLCached($url);
2336 $media_url = Post\Link::getByLink($uriid, $url);
2337 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2339 $entities["media"][] = [
2341 "id_str" => (string) ($start + 1),
2342 "indices" => [$start, $start+strlen($url)],
2343 "media_url" => Strings::normaliseLink($media_url),
2344 "media_url_https" => $media_url,
2346 "display_url" => $display_url,
2347 "expanded_url" => $url,
2348 "ext_alt_text" => $ext_alt_text,
2352 $offset = $start + 1;
2361 * @param array $item
2362 * @param string $text
2366 function api_format_items_embeded_images($item, $text)
2368 $text = preg_replace_callback(
2369 '|data:image/([^;]+)[^=]+=*|m',
2370 function () use ($item) {
2371 return DI::baseUrl() . '/display/' . $item['guid'];
2379 * return <a href='url'>name</a> as array
2381 * @param string $txt text
2386 function api_contactlink_to_array($txt)
2389 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2390 if ($r && count($match)==3) {
2392 'name' => $match[2],
2406 * return likes, dislikes and attend status for item
2408 * @param array $item array
2409 * @param string $type Return type (atom, rss, xml, json)
2412 * likes => int count,
2413 * dislikes => int count
2414 * @throws BadRequestException
2415 * @throws ImagickException
2416 * @throws InternalServerErrorException
2417 * @throws UnauthorizedException
2419 function api_format_items_activities($item, $type = "json")
2426 'attendmaybe' => [],
2430 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2431 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2433 while ($parent_item = Post::fetch($ret)) {
2434 // not used as result should be structured like other user data
2435 //builtin_activity_puller($i, $activities);
2437 // get user data and add it to the array of the activity
2438 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2439 switch ($parent_item['verb']) {
2440 case Activity::LIKE:
2441 $activities['like'][] = $user;
2443 case Activity::DISLIKE:
2444 $activities['dislike'][] = $user;
2446 case Activity::ATTEND:
2447 $activities['attendyes'][] = $user;
2449 case Activity::ATTENDNO:
2450 $activities['attendno'][] = $user;
2452 case Activity::ATTENDMAYBE:
2453 $activities['attendmaybe'][] = $user;
2455 case Activity::ANNOUNCE:
2456 $activities['announce'][] = $user;
2465 if ($type == "xml") {
2466 $xml_activities = [];
2467 foreach ($activities as $k => $v) {
2468 // change xml element from "like" to "friendica:like"
2469 $xml_activities["friendica:".$k] = $v;
2470 // add user data into xml output
2472 foreach ($v as $user) {
2473 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2476 $activities = $xml_activities;
2483 * format items to be returned by api
2485 * @param array $items array of items
2486 * @param array $user_info
2487 * @param bool $filter_user filter items by $user_info
2488 * @param string $type Return type (atom, rss, xml, json)
2490 * @throws BadRequestException
2491 * @throws ImagickException
2492 * @throws InternalServerErrorException
2493 * @throws UnauthorizedException
2495 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2501 if (empty($items)) {
2505 foreach ((array)$items as $item) {
2506 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2508 // Look if the posts are matching if they should be filtered by user id
2509 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2513 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2522 * @param array $item Item record
2523 * @param string $type Return format (atom, rss, xml, json)
2524 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2525 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2526 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2527 * @return array API-formatted status
2528 * @throws BadRequestException
2529 * @throws ImagickException
2530 * @throws InternalServerErrorException
2531 * @throws UnauthorizedException
2533 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2537 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2538 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2541 DI::contentItem()->localize($item);
2543 $in_reply_to = api_in_reply_to($item);
2545 $converted = api_convert_item($item);
2547 if ($type == "xml") {
2548 $geo = "georss:point";
2554 'text' => $converted["text"],
2555 'truncated' => false,
2556 'created_at'=> api_date($item['created']),
2557 'in_reply_to_status_id' => $in_reply_to['status_id'],
2558 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2559 'source' => (($item['app']) ? $item['app'] : 'web'),
2560 'id' => intval($item['id']),
2561 'id_str' => (string) intval($item['id']),
2562 'in_reply_to_user_id' => $in_reply_to['user_id'],
2563 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2564 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2566 'favorited' => $item['starred'] ? true : false,
2567 'user' => $status_user,
2568 'friendica_author' => $author_user,
2569 'friendica_owner' => $owner_user,
2570 'friendica_private' => $item['private'] == Item::PRIVATE,
2571 //'entities' => NULL,
2572 'statusnet_html' => $converted["html"],
2573 'statusnet_conversation_id' => $item['parent'],
2574 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2575 'friendica_activities' => api_format_items_activities($item, $type),
2576 'friendica_title' => $item['title'],
2577 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2580 if (count($converted["attachments"]) > 0) {
2581 $status["attachments"] = $converted["attachments"];
2584 if (count($converted["entities"]) > 0) {
2585 $status["entities"] = $converted["entities"];
2588 if ($status["source"] == 'web') {
2589 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2590 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2591 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2594 $retweeted_item = [];
2597 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2598 $announce = api_get_announce($item);
2599 if (!empty($announce)) {
2600 $retweeted_item = $item;
2602 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2606 if (!empty($quoted_item)) {
2607 if ($quoted_item['id'] != $item['id']) {
2608 $quoted_status = api_format_item($quoted_item);
2609 /// @todo Only remove the attachments that are also contained in the quotes status
2610 unset($status['attachments']);
2611 unset($status['entities']);
2613 $conv_quoted = api_convert_item($quoted_item);
2614 $quoted_status = $status;
2615 unset($quoted_status['attachments']);
2616 unset($quoted_status['entities']);
2617 unset($quoted_status['statusnet_conversation_id']);
2618 $quoted_status['text'] = $conv_quoted['text'];
2619 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2621 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2622 } catch (BadRequestException $e) {
2623 // user not found. should be found?
2624 /// @todo check if the user should be always found
2625 $quoted_status["user"] = [];
2628 unset($quoted_status['friendica_author']);
2629 unset($quoted_status['friendica_owner']);
2630 unset($quoted_status['friendica_activities']);
2631 unset($quoted_status['friendica_private']);
2634 if (!empty($retweeted_item)) {
2635 $retweeted_status = $status;
2636 unset($retweeted_status['friendica_author']);
2637 unset($retweeted_status['friendica_owner']);
2638 unset($retweeted_status['friendica_activities']);
2639 unset($retweeted_status['friendica_private']);
2640 unset($retweeted_status['statusnet_conversation_id']);
2641 $status['user'] = $status['friendica_owner'];
2643 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2644 } catch (BadRequestException $e) {
2645 // user not found. should be found?
2646 /// @todo check if the user should be always found
2647 $retweeted_status["user"] = [];
2650 $rt_converted = api_convert_item($retweeted_item);
2652 $retweeted_status['text'] = $rt_converted["text"];
2653 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2654 $retweeted_status['friendica_html'] = $rt_converted["html"];
2655 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2657 if (!empty($quoted_status)) {
2658 $retweeted_status['quoted_status'] = $quoted_status;
2661 $status['friendica_author'] = $retweeted_status['user'];
2662 $status['retweeted_status'] = $retweeted_status;
2663 } elseif (!empty($quoted_status)) {
2664 $root_status = api_convert_item($item);
2666 $status['text'] = $root_status["text"];
2667 $status['statusnet_html'] = $root_status["html"];
2668 $status['quoted_status'] = $quoted_status;
2671 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2672 unset($status["user"]["uid"]);
2673 unset($status["user"]["self"]);
2675 if ($item["coord"] != "") {
2676 $coords = explode(' ', $item["coord"]);
2677 if (count($coords) == 2) {
2678 if ($type == "json") {
2679 $status["geo"] = ['type' => 'Point',
2680 'coordinates' => [(float) $coords[0],
2681 (float) $coords[1]]];
2682 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2683 $status["georss:point"] = $item["coord"];
2692 * Returns all lists the user subscribes to.
2694 * @param string $type Return type (atom, rss, xml, json)
2696 * @return array|string
2697 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2699 function api_lists_list($type)
2702 /// @TODO $ret is not filled here?
2703 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2706 /// @TODO move to top of file or somewhere better
2707 api_register_func('api/lists/list', 'api_lists_list', true);
2708 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2711 * Returns all groups the user owns.
2713 * @param string $type Return type (atom, rss, xml, json)
2715 * @return array|string
2716 * @throws BadRequestException
2717 * @throws ForbiddenException
2718 * @throws ImagickException
2719 * @throws InternalServerErrorException
2720 * @throws UnauthorizedException
2721 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2723 function api_lists_ownerships($type)
2725 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2728 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2729 $uid = $user_info['uid'];
2731 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2733 // loop through all groups
2735 foreach ($groups as $group) {
2736 if ($group['visible']) {
2742 'name' => $group['name'],
2743 'id' => intval($group['id']),
2744 'id_str' => (string) $group['id'],
2745 'user' => $user_info,
2749 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2752 /// @TODO move to top of file or somewhere better
2753 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2756 * Returns recent statuses from users in the specified group.
2758 * @param string $type Return type (atom, rss, xml, json)
2760 * @return array|string
2761 * @throws BadRequestException
2762 * @throws ForbiddenException
2763 * @throws ImagickException
2764 * @throws InternalServerErrorException
2765 * @throws UnauthorizedException
2766 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2768 function api_lists_statuses($type)
2770 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2772 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2774 unset($_REQUEST["user_id"]);
2775 unset($_GET["user_id"]);
2777 unset($_REQUEST["screen_name"]);
2778 unset($_GET["screen_name"]);
2780 if (empty($_REQUEST['list_id'])) {
2781 throw new BadRequestException('list_id not specified');
2785 $count = $_REQUEST['count'] ?? 20;
2786 $page = $_REQUEST['page'] ?? 1;
2787 $since_id = $_REQUEST['since_id'] ?? 0;
2788 $max_id = $_REQUEST['max_id'] ?? 0;
2789 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2790 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2792 $start = max(0, ($page - 1) * $count);
2794 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2795 $gids = array_column($groups, 'contact-id');
2796 $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2797 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2800 $condition[0] .= " AND `id` <= ?";
2801 $condition[] = $max_id;
2803 if ($exclude_replies > 0) {
2804 $condition[0] .= ' AND `gravity` = ?';
2805 $condition[] = GRAVITY_PARENT;
2807 if ($conversation_id > 0) {
2808 $condition[0] .= " AND `parent` = ?";
2809 $condition[] = $conversation_id;
2812 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2813 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2815 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2817 $data = ['status' => $items];
2822 $data = api_rss_extra($data, $user_info);
2826 return DI::apiResponse()->formatData("statuses", $type, $data);
2829 /// @TODO move to top of file or somewhere better
2830 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2833 * Returns either the friends of the follower list
2835 * Considers friends and followers lists to be private and won't return
2836 * anything if any user_id parameter is passed.
2838 * @param string $qtype Either "friends" or "followers"
2839 * @return boolean|array
2840 * @throws BadRequestException
2841 * @throws ForbiddenException
2842 * @throws ImagickException
2843 * @throws InternalServerErrorException
2844 * @throws UnauthorizedException
2846 function api_statuses_f($qtype)
2848 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2851 $count = $_GET['count'] ?? 20;
2852 $page = $_GET['page'] ?? 1;
2854 $start = max(0, ($page - 1) * $count);
2856 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2858 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2859 /* this is to stop Hotot to load friends multiple times
2860 * I'm not sure if I'm missing return something or
2861 * is a bug in hotot. Workaround, meantime
2865 return array('$users' => $ret);*/
2870 if ($qtype == 'friends') {
2871 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2872 } elseif ($qtype == 'followers') {
2873 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2876 // friends and followers only for self
2877 if ($user_info['self'] == 0) {
2878 $sql_extra = " AND false ";
2881 if ($qtype == 'blocks') {
2882 $sql_filter = 'AND `blocked` AND NOT `pending`';
2883 } elseif ($qtype == 'incoming') {
2884 $sql_filter = 'AND `pending`';
2886 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2889 // @todo This query most likely can be replaced with a Contact::select...
2890 $r = DBA::toArray(DBA::p(
2899 BaseApi::getCurrentUserID(),
2905 foreach ($r as $cid) {
2906 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2907 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2908 unset($user["uid"]);
2909 unset($user["self"]);
2916 return ['user' => $ret];
2921 * Returns the list of friends of the provided user
2923 * @deprecated By Twitter API in favor of friends/list
2925 * @param string $type Either "json" or "xml"
2926 * @return boolean|string|array
2927 * @throws BadRequestException
2928 * @throws ForbiddenException
2930 function api_statuses_friends($type)
2932 $data = api_statuses_f("friends");
2933 if ($data === false) {
2936 return DI::apiResponse()->formatData("users", $type, $data);
2940 * Returns the list of followers of the provided user
2942 * @deprecated By Twitter API in favor of friends/list
2944 * @param string $type Either "json" or "xml"
2945 * @return boolean|string|array
2946 * @throws BadRequestException
2947 * @throws ForbiddenException
2949 function api_statuses_followers($type)
2951 $data = api_statuses_f("followers");
2952 if ($data === false) {
2955 return DI::apiResponse()->formatData("users", $type, $data);
2958 /// @TODO move to top of file or somewhere better
2959 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2960 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2963 * Returns the list of blocked users
2965 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
2967 * @param string $type Either "json" or "xml"
2969 * @return boolean|string|array
2970 * @throws BadRequestException
2971 * @throws ForbiddenException
2973 function api_blocks_list($type)
2975 $data = api_statuses_f('blocks');
2976 if ($data === false) {
2979 return DI::apiResponse()->formatData("users", $type, $data);
2982 /// @TODO move to top of file or somewhere better
2983 api_register_func('api/blocks/list', 'api_blocks_list', true);
2986 * Returns the list of pending users IDs
2988 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
2990 * @param string $type Either "json" or "xml"
2992 * @return boolean|string|array
2993 * @throws BadRequestException
2994 * @throws ForbiddenException
2996 function api_friendships_incoming($type)
2998 $data = api_statuses_f('incoming');
2999 if ($data === false) {
3004 foreach ($data['user'] as $user) {
3005 $ids[] = $user['id'];
3008 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3011 /// @TODO move to top of file or somewhere better
3012 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3015 * Sends a new direct message.
3017 * @param string $type Return type (atom, rss, xml, json)
3019 * @return array|string
3020 * @throws BadRequestException
3021 * @throws ForbiddenException
3022 * @throws ImagickException
3023 * @throws InternalServerErrorException
3024 * @throws NotFoundException
3025 * @throws UnauthorizedException
3026 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3028 function api_direct_messages_new($type)
3030 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3032 $uid = BaseApi::getCurrentUserID();
3034 throw new ForbiddenException();
3037 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3041 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
3044 if (!empty($_POST['screen_name'])) {
3045 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
3046 if (DBA::isResult($contacts)) {
3047 // Selecting the id by priority, friendica first
3048 api_best_nickname($contacts);
3050 $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
3053 $recipient = api_get_user($_POST['user_id']);
3056 if (empty($recipient)) {
3057 throw new NotFoundException('Recipient not found');
3061 if (!empty($_REQUEST['replyto'])) {
3062 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
3063 $replyto = $mail['parent-uri'];
3064 $sub = $mail['title'];
3066 if (!empty($_REQUEST['title'])) {
3067 $sub = $_REQUEST['title'];
3069 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3073 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3076 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3077 $ret = api_format_messages($mail, $recipient, $sender);
3079 $ret = ["error" => $id];
3082 $data = ['direct_message'=>$ret];
3088 $data = api_rss_extra($data, $sender);
3092 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3095 /// @TODO move to top of file or somewhere better
3096 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3099 * delete a direct_message from mail table through api
3101 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3102 * @return string|array
3103 * @throws BadRequestException
3104 * @throws ForbiddenException
3105 * @throws ImagickException
3106 * @throws InternalServerErrorException
3107 * @throws UnauthorizedException
3108 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3110 function api_direct_messages_destroy($type)
3112 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3115 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3117 $id = $_REQUEST['id'] ?? 0;
3119 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3120 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3121 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3123 $uid = $user_info['uid'];
3124 // error if no id or parenturi specified (for clients posting parent-uri as well)
3125 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3126 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3127 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3130 // BadRequestException if no id specified (for clients using Twitter API)
3132 throw new BadRequestException('Message id not specified');
3135 // add parent-uri to sql command if specified by calling app
3136 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3138 // error message if specified id is not in database
3139 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3140 if ($verbose == "true") {
3141 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3142 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3144 /// @todo BadRequestException ok for Twitter API clients?
3145 throw new BadRequestException('message id not in database');
3149 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3151 if ($verbose == "true") {
3154 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3155 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3157 $answer = ['result' => 'error', 'message' => 'unknown error'];
3158 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3161 /// @todo return JSON data like Twitter API not yet implemented
3164 /// @TODO move to top of file or somewhere better
3165 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3170 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3171 * @return string|array
3172 * @throws HTTPException\BadRequestException
3173 * @throws HTTPException\ExpectationFailedException
3174 * @throws HTTPException\ForbiddenException
3175 * @throws HTTPException\InternalServerErrorException
3176 * @throws HTTPException\NotFoundException
3177 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3179 function api_friendships_destroy($type)
3181 $uid = BaseApi::getCurrentUserID();
3183 if ($uid === false) {
3184 throw new HTTPException\ForbiddenException();
3187 $owner = User::getOwnerDataById($uid);
3189 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3190 throw new HTTPException\NotFoundException('Error Processing Request');
3193 $contact_id = $_REQUEST['user_id'] ?? 0;
3195 if (empty($contact_id)) {
3196 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3197 throw new HTTPException\BadRequestException('no user_id specified');
3200 // Get Contact by given id
3201 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3203 if(!DBA::isResult($contact)) {
3204 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3205 throw new HTTPException\NotFoundException('no contact found to given ID');
3208 $url = $contact['url'];
3210 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3211 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3212 Strings::normaliseLink($url), $url];
3213 $contact = DBA::selectFirst('contact', [], $condition);
3215 if (!DBA::isResult($contact)) {
3216 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3217 throw new HTTPException\NotFoundException('Not following Contact');
3221 $result = Contact::terminateFriendship($owner, $contact);
3223 if ($result === null) {
3224 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3225 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3228 if ($result === false) {
3229 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3231 } catch (Exception $e) {
3232 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3233 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3236 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3237 unset($contact['uid']);
3238 unset($contact['self']);
3240 // Set screen_name since Twidere requests it
3241 $contact['screen_name'] = $contact['nick'];
3243 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3246 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3250 * @param string $type Return type (atom, rss, xml, json)
3251 * @param string $box
3252 * @param string $verbose
3254 * @return array|string
3255 * @throws BadRequestException
3256 * @throws ForbiddenException
3257 * @throws ImagickException
3258 * @throws InternalServerErrorException
3259 * @throws UnauthorizedException
3261 function api_direct_messages_box($type, $box, $verbose)
3263 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3266 $count = $_GET['count'] ?? 20;
3267 $page = $_REQUEST['page'] ?? 1;
3269 $since_id = $_REQUEST['since_id'] ?? 0;
3270 $max_id = $_REQUEST['max_id'] ?? 0;
3272 $user_id = $_REQUEST['user_id'] ?? '';
3273 $screen_name = $_REQUEST['screen_name'] ?? '';
3276 unset($_REQUEST["user_id"]);
3277 unset($_GET["user_id"]);
3279 unset($_REQUEST["screen_name"]);
3280 unset($_GET["screen_name"]);
3282 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3284 $profile_url = $user_info["url"];
3287 $start = max(0, ($page - 1) * $count);
3292 if ($box=="sentbox") {
3293 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3294 } elseif ($box == "conversation") {
3295 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3296 } elseif ($box == "all") {
3297 $sql_extra = "true";
3298 } elseif ($box == "inbox") {
3299 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3303 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3306 if ($user_id != "") {
3307 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3308 } elseif ($screen_name !="") {
3309 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3312 $r = DBA::toArray(DBA::p(
3313 "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 ?,?",
3314 BaseApi::getCurrentUserID(),
3319 if ($verbose == "true" && !DBA::isResult($r)) {
3320 $answer = ['result' => 'error', 'message' => 'no mails available'];
3321 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3325 foreach ($r as $item) {
3326 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3327 $recipient = $user_info;
3328 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3329 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3330 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3331 $sender = $user_info;
3334 if (isset($recipient) && isset($sender)) {
3335 $ret[] = api_format_messages($item, $recipient, $sender);
3340 $data = ['direct_message' => $ret];
3345 $data = api_rss_extra($data, $user_info);
3349 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3353 * Returns the most recent direct messages sent by the user.
3355 * @param string $type Return type (atom, rss, xml, json)
3357 * @return array|string
3358 * @throws BadRequestException
3359 * @throws ForbiddenException
3360 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3362 function api_direct_messages_sentbox($type)
3364 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3365 return api_direct_messages_box($type, "sentbox", $verbose);
3369 * Returns the most recent direct messages sent to the user.
3371 * @param string $type Return type (atom, rss, xml, json)
3373 * @return array|string
3374 * @throws BadRequestException
3375 * @throws ForbiddenException
3376 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3378 function api_direct_messages_inbox($type)
3380 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3381 return api_direct_messages_box($type, "inbox", $verbose);
3386 * @param string $type Return type (atom, rss, xml, json)
3388 * @return array|string
3389 * @throws BadRequestException
3390 * @throws ForbiddenException
3392 function api_direct_messages_all($type)
3394 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3395 return api_direct_messages_box($type, "all", $verbose);
3400 * @param string $type Return type (atom, rss, xml, json)
3402 * @return array|string
3403 * @throws BadRequestException
3404 * @throws ForbiddenException
3406 function api_direct_messages_conversation($type)
3408 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3409 return api_direct_messages_box($type, "conversation", $verbose);
3412 /// @TODO move to top of file or somewhere better
3413 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3414 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3415 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3416 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3419 * list all photos of the authenticated user
3421 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3422 * @return string|array
3423 * @throws ForbiddenException
3424 * @throws InternalServerErrorException
3426 function api_fr_photos_list($type)
3428 if (BaseApi::getCurrentUserID() === false) {
3429 throw new ForbiddenException();
3431 $r = DBA::toArray(DBA::p(
3432 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3433 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3434 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3435 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3438 'image/jpeg' => 'jpg',
3439 'image/png' => 'png',
3440 'image/gif' => 'gif'
3442 $data = ['photo'=>[]];
3443 if (DBA::isResult($r)) {
3444 foreach ($r as $rr) {
3446 $photo['id'] = $rr['resource-id'];
3447 $photo['album'] = $rr['album'];
3448 $photo['filename'] = $rr['filename'];
3449 $photo['type'] = $rr['type'];
3450 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3451 $photo['created'] = $rr['created'];
3452 $photo['edited'] = $rr['edited'];
3453 $photo['desc'] = $rr['desc'];
3455 if ($type == "xml") {
3456 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3458 $photo['thumb'] = $thumb;
3459 $data['photo'][] = $photo;
3463 return DI::apiResponse()->formatData("photos", $type, $data);
3467 * upload a new photo or change an existing photo
3469 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3470 * @return string|array
3471 * @throws BadRequestException
3472 * @throws ForbiddenException
3473 * @throws ImagickException
3474 * @throws InternalServerErrorException
3475 * @throws NotFoundException
3477 function api_fr_photo_create_update($type)
3479 if (BaseApi::getCurrentUserID() === false) {
3480 throw new ForbiddenException();
3483 $photo_id = $_REQUEST['photo_id'] ?? null;
3484 $desc = $_REQUEST['desc'] ?? null;
3485 $album = $_REQUEST['album'] ?? null;
3486 $album_new = $_REQUEST['album_new'] ?? null;
3487 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3488 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3489 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3490 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3491 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3493 // do several checks on input parameters
3494 // we do not allow calls without album string
3495 if ($album == null) {
3496 throw new BadRequestException("no albumname specified");
3498 // if photo_id == null --> we are uploading a new photo
3499 if ($photo_id == null) {
3502 // error if no media posted in create-mode
3503 if (empty($_FILES['media'])) {
3505 throw new BadRequestException("no media data submitted");
3508 // album_new will be ignored in create-mode
3513 // check if photo is existing in databasei
3514 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3515 throw new BadRequestException("photo not available");
3519 // checks on acl strings provided by clients
3520 $acl_input_error = false;
3521 $acl_input_error |= check_acl_input($allow_cid);
3522 $acl_input_error |= check_acl_input($deny_cid);
3523 $acl_input_error |= check_acl_input($allow_gid);
3524 $acl_input_error |= check_acl_input($deny_gid);
3525 if ($acl_input_error) {
3526 throw new BadRequestException("acl data invalid");
3528 // now let's upload the new media in create-mode
3529 if ($mode == "create") {
3530 $media = $_FILES['media'];
3531 $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);
3533 // return success of updating or error message
3534 if (!is_null($data)) {
3535 return DI::apiResponse()->formatData("photo_create", $type, $data);
3537 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3541 // now let's do the changes in update-mode
3542 if ($mode == "update") {
3543 $updated_fields = [];
3545 if (!is_null($desc)) {
3546 $updated_fields['desc'] = $desc;
3549 if (!is_null($album_new)) {
3550 $updated_fields['album'] = $album_new;
3553 if (!is_null($allow_cid)) {
3554 $allow_cid = trim($allow_cid);
3555 $updated_fields['allow_cid'] = $allow_cid;
3558 if (!is_null($deny_cid)) {
3559 $deny_cid = trim($deny_cid);
3560 $updated_fields['deny_cid'] = $deny_cid;
3563 if (!is_null($allow_gid)) {
3564 $allow_gid = trim($allow_gid);
3565 $updated_fields['allow_gid'] = $allow_gid;
3568 if (!is_null($deny_gid)) {
3569 $deny_gid = trim($deny_gid);
3570 $updated_fields['deny_gid'] = $deny_gid;
3574 if (count($updated_fields) > 0) {
3575 $nothingtodo = false;
3576 $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3578 $nothingtodo = true;
3581 if (!empty($_FILES['media'])) {
3582 $nothingtodo = false;
3583 $media = $_FILES['media'];
3584 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3585 if (!is_null($data)) {
3586 return DI::apiResponse()->formatData("photo_update", $type, $data);
3590 // return success of updating or error message
3592 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3593 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3596 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3597 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3599 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3602 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3606 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3608 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3609 * @return string|array
3610 * @throws BadRequestException
3611 * @throws ForbiddenException
3612 * @throws InternalServerErrorException
3613 * @throws NotFoundException
3615 function api_fr_photo_detail($type)
3617 if (BaseApi::getCurrentUserID() === false) {
3618 throw new ForbiddenException();
3620 if (empty($_REQUEST['photo_id'])) {
3621 throw new BadRequestException("No photo id.");
3624 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3625 $photo_id = $_REQUEST['photo_id'];
3627 // prepare json/xml output with data from database for the requested photo
3628 $data = prepare_photo_data($type, $scale, $photo_id);
3630 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3635 * updates the profile image for the user (either a specified profile or the default profile)
3637 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3639 * @return string|array
3640 * @throws BadRequestException
3641 * @throws ForbiddenException
3642 * @throws ImagickException
3643 * @throws InternalServerErrorException
3644 * @throws NotFoundException
3645 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3647 function api_account_update_profile_image($type)
3649 if (BaseApi::getCurrentUserID() === false) {
3650 throw new ForbiddenException();
3653 $profile_id = $_REQUEST['profile_id'] ?? 0;
3655 // error if image data is missing
3656 if (empty($_FILES['image'])) {
3657 throw new BadRequestException("no media data submitted");
3660 // check if specified profile id is valid
3661 if ($profile_id != 0) {
3662 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3663 // error message if specified profile id is not in database
3664 if (!DBA::isResult($profile)) {
3665 throw new BadRequestException("profile_id not available");
3667 $is_default_profile = $profile['is-default'];
3669 $is_default_profile = 1;
3672 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3674 if (!empty($_FILES['image'])) {
3675 $media = $_FILES['image'];
3676 } elseif (!empty($_FILES['media'])) {
3677 $media = $_FILES['media'];
3679 // save new profile image
3680 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3683 if (is_array($media['type'])) {
3684 $filetype = $media['type'][0];
3686 $filetype = $media['type'];
3688 if ($filetype == "image/jpeg") {
3690 } elseif ($filetype == "image/png") {
3693 throw new InternalServerErrorException('Unsupported filetype');
3696 // change specified profile or all profiles to the new resource-id
3697 if ($is_default_profile) {
3698 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3699 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3701 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3702 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3703 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3706 Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3708 // Update global directory in background
3709 Profile::publishUpdate(BaseApi::getCurrentUserID());
3711 // output for client
3713 return api_account_verify_credentials($type);
3715 // SaveMediaToDatabase failed for some reason
3716 throw new InternalServerErrorException("image upload failed");
3720 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3721 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3722 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3723 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3724 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3725 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3728 * Update user profile
3730 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3732 * @return array|string
3733 * @throws BadRequestException
3734 * @throws ForbiddenException
3735 * @throws ImagickException
3736 * @throws InternalServerErrorException
3737 * @throws UnauthorizedException
3739 function api_account_update_profile($type)
3741 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3743 $local_user = BaseApi::getCurrentUserID();
3745 $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3747 if (!empty($_POST['name'])) {
3748 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3749 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3750 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3751 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3754 if (isset($_POST['description'])) {
3755 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3756 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3757 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3760 Profile::publishUpdate($local_user);
3762 return api_account_verify_credentials($type);
3765 /// @TODO move to top of file or somewhere better
3766 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3770 * @param string $acl_string
3774 function check_acl_input($acl_string)
3776 if (empty($acl_string)) {
3780 $contact_not_found = false;
3782 // split <x><y><z> into array of cid's
3783 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3785 // check for each cid if it is available on server
3786 $cid_array = $array[0];
3787 foreach ($cid_array as $cid) {
3788 $cid = str_replace("<", "", $cid);
3789 $cid = str_replace(">", "", $cid);
3790 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3791 $contact_not_found |= !DBA::exists('contact', $condition);
3793 return $contact_not_found;
3797 * @param string $mediatype
3798 * @param array $media
3799 * @param string $type
3800 * @param string $album
3801 * @param string $allow_cid
3802 * @param string $deny_cid
3803 * @param string $allow_gid
3804 * @param string $deny_gid
3805 * @param string $desc
3806 * @param integer $phototype
3807 * @param boolean $visibility
3808 * @param string $photo_id
3810 * @throws BadRequestException
3811 * @throws ForbiddenException
3812 * @throws ImagickException
3813 * @throws InternalServerErrorException
3814 * @throws NotFoundException
3815 * @throws UnauthorizedException
3817 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)
3825 if (is_array($media)) {
3826 if (is_array($media['tmp_name'])) {
3827 $src = $media['tmp_name'][0];
3829 $src = $media['tmp_name'];
3831 if (is_array($media['name'])) {
3832 $filename = basename($media['name'][0]);
3834 $filename = basename($media['name']);
3836 if (is_array($media['size'])) {
3837 $filesize = intval($media['size'][0]);
3839 $filesize = intval($media['size']);
3841 if (is_array($media['type'])) {
3842 $filetype = $media['type'][0];
3844 $filetype = $media['type'];
3848 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3851 "File upload src: " . $src . " - filename: " . $filename .
3852 " - size: " . $filesize . " - type: " . $filetype);
3854 // check if there was a php upload error
3855 if ($filesize == 0 && $media['error'] == 1) {
3856 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3858 // check against max upload size within Friendica instance
3859 $maximagesize = DI::config()->get('system', 'maximagesize');
3860 if ($maximagesize && ($filesize > $maximagesize)) {
3861 $formattedBytes = Strings::formatBytes($maximagesize);
3862 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3865 // create Photo instance with the data of the image
3866 $imagedata = @file_get_contents($src);
3867 $Image = new Image($imagedata, $filetype);
3868 if (!$Image->isValid()) {
3869 throw new InternalServerErrorException("unable to process image data");
3872 // check orientation of image
3873 $Image->orient($src);
3876 // check max length of images on server
3877 $max_length = DI::config()->get('system', 'max_image_length');
3878 if ($max_length > 0) {
3879 $Image->scaleDown($max_length);
3880 logger::info("File upload: Scaling picture to new size " . $max_length);
3882 $width = $Image->getWidth();
3883 $height = $Image->getHeight();
3885 // create a new resource-id if not already provided
3886 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3888 if ($mediatype == "photo") {
3889 // upload normal image (scales 0, 1, 2)
3890 logger::info("photo upload: starting new photo upload");
3892 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3894 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3896 if ($width > 640 || $height > 640) {
3897 $Image->scaleDown(640);
3898 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3900 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3904 if ($width > 320 || $height > 320) {
3905 $Image->scaleDown(320);
3906 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3908 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3911 logger::info("photo upload: new photo upload ended");
3912 } elseif ($mediatype == "profileimage") {
3913 // upload profile image (scales 4, 5, 6)
3914 logger::info("photo upload: starting new profile image upload");
3916 if ($width > 300 || $height > 300) {
3917 $Image->scaleDown(300);
3918 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3920 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3924 if ($width > 80 || $height > 80) {
3925 $Image->scaleDown(80);
3926 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3928 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3932 if ($width > 48 || $height > 48) {
3933 $Image->scaleDown(48);
3934 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3936 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3939 $Image->__destruct();
3940 logger::info("photo upload: new profile image upload ended");
3944 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3945 if ($photo_id == null && $mediatype == "photo") {
3946 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3948 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3949 return prepare_photo_data($type, false, $resource_id);
3951 throw new InternalServerErrorException("image upload failed");
3957 * @param string $hash
3958 * @param string $allow_cid
3959 * @param string $deny_cid
3960 * @param string $allow_gid
3961 * @param string $deny_gid
3962 * @param string $filetype
3963 * @param boolean $visibility
3964 * @throws InternalServerErrorException
3966 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
3968 // get data about the api authenticated user
3969 $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
3970 $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
3973 $arr['guid'] = System::createUUID();
3974 $arr['uid'] = intval(BaseApi::getCurrentUserID());
3976 $arr['type'] = 'photo';
3978 $arr['resource-id'] = $hash;
3979 $arr['contact-id'] = $owner_record['id'];
3980 $arr['owner-name'] = $owner_record['name'];
3981 $arr['owner-link'] = $owner_record['url'];
3982 $arr['owner-avatar'] = $owner_record['thumb'];
3983 $arr['author-name'] = $owner_record['name'];
3984 $arr['author-link'] = $owner_record['url'];
3985 $arr['author-avatar'] = $owner_record['thumb'];
3987 $arr['allow_cid'] = $allow_cid;
3988 $arr['allow_gid'] = $allow_gid;
3989 $arr['deny_cid'] = $deny_cid;
3990 $arr['deny_gid'] = $deny_gid;
3991 $arr['visible'] = $visibility;
3995 'image/jpeg' => 'jpg',
3996 'image/png' => 'png',
3997 'image/gif' => 'gif'
4000 // adds link to the thumbnail scale photo
4001 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4002 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4005 // do the magic for storing the item in the database and trigger the federation to other contacts
4011 * @param string $type
4013 * @param string $photo_id
4016 * @throws BadRequestException
4017 * @throws ForbiddenException
4018 * @throws ImagickException
4019 * @throws InternalServerErrorException
4020 * @throws NotFoundException
4021 * @throws UnauthorizedException
4023 function prepare_photo_data($type, $scale, $photo_id)
4025 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4027 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4029 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4030 $data_sql = ($scale === false ? "" : "data, ");
4032 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4033 // clients needs to convert this in their way for further processing
4034 $r = DBA::toArray(DBA::p(
4035 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4036 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4037 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4038 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4039 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4040 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4046 'image/jpeg' => 'jpg',
4047 'image/png' => 'png',
4048 'image/gif' => 'gif'
4051 // prepare output data for photo
4052 if (DBA::isResult($r)) {
4053 $data = ['photo' => $r[0]];
4054 $data['photo']['id'] = $data['photo']['resource-id'];
4055 if ($scale !== false) {
4056 $data['photo']['data'] = base64_encode($data['photo']['data']);
4058 unset($data['photo']['datasize']); //needed only with scale param
4060 if ($type == "xml") {
4061 $data['photo']['links'] = [];
4062 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4063 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4065 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4068 $data['photo']['link'] = [];
4069 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4071 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4072 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4076 unset($data['photo']['resource-id']);
4077 unset($data['photo']['minscale']);
4078 unset($data['photo']['maxscale']);
4080 throw new NotFoundException();
4083 // retrieve item element for getting activities (like, dislike etc.) related to photo
4084 $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
4085 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4086 if (!DBA::isResult($item)) {
4087 throw new NotFoundException('Photo-related item not found.');
4090 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4092 // retrieve comments on photo
4093 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4094 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
4096 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
4098 // prepare output of comments
4099 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4101 if ($type == "xml") {
4103 foreach ($commentData as $comment) {
4104 $comments[$k++ . ":comment"] = $comment;
4107 foreach ($commentData as $comment) {
4108 $comments[] = $comment;
4111 $data['photo']['friendica_comments'] = $comments;
4113 // include info if rights on photo and rights on item are mismatching
4114 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4115 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4116 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4117 $data['photo']['deny_gid'] != $item['deny_gid'];
4118 $data['photo']['rights_mismatch'] = $rights_mismatch;
4124 * Return an item with announcer data if it had been announced
4126 * @param array $item Item array
4127 * @return array Item array with announce data
4129 function api_get_announce($item)
4131 // Quit if the item already has got a different owner and author
4132 if ($item['owner-id'] != $item['author-id']) {
4136 // Don't change original or Diaspora posts
4137 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4141 // Quit if we do now the original author and it had been a post from a native network
4142 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4146 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4147 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4148 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4149 if (!DBA::isResult($announce)) {
4153 return array_merge($item, $announce);
4158 * @param array $item
4163 function api_in_reply_to($item)
4167 $in_reply_to['status_id'] = null;
4168 $in_reply_to['user_id'] = null;
4169 $in_reply_to['status_id_str'] = null;
4170 $in_reply_to['user_id_str'] = null;
4171 $in_reply_to['screen_name'] = null;
4173 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4174 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4175 if (DBA::isResult($parent)) {
4176 $in_reply_to['status_id'] = intval($parent['id']);
4178 $in_reply_to['status_id'] = intval($item['parent']);
4181 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4183 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4184 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4186 if (DBA::isResult($parent)) {
4187 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4188 $in_reply_to['user_id'] = intval($parent['author-id']);
4189 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4192 // There seems to be situation, where both fields are identical:
4193 // https://github.com/friendica/friendica/issues/1010
4194 // This is a bugfix for that.
4195 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4196 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']]);
4197 $in_reply_to['status_id'] = null;
4198 $in_reply_to['user_id'] = null;
4199 $in_reply_to['status_id_str'] = null;
4200 $in_reply_to['user_id_str'] = null;
4201 $in_reply_to['screen_name'] = null;
4205 return $in_reply_to;
4210 * @param string $text
4213 * @throws InternalServerErrorException
4215 function api_clean_plain_items($text)
4217 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4219 $text = BBCode::cleanPictureLinks($text);
4220 $URLSearchString = "^\[\]";
4222 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4224 if ($include_entities == "true") {
4225 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4228 // Simplify "attachment" element
4229 $text = BBCode::removeAttachment($text);
4236 * @param array $contacts
4240 function api_best_nickname(&$contacts)
4244 if (count($contacts) == 0) {
4248 foreach ($contacts as $contact) {
4249 if ($contact["network"] == "") {
4250 $contact["network"] = "dfrn";
4251 $best_contact = [$contact];
4255 if (sizeof($best_contact) == 0) {
4256 foreach ($contacts as $contact) {
4257 if ($contact["network"] == "dfrn") {
4258 $best_contact = [$contact];
4263 if (sizeof($best_contact) == 0) {
4264 foreach ($contacts as $contact) {
4265 if ($contact["network"] == "dspr") {
4266 $best_contact = [$contact];
4271 if (sizeof($best_contact) == 0) {
4272 foreach ($contacts as $contact) {
4273 if ($contact["network"] == "stat") {
4274 $best_contact = [$contact];
4279 if (sizeof($best_contact) == 0) {
4280 foreach ($contacts as $contact) {
4281 if ($contact["network"] == "pump") {
4282 $best_contact = [$contact];
4287 if (sizeof($best_contact) == 0) {
4288 foreach ($contacts as $contact) {
4289 if ($contact["network"] == "twit") {
4290 $best_contact = [$contact];
4295 if (sizeof($best_contact) == 1) {
4296 $contacts = $best_contact;
4298 $contacts = [$contacts[0]];
4303 * Return all or a specified group of the user with the containing contacts.
4305 * @param string $type Return type (atom, rss, xml, json)
4307 * @return array|string
4308 * @throws BadRequestException
4309 * @throws ForbiddenException
4310 * @throws ImagickException
4311 * @throws InternalServerErrorException
4312 * @throws UnauthorizedException
4314 function api_friendica_group_show($type)
4316 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4319 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4320 $gid = $_REQUEST['gid'] ?? 0;
4321 $uid = $user_info['uid'];
4323 // get data of the specified group id or all groups if not specified
4325 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4327 // error message if specified gid is not in database
4328 if (!DBA::isResult($groups)) {
4329 throw new BadRequestException("gid not available");
4332 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4335 // loop through all groups and retrieve all members for adding data in the user array
4337 foreach ($groups as $rr) {
4338 $members = Contact\Group::getById($rr['id']);
4341 if ($type == "xml") {
4342 $user_element = "users";
4344 foreach ($members as $member) {
4345 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4346 $users[$k++.":user"] = $user;
4349 $user_element = "user";
4350 foreach ($members as $member) {
4351 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4355 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4357 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4360 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4365 * @param string $type Return type (atom, rss, xml, json)
4367 * @return array|string
4368 * @throws BadRequestException
4369 * @throws ForbiddenException
4370 * @throws ImagickException
4371 * @throws InternalServerErrorException
4372 * @throws UnauthorizedException
4373 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4375 function api_lists_destroy($type)
4377 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4380 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4381 $gid = $_REQUEST['list_id'] ?? 0;
4382 $uid = $user_info['uid'];
4384 // error if no gid specified
4386 throw new BadRequestException('gid not specified');
4389 // get data of the specified group id
4390 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4391 // error message if specified gid is not in database
4393 throw new BadRequestException('gid not available');
4396 if (Group::remove($gid)) {
4398 'name' => $group['name'],
4399 'id' => intval($gid),
4400 'id_str' => (string) $gid,
4401 'user' => $user_info
4404 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4408 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4411 * Add a new group to the database.
4413 * @param string $name Group name
4414 * @param int $uid User ID
4415 * @param array $users List of users to add to the group
4418 * @throws BadRequestException
4420 function group_create($name, $uid, $users = [])
4422 // error if no name specified
4424 throw new BadRequestException('group name not specified');
4427 // error message if specified group name already exists
4428 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4429 throw new BadRequestException('group name already exists');
4432 // Check if the group needs to be reactivated
4433 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4434 $reactivate_group = true;
4438 $ret = Group::create($uid, $name);
4440 $gid = Group::getIdByName($uid, $name);
4442 throw new BadRequestException('other API error');
4446 $erroraddinguser = false;
4448 foreach ($users as $user) {
4449 $cid = $user['cid'];
4450 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4451 Group::addMember($gid, $cid);
4453 $erroraddinguser = true;
4454 $errorusers[] = $cid;
4458 // return success message incl. missing users in array
4459 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4461 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4465 * Create the specified group with the posted array of contacts.
4467 * @param string $type Return type (atom, rss, xml, json)
4469 * @return array|string
4470 * @throws BadRequestException
4471 * @throws ForbiddenException
4472 * @throws ImagickException
4473 * @throws InternalServerErrorException
4474 * @throws UnauthorizedException
4476 function api_friendica_group_create($type)
4478 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4481 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4482 $name = $_REQUEST['name'] ?? '';
4483 $uid = $user_info['uid'];
4484 $json = json_decode($_POST['json'], true);
4485 $users = $json['user'];
4487 $success = group_create($name, $uid, $users);
4489 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4492 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4495 * Create a new group.
4497 * @param string $type Return type (atom, rss, xml, json)
4499 * @return array|string
4500 * @throws BadRequestException
4501 * @throws ForbiddenException
4502 * @throws ImagickException
4503 * @throws InternalServerErrorException
4504 * @throws UnauthorizedException
4505 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4507 function api_lists_create($type)
4509 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4512 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4513 $name = $_REQUEST['name'] ?? '';
4514 $uid = $user_info['uid'];
4516 $success = group_create($name, $uid);
4517 if ($success['success']) {
4519 'name' => $success['name'],
4520 'id' => intval($success['gid']),
4521 'id_str' => (string) $success['gid'],
4522 'user' => $user_info
4525 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4529 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4532 * Update the specified group with the posted array of contacts.
4534 * @param string $type Return type (atom, rss, xml, json)
4536 * @return array|string
4537 * @throws BadRequestException
4538 * @throws ForbiddenException
4539 * @throws ImagickException
4540 * @throws InternalServerErrorException
4541 * @throws UnauthorizedException
4543 function api_friendica_group_update($type)
4545 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4548 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4549 $uid = $user_info['uid'];
4550 $gid = $_REQUEST['gid'] ?? 0;
4551 $name = $_REQUEST['name'] ?? '';
4552 $json = json_decode($_POST['json'], true);
4553 $users = $json['user'];
4555 // error if no name specified
4557 throw new BadRequestException('group name not specified');
4560 // error if no gid specified
4562 throw new BadRequestException('gid not specified');
4566 $members = Contact\Group::getById($gid);
4567 foreach ($members as $member) {
4568 $cid = $member['id'];
4569 foreach ($users as $user) {
4570 $found = ($user['cid'] == $cid ? true : false);
4572 if (!isset($found) || !$found) {
4573 $gid = Group::getIdByName($uid, $name);
4574 Group::removeMember($gid, $cid);
4579 $erroraddinguser = false;
4581 foreach ($users as $user) {
4582 $cid = $user['cid'];
4584 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4585 Group::addMember($gid, $cid);
4587 $erroraddinguser = true;
4588 $errorusers[] = $cid;
4592 // return success message incl. missing users in array
4593 $status = ($erroraddinguser ? "missing user" : "ok");
4594 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4595 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4598 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4601 * Update information about a group.
4603 * @param string $type Return type (atom, rss, xml, json)
4605 * @return array|string
4606 * @throws BadRequestException
4607 * @throws ForbiddenException
4608 * @throws ImagickException
4609 * @throws InternalServerErrorException
4610 * @throws UnauthorizedException
4611 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4613 function api_lists_update($type)
4615 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4618 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4619 $gid = $_REQUEST['list_id'] ?? 0;
4620 $name = $_REQUEST['name'] ?? '';
4621 $uid = $user_info['uid'];
4623 // error if no gid specified
4625 throw new BadRequestException('gid not specified');
4628 // get data of the specified group id
4629 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4630 // error message if specified gid is not in database
4632 throw new BadRequestException('gid not available');
4635 if (Group::update($gid, $name)) {
4638 'id' => intval($gid),
4639 'id_str' => (string) $gid,
4640 'user' => $user_info
4643 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4647 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4650 * Set notification as seen and returns associated item (if possible)
4652 * POST request with 'id' param as notification id
4654 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4655 * @return string|array
4656 * @throws BadRequestException
4657 * @throws ForbiddenException
4658 * @throws ImagickException
4659 * @throws InternalServerErrorException
4660 * @throws UnauthorizedException
4662 function api_friendica_notification_seen($type)
4664 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4666 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4668 if (DI::args()->getArgc() !== 4) {
4669 throw new BadRequestException('Invalid argument count');
4672 $id = intval($_REQUEST['id'] ?? 0);
4675 $Notify = DI::notify()->selectOneById($id);
4676 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4677 throw new NotFoundException();
4680 if ($Notify->uriId) {
4681 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4685 DI::notify()->save($Notify);
4687 if ($Notify->otype === Notification\ObjectType::ITEM) {
4688 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4689 if (DBA::isResult($item)) {
4690 // we found the item, return it to the user
4691 $ret = api_format_items([$item], $user_info, false, $type);
4692 $data = ['status' => $ret];
4693 return DI::apiResponse()->formatData('status', $type, $data);
4695 // the item can't be found, but we set the notification as seen, so we count this as a success
4698 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4699 } catch (NotFoundException $e) {
4700 throw new BadRequestException('Invalid argument', $e);
4701 } catch (Exception $e) {
4702 throw new InternalServerErrorException('Internal Server exception', $e);
4706 /// @TODO move to top of file or somewhere better
4707 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4710 * search for direct_messages containing a searchstring through api
4712 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4713 * @param string $box
4714 * @return string|array (success: success=true if found and search_result contains found messages,
4715 * success=false if nothing was found, search_result='nothing found',
4716 * error: result=error with error message)
4717 * @throws BadRequestException
4718 * @throws ForbiddenException
4719 * @throws ImagickException
4720 * @throws InternalServerErrorException
4721 * @throws UnauthorizedException
4723 function api_friendica_direct_messages_search($type, $box = "")
4725 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4728 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4729 $searchstring = $_REQUEST['searchstring'] ?? '';
4730 $uid = $user_info['uid'];
4732 // error if no searchstring specified
4733 if ($searchstring == "") {
4734 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4735 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4738 // get data for the specified searchstring
4739 $r = DBA::toArray(DBA::p(
4740 "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",
4742 '%'.$searchstring.'%'
4745 $profile_url = $user_info["url"];
4747 // message if nothing was found
4748 if (!DBA::isResult($r)) {
4749 $success = ['success' => false, 'search_results' => 'problem with query'];
4750 } elseif (count($r) == 0) {
4751 $success = ['success' => false, 'search_results' => 'nothing found'];
4754 foreach ($r as $item) {
4755 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4756 $recipient = $user_info;
4757 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4758 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4759 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4760 $sender = $user_info;
4763 if (isset($recipient) && isset($sender)) {
4764 $ret[] = api_format_messages($item, $recipient, $sender);
4767 $success = ['success' => true, 'search_results' => $ret];
4770 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4773 /// @TODO move to top of file or somewhere better
4774 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4777 * Number of comments
4779 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4781 * @param object $data [Status, Status]
4785 function bindComments(&$data)
4787 if (count($data) == 0) {
4793 foreach ($data as $item) {
4794 $ids[] = $item['id'];
4797 $idStr = DBA::escape(implode(', ', $ids));
4798 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4799 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4800 $itemsData = DBA::toArray($items);
4802 foreach ($itemsData as $item) {
4803 $comments[$item['parent']] = $item['comments'];
4806 foreach ($data as $idx => $item) {
4808 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4813 @TODO Maybe open to implement?
4815 [pagename] => api/1.1/statuses/lookup.json
4816 [id] => 605138389168451584
4817 [include_cards] => true
4818 [cards_platform] => Android-12
4819 [include_entities] => true
4820 [include_my_retweet] => 1
4822 [include_reply_count] => true
4823 [include_descendent_reply_count] => true
4827 Not implemented by now:
4828 statuses/retweets_of_me
4833 account/update_location
4834 account/update_profile_background_image
4837 friendica/profile/update
4838 friendica/profile/create
4839 friendica/profile/delete
4841 Not implemented in status.net:
4842 statuses/retweeted_to_me
4843 statuses/retweeted_by_me
4844 direct_messages/destroy
4846 account/update_delivery_device
4847 notifications/follow