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 if (empty(BaseApi::getCurrentUserID())) {
1116 throw new ForbiddenException();
1118 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1120 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1122 if (empty($_REQUEST['q'])) {
1123 throw new BadRequestException('q parameter is required.');
1126 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1129 $data['status'] = [];
1131 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1132 if (!empty($_REQUEST['rpp'])) {
1133 $count = $_REQUEST['rpp'];
1134 } elseif (!empty($_REQUEST['count'])) {
1135 $count = $_REQUEST['count'];
1138 $since_id = $_REQUEST['since_id'] ?? 0;
1139 $max_id = $_REQUEST['max_id'] ?? 0;
1140 $page = $_REQUEST['page'] ?? 1;
1142 $start = max(0, ($page - 1) * $count);
1144 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1145 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1146 $searchTerm = $matches[1];
1147 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1148 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1150 while ($tag = DBA::fetch($tags)) {
1151 $uriids[] = $tag['uri-id'];
1155 if (empty($uriids)) {
1156 return DI::apiResponse()->formatData('statuses', $type, $data);
1159 $condition = ['uri-id' => $uriids];
1160 if ($exclude_replies) {
1161 $condition['gravity'] = GRAVITY_PARENT;
1164 $params['group_by'] = ['uri-id'];
1166 $condition = ["`id` > ?
1167 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1168 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1169 AND `body` LIKE CONCAT('%',?,'%')",
1170 $since_id, BaseApi::getCurrentUserID(), $_REQUEST['q']];
1172 $condition[0] .= ' AND `id` <= ?';
1173 $condition[] = $max_id;
1179 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1180 $id = Item::fetchByLink($searchTerm, BaseApi::getCurrentUserID());
1183 $id = Item::fetchByLink($searchTerm);
1187 $statuses = Post::select([], ['id' => $id]);
1191 $statuses = $statuses ?: Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1193 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1195 bindComments($data['status']);
1197 return DI::apiResponse()->formatData('statuses', $type, $data);
1200 /// @TODO move to top of file or somewhere better
1201 api_register_func('api/search/tweets', 'api_search', true);
1202 api_register_func('api/search', 'api_search', true);
1205 * Returns the most recent statuses posted by the user and the users they follow.
1207 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1209 * @param string $type Return type (atom, rss, xml, json)
1211 * @return array|string
1212 * @throws BadRequestException
1213 * @throws ForbiddenException
1214 * @throws ImagickException
1215 * @throws InternalServerErrorException
1216 * @throws UnauthorizedException
1217 * @todo Optional parameters
1218 * @todo Add reply info
1220 function api_statuses_home_timeline($type)
1222 if (empty(BaseApi::getCurrentUserID())) {
1223 throw new ForbiddenException();
1225 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1227 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1229 unset($_REQUEST["user_id"]);
1230 unset($_GET["user_id"]);
1232 unset($_REQUEST["screen_name"]);
1233 unset($_GET["screen_name"]);
1235 // get last network messages
1238 $count = $_REQUEST['count'] ?? 20;
1239 $page = $_REQUEST['page']?? 0;
1240 $since_id = $_REQUEST['since_id'] ?? 0;
1241 $max_id = $_REQUEST['max_id'] ?? 0;
1242 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1243 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1245 $start = max(0, ($page - 1) * $count);
1247 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1248 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1251 $condition[0] .= " AND `id` <= ?";
1252 $condition[] = $max_id;
1254 if ($exclude_replies) {
1255 $condition[0] .= ' AND `gravity` = ?';
1256 $condition[] = GRAVITY_PARENT;
1258 if ($conversation_id > 0) {
1259 $condition[0] .= " AND `parent` = ?";
1260 $condition[] = $conversation_id;
1263 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1264 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1266 $items = Post::toArray($statuses);
1268 $ret = api_format_items($items, $user_info, false, $type);
1270 // Set all posts from the query above to seen
1272 foreach ($items as $item) {
1273 $idarray[] = intval($item["id"]);
1276 if (!empty($idarray)) {
1277 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1279 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1285 $data = ['status' => $ret];
1290 $data = api_rss_extra($data, $user_info);
1294 return DI::apiResponse()->formatData("statuses", $type, $data);
1298 /// @TODO move to top of file or somewhere better
1299 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1300 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1303 * Returns the most recent statuses from public users.
1305 * @param string $type Return type (atom, rss, xml, json)
1307 * @return array|string
1308 * @throws BadRequestException
1309 * @throws ForbiddenException
1310 * @throws ImagickException
1311 * @throws InternalServerErrorException
1312 * @throws UnauthorizedException
1314 function api_statuses_public_timeline($type)
1316 if (empty(BaseApi::getCurrentUserID())) {
1317 throw new ForbiddenException();
1319 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1321 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1323 // get last network messages
1326 $count = $_REQUEST['count'] ?? 20;
1327 $page = $_REQUEST['page'] ?? 1;
1328 $since_id = $_REQUEST['since_id'] ?? 0;
1329 $max_id = $_REQUEST['max_id'] ?? 0;
1330 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1331 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1333 $start = max(0, ($page - 1) * $count);
1335 if ($exclude_replies && !$conversation_id) {
1336 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1337 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1340 $condition[0] .= " AND `id` <= ?";
1341 $condition[] = $max_id;
1344 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1345 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1347 $r = Post::toArray($statuses);
1349 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1350 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1353 $condition[0] .= " AND `id` <= ?";
1354 $condition[] = $max_id;
1356 if ($conversation_id > 0) {
1357 $condition[0] .= " AND `parent` = ?";
1358 $condition[] = $conversation_id;
1361 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1362 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1364 $r = Post::toArray($statuses);
1367 $ret = api_format_items($r, $user_info, false, $type);
1371 $data = ['status' => $ret];
1376 $data = api_rss_extra($data, $user_info);
1380 return DI::apiResponse()->formatData("statuses", $type, $data);
1383 /// @TODO move to top of file or somewhere better
1384 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1387 * Returns the most recent statuses posted by users this node knows about.
1389 * @param string $type Return format: json, xml, atom, rss
1390 * @return array|string
1391 * @throws BadRequestException
1392 * @throws ForbiddenException
1393 * @throws ImagickException
1394 * @throws InternalServerErrorException
1395 * @throws UnauthorizedException
1397 function api_statuses_networkpublic_timeline($type)
1399 if (empty(BaseApi::getCurrentUserID())) {
1400 throw new ForbiddenException();
1402 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1404 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1406 $since_id = $_REQUEST['since_id'] ?? 0;
1407 $max_id = $_REQUEST['max_id'] ?? 0;
1410 $count = $_REQUEST['count'] ?? 20;
1411 $page = $_REQUEST['page'] ?? 1;
1413 $start = max(0, ($page - 1) * $count);
1415 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1416 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1419 $condition[0] .= " AND `id` <= ?";
1420 $condition[] = $max_id;
1423 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1424 $statuses = Post::toArray(Post::selectForUser(BaseApi::getCurrentUserID(), Item::DISPLAY_FIELDLIST, $condition, $params));
1426 $ret = api_format_items($statuses, $user_info, false, $type);
1430 $data = ['status' => $ret];
1435 $data = api_rss_extra($data, $user_info);
1439 return DI::apiResponse()->formatData("statuses", $type, $data);
1442 /// @TODO move to top of file or somewhere better
1443 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1446 * Returns a single status.
1448 * @param string $type Return type (atom, rss, xml, json)
1450 * @return array|string
1451 * @throws BadRequestException
1452 * @throws ForbiddenException
1453 * @throws ImagickException
1454 * @throws InternalServerErrorException
1455 * @throws UnauthorizedException
1456 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1458 function api_statuses_show($type)
1460 if (empty(BaseApi::getCurrentUserID())) {
1461 throw new ForbiddenException();
1463 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1465 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1468 $id = intval(DI::args()->getArgv()[3] ?? 0);
1471 $id = intval($_REQUEST['id'] ?? 0);
1476 $id = intval(DI::args()->getArgv()[4] ?? 0);
1479 logger::notice('API: api_statuses_show: ' . $id);
1481 $conversation = !empty($_REQUEST['conversation']);
1483 // try to fetch the item for the local user - or the public item, if there is no local one
1484 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1485 if (!DBA::isResult($uri_item)) {
1486 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1489 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1490 if (!DBA::isResult($item)) {
1491 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1496 if ($conversation) {
1497 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1498 $params = ['order' => ['id' => true]];
1500 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1504 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1506 /// @TODO How about copying this to above methods which don't check $r ?
1507 if (!DBA::isResult($statuses)) {
1508 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1511 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1513 if ($conversation) {
1514 $data = ['status' => $ret];
1515 return DI::apiResponse()->formatData("statuses", $type, $data);
1517 $data = ['status' => $ret[0]];
1518 return DI::apiResponse()->formatData("status", $type, $data);
1522 /// @TODO move to top of file or somewhere better
1523 api_register_func('api/statuses/show', 'api_statuses_show', true);
1527 * @param string $type Return type (atom, rss, xml, json)
1529 * @return array|string
1530 * @throws BadRequestException
1531 * @throws ForbiddenException
1532 * @throws ImagickException
1533 * @throws InternalServerErrorException
1534 * @throws UnauthorizedException
1535 * @todo nothing to say?
1537 function api_conversation_show($type)
1539 if (empty(BaseApi::getCurrentUserID())) {
1540 throw new ForbiddenException();
1542 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1544 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1547 $id = intval(DI::args()->getArgv()[3] ?? 0);
1548 $since_id = intval($_REQUEST['since_id'] ?? 0);
1549 $max_id = intval($_REQUEST['max_id'] ?? 0);
1550 $count = intval($_REQUEST['count'] ?? 20);
1551 $page = intval($_REQUEST['page'] ?? 1);
1553 $start = max(0, ($page - 1) * $count);
1556 $id = intval($_REQUEST['id'] ?? 0);
1561 $id = intval(DI::args()->getArgv()[4] ?? 0);
1564 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1566 // try to fetch the item for the local user - or the public item, if there is no local one
1567 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1568 if (!DBA::isResult($item)) {
1569 throw new BadRequestException("There is no status with the id $id.");
1572 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, BaseApi::getCurrentUserID()]], ['order' => ['uid' => true]]);
1573 if (!DBA::isResult($parent)) {
1574 throw new BadRequestException("There is no status with this id.");
1577 $id = $parent['id'];
1579 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1580 $id, BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1583 $condition[0] .= " AND `id` <= ?";
1584 $condition[] = $max_id;
1587 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1588 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1590 if (!DBA::isResult($statuses)) {
1591 throw new BadRequestException("There is no status with id $id.");
1594 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1596 $data = ['status' => $ret];
1597 return DI::apiResponse()->formatData("statuses", $type, $data);
1600 /// @TODO move to top of file or somewhere better
1601 api_register_func('api/conversation/show', 'api_conversation_show', true);
1602 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1607 * @param string $type Return type (atom, rss, xml, json)
1609 * @return array|string
1610 * @throws BadRequestException
1611 * @throws ForbiddenException
1612 * @throws ImagickException
1613 * @throws InternalServerErrorException
1614 * @throws UnauthorizedException
1615 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1617 function api_statuses_repeat($type)
1623 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1626 $id = intval(DI::args()->getArgv()[3] ?? 0);
1629 $id = intval($_REQUEST['id'] ?? 0);
1634 $id = intval(DI::args()->getArgv()[4] ?? 0);
1637 logger::notice('API: api_statuses_repeat: ' . $id);
1639 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1640 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1642 if (DBA::isResult($item) && !empty($item['body'])) {
1643 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1644 if (!Item::performActivity($id, 'announce', local_user())) {
1645 throw new InternalServerErrorException();
1650 if (strpos($item['body'], "[/share]") !== false) {
1651 $pos = strpos($item['body'], "[share");
1652 $post = substr($item['body'], $pos);
1654 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1656 if (!empty($item['title'])) {
1657 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1660 $post .= $item['body'];
1661 $post .= "[/share]";
1663 $_REQUEST['body'] = $post;
1664 $_REQUEST['profile_uid'] = BaseApi::getCurrentUserID();
1665 $_REQUEST['api_source'] = true;
1667 if (empty($_REQUEST['source'])) {
1668 $_REQUEST["source"] = api_source();
1671 $item_id = item_post($a);
1674 throw new ForbiddenException();
1677 // output the post that we just posted.
1679 return api_status_show($type, $item_id);
1682 /// @TODO move to top of file or somewhere better
1683 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1686 * Destroys a specific status.
1688 * @param string $type Return type (atom, rss, xml, json)
1690 * @return array|string
1691 * @throws BadRequestException
1692 * @throws ForbiddenException
1693 * @throws ImagickException
1694 * @throws InternalServerErrorException
1695 * @throws UnauthorizedException
1696 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1698 function api_statuses_destroy($type)
1700 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1703 $id = intval(DI::args()->getArgv()[3] ?? 0);
1706 $id = intval($_REQUEST['id'] ?? 0);
1711 $id = intval(DI::args()->getArgv()[4] ?? 0);
1714 logger::notice('API: api_statuses_destroy: ' . $id);
1716 $ret = api_statuses_show($type);
1718 Item::deleteForUser(['id' => $id], BaseApi::getCurrentUserID());
1723 /// @TODO move to top of file or somewhere better
1724 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1727 * Returns the most recent mentions.
1729 * @param string $type Return type (atom, rss, xml, json)
1731 * @return array|string
1732 * @throws BadRequestException
1733 * @throws ForbiddenException
1734 * @throws ImagickException
1735 * @throws InternalServerErrorException
1736 * @throws UnauthorizedException
1737 * @see http://developer.twitter.com/doc/get/statuses/mentions
1739 function api_statuses_mentions($type)
1741 if (empty(BaseApi::getCurrentUserID())) {
1742 throw new ForbiddenException();
1744 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1746 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1748 unset($_REQUEST["user_id"]);
1749 unset($_GET["user_id"]);
1751 unset($_REQUEST["screen_name"]);
1752 unset($_GET["screen_name"]);
1754 // get last network messages
1757 $since_id = intval($_REQUEST['since_id'] ?? 0);
1758 $max_id = intval($_REQUEST['max_id'] ?? 0);
1759 $count = intval($_REQUEST['count'] ?? 20);
1760 $page = intval($_REQUEST['page'] ?? 1);
1762 $start = max(0, ($page - 1) * $count);
1764 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1765 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1766 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1769 GRAVITY_PARENT, GRAVITY_COMMENT,
1770 BaseApi::getCurrentUserID(),
1771 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1772 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1773 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1774 BaseApi::getCurrentUserID(), $since_id,
1778 $query .= " AND `id` <= ?";
1779 $condition[] = $max_id;
1782 array_unshift($condition, $query);
1784 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1785 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1787 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1789 $data = ['status' => $ret];
1794 $data = api_rss_extra($data, $user_info);
1798 return DI::apiResponse()->formatData("statuses", $type, $data);
1801 /// @TODO move to top of file or somewhere better
1802 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1803 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1806 * Returns the most recent statuses posted by the user.
1808 * @param string $type Either "json" or "xml"
1809 * @return string|array
1810 * @throws BadRequestException
1811 * @throws ForbiddenException
1812 * @throws ImagickException
1813 * @throws InternalServerErrorException
1814 * @throws UnauthorizedException
1815 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1817 function api_statuses_user_timeline($type)
1819 if (empty(BaseApi::getCurrentUserID())) {
1820 throw new ForbiddenException();
1822 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1824 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1826 Logger::info('api_statuses_user_timeline', ['api_user' => BaseApi::getCurrentUserID(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1828 $since_id = $_REQUEST['since_id'] ?? 0;
1829 $max_id = $_REQUEST['max_id'] ?? 0;
1830 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1831 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1834 $count = $_REQUEST['count'] ?? 20;
1835 $page = $_REQUEST['page'] ?? 1;
1837 $start = max(0, ($page - 1) * $count);
1839 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1840 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1842 if ($user_info['self'] == 1) {
1843 $condition[0] .= ' AND `wall` ';
1846 if ($exclude_replies) {
1847 $condition[0] .= ' AND `gravity` = ?';
1848 $condition[] = GRAVITY_PARENT;
1851 if ($conversation_id > 0) {
1852 $condition[0] .= " AND `parent` = ?";
1853 $condition[] = $conversation_id;
1857 $condition[0] .= " AND `id` <= ?";
1858 $condition[] = $max_id;
1860 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1861 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
1863 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1867 $data = ['status' => $ret];
1872 $data = api_rss_extra($data, $user_info);
1876 return DI::apiResponse()->formatData("statuses", $type, $data);
1879 /// @TODO move to top of file or somewhere better
1880 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1883 * Star/unstar an item.
1884 * param: id : id of the item
1886 * @param string $type Return type (atom, rss, xml, json)
1888 * @return array|string
1889 * @throws BadRequestException
1890 * @throws ForbiddenException
1891 * @throws ImagickException
1892 * @throws InternalServerErrorException
1893 * @throws UnauthorizedException
1894 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1896 function api_favorites_create_destroy($type)
1898 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
1900 // for versioned api.
1901 /// @TODO We need a better global soluton
1902 $action_argv_id = 2;
1903 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1904 $action_argv_id = 3;
1907 if (DI::args()->getArgc() <= $action_argv_id) {
1908 throw new BadRequestException("Invalid request.");
1910 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1911 if (DI::args()->getArgc() == $action_argv_id + 2) {
1912 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1914 $itemid = intval($_REQUEST['id'] ?? 0);
1917 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $itemid, 'uid' => BaseApi::getCurrentUserID()]);
1919 if (!DBA::isResult($item)) {
1920 throw new BadRequestException("Invalid item.");
1925 $item['starred'] = 1;
1928 $item['starred'] = 0;
1931 throw new BadRequestException("Invalid action ".$action);
1934 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1937 throw new InternalServerErrorException("DB error");
1940 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1941 $rets = api_format_items([$item], $user_info, false, $type);
1944 $data = ['status' => $ret];
1949 $data = api_rss_extra($data, $user_info);
1953 return DI::apiResponse()->formatData("status", $type, $data);
1956 /// @TODO move to top of file or somewhere better
1957 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1958 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1961 * Returns the most recent favorite statuses.
1963 * @param string $type Return type (atom, rss, xml, json)
1965 * @return string|array
1966 * @throws BadRequestException
1967 * @throws ForbiddenException
1968 * @throws ImagickException
1969 * @throws InternalServerErrorException
1970 * @throws UnauthorizedException
1972 function api_favorites($type)
1976 if (empty(BaseApi::getCurrentUserID())) {
1977 throw new ForbiddenException();
1979 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
1981 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
1985 // in friendica starred item are private
1986 // return favorites only for self
1987 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
1989 if ($user_info['self'] == 0) {
1993 $since_id = $_REQUEST['since_id'] ?? 0;
1994 $max_id = $_REQUEST['max_id'] ?? 0;
1995 $count = $_GET['count'] ?? 20;
1996 $page = $_REQUEST['page'] ?? 1;
1998 $start = max(0, ($page - 1) * $count);
2000 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2001 BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2003 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2006 $condition[0] .= " AND `id` <= ?";
2007 $condition[] = $max_id;
2010 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2012 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2017 $data = ['status' => $ret];
2022 $data = api_rss_extra($data, $user_info);
2026 return DI::apiResponse()->formatData("statuses", $type, $data);
2029 /// @TODO move to top of file or somewhere better
2030 api_register_func('api/favorites', 'api_favorites', true);
2034 * @param array $item
2035 * @param array $recipient
2036 * @param array $sender
2039 * @throws InternalServerErrorException
2041 function api_format_messages($item, $recipient, $sender)
2043 // standard meta information
2045 'id' => $item['id'],
2046 'sender_id' => $sender['id'],
2048 'recipient_id' => $recipient['id'],
2049 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2050 'sender_screen_name' => $sender['screen_name'],
2051 'recipient_screen_name' => $recipient['screen_name'],
2052 'sender' => $sender,
2053 'recipient' => $recipient,
2055 'friendica_seen' => $item['seen'] ?? 0,
2056 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2059 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2060 if (isset($ret['sender']['uid'])) {
2061 unset($ret['sender']['uid']);
2063 if (isset($ret['sender']['self'])) {
2064 unset($ret['sender']['self']);
2066 if (isset($ret['recipient']['uid'])) {
2067 unset($ret['recipient']['uid']);
2069 if (isset($ret['recipient']['self'])) {
2070 unset($ret['recipient']['self']);
2073 //don't send title to regular StatusNET requests to avoid confusing these apps
2074 if (!empty($_GET['getText'])) {
2075 $ret['title'] = $item['title'];
2076 if ($_GET['getText'] == 'html') {
2077 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2078 } elseif ($_GET['getText'] == 'plain') {
2079 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2082 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2084 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2085 unset($ret['sender']);
2086 unset($ret['recipient']);
2094 * @param array $item
2097 * @throws InternalServerErrorException
2099 function api_convert_item($item)
2101 $body = api_add_attachments_to_body($item);
2103 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2105 // Add pictures to the attachment array and remove them from the body
2106 $attachments = api_get_attachments($body, $item['uri-id']);
2108 // Workaround for ostatus messages where the title is identically to the body
2109 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2110 $statusbody = trim(HTML::toPlaintext($html, 0));
2112 // handle data: images
2113 $statusbody = api_format_items_embeded_images($item, $statusbody);
2115 $statustitle = trim($item['title']);
2117 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2118 $statustext = trim($statusbody);
2120 $statustext = trim($statustitle."\n\n".$statusbody);
2123 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2124 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2127 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2129 // Workaround for clients with limited HTML parser functionality
2130 $search = ["<br>", "<blockquote>", "</blockquote>",
2131 "<h1>", "</h1>", "<h2>", "</h2>",
2132 "<h3>", "</h3>", "<h4>", "</h4>",
2133 "<h5>", "</h5>", "<h6>", "</h6>"];
2134 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2135 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2136 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2137 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2138 $statushtml = str_replace($search, $replace, $statushtml);
2140 if ($item['title'] != "") {
2141 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2145 $oldtext = $statushtml;
2146 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2147 } while ($oldtext != $statushtml);
2149 if (substr($statushtml, 0, 4) == '<br>') {
2150 $statushtml = substr($statushtml, 4);
2153 if (substr($statushtml, 0, -4) == '<br>') {
2154 $statushtml = substr($statushtml, -4);
2157 // feeds without body should contain the link
2158 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2159 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2163 "text" => $statustext,
2164 "html" => $statushtml,
2165 "attachments" => $attachments,
2166 "entities" => $entities
2171 * Add media attachments to the body
2173 * @param array $item
2174 * @return string body with added media
2176 function api_add_attachments_to_body(array $item)
2178 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2180 if (strpos($body, '[/img]') !== false) {
2184 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2185 if (!empty($media['preview'])) {
2186 $description = $media['description'] ?: $media['name'];
2187 if (!empty($description)) {
2188 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2190 $body .= "\n[img]" . $media['preview'] .'[/img]';
2200 * @param string $body
2204 * @throws InternalServerErrorException
2206 function api_get_attachments(&$body, $uriid)
2208 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2209 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2211 $URLSearchString = "^\[\]";
2212 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2216 // Remove all embedded pictures, since they are added as attachments
2217 foreach ($images[0] as $orig) {
2218 $body = str_replace($orig, '', $body);
2223 foreach ($images[1] as $image) {
2224 $imagedata = Images::getInfoFromURLCached($image);
2227 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2231 return $attachments;
2236 * @param string $text
2237 * @param string $bbcode
2240 * @throws InternalServerErrorException
2241 * @todo Links at the first character of the post
2243 function api_get_entitities(&$text, $bbcode, $uriid)
2245 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2247 if ($include_entities != "true") {
2248 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2250 foreach ($images[1] as $image) {
2251 $replace = Post\Link::getByLink($uriid, $image);
2252 $text = str_replace($image, $replace, $text);
2257 $bbcode = BBCode::cleanPictureLinks($bbcode);
2259 // Change pure links in text to bbcode uris
2260 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2263 $entities["hashtags"] = [];
2264 $entities["symbols"] = [];
2265 $entities["urls"] = [];
2266 $entities["user_mentions"] = [];
2268 $URLSearchString = "^\[\]";
2270 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2272 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2273 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2275 $bbcode = preg_replace(
2276 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2277 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2280 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2282 $bbcode = preg_replace(
2283 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2284 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2287 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2289 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2291 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2294 foreach ($urls[1] as $id => $url) {
2295 $start = iconv_strpos($text, $url, 0, "UTF-8");
2296 if (!($start === false)) {
2297 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2301 ksort($ordered_urls);
2305 foreach ($ordered_urls as $url) {
2306 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2307 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2309 $display_url = $url["title"];
2311 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2312 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2314 if (strlen($display_url) > 26) {
2315 $display_url = substr($display_url, 0, 25)."…";
2319 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2320 if (!($start === false)) {
2321 $entities["urls"][] = ["url" => $url["url"],
2322 "expanded_url" => $url["url"],
2323 "display_url" => $display_url,
2324 "indices" => [$start, $start+strlen($url["url"])]];
2325 $offset = $start + 1;
2329 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2330 $ordered_images = [];
2331 foreach ($images as $image) {
2332 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2333 if (!($start === false)) {
2334 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2338 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2339 foreach ($images[1] as $image) {
2340 $start = iconv_strpos($text, $image, 0, "UTF-8");
2341 if (!($start === false)) {
2342 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2348 foreach ($ordered_images as $image) {
2349 $url = $image['url'];
2350 $ext_alt_text = $image['alt'];
2352 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2353 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2355 if (strlen($display_url) > 26) {
2356 $display_url = substr($display_url, 0, 25)."…";
2359 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2360 if (!($start === false)) {
2361 $image = Images::getInfoFromURLCached($url);
2363 $media_url = Post\Link::getByLink($uriid, $url);
2364 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2366 $entities["media"][] = [
2368 "id_str" => (string) ($start + 1),
2369 "indices" => [$start, $start+strlen($url)],
2370 "media_url" => Strings::normaliseLink($media_url),
2371 "media_url_https" => $media_url,
2373 "display_url" => $display_url,
2374 "expanded_url" => $url,
2375 "ext_alt_text" => $ext_alt_text,
2379 $offset = $start + 1;
2388 * @param array $item
2389 * @param string $text
2393 function api_format_items_embeded_images($item, $text)
2395 $text = preg_replace_callback(
2396 '|data:image/([^;]+)[^=]+=*|m',
2397 function () use ($item) {
2398 return DI::baseUrl() . '/display/' . $item['guid'];
2406 * return <a href='url'>name</a> as array
2408 * @param string $txt text
2413 function api_contactlink_to_array($txt)
2416 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2417 if ($r && count($match)==3) {
2419 'name' => $match[2],
2433 * return likes, dislikes and attend status for item
2435 * @param array $item array
2436 * @param string $type Return type (atom, rss, xml, json)
2439 * likes => int count,
2440 * dislikes => int count
2441 * @throws BadRequestException
2442 * @throws ImagickException
2443 * @throws InternalServerErrorException
2444 * @throws UnauthorizedException
2446 function api_format_items_activities($item, $type = "json")
2453 'attendmaybe' => [],
2457 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2458 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2460 while ($parent_item = Post::fetch($ret)) {
2461 // not used as result should be structured like other user data
2462 //builtin_activity_puller($i, $activities);
2464 // get user data and add it to the array of the activity
2465 $user = DI::twitterUser()->createFromContactId($parent_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2466 switch ($parent_item['verb']) {
2467 case Activity::LIKE:
2468 $activities['like'][] = $user;
2470 case Activity::DISLIKE:
2471 $activities['dislike'][] = $user;
2473 case Activity::ATTEND:
2474 $activities['attendyes'][] = $user;
2476 case Activity::ATTENDNO:
2477 $activities['attendno'][] = $user;
2479 case Activity::ATTENDMAYBE:
2480 $activities['attendmaybe'][] = $user;
2482 case Activity::ANNOUNCE:
2483 $activities['announce'][] = $user;
2492 if ($type == "xml") {
2493 $xml_activities = [];
2494 foreach ($activities as $k => $v) {
2495 // change xml element from "like" to "friendica:like"
2496 $xml_activities["friendica:".$k] = $v;
2497 // add user data into xml output
2499 foreach ($v as $user) {
2500 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2503 $activities = $xml_activities;
2510 * format items to be returned by api
2512 * @param array $items array of items
2513 * @param array $user_info
2514 * @param bool $filter_user filter items by $user_info
2515 * @param string $type Return type (atom, rss, xml, json)
2517 * @throws BadRequestException
2518 * @throws ImagickException
2519 * @throws InternalServerErrorException
2520 * @throws UnauthorizedException
2522 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2528 if (empty($items)) {
2532 foreach ((array)$items as $item) {
2533 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2535 // Look if the posts are matching if they should be filtered by user id
2536 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2540 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2549 * @param array $item Item record
2550 * @param string $type Return format (atom, rss, xml, json)
2551 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2552 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2553 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2554 * @return array API-formatted status
2555 * @throws BadRequestException
2556 * @throws ImagickException
2557 * @throws InternalServerErrorException
2558 * @throws UnauthorizedException
2560 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2564 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2565 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2568 DI::contentItem()->localize($item);
2570 $in_reply_to = api_in_reply_to($item);
2572 $converted = api_convert_item($item);
2574 if ($type == "xml") {
2575 $geo = "georss:point";
2581 'text' => $converted["text"],
2582 'truncated' => false,
2583 'created_at'=> api_date($item['created']),
2584 'in_reply_to_status_id' => $in_reply_to['status_id'],
2585 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2586 'source' => (($item['app']) ? $item['app'] : 'web'),
2587 'id' => intval($item['id']),
2588 'id_str' => (string) intval($item['id']),
2589 'in_reply_to_user_id' => $in_reply_to['user_id'],
2590 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2591 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2593 'favorited' => $item['starred'] ? true : false,
2594 'user' => $status_user,
2595 'friendica_author' => $author_user,
2596 'friendica_owner' => $owner_user,
2597 'friendica_private' => $item['private'] == Item::PRIVATE,
2598 //'entities' => NULL,
2599 'statusnet_html' => $converted["html"],
2600 'statusnet_conversation_id' => $item['parent'],
2601 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2602 'friendica_activities' => api_format_items_activities($item, $type),
2603 'friendica_title' => $item['title'],
2604 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2607 if (count($converted["attachments"]) > 0) {
2608 $status["attachments"] = $converted["attachments"];
2611 if (count($converted["entities"]) > 0) {
2612 $status["entities"] = $converted["entities"];
2615 if ($status["source"] == 'web') {
2616 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2617 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2618 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2621 $retweeted_item = [];
2624 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2625 $announce = api_get_announce($item);
2626 if (!empty($announce)) {
2627 $retweeted_item = $item;
2629 $status['friendica_owner'] = DI::twitterUser()->createFromContactId($announce['author-id'], BaseApi::getCurrentUserID())->toArray();
2633 if (!empty($quoted_item)) {
2634 if ($quoted_item['id'] != $item['id']) {
2635 $quoted_status = api_format_item($quoted_item);
2636 /// @todo Only remove the attachments that are also contained in the quotes status
2637 unset($status['attachments']);
2638 unset($status['entities']);
2640 $conv_quoted = api_convert_item($quoted_item);
2641 $quoted_status = $status;
2642 unset($quoted_status['attachments']);
2643 unset($quoted_status['entities']);
2644 unset($quoted_status['statusnet_conversation_id']);
2645 $quoted_status['text'] = $conv_quoted['text'];
2646 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2648 $quoted_status["user"] = DI::twitterUser()->createFromContactId($quoted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2649 } catch (BadRequestException $e) {
2650 // user not found. should be found?
2651 /// @todo check if the user should be always found
2652 $quoted_status["user"] = [];
2655 unset($quoted_status['friendica_author']);
2656 unset($quoted_status['friendica_owner']);
2657 unset($quoted_status['friendica_activities']);
2658 unset($quoted_status['friendica_private']);
2661 if (!empty($retweeted_item)) {
2662 $retweeted_status = $status;
2663 unset($retweeted_status['friendica_author']);
2664 unset($retweeted_status['friendica_owner']);
2665 unset($retweeted_status['friendica_activities']);
2666 unset($retweeted_status['friendica_private']);
2667 unset($retweeted_status['statusnet_conversation_id']);
2668 $status['user'] = $status['friendica_owner'];
2670 $retweeted_status["user"] = DI::twitterUser()->createFromContactId($retweeted_item['author-id'], BaseApi::getCurrentUserID())->toArray();
2671 } catch (BadRequestException $e) {
2672 // user not found. should be found?
2673 /// @todo check if the user should be always found
2674 $retweeted_status["user"] = [];
2677 $rt_converted = api_convert_item($retweeted_item);
2679 $retweeted_status['text'] = $rt_converted["text"];
2680 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2681 $retweeted_status['friendica_html'] = $rt_converted["html"];
2682 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2684 if (!empty($quoted_status)) {
2685 $retweeted_status['quoted_status'] = $quoted_status;
2688 $status['friendica_author'] = $retweeted_status['user'];
2689 $status['retweeted_status'] = $retweeted_status;
2690 } elseif (!empty($quoted_status)) {
2691 $root_status = api_convert_item($item);
2693 $status['text'] = $root_status["text"];
2694 $status['statusnet_html'] = $root_status["html"];
2695 $status['quoted_status'] = $quoted_status;
2698 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2699 unset($status["user"]["uid"]);
2700 unset($status["user"]["self"]);
2702 if ($item["coord"] != "") {
2703 $coords = explode(' ', $item["coord"]);
2704 if (count($coords) == 2) {
2705 if ($type == "json") {
2706 $status["geo"] = ['type' => 'Point',
2707 'coordinates' => [(float) $coords[0],
2708 (float) $coords[1]]];
2709 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2710 $status["georss:point"] = $item["coord"];
2719 * Returns all lists the user subscribes to.
2721 * @param string $type Return type (atom, rss, xml, json)
2723 * @return array|string
2724 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2726 function api_lists_list($type)
2729 /// @TODO $ret is not filled here?
2730 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2733 /// @TODO move to top of file or somewhere better
2734 api_register_func('api/lists/list', 'api_lists_list', true);
2735 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2738 * Returns all groups the user owns.
2740 * @param string $type Return type (atom, rss, xml, json)
2742 * @return array|string
2743 * @throws BadRequestException
2744 * @throws ForbiddenException
2745 * @throws ImagickException
2746 * @throws InternalServerErrorException
2747 * @throws UnauthorizedException
2748 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2750 function api_lists_ownerships($type)
2752 if (empty(BaseApi::getCurrentUserID())) {
2753 throw new ForbiddenException();
2755 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2758 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2759 $uid = $user_info['uid'];
2761 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2763 // loop through all groups
2765 foreach ($groups as $group) {
2766 if ($group['visible']) {
2772 'name' => $group['name'],
2773 'id' => intval($group['id']),
2774 'id_str' => (string) $group['id'],
2775 'user' => $user_info,
2779 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2782 /// @TODO move to top of file or somewhere better
2783 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2786 * Returns recent statuses from users in the specified group.
2788 * @param string $type Return type (atom, rss, xml, json)
2790 * @return array|string
2791 * @throws BadRequestException
2792 * @throws ForbiddenException
2793 * @throws ImagickException
2794 * @throws InternalServerErrorException
2795 * @throws UnauthorizedException
2796 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2798 function api_lists_statuses($type)
2800 if (empty(BaseApi::getCurrentUserID())) {
2801 throw new ForbiddenException();
2803 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2805 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2807 unset($_REQUEST["user_id"]);
2808 unset($_GET["user_id"]);
2810 unset($_REQUEST["screen_name"]);
2811 unset($_GET["screen_name"]);
2813 if (empty($_REQUEST['list_id'])) {
2814 throw new BadRequestException('list_id not specified');
2818 $count = $_REQUEST['count'] ?? 20;
2819 $page = $_REQUEST['page'] ?? 1;
2820 $since_id = $_REQUEST['since_id'] ?? 0;
2821 $max_id = $_REQUEST['max_id'] ?? 0;
2822 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2823 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2825 $start = max(0, ($page - 1) * $count);
2827 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2828 $gids = array_column($groups, 'contact-id');
2829 $condition = ['uid' => BaseApi::getCurrentUserID(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2830 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2833 $condition[0] .= " AND `id` <= ?";
2834 $condition[] = $max_id;
2836 if ($exclude_replies > 0) {
2837 $condition[0] .= ' AND `gravity` = ?';
2838 $condition[] = GRAVITY_PARENT;
2840 if ($conversation_id > 0) {
2841 $condition[0] .= " AND `parent` = ?";
2842 $condition[] = $conversation_id;
2845 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2846 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition, $params);
2848 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2850 $data = ['status' => $items];
2855 $data = api_rss_extra($data, $user_info);
2859 return DI::apiResponse()->formatData("statuses", $type, $data);
2862 /// @TODO move to top of file or somewhere better
2863 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2866 * Returns either the friends of the follower list
2868 * Considers friends and followers lists to be private and won't return
2869 * anything if any user_id parameter is passed.
2871 * @param string $qtype Either "friends" or "followers"
2872 * @return boolean|array
2873 * @throws BadRequestException
2874 * @throws ForbiddenException
2875 * @throws ImagickException
2876 * @throws InternalServerErrorException
2877 * @throws UnauthorizedException
2879 function api_statuses_f($qtype)
2881 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
2884 $count = $_GET['count'] ?? 20;
2885 $page = $_GET['page'] ?? 1;
2887 $start = max(0, ($page - 1) * $count);
2889 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
2891 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2892 /* this is to stop Hotot to load friends multiple times
2893 * I'm not sure if I'm missing return something or
2894 * is a bug in hotot. Workaround, meantime
2898 return array('$users' => $ret);*/
2903 if ($qtype == 'friends') {
2904 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2905 } elseif ($qtype == 'followers') {
2906 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2909 // friends and followers only for self
2910 if ($user_info['self'] == 0) {
2911 $sql_extra = " AND false ";
2914 if ($qtype == 'blocks') {
2915 $sql_filter = 'AND `blocked` AND NOT `pending`';
2916 } elseif ($qtype == 'incoming') {
2917 $sql_filter = 'AND `pending`';
2919 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2922 // @todo This query most likely can be replaced with a Contact::select...
2923 $r = DBA::toArray(DBA::p(
2932 BaseApi::getCurrentUserID(),
2938 foreach ($r as $cid) {
2939 $user = DI::twitterUser()->createFromContactId($cid['id'], BaseApi::getCurrentUserID())->toArray();
2940 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2941 unset($user["uid"]);
2942 unset($user["self"]);
2949 return ['user' => $ret];
2954 * Returns the list of friends of the provided user
2956 * @deprecated By Twitter API in favor of friends/list
2958 * @param string $type Either "json" or "xml"
2959 * @return boolean|string|array
2960 * @throws BadRequestException
2961 * @throws ForbiddenException
2963 function api_statuses_friends($type)
2965 $data = api_statuses_f("friends");
2966 if ($data === false) {
2969 return DI::apiResponse()->formatData("users", $type, $data);
2973 * Returns the list of followers of the provided user
2975 * @deprecated By Twitter API in favor of friends/list
2977 * @param string $type Either "json" or "xml"
2978 * @return boolean|string|array
2979 * @throws BadRequestException
2980 * @throws ForbiddenException
2982 function api_statuses_followers($type)
2984 $data = api_statuses_f("followers");
2985 if ($data === false) {
2988 return DI::apiResponse()->formatData("users", $type, $data);
2991 /// @TODO move to top of file or somewhere better
2992 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
2993 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
2996 * Returns the list of blocked users
2998 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3000 * @param string $type Either "json" or "xml"
3002 * @return boolean|string|array
3003 * @throws BadRequestException
3004 * @throws ForbiddenException
3006 function api_blocks_list($type)
3008 $data = api_statuses_f('blocks');
3009 if ($data === false) {
3012 return DI::apiResponse()->formatData("users", $type, $data);
3015 /// @TODO move to top of file or somewhere better
3016 api_register_func('api/blocks/list', 'api_blocks_list', true);
3019 * Returns the list of pending users IDs
3021 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3023 * @param string $type Either "json" or "xml"
3025 * @return boolean|string|array
3026 * @throws BadRequestException
3027 * @throws ForbiddenException
3029 function api_friendships_incoming($type)
3031 $data = api_statuses_f('incoming');
3032 if ($data === false) {
3037 foreach ($data['user'] as $user) {
3038 $ids[] = $user['id'];
3041 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3044 /// @TODO move to top of file or somewhere better
3045 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3048 * Sends a new direct message.
3050 * @param string $type Return type (atom, rss, xml, json)
3052 * @return array|string
3053 * @throws BadRequestException
3054 * @throws ForbiddenException
3055 * @throws ImagickException
3056 * @throws InternalServerErrorException
3057 * @throws NotFoundException
3058 * @throws UnauthorizedException
3059 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3061 function api_direct_messages_new($type)
3063 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3065 $uid = BaseApi::getCurrentUserID();
3067 throw new ForbiddenException();
3070 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3074 $sender = DI::twitterUser()->createFromUserId($uid)->toArray();
3077 if (!empty($_POST['screen_name'])) {
3078 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => BaseApi::getCurrentUserID(), 'nick' => $_POST['screen_name']]);
3079 if (DBA::isResult($contacts)) {
3080 // Selecting the id by priority, friendica first
3081 api_best_nickname($contacts);
3083 $recipient = DI::twitterUser()->createFromContactId($contacts[0]['id'], $uid)->toArray();
3086 $recipient = api_get_user($_POST['user_id']);
3089 if (empty($recipient)) {
3090 throw new NotFoundException('Recipient not found');
3094 if (!empty($_REQUEST['replyto'])) {
3095 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $_REQUEST['replyto']]);
3096 $replyto = $mail['parent-uri'];
3097 $sub = $mail['title'];
3099 if (!empty($_REQUEST['title'])) {
3100 $sub = $_REQUEST['title'];
3102 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3106 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3109 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3110 $ret = api_format_messages($mail, $recipient, $sender);
3112 $ret = ["error" => $id];
3115 $data = ['direct_message'=>$ret];
3121 $data = api_rss_extra($data, $sender);
3125 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3128 /// @TODO move to top of file or somewhere better
3129 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3132 * delete a direct_message from mail table through api
3134 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3135 * @return string|array
3136 * @throws BadRequestException
3137 * @throws ForbiddenException
3138 * @throws ImagickException
3139 * @throws InternalServerErrorException
3140 * @throws UnauthorizedException
3141 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3143 function api_direct_messages_destroy($type)
3145 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3148 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3150 $id = $_REQUEST['id'] ?? 0;
3152 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3153 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3154 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3156 $uid = $user_info['uid'];
3157 // error if no id or parenturi specified (for clients posting parent-uri as well)
3158 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3159 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3160 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3163 // BadRequestException if no id specified (for clients using Twitter API)
3165 throw new BadRequestException('Message id not specified');
3168 // add parent-uri to sql command if specified by calling app
3169 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3171 // error message if specified id is not in database
3172 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3173 if ($verbose == "true") {
3174 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3175 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3177 /// @todo BadRequestException ok for Twitter API clients?
3178 throw new BadRequestException('message id not in database');
3182 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3184 if ($verbose == "true") {
3187 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3188 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3190 $answer = ['result' => 'error', 'message' => 'unknown error'];
3191 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3194 /// @todo return JSON data like Twitter API not yet implemented
3197 /// @TODO move to top of file or somewhere better
3198 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3203 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3204 * @return string|array
3205 * @throws HTTPException\BadRequestException
3206 * @throws HTTPException\ExpectationFailedException
3207 * @throws HTTPException\ForbiddenException
3208 * @throws HTTPException\InternalServerErrorException
3209 * @throws HTTPException\NotFoundException
3210 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3212 function api_friendships_destroy($type)
3214 $uid = BaseApi::getCurrentUserID();
3216 if ($uid === false) {
3217 throw new HTTPException\ForbiddenException();
3220 $owner = User::getOwnerDataById($uid);
3222 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3223 throw new HTTPException\NotFoundException('Error Processing Request');
3226 $contact_id = $_REQUEST['user_id'] ?? 0;
3228 if (empty($contact_id)) {
3229 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3230 throw new HTTPException\BadRequestException('no user_id specified');
3233 // Get Contact by given id
3234 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3236 if(!DBA::isResult($contact)) {
3237 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3238 throw new HTTPException\NotFoundException('no contact found to given ID');
3241 $url = $contact['url'];
3243 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3244 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3245 Strings::normaliseLink($url), $url];
3246 $contact = DBA::selectFirst('contact', [], $condition);
3248 if (!DBA::isResult($contact)) {
3249 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3250 throw new HTTPException\NotFoundException('Not following Contact');
3254 $result = Contact::terminateFriendship($owner, $contact);
3256 if ($result === null) {
3257 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3258 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3261 if ($result === false) {
3262 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3264 } catch (Exception $e) {
3265 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3266 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3269 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3270 unset($contact['uid']);
3271 unset($contact['self']);
3273 // Set screen_name since Twidere requests it
3274 $contact['screen_name'] = $contact['nick'];
3276 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3279 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3283 * @param string $type Return type (atom, rss, xml, json)
3284 * @param string $box
3285 * @param string $verbose
3287 * @return array|string
3288 * @throws BadRequestException
3289 * @throws ForbiddenException
3290 * @throws ImagickException
3291 * @throws InternalServerErrorException
3292 * @throws UnauthorizedException
3294 function api_direct_messages_box($type, $box, $verbose)
3296 if (empty(BaseApi::getCurrentUserID())) {
3297 throw new ForbiddenException();
3299 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
3302 $count = $_GET['count'] ?? 20;
3303 $page = $_REQUEST['page'] ?? 1;
3305 $since_id = $_REQUEST['since_id'] ?? 0;
3306 $max_id = $_REQUEST['max_id'] ?? 0;
3308 $user_id = $_REQUEST['user_id'] ?? '';
3309 $screen_name = $_REQUEST['screen_name'] ?? '';
3312 unset($_REQUEST["user_id"]);
3313 unset($_GET["user_id"]);
3315 unset($_REQUEST["screen_name"]);
3316 unset($_GET["screen_name"]);
3318 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3320 $profile_url = $user_info["url"];
3323 $start = max(0, ($page - 1) * $count);
3328 if ($box=="sentbox") {
3329 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3330 } elseif ($box == "conversation") {
3331 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3332 } elseif ($box == "all") {
3333 $sql_extra = "true";
3334 } elseif ($box == "inbox") {
3335 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3339 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3342 if ($user_id != "") {
3343 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3344 } elseif ($screen_name !="") {
3345 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3348 $r = DBA::toArray(DBA::p(
3349 "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 ?,?",
3350 BaseApi::getCurrentUserID(),
3355 if ($verbose == "true" && !DBA::isResult($r)) {
3356 $answer = ['result' => 'error', 'message' => 'no mails available'];
3357 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3361 foreach ($r as $item) {
3362 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3363 $recipient = $user_info;
3364 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3365 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3366 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
3367 $sender = $user_info;
3370 if (isset($recipient) && isset($sender)) {
3371 $ret[] = api_format_messages($item, $recipient, $sender);
3376 $data = ['direct_message' => $ret];
3381 $data = api_rss_extra($data, $user_info);
3385 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3389 * Returns the most recent direct messages sent by the user.
3391 * @param string $type Return type (atom, rss, xml, json)
3393 * @return array|string
3394 * @throws BadRequestException
3395 * @throws ForbiddenException
3396 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3398 function api_direct_messages_sentbox($type)
3400 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3401 return api_direct_messages_box($type, "sentbox", $verbose);
3405 * Returns the most recent direct messages sent to the user.
3407 * @param string $type Return type (atom, rss, xml, json)
3409 * @return array|string
3410 * @throws BadRequestException
3411 * @throws ForbiddenException
3412 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3414 function api_direct_messages_inbox($type)
3416 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3417 return api_direct_messages_box($type, "inbox", $verbose);
3422 * @param string $type Return type (atom, rss, xml, json)
3424 * @return array|string
3425 * @throws BadRequestException
3426 * @throws ForbiddenException
3428 function api_direct_messages_all($type)
3430 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3431 return api_direct_messages_box($type, "all", $verbose);
3436 * @param string $type Return type (atom, rss, xml, json)
3438 * @return array|string
3439 * @throws BadRequestException
3440 * @throws ForbiddenException
3442 function api_direct_messages_conversation($type)
3444 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3445 return api_direct_messages_box($type, "conversation", $verbose);
3448 /// @TODO move to top of file or somewhere better
3449 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3450 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3451 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3452 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3455 * list all photos of the authenticated user
3457 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3458 * @return string|array
3459 * @throws ForbiddenException
3460 * @throws InternalServerErrorException
3462 function api_fr_photos_list($type)
3464 if (BaseApi::getCurrentUserID() === false) {
3465 throw new ForbiddenException();
3467 $r = DBA::toArray(DBA::p(
3468 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3469 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3470 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3471 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3474 'image/jpeg' => 'jpg',
3475 'image/png' => 'png',
3476 'image/gif' => 'gif'
3478 $data = ['photo'=>[]];
3479 if (DBA::isResult($r)) {
3480 foreach ($r as $rr) {
3482 $photo['id'] = $rr['resource-id'];
3483 $photo['album'] = $rr['album'];
3484 $photo['filename'] = $rr['filename'];
3485 $photo['type'] = $rr['type'];
3486 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3487 $photo['created'] = $rr['created'];
3488 $photo['edited'] = $rr['edited'];
3489 $photo['desc'] = $rr['desc'];
3491 if ($type == "xml") {
3492 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3494 $photo['thumb'] = $thumb;
3495 $data['photo'][] = $photo;
3499 return DI::apiResponse()->formatData("photos", $type, $data);
3503 * upload a new photo or change an existing photo
3505 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3506 * @return string|array
3507 * @throws BadRequestException
3508 * @throws ForbiddenException
3509 * @throws ImagickException
3510 * @throws InternalServerErrorException
3511 * @throws NotFoundException
3513 function api_fr_photo_create_update($type)
3515 if (BaseApi::getCurrentUserID() === false) {
3516 throw new ForbiddenException();
3519 $photo_id = $_REQUEST['photo_id'] ?? null;
3520 $desc = $_REQUEST['desc'] ?? null;
3521 $album = $_REQUEST['album'] ?? null;
3522 $album_new = $_REQUEST['album_new'] ?? null;
3523 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3524 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3525 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3526 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3527 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3529 // do several checks on input parameters
3530 // we do not allow calls without album string
3531 if ($album == null) {
3532 throw new BadRequestException("no albumname specified");
3534 // if photo_id == null --> we are uploading a new photo
3535 if ($photo_id == null) {
3538 // error if no media posted in create-mode
3539 if (empty($_FILES['media'])) {
3541 throw new BadRequestException("no media data submitted");
3544 // album_new will be ignored in create-mode
3549 // check if photo is existing in databasei
3550 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => BaseApi::getCurrentUserID(), 'album' => $album])) {
3551 throw new BadRequestException("photo not available");
3555 // checks on acl strings provided by clients
3556 $acl_input_error = false;
3557 $acl_input_error |= check_acl_input($allow_cid);
3558 $acl_input_error |= check_acl_input($deny_cid);
3559 $acl_input_error |= check_acl_input($allow_gid);
3560 $acl_input_error |= check_acl_input($deny_gid);
3561 if ($acl_input_error) {
3562 throw new BadRequestException("acl data invalid");
3564 // now let's upload the new media in create-mode
3565 if ($mode == "create") {
3566 $media = $_FILES['media'];
3567 $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);
3569 // return success of updating or error message
3570 if (!is_null($data)) {
3571 return DI::apiResponse()->formatData("photo_create", $type, $data);
3573 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3577 // now let's do the changes in update-mode
3578 if ($mode == "update") {
3579 $updated_fields = [];
3581 if (!is_null($desc)) {
3582 $updated_fields['desc'] = $desc;
3585 if (!is_null($album_new)) {
3586 $updated_fields['album'] = $album_new;
3589 if (!is_null($allow_cid)) {
3590 $allow_cid = trim($allow_cid);
3591 $updated_fields['allow_cid'] = $allow_cid;
3594 if (!is_null($deny_cid)) {
3595 $deny_cid = trim($deny_cid);
3596 $updated_fields['deny_cid'] = $deny_cid;
3599 if (!is_null($allow_gid)) {
3600 $allow_gid = trim($allow_gid);
3601 $updated_fields['allow_gid'] = $allow_gid;
3604 if (!is_null($deny_gid)) {
3605 $deny_gid = trim($deny_gid);
3606 $updated_fields['deny_gid'] = $deny_gid;
3610 if (count($updated_fields) > 0) {
3611 $nothingtodo = false;
3612 $result = Photo::update($updated_fields, ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id, 'album' => $album]);
3614 $nothingtodo = true;
3617 if (!empty($_FILES['media'])) {
3618 $nothingtodo = false;
3619 $media = $_FILES['media'];
3620 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3621 if (!is_null($data)) {
3622 return DI::apiResponse()->formatData("photo_update", $type, $data);
3626 // return success of updating or error message
3628 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3629 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3632 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3633 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3635 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3638 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3642 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3644 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3645 * @return string|array
3646 * @throws BadRequestException
3647 * @throws ForbiddenException
3648 * @throws InternalServerErrorException
3649 * @throws NotFoundException
3651 function api_fr_photo_detail($type)
3653 if (BaseApi::getCurrentUserID() === false) {
3654 throw new ForbiddenException();
3656 if (empty($_REQUEST['photo_id'])) {
3657 throw new BadRequestException("No photo id.");
3660 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3661 $photo_id = $_REQUEST['photo_id'];
3663 // prepare json/xml output with data from database for the requested photo
3664 $data = prepare_photo_data($type, $scale, $photo_id);
3666 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3671 * updates the profile image for the user (either a specified profile or the default profile)
3673 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3675 * @return string|array
3676 * @throws BadRequestException
3677 * @throws ForbiddenException
3678 * @throws ImagickException
3679 * @throws InternalServerErrorException
3680 * @throws NotFoundException
3681 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3683 function api_account_update_profile_image($type)
3685 if (BaseApi::getCurrentUserID() === false) {
3686 throw new ForbiddenException();
3689 $profile_id = $_REQUEST['profile_id'] ?? 0;
3691 // error if image data is missing
3692 if (empty($_FILES['image'])) {
3693 throw new BadRequestException("no media data submitted");
3696 // check if specified profile id is valid
3697 if ($profile_id != 0) {
3698 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => BaseApi::getCurrentUserID(), 'id' => $profile_id]);
3699 // error message if specified profile id is not in database
3700 if (!DBA::isResult($profile)) {
3701 throw new BadRequestException("profile_id not available");
3703 $is_default_profile = $profile['is-default'];
3705 $is_default_profile = 1;
3708 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3710 if (!empty($_FILES['image'])) {
3711 $media = $_FILES['image'];
3712 } elseif (!empty($_FILES['media'])) {
3713 $media = $_FILES['media'];
3715 // save new profile image
3716 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3719 if (is_array($media['type'])) {
3720 $filetype = $media['type'][0];
3722 $filetype = $media['type'];
3724 if ($filetype == "image/jpeg") {
3726 } elseif ($filetype == "image/png") {
3729 throw new InternalServerErrorException('Unsupported filetype');
3732 // change specified profile or all profiles to the new resource-id
3733 if ($is_default_profile) {
3734 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], BaseApi::getCurrentUserID()];
3735 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3737 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3738 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3739 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => BaseApi::getCurrentUserID()]);
3742 Contact::updateSelfFromUserID(BaseApi::getCurrentUserID(), true);
3744 // Update global directory in background
3745 Profile::publishUpdate(BaseApi::getCurrentUserID());
3747 // output for client
3749 return api_account_verify_credentials($type);
3751 // SaveMediaToDatabase failed for some reason
3752 throw new InternalServerErrorException("image upload failed");
3756 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3757 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3758 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3759 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3760 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3761 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3764 * Update user profile
3766 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3768 * @return array|string
3769 * @throws BadRequestException
3770 * @throws ForbiddenException
3771 * @throws ImagickException
3772 * @throws InternalServerErrorException
3773 * @throws UnauthorizedException
3775 function api_account_update_profile($type)
3777 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
3779 $local_user = BaseApi::getCurrentUserID();
3781 $api_user = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
3783 if (!empty($_POST['name'])) {
3784 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3785 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3786 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3787 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3790 if (isset($_POST['description'])) {
3791 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3792 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3793 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3796 Profile::publishUpdate($local_user);
3798 return api_account_verify_credentials($type);
3801 /// @TODO move to top of file or somewhere better
3802 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3806 * @param string $acl_string
3810 function check_acl_input($acl_string)
3812 if (empty($acl_string)) {
3816 $contact_not_found = false;
3818 // split <x><y><z> into array of cid's
3819 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3821 // check for each cid if it is available on server
3822 $cid_array = $array[0];
3823 foreach ($cid_array as $cid) {
3824 $cid = str_replace("<", "", $cid);
3825 $cid = str_replace(">", "", $cid);
3826 $condition = ['id' => $cid, 'uid' => BaseApi::getCurrentUserID()];
3827 $contact_not_found |= !DBA::exists('contact', $condition);
3829 return $contact_not_found;
3833 * @param string $mediatype
3834 * @param array $media
3835 * @param string $type
3836 * @param string $album
3837 * @param string $allow_cid
3838 * @param string $deny_cid
3839 * @param string $allow_gid
3840 * @param string $deny_gid
3841 * @param string $desc
3842 * @param integer $phototype
3843 * @param boolean $visibility
3844 * @param string $photo_id
3846 * @throws BadRequestException
3847 * @throws ForbiddenException
3848 * @throws ImagickException
3849 * @throws InternalServerErrorException
3850 * @throws NotFoundException
3851 * @throws UnauthorizedException
3853 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)
3861 if (is_array($media)) {
3862 if (is_array($media['tmp_name'])) {
3863 $src = $media['tmp_name'][0];
3865 $src = $media['tmp_name'];
3867 if (is_array($media['name'])) {
3868 $filename = basename($media['name'][0]);
3870 $filename = basename($media['name']);
3872 if (is_array($media['size'])) {
3873 $filesize = intval($media['size'][0]);
3875 $filesize = intval($media['size']);
3877 if (is_array($media['type'])) {
3878 $filetype = $media['type'][0];
3880 $filetype = $media['type'];
3884 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3887 "File upload src: " . $src . " - filename: " . $filename .
3888 " - size: " . $filesize . " - type: " . $filetype);
3890 // check if there was a php upload error
3891 if ($filesize == 0 && $media['error'] == 1) {
3892 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3894 // check against max upload size within Friendica instance
3895 $maximagesize = DI::config()->get('system', 'maximagesize');
3896 if ($maximagesize && ($filesize > $maximagesize)) {
3897 $formattedBytes = Strings::formatBytes($maximagesize);
3898 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3901 // create Photo instance with the data of the image
3902 $imagedata = @file_get_contents($src);
3903 $Image = new Image($imagedata, $filetype);
3904 if (!$Image->isValid()) {
3905 throw new InternalServerErrorException("unable to process image data");
3908 // check orientation of image
3909 $Image->orient($src);
3912 // check max length of images on server
3913 $max_length = DI::config()->get('system', 'max_image_length');
3914 if ($max_length > 0) {
3915 $Image->scaleDown($max_length);
3916 logger::info("File upload: Scaling picture to new size " . $max_length);
3918 $width = $Image->getWidth();
3919 $height = $Image->getHeight();
3921 // create a new resource-id if not already provided
3922 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3924 if ($mediatype == "photo") {
3925 // upload normal image (scales 0, 1, 2)
3926 logger::info("photo upload: starting new photo upload");
3928 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3930 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3932 if ($width > 640 || $height > 640) {
3933 $Image->scaleDown(640);
3934 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3936 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3940 if ($width > 320 || $height > 320) {
3941 $Image->scaleDown(320);
3942 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3944 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3947 logger::info("photo upload: new photo upload ended");
3948 } elseif ($mediatype == "profileimage") {
3949 // upload profile image (scales 4, 5, 6)
3950 logger::info("photo upload: starting new profile image upload");
3952 if ($width > 300 || $height > 300) {
3953 $Image->scaleDown(300);
3954 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3956 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
3960 if ($width > 80 || $height > 80) {
3961 $Image->scaleDown(80);
3962 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3964 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
3968 if ($width > 48 || $height > 48) {
3969 $Image->scaleDown(48);
3970 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3972 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
3975 $Image->__destruct();
3976 logger::info("photo upload: new profile image upload ended");
3980 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
3981 if ($photo_id == null && $mediatype == "photo") {
3982 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
3984 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
3985 return prepare_photo_data($type, false, $resource_id);
3987 throw new InternalServerErrorException("image upload failed");
3993 * @param string $hash
3994 * @param string $allow_cid
3995 * @param string $deny_cid
3996 * @param string $allow_gid
3997 * @param string $deny_gid
3998 * @param string $filetype
3999 * @param boolean $visibility
4000 * @throws InternalServerErrorException
4002 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4004 // get data about the api authenticated user
4005 $uri = Item::newURI(intval(BaseApi::getCurrentUserID()));
4006 $owner_record = DBA::selectFirst('contact', [], ['uid' => BaseApi::getCurrentUserID(), 'self' => true]);
4009 $arr['guid'] = System::createUUID();
4010 $arr['uid'] = intval(BaseApi::getCurrentUserID());
4012 $arr['type'] = 'photo';
4014 $arr['resource-id'] = $hash;
4015 $arr['contact-id'] = $owner_record['id'];
4016 $arr['owner-name'] = $owner_record['name'];
4017 $arr['owner-link'] = $owner_record['url'];
4018 $arr['owner-avatar'] = $owner_record['thumb'];
4019 $arr['author-name'] = $owner_record['name'];
4020 $arr['author-link'] = $owner_record['url'];
4021 $arr['author-avatar'] = $owner_record['thumb'];
4023 $arr['allow_cid'] = $allow_cid;
4024 $arr['allow_gid'] = $allow_gid;
4025 $arr['deny_cid'] = $deny_cid;
4026 $arr['deny_gid'] = $deny_gid;
4027 $arr['visible'] = $visibility;
4031 'image/jpeg' => 'jpg',
4032 'image/png' => 'png',
4033 'image/gif' => 'gif'
4036 // adds link to the thumbnail scale photo
4037 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4038 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4041 // do the magic for storing the item in the database and trigger the federation to other contacts
4047 * @param string $type
4049 * @param string $photo_id
4052 * @throws BadRequestException
4053 * @throws ForbiddenException
4054 * @throws ImagickException
4055 * @throws InternalServerErrorException
4056 * @throws NotFoundException
4057 * @throws UnauthorizedException
4059 function prepare_photo_data($type, $scale, $photo_id)
4061 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4063 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4065 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4066 $data_sql = ($scale === false ? "" : "data, ");
4068 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4069 // clients needs to convert this in their way for further processing
4070 $r = DBA::toArray(DBA::p(
4071 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4072 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4073 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4074 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4075 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4076 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4082 'image/jpeg' => 'jpg',
4083 'image/png' => 'png',
4084 'image/gif' => 'gif'
4087 // prepare output data for photo
4088 if (DBA::isResult($r)) {
4089 $data = ['photo' => $r[0]];
4090 $data['photo']['id'] = $data['photo']['resource-id'];
4091 if ($scale !== false) {
4092 $data['photo']['data'] = base64_encode($data['photo']['data']);
4094 unset($data['photo']['datasize']); //needed only with scale param
4096 if ($type == "xml") {
4097 $data['photo']['links'] = [];
4098 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4099 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4101 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4104 $data['photo']['link'] = [];
4105 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4107 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4108 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4112 unset($data['photo']['resource-id']);
4113 unset($data['photo']['minscale']);
4114 unset($data['photo']['maxscale']);
4116 throw new NotFoundException();
4119 // retrieve item element for getting activities (like, dislike etc.) related to photo
4120 $condition = ['uid' => BaseApi::getCurrentUserID(), 'resource-id' => $photo_id];
4121 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4122 if (!DBA::isResult($item)) {
4123 throw new NotFoundException('Photo-related item not found.');
4126 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4128 // retrieve comments on photo
4129 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4130 $item['parent'], BaseApi::getCurrentUserID(), GRAVITY_PARENT, GRAVITY_COMMENT];
4132 $statuses = Post::selectForUser(BaseApi::getCurrentUserID(), [], $condition);
4134 // prepare output of comments
4135 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4137 if ($type == "xml") {
4139 foreach ($commentData as $comment) {
4140 $comments[$k++ . ":comment"] = $comment;
4143 foreach ($commentData as $comment) {
4144 $comments[] = $comment;
4147 $data['photo']['friendica_comments'] = $comments;
4149 // include info if rights on photo and rights on item are mismatching
4150 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4151 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4152 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4153 $data['photo']['deny_gid'] != $item['deny_gid'];
4154 $data['photo']['rights_mismatch'] = $rights_mismatch;
4160 * Return an item with announcer data if it had been announced
4162 * @param array $item Item array
4163 * @return array Item array with announce data
4165 function api_get_announce($item)
4167 // Quit if the item already has got a different owner and author
4168 if ($item['owner-id'] != $item['author-id']) {
4172 // Don't change original or Diaspora posts
4173 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4177 // Quit if we do now the original author and it had been a post from a native network
4178 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4182 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4183 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4184 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4185 if (!DBA::isResult($announce)) {
4189 return array_merge($item, $announce);
4194 * @param array $item
4199 function api_in_reply_to($item)
4203 $in_reply_to['status_id'] = null;
4204 $in_reply_to['user_id'] = null;
4205 $in_reply_to['status_id_str'] = null;
4206 $in_reply_to['user_id_str'] = null;
4207 $in_reply_to['screen_name'] = null;
4209 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4210 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4211 if (DBA::isResult($parent)) {
4212 $in_reply_to['status_id'] = intval($parent['id']);
4214 $in_reply_to['status_id'] = intval($item['parent']);
4217 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4219 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4220 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4222 if (DBA::isResult($parent)) {
4223 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4224 $in_reply_to['user_id'] = intval($parent['author-id']);
4225 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4228 // There seems to be situation, where both fields are identical:
4229 // https://github.com/friendica/friendica/issues/1010
4230 // This is a bugfix for that.
4231 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4232 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']]);
4233 $in_reply_to['status_id'] = null;
4234 $in_reply_to['user_id'] = null;
4235 $in_reply_to['status_id_str'] = null;
4236 $in_reply_to['user_id_str'] = null;
4237 $in_reply_to['screen_name'] = null;
4241 return $in_reply_to;
4246 * @param string $text
4249 * @throws InternalServerErrorException
4251 function api_clean_plain_items($text)
4253 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4255 $text = BBCode::cleanPictureLinks($text);
4256 $URLSearchString = "^\[\]";
4258 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4260 if ($include_entities == "true") {
4261 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4264 // Simplify "attachment" element
4265 $text = BBCode::removeAttachment($text);
4272 * @param array $contacts
4276 function api_best_nickname(&$contacts)
4280 if (count($contacts) == 0) {
4284 foreach ($contacts as $contact) {
4285 if ($contact["network"] == "") {
4286 $contact["network"] = "dfrn";
4287 $best_contact = [$contact];
4291 if (sizeof($best_contact) == 0) {
4292 foreach ($contacts as $contact) {
4293 if ($contact["network"] == "dfrn") {
4294 $best_contact = [$contact];
4299 if (sizeof($best_contact) == 0) {
4300 foreach ($contacts as $contact) {
4301 if ($contact["network"] == "dspr") {
4302 $best_contact = [$contact];
4307 if (sizeof($best_contact) == 0) {
4308 foreach ($contacts as $contact) {
4309 if ($contact["network"] == "stat") {
4310 $best_contact = [$contact];
4315 if (sizeof($best_contact) == 0) {
4316 foreach ($contacts as $contact) {
4317 if ($contact["network"] == "pump") {
4318 $best_contact = [$contact];
4323 if (sizeof($best_contact) == 0) {
4324 foreach ($contacts as $contact) {
4325 if ($contact["network"] == "twit") {
4326 $best_contact = [$contact];
4331 if (sizeof($best_contact) == 1) {
4332 $contacts = $best_contact;
4334 $contacts = [$contacts[0]];
4339 * Return all or a specified group of the user with the containing contacts.
4341 * @param string $type Return type (atom, rss, xml, json)
4343 * @return array|string
4344 * @throws BadRequestException
4345 * @throws ForbiddenException
4346 * @throws ImagickException
4347 * @throws InternalServerErrorException
4348 * @throws UnauthorizedException
4350 function api_friendica_group_show($type)
4352 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4355 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4356 $gid = $_REQUEST['gid'] ?? 0;
4357 $uid = $user_info['uid'];
4359 // get data of the specified group id or all groups if not specified
4361 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4363 // error message if specified gid is not in database
4364 if (!DBA::isResult($groups)) {
4365 throw new BadRequestException("gid not available");
4368 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4371 // loop through all groups and retrieve all members for adding data in the user array
4373 foreach ($groups as $rr) {
4374 $members = Contact\Group::getById($rr['id']);
4377 if ($type == "xml") {
4378 $user_element = "users";
4380 foreach ($members as $member) {
4381 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4382 $users[$k++.":user"] = $user;
4385 $user_element = "user";
4386 foreach ($members as $member) {
4387 $user = DI::twitterUser()->createFromContactId($member['contact-id'], BaseApi::getCurrentUserID())->toArray();
4391 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4393 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4396 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4401 * @param string $type Return type (atom, rss, xml, json)
4403 * @return array|string
4404 * @throws BadRequestException
4405 * @throws ForbiddenException
4406 * @throws ImagickException
4407 * @throws InternalServerErrorException
4408 * @throws UnauthorizedException
4409 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4411 function api_lists_destroy($type)
4413 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4416 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4417 $gid = $_REQUEST['list_id'] ?? 0;
4418 $uid = $user_info['uid'];
4420 // error if no gid specified
4422 throw new BadRequestException('gid not specified');
4425 // get data of the specified group id
4426 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4427 // error message if specified gid is not in database
4429 throw new BadRequestException('gid not available');
4432 if (Group::remove($gid)) {
4434 'name' => $group['name'],
4435 'id' => intval($gid),
4436 'id_str' => (string) $gid,
4437 'user' => $user_info
4440 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4444 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4447 * Add a new group to the database.
4449 * @param string $name Group name
4450 * @param int $uid User ID
4451 * @param array $users List of users to add to the group
4454 * @throws BadRequestException
4456 function group_create($name, $uid, $users = [])
4458 // error if no name specified
4460 throw new BadRequestException('group name not specified');
4463 // error message if specified group name already exists
4464 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4465 throw new BadRequestException('group name already exists');
4468 // Check if the group needs to be reactivated
4469 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4470 $reactivate_group = true;
4474 $ret = Group::create($uid, $name);
4476 $gid = Group::getIdByName($uid, $name);
4478 throw new BadRequestException('other API error');
4482 $erroraddinguser = false;
4484 foreach ($users as $user) {
4485 $cid = $user['cid'];
4486 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4487 Group::addMember($gid, $cid);
4489 $erroraddinguser = true;
4490 $errorusers[] = $cid;
4494 // return success message incl. missing users in array
4495 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4497 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4501 * Create the specified group with the posted array of contacts.
4503 * @param string $type Return type (atom, rss, xml, json)
4505 * @return array|string
4506 * @throws BadRequestException
4507 * @throws ForbiddenException
4508 * @throws ImagickException
4509 * @throws InternalServerErrorException
4510 * @throws UnauthorizedException
4512 function api_friendica_group_create($type)
4514 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4517 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4518 $name = $_REQUEST['name'] ?? '';
4519 $uid = $user_info['uid'];
4520 $json = json_decode($_POST['json'], true);
4521 $users = $json['user'];
4523 $success = group_create($name, $uid, $users);
4525 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4528 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4531 * Create a new group.
4533 * @param string $type Return type (atom, rss, xml, json)
4535 * @return array|string
4536 * @throws BadRequestException
4537 * @throws ForbiddenException
4538 * @throws ImagickException
4539 * @throws InternalServerErrorException
4540 * @throws UnauthorizedException
4541 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4543 function api_lists_create($type)
4545 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4548 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4549 $name = $_REQUEST['name'] ?? '';
4550 $uid = $user_info['uid'];
4552 $success = group_create($name, $uid);
4553 if ($success['success']) {
4555 'name' => $success['name'],
4556 'id' => intval($success['gid']),
4557 'id_str' => (string) $success['gid'],
4558 'user' => $user_info
4561 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4565 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4568 * Update the specified group with the posted array of contacts.
4570 * @param string $type Return type (atom, rss, xml, json)
4572 * @return array|string
4573 * @throws BadRequestException
4574 * @throws ForbiddenException
4575 * @throws ImagickException
4576 * @throws InternalServerErrorException
4577 * @throws UnauthorizedException
4579 function api_friendica_group_update($type)
4581 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4584 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4585 $uid = $user_info['uid'];
4586 $gid = $_REQUEST['gid'] ?? 0;
4587 $name = $_REQUEST['name'] ?? '';
4588 $json = json_decode($_POST['json'], true);
4589 $users = $json['user'];
4591 // error if no name specified
4593 throw new BadRequestException('group name not specified');
4596 // error if no gid specified
4598 throw new BadRequestException('gid not specified');
4602 $members = Contact\Group::getById($gid);
4603 foreach ($members as $member) {
4604 $cid = $member['id'];
4605 foreach ($users as $user) {
4606 $found = ($user['cid'] == $cid ? true : false);
4608 if (!isset($found) || !$found) {
4609 $gid = Group::getIdByName($uid, $name);
4610 Group::removeMember($gid, $cid);
4615 $erroraddinguser = false;
4617 foreach ($users as $user) {
4618 $cid = $user['cid'];
4620 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4621 Group::addMember($gid, $cid);
4623 $erroraddinguser = true;
4624 $errorusers[] = $cid;
4628 // return success message incl. missing users in array
4629 $status = ($erroraddinguser ? "missing user" : "ok");
4630 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4631 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4634 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4637 * Update information about a group.
4639 * @param string $type Return type (atom, rss, xml, json)
4641 * @return array|string
4642 * @throws BadRequestException
4643 * @throws ForbiddenException
4644 * @throws ImagickException
4645 * @throws InternalServerErrorException
4646 * @throws UnauthorizedException
4647 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4649 function api_lists_update($type)
4651 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4654 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4655 $gid = $_REQUEST['list_id'] ?? 0;
4656 $name = $_REQUEST['name'] ?? '';
4657 $uid = $user_info['uid'];
4659 // error if no gid specified
4661 throw new BadRequestException('gid not specified');
4664 // get data of the specified group id
4665 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4666 // error message if specified gid is not in database
4668 throw new BadRequestException('gid not available');
4671 if (Group::update($gid, $name)) {
4674 'id' => intval($gid),
4675 'id_str' => (string) $gid,
4676 'user' => $user_info
4679 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4683 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4686 * Set notification as seen and returns associated item (if possible)
4688 * POST request with 'id' param as notification id
4690 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4691 * @return string|array
4692 * @throws BadRequestException
4693 * @throws ForbiddenException
4694 * @throws ImagickException
4695 * @throws InternalServerErrorException
4696 * @throws UnauthorizedException
4698 function api_friendica_notification_seen($type)
4700 BaseApi::checkAllowedScope(BaseApi::SCOPE_WRITE);
4702 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4704 if (DI::args()->getArgc() !== 4) {
4705 throw new BadRequestException('Invalid argument count');
4708 $id = intval($_REQUEST['id'] ?? 0);
4711 $Notify = DI::notify()->selectOneById($id);
4712 if ($Notify->uid !== BaseApi::getCurrentUserID()) {
4713 throw new NotFoundException();
4716 if ($Notify->uriId) {
4717 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4721 DI::notify()->save($Notify);
4723 if ($Notify->otype === Notification\ObjectType::ITEM) {
4724 $item = Post::selectFirstForUser(BaseApi::getCurrentUserID(), [], ['id' => $Notify->iid, 'uid' => BaseApi::getCurrentUserID()]);
4725 if (DBA::isResult($item)) {
4726 // we found the item, return it to the user
4727 $ret = api_format_items([$item], $user_info, false, $type);
4728 $data = ['status' => $ret];
4729 return DI::apiResponse()->formatData('status', $type, $data);
4731 // the item can't be found, but we set the notification as seen, so we count this as a success
4734 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4735 } catch (NotFoundException $e) {
4736 throw new BadRequestException('Invalid argument', $e);
4737 } catch (Exception $e) {
4738 throw new InternalServerErrorException('Internal Server exception', $e);
4742 /// @TODO move to top of file or somewhere better
4743 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4746 * search for direct_messages containing a searchstring through api
4748 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4749 * @param string $box
4750 * @return string|array (success: success=true if found and search_result contains found messages,
4751 * success=false if nothing was found, search_result='nothing found',
4752 * error: result=error with error message)
4753 * @throws BadRequestException
4754 * @throws ForbiddenException
4755 * @throws ImagickException
4756 * @throws InternalServerErrorException
4757 * @throws UnauthorizedException
4759 function api_friendica_direct_messages_search($type, $box = "")
4761 BaseApi::checkAllowedScope(BaseApi::SCOPE_READ);
4764 $user_info = DI::twitterUser()->createFromUserId(BaseApi::getCurrentUserID())->toArray();
4765 $searchstring = $_REQUEST['searchstring'] ?? '';
4766 $uid = $user_info['uid'];
4768 // error if no searchstring specified
4769 if ($searchstring == "") {
4770 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4771 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4774 // get data for the specified searchstring
4775 $r = DBA::toArray(DBA::p(
4776 "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",
4778 '%'.$searchstring.'%'
4781 $profile_url = $user_info["url"];
4783 // message if nothing was found
4784 if (!DBA::isResult($r)) {
4785 $success = ['success' => false, 'search_results' => 'problem with query'];
4786 } elseif (count($r) == 0) {
4787 $success = ['success' => false, 'search_results' => 'nothing found'];
4790 foreach ($r as $item) {
4791 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4792 $recipient = $user_info;
4793 $sender = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4794 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4795 $recipient = DI::twitterUser()->createFromContactId($item['contact-id'], BaseApi::getCurrentUserID())->toArray();
4796 $sender = $user_info;
4799 if (isset($recipient) && isset($sender)) {
4800 $ret[] = api_format_messages($item, $recipient, $sender);
4803 $success = ['success' => true, 'search_results' => $ret];
4806 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4809 /// @TODO move to top of file or somewhere better
4810 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4813 * Number of comments
4815 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4817 * @param object $data [Status, Status]
4821 function bindComments(&$data)
4823 if (count($data) == 0) {
4829 foreach ($data as $item) {
4830 $ids[] = $item['id'];
4833 $idStr = DBA::escape(implode(', ', $ids));
4834 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4835 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4836 $itemsData = DBA::toArray($items);
4838 foreach ($itemsData as $item) {
4839 $comments[$item['parent']] = $item['comments'];
4842 foreach ($data as $idx => $item) {
4844 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4849 @TODO Maybe open to implement?
4851 [pagename] => api/1.1/statuses/lookup.json
4852 [id] => 605138389168451584
4853 [include_cards] => true
4854 [cards_platform] => Android-12
4855 [include_entities] => true
4856 [include_my_retweet] => 1
4858 [include_reply_count] => true
4859 [include_descendent_reply_count] => true
4863 Not implemented by now:
4864 statuses/retweets_of_me
4869 account/update_location
4870 account/update_profile_background_image
4873 friendica/profile/update
4874 friendica/profile/create
4875 friendica/profile/delete
4877 Not implemented in status.net:
4878 statuses/retweeted_to_me
4879 statuses/retweeted_by_me
4880 direct_messages/destroy
4882 account/update_delivery_device
4883 notifications/follow