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\Api\ApiResponse;
46 use Friendica\Module\BaseApi;
47 use Friendica\Network\HTTPException;
48 use Friendica\Network\HTTPException\BadRequestException;
49 use Friendica\Network\HTTPException\ForbiddenException;
50 use Friendica\Network\HTTPException\InternalServerErrorException;
51 use Friendica\Network\HTTPException\MethodNotAllowedException;
52 use Friendica\Network\HTTPException\NotFoundException;
53 use Friendica\Network\HTTPException\TooManyRequestsException;
54 use Friendica\Network\HTTPException\UnauthorizedException;
55 use Friendica\Object\Image;
56 use Friendica\Protocol\Activity;
57 use Friendica\Security\BasicAuth;
58 use Friendica\Security\OAuth;
59 use Friendica\Util\DateTimeFormat;
60 use Friendica\Util\Images;
61 use Friendica\Util\Network;
62 use Friendica\Util\Proxy;
63 use Friendica\Util\Strings;
65 require_once __DIR__ . '/../mod/item.php';
66 require_once __DIR__ . '/../mod/wall_upload.php';
68 define('API_METHOD_ANY', '*');
69 define('API_METHOD_GET', 'GET');
70 define('API_METHOD_POST', 'POST,PUT');
71 define('API_METHOD_DELETE', 'POST,DELETE');
73 define('API_LOG_PREFIX', 'API {action} - ');
81 * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
82 * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
83 * into a page, and visitors will post something without noticing it).
87 $user = OAuth::getCurrentUserID();
92 if (!empty($_SESSION['allow_api'])) {
100 * Get source name from API client
102 * Clients can send 'source' parameter to be show in post metadata
103 * as "sent via <source>".
104 * Some clients doesn't send a source param, we support ones we know
105 * (only Twidere, atm)
108 * Client source name, default to "api" if unset/unknown
111 function api_source()
113 if (requestdata('source')) {
114 return requestdata('source');
117 // Support for known clients that doesn't send a source name
118 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
119 if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
123 Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
125 Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
132 * Format date for API
134 * @param string $str Source date, as UTC
135 * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
138 function api_date($str)
140 // Wed May 23 06:01:13 +0000 2007
141 return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
145 * Register a function to be the endpoint for defined API path.
147 * @param string $path API URL path, relative to DI::baseUrl()
148 * @param string $func Function name to call on path request
149 * @param bool $auth API need logged user
150 * @param string $method HTTP method reqiured to call this endpoint.
151 * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
152 * Default to API_METHOD_ANY
154 function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
164 // Workaround for hotot
165 $path = str_replace("api/", "api/1.1/", $path);
175 * Check HTTP method of called API
177 * API endpoints can define which HTTP method to accept when called.
178 * This function check the current HTTP method agains endpoint
181 * @param string $method Required methods, uppercase, separated by comma
184 function api_check_method($method)
186 if ($method == "*") {
189 return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
193 * Main API entry point
195 * Authenticate user, call registered API function, set HTTP headers
198 * @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
199 * @return string|array API call result
202 function api_call(App $a, App\Arguments $args = null)
204 global $API, $called_api;
211 if (strpos($args->getCommand(), ".xml") > 0) {
214 if (strpos($args->getCommand(), ".json") > 0) {
217 if (strpos($args->getCommand(), ".rss") > 0) {
220 if (strpos($args->getCommand(), ".atom") > 0) {
225 foreach ($API as $p => $info) {
226 if (strpos($args->getCommand(), $p) === 0) {
227 if (!api_check_method($info['method'])) {
228 throw new MethodNotAllowedException();
231 $called_api = explode("/", $p);
233 if (!empty($info['auth']) && api_user() === false) {
234 BasicAuth::getCurrentUserID(true);
235 Logger::info(API_LOG_PREFIX . 'nickname {nickname}', ['module' => 'api', 'action' => 'call', 'nickname' => $a->getLoggedInUserNickname()]);
238 Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
240 $stamp = microtime(true);
241 $return = call_user_func($info['func'], $type);
242 $duration = floatval(microtime(true) - $stamp);
244 Logger::info(API_LOG_PREFIX . 'duration {duration}', ['module' => 'api', 'action' => 'call', 'duration' => round($duration, 2)]);
246 DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
248 if (false === $return) {
250 * api function returned false withour throw an
251 * exception. This should not happend, throw a 500
253 throw new InternalServerErrorException();
258 header("Content-Type: text/xml");
261 header("Content-Type: application/json");
262 if (!empty($return)) {
263 $json = json_encode(end($return));
264 if (!empty($_GET['callback'])) {
265 $json = $_GET['callback'] . "(" . $json . ")";
271 header("Content-Type: application/rss+xml");
272 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
275 header("Content-Type: application/atom+xml");
276 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
283 Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
284 throw new NotFoundException();
285 } catch (HTTPException $e) {
286 DI::apiResponse()->error($e->getCode(), $e->getDescription(), $e->getMessage(), $type);
291 * Set values for RSS template
294 * @param array $arr Array to be passed to template
295 * @param array $user_info User info
297 * @throws BadRequestException
298 * @throws ImagickException
299 * @throws InternalServerErrorException
300 * @throws UnauthorizedException
301 * @todo find proper type-hints
303 function api_rss_extra(App $a, $arr, $user_info)
305 if (is_null($user_info)) {
306 $user_info = api_get_user();
309 $arr['$user'] = $user_info;
311 'alternate' => $user_info['url'],
312 'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
313 'base' => DI::baseUrl(),
314 'updated' => api_date(null),
315 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
316 'language' => $user_info['lang'],
317 'logo' => DI::baseUrl() . "/images/friendica-32.png",
325 * Unique contact to contact url.
327 * @param int $id Contact id
328 * @return bool|string
329 * Contact url or False if contact id is unknown
332 function api_unique_id_to_nurl($id)
334 $r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
336 if (DBA::isResult($r)) {
344 * Get user info array.
347 * @param int|string $contact_id Contact ID or URL
349 * @throws BadRequestException
350 * @throws ImagickException
351 * @throws InternalServerErrorException
352 * @throws UnauthorizedException
354 function api_get_user($contact_id = null)
362 Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
364 // Searching for contact URL
365 if (!is_null($contact_id) && (intval($contact_id) == 0)) {
366 $user = Strings::normaliseLink($contact_id);
368 $extra_query = "AND `contact`.`nurl` = ? ";
369 if (api_user() !== false) {
370 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
374 // Searching for contact id with uid = 0
375 if (!is_null($contact_id) && (intval($contact_id) != 0)) {
376 $user = api_unique_id_to_nurl(intval($contact_id));
379 throw new BadRequestException("User ID ".$contact_id." not found.");
383 $extra_query = "AND `contact`.`nurl` = ? ";
384 if (api_user() !== false) {
385 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
389 if (is_null($user) && !empty($_GET['user_id'])) {
390 $user = api_unique_id_to_nurl($_GET['user_id']);
393 throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
397 $extra_query = "AND `contact`.`nurl` = ? ";
398 if (api_user() !== false) {
399 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
402 if (is_null($user) && !empty($_GET['screen_name'])) {
403 $user = $_GET['screen_name'];
404 $extra_query = "AND `contact`.`nick` = ? ";
405 if (api_user() !== false) {
406 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
410 if (is_null($user) && !empty($_GET['profileurl'])) {
411 $user = Strings::normaliseLink($_GET['profileurl']);
412 $extra_query = "AND `contact`.`nurl` = ? ";
413 if (api_user() !== false) {
414 $extra_query .= "AND `contact`.`uid`=".intval(api_user());
418 // $called_api is the API path exploded on / and is expected to have at least 2 elements
419 if (is_null($user) && (DI::args()->getArgc() > (count($called_api) - 1)) && (count($called_api) > 0)) {
420 $argid = count($called_api);
421 if (!empty(DI::args()->getArgv()[$argid])) {
422 $data = explode(".", DI::args()->getArgv()[$argid]);
423 if (count($data) > 1) {
424 [$user, $null] = $data;
427 if (is_numeric($user)) {
428 $user = api_unique_id_to_nurl(intval($user));
432 $extra_query = "AND `contact`.`nurl` = ? ";
433 if (api_user() !== false) {
434 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
438 $extra_query = "AND `contact`.`nick` = ? ";
439 if (api_user() !== false) {
440 $extra_query .= "AND `contact`.`uid`=" . intval(api_user());
445 Logger::info(API_LOG_PREFIX . 'getting user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user]);
448 if (api_user() === false) {
449 BasicAuth::getCurrentUserID(true);
453 $extra_query = "AND `contact`.`uid` = ? AND `contact`.`self` ";
457 Logger::info(API_LOG_PREFIX . 'found user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $user, 'extra_query' => $extra_query]);
460 $uinfo = DBA::toArray(DBA::p(
461 "SELECT *, `contact`.`id` AS `cid` FROM `contact`
467 if (DBA::isResult($uinfo)) {
468 // Selecting the id by priority, friendica first
469 api_best_nickname($uinfo);
470 return DI::twitterUser()->createFromContactId($uinfo[0]['cid'], $uinfo[0]['uid'])->toArray();
474 throw new BadRequestException("User not found.");
477 $cid = Contact::getIdForURL($url, 0, false);
480 return DI::twitterUser()->createFromContactId($cid, 0)->toArray();
482 throw new BadRequestException("User ".$url." not found.");
487 * return api-formatted array for item's author and owner
490 * @param array $item item from db
491 * @return array(array:author, array:owner)
492 * @throws BadRequestException
493 * @throws ImagickException
494 * @throws InternalServerErrorException
495 * @throws UnauthorizedException
497 function api_item_get_user(App $a, $item)
499 $status_user = api_get_user($item['author-id'] ?? null);
501 $author_user = $status_user;
503 $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE);
505 if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) {
506 $owner_user = api_get_user($item['owner-id'] ?? null);
508 $owner_user = $author_user;
511 return ([$status_user, $author_user, $owner_user]);
519 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
520 * returns a 401 status code and an error message if not.
522 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials
524 * @param string $type Return type (atom, rss, xml, json)
525 * @return array|string
526 * @throws BadRequestException
527 * @throws ForbiddenException
528 * @throws ImagickException
529 * @throws InternalServerErrorException
530 * @throws UnauthorizedException
532 function api_account_verify_credentials($type)
536 if (api_user() === false) {
537 throw new ForbiddenException();
540 unset($_REQUEST["user_id"]);
541 unset($_GET["user_id"]);
543 unset($_REQUEST["screen_name"]);
544 unset($_GET["screen_name"]);
546 $skip_status = $_REQUEST['skip_status'] ?? false;
548 $user_info = api_get_user();
550 // "verified" isn't used here in the standard
551 unset($user_info["verified"]);
553 // - Adding last status
555 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
557 $user_info['status'] = api_format_item($item, $type);
561 // "uid" and "self" are only needed for some internal stuff, so remove it from here
562 unset($user_info["uid"]);
563 unset($user_info["self"]);
565 return DI::apiResponse()->formatData("user", $type, ['user' => $user_info]);
568 /// @TODO move to top of file or somewhere better
569 api_register_func('api/account/verify_credentials', 'api_account_verify_credentials', true);
572 * Get data from $_POST or $_GET
577 function requestdata($k)
579 if (!empty($_POST[$k])) {
582 if (!empty($_GET[$k])) {
589 * Deprecated function to upload media.
591 * @param string $type Return type (atom, rss, xml, json)
593 * @return array|string
594 * @throws BadRequestException
595 * @throws ForbiddenException
596 * @throws ImagickException
597 * @throws InternalServerErrorException
598 * @throws UnauthorizedException
600 function api_statuses_mediap($type)
604 if (api_user() === false) {
605 logger::notice('api_statuses_update: no user');
606 throw new ForbiddenException();
608 $user_info = api_get_user();
610 $_REQUEST['profile_uid'] = api_user();
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 if (api_user() === false) {
659 logger::notice('api_statuses_update: no user');
660 throw new ForbiddenException();
665 // convert $_POST array items to the form we use for web posts.
666 if (requestdata('htmlstatus')) {
667 $txt = requestdata('htmlstatus') ?? '';
668 if ((strpos($txt, '<') !== false) || (strpos($txt, '>') !== false)) {
669 $txt = HTML::toBBCodeVideo($txt);
671 $config = HTMLPurifier_Config::createDefault();
672 $config->set('Cache.DefinitionImpl', null);
674 $purifier = new HTMLPurifier($config);
675 $txt = $purifier->purify($txt);
677 $_REQUEST['body'] = HTML::toBBCode($txt);
680 $_REQUEST['body'] = requestdata('status');
683 $_REQUEST['title'] = requestdata('title');
685 $parent = requestdata('in_reply_to_status_id');
687 // Twidere sends "-1" if it is no reply ...
692 if (ctype_digit($parent)) {
693 $_REQUEST['parent'] = $parent;
695 $_REQUEST['parent_uri'] = $parent;
698 if (requestdata('lat') && requestdata('long')) {
699 $_REQUEST['coord'] = sprintf("%s %s", requestdata('lat'), requestdata('long'));
701 $_REQUEST['profile_uid'] = api_user();
704 // Check for throttling (maximum posts per day, week and month)
705 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
706 if ($throttle_day > 0) {
707 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
709 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
710 $posts_day = Post::count($condition);
712 if ($posts_day > $throttle_day) {
713 logger::info('Daily posting limit reached for user '.api_user());
714 // die(api_error($type, DI::l10n()->t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
715 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));
719 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
720 if ($throttle_week > 0) {
721 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
723 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
724 $posts_week = Post::count($condition);
726 if ($posts_week > $throttle_week) {
727 logger::info('Weekly posting limit reached for user '.api_user());
728 // die(api_error($type, DI::l10n()->t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
729 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));
733 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
734 if ($throttle_month > 0) {
735 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
737 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, api_user(), $datefrom];
738 $posts_month = Post::count($condition);
740 if ($posts_month > $throttle_month) {
741 logger::info('Monthly posting limit reached for user '.api_user());
742 // die(api_error($type, DI::l10n()->t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
743 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));
748 if (requestdata('media_ids')) {
749 $ids = explode(',', requestdata('media_ids') ?? '');
750 } elseif (!empty($_FILES['media'])) {
751 // upload the image if we have one
752 $picture = wall_upload_post($a, false);
753 if (is_array($picture)) {
754 $ids[] = $picture['id'];
762 foreach ($ids as $id) {
763 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `nickname`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
764 INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN
765 (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
766 ORDER BY `photo`.`width` DESC LIMIT 2", $id, api_user()));
768 if (!empty($media)) {
769 $ressources[] = $media[0]['resource-id'];
770 $phototypes = Images::supportedTypes();
771 $ext = $phototypes[$media[0]['type']];
773 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
774 'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
775 'size' => $media[0]['datasize'],
776 'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
777 'description' => $media[0]['desc'] ?? '',
778 'width' => $media[0]['width'],
779 'height' => $media[0]['height']];
781 if (count($media) > 1) {
782 $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
783 $attachment['preview-width'] = $media[1]['width'];
784 $attachment['preview-height'] = $media[1]['height'];
786 $attachments[] = $attachment;
790 // We have to avoid that the post is rejected because of an empty body
791 if (empty($_REQUEST['body'])) {
792 $_REQUEST['body'] = '[hr]';
796 if (!empty($attachments)) {
797 $_REQUEST['attachments'] = $attachments;
800 // set this so that the item_post() function is quiet and doesn't redirect or emit json
802 $_REQUEST['api_source'] = true;
804 if (empty($_REQUEST['source'])) {
805 $_REQUEST["source"] = api_source();
808 // call out normal post function
809 $item_id = item_post($a);
811 if (!empty($ressources) && !empty($item_id)) {
812 $item = Post::selectFirst(['uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['id' => $item_id]);
813 foreach ($ressources as $ressource) {
814 Photo::setPermissionForRessource($ressource, api_user(), $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
818 // output the post that we just posted.
819 return api_status_show($type, $item_id);
822 /// @TODO move to top of file or somewhere better
823 api_register_func('api/statuses/update', 'api_statuses_update', true, API_METHOD_POST);
824 api_register_func('api/statuses/update_with_media', 'api_statuses_update', true, API_METHOD_POST);
827 * Uploads an image to Friendica.
830 * @throws BadRequestException
831 * @throws ForbiddenException
832 * @throws ImagickException
833 * @throws InternalServerErrorException
834 * @throws UnauthorizedException
835 * @see https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload
837 function api_media_upload()
841 if (api_user() === false) {
842 logger::notice('no user');
843 throw new ForbiddenException();
848 if (empty($_FILES['media'])) {
850 throw new BadRequestException("No media.");
853 $media = wall_upload_post($a, false);
856 throw new InternalServerErrorException();
860 $returndata["media_id"] = $media["id"];
861 $returndata["media_id_string"] = (string)$media["id"];
862 $returndata["size"] = $media["size"];
863 $returndata["image"] = ["w" => $media["width"],
864 "h" => $media["height"],
865 "image_type" => $media["type"],
866 "friendica_preview_url" => $media["preview"]];
868 Logger::info('Media uploaded', ['return' => $returndata]);
870 return ["media" => $returndata];
873 /// @TODO move to top of file or somewhere better
874 api_register_func('api/media/upload', 'api_media_upload', true, API_METHOD_POST);
877 * Updates media meta data (picture descriptions)
879 * @param string $type Return type (atom, rss, xml, json)
881 * @return array|string
882 * @throws BadRequestException
883 * @throws ForbiddenException
884 * @throws ImagickException
885 * @throws InternalServerErrorException
886 * @throws TooManyRequestsException
887 * @throws UnauthorizedException
888 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update
890 * @todo Compare the corresponding Twitter function for correct return values
892 function api_media_metadata_create($type)
896 if (api_user() === false) {
897 Logger::info('no user');
898 throw new ForbiddenException();
903 $postdata = Network::postdata();
905 if (empty($postdata)) {
906 throw new BadRequestException("No post data");
909 $data = json_decode($postdata, true);
911 throw new BadRequestException("Invalid post data");
914 if (empty($data['media_id']) || empty($data['alt_text'])) {
915 throw new BadRequestException("Missing post data values");
918 if (empty($data['alt_text']['text'])) {
919 throw new BadRequestException("No alt text.");
922 Logger::info('Updating metadata', ['media_id' => $data['media_id']]);
924 $condition = ['id' => $data['media_id'], 'uid' => api_user()];
925 $photo = DBA::selectFirst('photo', ['resource-id'], $condition);
926 if (!DBA::isResult($photo)) {
927 throw new BadRequestException("Metadata not found.");
930 DBA::update('photo', ['desc' => $data['alt_text']['text']], ['resource-id' => $photo['resource-id']]);
933 api_register_func('api/media/metadata/create', 'api_media_metadata_create', true, API_METHOD_POST);
936 * @param string $type Return format (atom, rss, xml, json)
937 * @param int $item_id
938 * @return array|string
941 function api_status_show($type, $item_id)
943 Logger::info(API_LOG_PREFIX . 'Start', ['action' => 'status_show', 'type' => $type, 'item_id' => $item_id]);
947 $item = api_get_item(['id' => $item_id]);
949 $status_info = api_format_item($item, $type);
952 Logger::info(API_LOG_PREFIX . 'End', ['action' => 'get_status', 'status_info' => $status_info]);
954 return DI::apiResponse()->formatData('statuses', $type, ['status' => $status_info]);
958 * Retrieves the last public status of the provided user info
960 * @param int $ownerId Public contact Id
961 * @param int $uid User Id
965 function api_get_last_status($ownerId, $uid)
968 'author-id'=> $ownerId,
970 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
971 'private' => [Item::PUBLIC, Item::UNLISTED]
974 $item = api_get_item($condition);
980 * Retrieves a single item record based on the provided condition and converts it for API use.
982 * @param array $condition Item table condition array
986 function api_get_item(array $condition)
988 $item = Post::selectFirst(Item::DISPLAY_FIELDLIST, $condition, ['order' => ['id' => true]]);
994 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
995 * The author's most recent status will be returned inline.
997 * @param string $type Return type (atom, rss, xml, json)
998 * @return array|string
999 * @throws BadRequestException
1000 * @throws ImagickException
1001 * @throws InternalServerErrorException
1002 * @throws UnauthorizedException
1003 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-show
1005 function api_users_show($type)
1007 $a = Friendica\DI::app();
1009 $user_info = api_get_user();
1011 $item = api_get_last_status($user_info['pid'], $user_info['uid']);
1012 if (!empty($item)) {
1013 $user_info['status'] = api_format_item($item, $type);
1016 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1017 unset($user_info['uid']);
1018 unset($user_info['self']);
1020 return DI::apiResponse()->formatData('user', $type, ['user' => $user_info]);
1023 /// @TODO move to top of file or somewhere better
1024 api_register_func('api/users/show', 'api_users_show');
1025 api_register_func('api/externalprofile/show', 'api_users_show');
1028 * Search a public user account.
1030 * @param string $type Return type (atom, rss, xml, json)
1032 * @return array|string
1033 * @throws BadRequestException
1034 * @throws ImagickException
1035 * @throws InternalServerErrorException
1036 * @throws UnauthorizedException
1037 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-search
1039 function api_users_search($type)
1045 if (!empty($_GET['q'])) {
1046 $contacts = Contact::selectToArray(
1049 '`uid` = 0 AND (`name` = ? OR `nick` = ? OR `url` = ? OR `addr` = ?)',
1057 if (DBA::isResult($contacts)) {
1059 foreach ($contacts as $contact) {
1060 $user_info = api_get_user($contact['id']);
1062 if ($type == 'xml') {
1063 $userlist[$k++ . ':user'] = $user_info;
1065 $userlist[] = $user_info;
1068 $userlist = ['users' => $userlist];
1070 throw new NotFoundException('User ' . $_GET['q'] . ' not found.');
1073 throw new BadRequestException('No search term specified.');
1076 return DI::apiResponse()->formatData('users', $type, $userlist);
1079 /// @TODO move to top of file or somewhere better
1080 api_register_func('api/users/search', 'api_users_search');
1083 * Return user objects
1085 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-users-lookup
1087 * @param string $type Return format: json or xml
1089 * @return array|string
1090 * @throws BadRequestException
1091 * @throws ImagickException
1092 * @throws InternalServerErrorException
1093 * @throws NotFoundException if the results are empty.
1094 * @throws UnauthorizedException
1096 function api_users_lookup($type)
1100 if (!empty($_REQUEST['user_id'])) {
1101 foreach (explode(',', $_REQUEST['user_id']) as $id) {
1103 $users[] = api_get_user($id);
1108 if (empty($users)) {
1109 throw new NotFoundException;
1112 return DI::apiResponse()->formatData("users", $type, ['users' => $users]);
1115 /// @TODO move to top of file or somewhere better
1116 api_register_func('api/users/lookup', 'api_users_lookup', true);
1119 * Returns statuses that match a specified query.
1121 * @see https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets
1123 * @param string $type Return format: json, xml, atom, rss
1125 * @return array|string
1126 * @throws BadRequestException if the "q" parameter is missing.
1127 * @throws ForbiddenException
1128 * @throws ImagickException
1129 * @throws InternalServerErrorException
1130 * @throws UnauthorizedException
1132 function api_search($type)
1135 $user_info = api_get_user();
1137 if (api_user() === false || $user_info === false) {
1138 throw new ForbiddenException();
1141 if (empty($_REQUEST['q'])) {
1142 throw new BadRequestException('q parameter is required.');
1145 $searchTerm = trim(rawurldecode($_REQUEST['q']));
1148 $data['status'] = [];
1150 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1151 if (!empty($_REQUEST['rpp'])) {
1152 $count = $_REQUEST['rpp'];
1153 } elseif (!empty($_REQUEST['count'])) {
1154 $count = $_REQUEST['count'];
1157 $since_id = $_REQUEST['since_id'] ?? 0;
1158 $max_id = $_REQUEST['max_id'] ?? 0;
1159 $page = $_REQUEST['page'] ?? 1;
1161 $start = max(0, ($page - 1) * $count);
1163 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1164 if (preg_match('/^#(\w+)$/', $searchTerm, $matches) === 1 && isset($matches[1])) {
1165 $searchTerm = $matches[1];
1166 $condition = ["`iid` > ? AND `name` = ? AND (NOT `private` OR (`private` AND `uid` = ?))", $since_id, $searchTerm, local_user()];
1167 $tags = DBA::select('tag-search-view', ['uri-id'], $condition);
1169 while ($tag = DBA::fetch($tags)) {
1170 $uriids[] = $tag['uri-id'];
1174 if (empty($uriids)) {
1175 return DI::apiResponse()->formatData('statuses', $type, $data);
1178 $condition = ['uri-id' => $uriids];
1179 if ($exclude_replies) {
1180 $condition['gravity'] = GRAVITY_PARENT;
1183 $params['group_by'] = ['uri-id'];
1185 $condition = ["`id` > ?
1186 " . ($exclude_replies ? " AND `gravity` = " . GRAVITY_PARENT : ' ') . "
1187 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))
1188 AND `body` LIKE CONCAT('%',?,'%')",
1189 $since_id, api_user(), $_REQUEST['q']];
1191 $condition[0] .= ' AND `id` <= ?';
1192 $condition[] = $max_id;
1198 if (parse_url($searchTerm, PHP_URL_SCHEME) != '') {
1199 $id = Item::fetchByLink($searchTerm, api_user());
1202 $id = Item::fetchByLink($searchTerm);
1206 $statuses = Post::select([], ['id' => $id]);
1210 $statuses = $statuses ?: Post::selectForUser(api_user(), [], $condition, $params);
1212 $data['status'] = api_format_items(Post::toArray($statuses), $user_info);
1214 bindComments($data['status']);
1216 return DI::apiResponse()->formatData('statuses', $type, $data);
1219 /// @TODO move to top of file or somewhere better
1220 api_register_func('api/search/tweets', 'api_search', true);
1221 api_register_func('api/search', 'api_search', true);
1224 * Returns the most recent statuses posted by the user and the users they follow.
1226 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
1228 * @param string $type Return type (atom, rss, xml, json)
1230 * @return array|string
1231 * @throws BadRequestException
1232 * @throws ForbiddenException
1233 * @throws ImagickException
1234 * @throws InternalServerErrorException
1235 * @throws UnauthorizedException
1236 * @todo Optional parameters
1237 * @todo Add reply info
1239 function api_statuses_home_timeline($type)
1242 $user_info = api_get_user();
1244 if (api_user() === false || $user_info === false) {
1245 throw new ForbiddenException();
1248 unset($_REQUEST["user_id"]);
1249 unset($_GET["user_id"]);
1251 unset($_REQUEST["screen_name"]);
1252 unset($_GET["screen_name"]);
1254 // get last network messages
1257 $count = $_REQUEST['count'] ?? 20;
1258 $page = $_REQUEST['page']?? 0;
1259 $since_id = $_REQUEST['since_id'] ?? 0;
1260 $max_id = $_REQUEST['max_id'] ?? 0;
1261 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1262 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1264 $start = max(0, ($page - 1) * $count);
1266 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ?",
1267 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1270 $condition[0] .= " AND `id` <= ?";
1271 $condition[] = $max_id;
1273 if ($exclude_replies) {
1274 $condition[0] .= ' AND `gravity` = ?';
1275 $condition[] = GRAVITY_PARENT;
1277 if ($conversation_id > 0) {
1278 $condition[0] .= " AND `parent` = ?";
1279 $condition[] = $conversation_id;
1282 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1283 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1285 $items = Post::toArray($statuses);
1287 $ret = api_format_items($items, $user_info, false, $type);
1289 // Set all posts from the query above to seen
1291 foreach ($items as $item) {
1292 $idarray[] = intval($item["id"]);
1295 if (!empty($idarray)) {
1296 $unseen = Post::exists(['unseen' => true, 'id' => $idarray]);
1298 Item::update(['unseen' => false], ['unseen' => true, 'id' => $idarray]);
1304 $data = ['status' => $ret];
1309 $data = api_rss_extra($a, $data, $user_info);
1313 return DI::apiResponse()->formatData("statuses", $type, $data);
1317 /// @TODO move to top of file or somewhere better
1318 api_register_func('api/statuses/home_timeline', 'api_statuses_home_timeline', true);
1319 api_register_func('api/statuses/friends_timeline', 'api_statuses_home_timeline', true);
1322 * Returns the most recent statuses from public users.
1324 * @param string $type Return type (atom, rss, xml, json)
1326 * @return array|string
1327 * @throws BadRequestException
1328 * @throws ForbiddenException
1329 * @throws ImagickException
1330 * @throws InternalServerErrorException
1331 * @throws UnauthorizedException
1333 function api_statuses_public_timeline($type)
1336 $user_info = api_get_user();
1338 if (api_user() === false || $user_info === false) {
1339 throw new ForbiddenException();
1342 // get last network messages
1345 $count = $_REQUEST['count'] ?? 20;
1346 $page = $_REQUEST['page'] ?? 1;
1347 $since_id = $_REQUEST['since_id'] ?? 0;
1348 $max_id = $_REQUEST['max_id'] ?? 0;
1349 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
1350 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1352 $start = max(0, ($page - 1) * $count);
1354 if ($exclude_replies && !$conversation_id) {
1355 $condition = ["`gravity` = ? AND `id` > ? AND `private` = ? AND `wall` AND NOT `author-hidden`",
1356 GRAVITY_PARENT, $since_id, Item::PUBLIC];
1359 $condition[0] .= " AND `id` <= ?";
1360 $condition[] = $max_id;
1363 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1364 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1366 $r = Post::toArray($statuses);
1368 $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `origin` AND NOT `author-hidden`",
1369 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1372 $condition[0] .= " AND `id` <= ?";
1373 $condition[] = $max_id;
1375 if ($conversation_id > 0) {
1376 $condition[0] .= " AND `parent` = ?";
1377 $condition[] = $conversation_id;
1380 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1381 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1383 $r = Post::toArray($statuses);
1386 $ret = api_format_items($r, $user_info, false, $type);
1390 $data = ['status' => $ret];
1395 $data = api_rss_extra($a, $data, $user_info);
1399 return DI::apiResponse()->formatData("statuses", $type, $data);
1402 /// @TODO move to top of file or somewhere better
1403 api_register_func('api/statuses/public_timeline', 'api_statuses_public_timeline', true);
1406 * Returns the most recent statuses posted by users this node knows about.
1408 * @param string $type Return format: json, xml, atom, rss
1409 * @return array|string
1410 * @throws BadRequestException
1411 * @throws ForbiddenException
1412 * @throws ImagickException
1413 * @throws InternalServerErrorException
1414 * @throws UnauthorizedException
1416 function api_statuses_networkpublic_timeline($type)
1419 $user_info = api_get_user();
1421 if (api_user() === false || $user_info === false) {
1422 throw new ForbiddenException();
1425 $since_id = $_REQUEST['since_id'] ?? 0;
1426 $max_id = $_REQUEST['max_id'] ?? 0;
1429 $count = $_REQUEST['count'] ?? 20;
1430 $page = $_REQUEST['page'] ?? 1;
1432 $start = max(0, ($page - 1) * $count);
1434 $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `id` > ? AND `private` = ?",
1435 GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC];
1438 $condition[0] .= " AND `id` <= ?";
1439 $condition[] = $max_id;
1442 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1443 $statuses = Post::toArray(Post::selectForUser(api_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1445 $ret = api_format_items($statuses, $user_info, false, $type);
1449 $data = ['status' => $ret];
1454 $data = api_rss_extra($a, $data, $user_info);
1458 return DI::apiResponse()->formatData("statuses", $type, $data);
1461 /// @TODO move to top of file or somewhere better
1462 api_register_func('api/statuses/networkpublic_timeline', 'api_statuses_networkpublic_timeline', true);
1465 * Returns a single status.
1467 * @param string $type Return type (atom, rss, xml, json)
1469 * @return array|string
1470 * @throws BadRequestException
1471 * @throws ForbiddenException
1472 * @throws ImagickException
1473 * @throws InternalServerErrorException
1474 * @throws UnauthorizedException
1475 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id
1477 function api_statuses_show($type)
1480 $user_info = api_get_user();
1482 if (api_user() === false || $user_info === false) {
1483 throw new ForbiddenException();
1487 $id = intval(DI::args()->getArgv()[3] ?? 0);
1490 $id = intval($_REQUEST['id'] ?? 0);
1495 $id = intval(DI::args()->getArgv()[4] ?? 0);
1498 logger::notice('API: api_statuses_show: ' . $id);
1500 $conversation = !empty($_REQUEST['conversation']);
1502 // try to fetch the item for the local user - or the public item, if there is no local one
1503 $uri_item = Post::selectFirst(['uri-id'], ['id' => $id]);
1504 if (!DBA::isResult($uri_item)) {
1505 throw new BadRequestException(sprintf("There is no status with the id %d", $id));
1508 $item = Post::selectFirst(['id'], ['uri-id' => $uri_item['uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1509 if (!DBA::isResult($item)) {
1510 throw new BadRequestException(sprintf("There is no status with the uri-id %d for the given user.", $uri_item['uri-id']));
1515 if ($conversation) {
1516 $condition = ['parent' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1517 $params = ['order' => ['id' => true]];
1519 $condition = ['id' => $id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]];
1523 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1525 /// @TODO How about copying this to above methods which don't check $r ?
1526 if (!DBA::isResult($statuses)) {
1527 throw new BadRequestException(sprintf("There is no status or conversation with the id %d.", $id));
1530 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1532 if ($conversation) {
1533 $data = ['status' => $ret];
1534 return DI::apiResponse()->formatData("statuses", $type, $data);
1536 $data = ['status' => $ret[0]];
1537 return DI::apiResponse()->formatData("status", $type, $data);
1541 /// @TODO move to top of file or somewhere better
1542 api_register_func('api/statuses/show', 'api_statuses_show', true);
1546 * @param string $type Return type (atom, rss, xml, json)
1548 * @return array|string
1549 * @throws BadRequestException
1550 * @throws ForbiddenException
1551 * @throws ImagickException
1552 * @throws InternalServerErrorException
1553 * @throws UnauthorizedException
1554 * @todo nothing to say?
1556 function api_conversation_show($type)
1559 $user_info = api_get_user();
1561 if (api_user() === false || $user_info === false) {
1562 throw new ForbiddenException();
1566 $id = intval(DI::args()->getArgv()[3] ?? 0);
1567 $since_id = intval($_REQUEST['since_id'] ?? 0);
1568 $max_id = intval($_REQUEST['max_id'] ?? 0);
1569 $count = intval($_REQUEST['count'] ?? 20);
1570 $page = intval($_REQUEST['page'] ?? 1);
1572 $start = max(0, ($page - 1) * $count);
1575 $id = intval($_REQUEST['id'] ?? 0);
1580 $id = intval(DI::args()->getArgv()[4] ?? 0);
1583 Logger::info(API_LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
1585 // try to fetch the item for the local user - or the public item, if there is no local one
1586 $item = Post::selectFirst(['parent-uri-id'], ['id' => $id]);
1587 if (!DBA::isResult($item)) {
1588 throw new BadRequestException("There is no status with the id $id.");
1591 $parent = Post::selectFirst(['id'], ['uri-id' => $item['parent-uri-id'], 'uid' => [0, api_user()]], ['order' => ['uid' => true]]);
1592 if (!DBA::isResult($parent)) {
1593 throw new BadRequestException("There is no status with this id.");
1596 $id = $parent['id'];
1598 $condition = ["`parent` = ? AND `uid` IN (0, ?) AND `gravity` IN (?, ?) AND `id` > ?",
1599 $id, api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
1602 $condition[0] .= " AND `id` <= ?";
1603 $condition[] = $max_id;
1606 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1607 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1609 if (!DBA::isResult($statuses)) {
1610 throw new BadRequestException("There is no status with id $id.");
1613 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1615 $data = ['status' => $ret];
1616 return DI::apiResponse()->formatData("statuses", $type, $data);
1619 /// @TODO move to top of file or somewhere better
1620 api_register_func('api/conversation/show', 'api_conversation_show', true);
1621 api_register_func('api/statusnet/conversation', 'api_conversation_show', true);
1626 * @param string $type Return type (atom, rss, xml, json)
1628 * @return array|string
1629 * @throws BadRequestException
1630 * @throws ForbiddenException
1631 * @throws ImagickException
1632 * @throws InternalServerErrorException
1633 * @throws UnauthorizedException
1634 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-retweet-id
1636 function api_statuses_repeat($type)
1642 if (api_user() === false) {
1643 throw new ForbiddenException();
1649 $id = intval(DI::args()->getArgv()[3] ?? 0);
1652 $id = intval($_REQUEST['id'] ?? 0);
1657 $id = intval(DI::args()->getArgv()[4] ?? 0);
1660 logger::notice('API: api_statuses_repeat: ' . $id);
1662 $fields = ['uri-id', 'network', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
1663 $item = Post::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]);
1665 if (DBA::isResult($item) && !empty($item['body'])) {
1666 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::TWITTER])) {
1667 if (!Item::performActivity($id, 'announce', local_user())) {
1668 throw new InternalServerErrorException();
1673 if (strpos($item['body'], "[/share]") !== false) {
1674 $pos = strpos($item['body'], "[share");
1675 $post = substr($item['body'], $pos);
1677 $post = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid']);
1679 if (!empty($item['title'])) {
1680 $post .= '[h3]' . $item['title'] . "[/h3]\n";
1683 $post .= $item['body'];
1684 $post .= "[/share]";
1686 $_REQUEST['body'] = $post;
1687 $_REQUEST['profile_uid'] = api_user();
1688 $_REQUEST['api_source'] = true;
1690 if (empty($_REQUEST['source'])) {
1691 $_REQUEST["source"] = api_source();
1694 $item_id = item_post($a);
1697 throw new ForbiddenException();
1700 // output the post that we just posted.
1702 return api_status_show($type, $item_id);
1705 /// @TODO move to top of file or somewhere better
1706 api_register_func('api/statuses/retweet', 'api_statuses_repeat', true, API_METHOD_POST);
1709 * Destroys a specific status.
1711 * @param string $type Return type (atom, rss, xml, json)
1713 * @return array|string
1714 * @throws BadRequestException
1715 * @throws ForbiddenException
1716 * @throws ImagickException
1717 * @throws InternalServerErrorException
1718 * @throws UnauthorizedException
1719 * @see https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id
1721 function api_statuses_destroy($type)
1725 if (api_user() === false) {
1726 throw new ForbiddenException();
1732 $id = intval(DI::args()->getArgv()[3] ?? 0);
1735 $id = intval($_REQUEST['id'] ?? 0);
1740 $id = intval(DI::args()->getArgv()[4] ?? 0);
1743 logger::notice('API: api_statuses_destroy: ' . $id);
1745 $ret = api_statuses_show($type);
1747 Item::deleteForUser(['id' => $id], api_user());
1752 /// @TODO move to top of file or somewhere better
1753 api_register_func('api/statuses/destroy', 'api_statuses_destroy', true, API_METHOD_DELETE);
1756 * Returns the most recent mentions.
1758 * @param string $type Return type (atom, rss, xml, json)
1760 * @return array|string
1761 * @throws BadRequestException
1762 * @throws ForbiddenException
1763 * @throws ImagickException
1764 * @throws InternalServerErrorException
1765 * @throws UnauthorizedException
1766 * @see http://developer.twitter.com/doc/get/statuses/mentions
1768 function api_statuses_mentions($type)
1771 $user_info = api_get_user();
1773 if (api_user() === false || $user_info === false) {
1774 throw new ForbiddenException();
1777 unset($_REQUEST["user_id"]);
1778 unset($_GET["user_id"]);
1780 unset($_REQUEST["screen_name"]);
1781 unset($_GET["screen_name"]);
1783 // get last network messages
1786 $since_id = intval($_REQUEST['since_id'] ?? 0);
1787 $max_id = intval($_REQUEST['max_id'] ?? 0);
1788 $count = intval($_REQUEST['count'] ?? 20);
1789 $page = intval($_REQUEST['page'] ?? 1);
1791 $start = max(0, ($page - 1) * $count);
1793 $query = "`gravity` IN (?, ?) AND `uri-id` IN
1794 (SELECT `uri-id` FROM `post-user-notification` WHERE `uid` = ? AND `notification-type` & ? != 0 ORDER BY `uri-id`)
1795 AND (`uid` = 0 OR (`uid` = ? AND NOT `global`)) AND `id` > ?";
1798 GRAVITY_PARENT, GRAVITY_COMMENT,
1800 Post\UserNotification::TYPE_EXPLICIT_TAGGED | Post\UserNotification::TYPE_IMPLICIT_TAGGED |
1801 Post\UserNotification::TYPE_THREAD_COMMENT | Post\UserNotification::TYPE_DIRECT_COMMENT |
1802 Post\UserNotification::TYPE_DIRECT_THREAD_COMMENT,
1803 api_user(), $since_id,
1807 $query .= " AND `id` <= ?";
1808 $condition[] = $max_id;
1811 array_unshift($condition, $query);
1813 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1814 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1816 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
1818 $data = ['status' => $ret];
1823 $data = api_rss_extra($a, $data, $user_info);
1827 return DI::apiResponse()->formatData("statuses", $type, $data);
1830 /// @TODO move to top of file or somewhere better
1831 api_register_func('api/statuses/mentions', 'api_statuses_mentions', true);
1832 api_register_func('api/statuses/replies', 'api_statuses_mentions', true);
1835 * Returns the most recent statuses posted by the user.
1837 * @param string $type Either "json" or "xml"
1838 * @return string|array
1839 * @throws BadRequestException
1840 * @throws ForbiddenException
1841 * @throws ImagickException
1842 * @throws InternalServerErrorException
1843 * @throws UnauthorizedException
1844 * @see https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline
1846 function api_statuses_user_timeline($type)
1849 $user_info = api_get_user();
1851 if (api_user() === false || $user_info === false) {
1852 throw new ForbiddenException();
1855 Logger::info('api_statuses_user_timeline', ['api_user' => api_user(), 'user_info' => $user_info, '_REQUEST' => $_REQUEST]);
1857 $since_id = $_REQUEST['since_id'] ?? 0;
1858 $max_id = $_REQUEST['max_id'] ?? 0;
1859 $exclude_replies = !empty($_REQUEST['exclude_replies']);
1860 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
1863 $count = $_REQUEST['count'] ?? 20;
1864 $page = $_REQUEST['page'] ?? 1;
1866 $start = max(0, ($page - 1) * $count);
1868 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `contact-id` = ?",
1869 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, $user_info['cid']];
1871 if ($user_info['self'] == 1) {
1872 $condition[0] .= ' AND `wall` ';
1875 if ($exclude_replies) {
1876 $condition[0] .= ' AND `gravity` = ?';
1877 $condition[] = GRAVITY_PARENT;
1880 if ($conversation_id > 0) {
1881 $condition[0] .= " AND `parent` = ?";
1882 $condition[] = $conversation_id;
1886 $condition[0] .= " AND `id` <= ?";
1887 $condition[] = $max_id;
1889 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
1890 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
1892 $ret = api_format_items(Post::toArray($statuses), $user_info, true, $type);
1896 $data = ['status' => $ret];
1901 $data = api_rss_extra($a, $data, $user_info);
1905 return DI::apiResponse()->formatData("statuses", $type, $data);
1908 /// @TODO move to top of file or somewhere better
1909 api_register_func('api/statuses/user_timeline', 'api_statuses_user_timeline', true);
1912 * Star/unstar an item.
1913 * param: id : id of the item
1915 * @param string $type Return type (atom, rss, xml, json)
1917 * @return array|string
1918 * @throws BadRequestException
1919 * @throws ForbiddenException
1920 * @throws ImagickException
1921 * @throws InternalServerErrorException
1922 * @throws UnauthorizedException
1923 * @see https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1925 function api_favorites_create_destroy($type)
1929 if (api_user() === false) {
1930 throw new ForbiddenException();
1933 // for versioned api.
1934 /// @TODO We need a better global soluton
1935 $action_argv_id = 2;
1936 if (count(DI::args()->getArgv()) > 1 && DI::args()->getArgv()[1] == "1.1") {
1937 $action_argv_id = 3;
1940 if (DI::args()->getArgc() <= $action_argv_id) {
1941 throw new BadRequestException("Invalid request.");
1943 $action = str_replace("." . $type, "", DI::args()->getArgv()[$action_argv_id]);
1944 if (DI::args()->getArgc() == $action_argv_id + 2) {
1945 $itemid = intval(DI::args()->getArgv()[$action_argv_id + 1] ?? 0);
1947 $itemid = intval($_REQUEST['id'] ?? 0);
1950 $item = Post::selectFirstForUser(api_user(), [], ['id' => $itemid, 'uid' => api_user()]);
1952 if (!DBA::isResult($item)) {
1953 throw new BadRequestException("Invalid item.");
1958 $item['starred'] = 1;
1961 $item['starred'] = 0;
1964 throw new BadRequestException("Invalid action ".$action);
1967 $r = Item::update(['starred' => $item['starred']], ['id' => $itemid]);
1970 throw new InternalServerErrorException("DB error");
1974 $user_info = api_get_user();
1975 $rets = api_format_items([$item], $user_info, false, $type);
1978 $data = ['status' => $ret];
1983 $data = api_rss_extra($a, $data, $user_info);
1987 return DI::apiResponse()->formatData("status", $type, $data);
1990 /// @TODO move to top of file or somewhere better
1991 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1992 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1995 * Returns the most recent favorite statuses.
1997 * @param string $type Return type (atom, rss, xml, json)
1999 * @return string|array
2000 * @throws BadRequestException
2001 * @throws ForbiddenException
2002 * @throws ImagickException
2003 * @throws InternalServerErrorException
2004 * @throws UnauthorizedException
2006 function api_favorites($type)
2011 $user_info = api_get_user();
2013 if (api_user() === false || $user_info === false) {
2014 throw new ForbiddenException();
2019 // in friendica starred item are private
2020 // return favorites only for self
2021 Logger::info(API_LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites', 'self' => $user_info['self']]);
2023 if ($user_info['self'] == 0) {
2027 $since_id = $_REQUEST['since_id'] ?? 0;
2028 $max_id = $_REQUEST['max_id'] ?? 0;
2029 $count = $_GET['count'] ?? 20;
2030 $page = $_REQUEST['page'] ?? 1;
2032 $start = max(0, ($page - 1) * $count);
2034 $condition = ["`uid` = ? AND `gravity` IN (?, ?) AND `id` > ? AND `starred`",
2035 api_user(), GRAVITY_PARENT, GRAVITY_COMMENT, $since_id];
2037 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2040 $condition[0] .= " AND `id` <= ?";
2041 $condition[] = $max_id;
2044 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2046 $ret = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2051 $data = ['status' => $ret];
2056 $data = api_rss_extra($a, $data, $user_info);
2060 return DI::apiResponse()->formatData("statuses", $type, $data);
2063 /// @TODO move to top of file or somewhere better
2064 api_register_func('api/favorites', 'api_favorites', true);
2068 * @param array $item
2069 * @param array $recipient
2070 * @param array $sender
2073 * @throws InternalServerErrorException
2075 function api_format_messages($item, $recipient, $sender)
2077 // standard meta information
2079 'id' => $item['id'],
2080 'sender_id' => $sender['id'],
2082 'recipient_id' => $recipient['id'],
2083 'created_at' => api_date($item['created'] ?? DateTimeFormat::utcNow()),
2084 'sender_screen_name' => $sender['screen_name'],
2085 'recipient_screen_name' => $recipient['screen_name'],
2086 'sender' => $sender,
2087 'recipient' => $recipient,
2089 'friendica_seen' => $item['seen'] ?? 0,
2090 'friendica_parent_uri' => $item['parent-uri'] ?? '',
2093 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2094 if (isset($ret['sender']['uid'])) {
2095 unset($ret['sender']['uid']);
2097 if (isset($ret['sender']['self'])) {
2098 unset($ret['sender']['self']);
2100 if (isset($ret['recipient']['uid'])) {
2101 unset($ret['recipient']['uid']);
2103 if (isset($ret['recipient']['self'])) {
2104 unset($ret['recipient']['self']);
2107 //don't send title to regular StatusNET requests to avoid confusing these apps
2108 if (!empty($_GET['getText'])) {
2109 $ret['title'] = $item['title'];
2110 if ($_GET['getText'] == 'html') {
2111 $ret['text'] = BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::API);
2112 } elseif ($_GET['getText'] == 'plain') {
2113 $ret['text'] = trim(HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0));
2116 $ret['text'] = $item['title'] . "\n" . HTML::toPlaintext(BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($item['body']), BBCode::API), 0);
2118 if (!empty($_GET['getUserObjects']) && $_GET['getUserObjects'] == 'false') {
2119 unset($ret['sender']);
2120 unset($ret['recipient']);
2128 * @param array $item
2131 * @throws InternalServerErrorException
2133 function api_convert_item($item)
2135 $body = api_add_attachments_to_body($item);
2137 $entities = api_get_entitities($statustext, $body, $item['uri-id']);
2139 // Add pictures to the attachment array and remove them from the body
2140 $attachments = api_get_attachments($body, $item['uri-id']);
2142 // Workaround for ostatus messages where the title is identically to the body
2143 $html = BBCode::convertForUriId($item['uri-id'], api_clean_plain_items($body), BBCode::API);
2144 $statusbody = trim(HTML::toPlaintext($html, 0));
2146 // handle data: images
2147 $statusbody = api_format_items_embeded_images($item, $statusbody);
2149 $statustitle = trim($item['title']);
2151 if (($statustitle != '') && (strpos($statusbody, $statustitle) !== false)) {
2152 $statustext = trim($statusbody);
2154 $statustext = trim($statustitle."\n\n".$statusbody);
2157 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (mb_strlen($statustext)> 1000)) {
2158 $statustext = mb_substr($statustext, 0, 1000) . "... \n" . ($item['plink'] ?? '');
2161 $statushtml = BBCode::convertForUriId($item['uri-id'], BBCode::removeAttachment($body), BBCode::API);
2163 // Workaround for clients with limited HTML parser functionality
2164 $search = ["<br>", "<blockquote>", "</blockquote>",
2165 "<h1>", "</h1>", "<h2>", "</h2>",
2166 "<h3>", "</h3>", "<h4>", "</h4>",
2167 "<h5>", "</h5>", "<h6>", "</h6>"];
2168 $replace = ["<br>", "<br><blockquote>", "</blockquote><br>",
2169 "<br><h1>", "</h1><br>", "<br><h2>", "</h2><br>",
2170 "<br><h3>", "</h3><br>", "<br><h4>", "</h4><br>",
2171 "<br><h5>", "</h5><br>", "<br><h6>", "</h6><br>"];
2172 $statushtml = str_replace($search, $replace, $statushtml);
2174 if ($item['title'] != "") {
2175 $statushtml = "<br><h4>" . BBCode::convertForUriId($item['uri-id'], $item['title']) . "</h4><br>" . $statushtml;
2179 $oldtext = $statushtml;
2180 $statushtml = str_replace("<br><br>", "<br>", $statushtml);
2181 } while ($oldtext != $statushtml);
2183 if (substr($statushtml, 0, 4) == '<br>') {
2184 $statushtml = substr($statushtml, 4);
2187 if (substr($statushtml, 0, -4) == '<br>') {
2188 $statushtml = substr($statushtml, -4);
2191 // feeds without body should contain the link
2192 if ((($item['network'] ?? Protocol::PHANTOM) == Protocol::FEED) && (strlen($item['body']) == 0)) {
2193 $statushtml .= BBCode::convertForUriId($item['uri-id'], $item['plink']);
2197 "text" => $statustext,
2198 "html" => $statushtml,
2199 "attachments" => $attachments,
2200 "entities" => $entities
2205 * Add media attachments to the body
2207 * @param array $item
2208 * @return string body with added media
2210 function api_add_attachments_to_body(array $item)
2212 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
2214 if (strpos($body, '[/img]') !== false) {
2218 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]) as $media) {
2219 if (!empty($media['preview'])) {
2220 $description = $media['description'] ?: $media['name'];
2221 if (!empty($description)) {
2222 $body .= "\n[img=" . $media['preview'] . ']' . $description .'[/img]';
2224 $body .= "\n[img]" . $media['preview'] .'[/img]';
2234 * @param string $body
2238 * @throws InternalServerErrorException
2240 function api_get_attachments(&$body, $uriid)
2242 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
2243 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
2245 $URLSearchString = "^\[\]";
2246 if (!preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $body, $images)) {
2250 // Remove all embedded pictures, since they are added as attachments
2251 foreach ($images[0] as $orig) {
2252 $body = str_replace($orig, '', $body);
2257 foreach ($images[1] as $image) {
2258 $imagedata = Images::getInfoFromURLCached($image);
2261 $attachments[] = ["url" => Post\Link::getByLink($uriid, $image), "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]];
2265 return $attachments;
2270 * @param string $text
2271 * @param string $bbcode
2274 * @throws InternalServerErrorException
2275 * @todo Links at the first character of the post
2277 function api_get_entitities(&$text, $bbcode, $uriid)
2279 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
2281 if ($include_entities != "true") {
2282 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2284 foreach ($images[1] as $image) {
2285 $replace = Post\Link::getByLink($uriid, $image);
2286 $text = str_replace($image, $replace, $text);
2291 $bbcode = BBCode::cleanPictureLinks($bbcode);
2293 // Change pure links in text to bbcode uris
2294 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2297 $entities["hashtags"] = [];
2298 $entities["symbols"] = [];
2299 $entities["urls"] = [];
2300 $entities["user_mentions"] = [];
2302 $URLSearchString = "^\[\]";
2304 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode);
2306 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode);
2307 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode);
2309 $bbcode = preg_replace(
2310 "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2311 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]',
2314 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism", '[url=$1]$1[/url]', $bbcode);
2316 $bbcode = preg_replace(
2317 "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2318 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]',
2321 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism", '[url=$1]$1[/url]', $bbcode);
2323 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2325 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2328 foreach ($urls[1] as $id => $url) {
2329 $start = iconv_strpos($text, $url, 0, "UTF-8");
2330 if (!($start === false)) {
2331 $ordered_urls[$start] = ["url" => $url, "title" => $urls[2][$id]];
2335 ksort($ordered_urls);
2339 foreach ($ordered_urls as $url) {
2340 if ((substr($url["title"], 0, 7) != "http://") && (substr($url["title"], 0, 8) != "https://")
2341 && !strpos($url["title"], "http://") && !strpos($url["title"], "https://")
2343 $display_url = $url["title"];
2345 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url["url"]);
2346 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2348 if (strlen($display_url) > 26) {
2349 $display_url = substr($display_url, 0, 25)."…";
2353 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2354 if (!($start === false)) {
2355 $entities["urls"][] = ["url" => $url["url"],
2356 "expanded_url" => $url["url"],
2357 "display_url" => $display_url,
2358 "indices" => [$start, $start+strlen($url["url"])]];
2359 $offset = $start + 1;
2363 preg_match_all("/\[img\=(.*?)\](.*?)\[\/img\]/ism", $bbcode, $images, PREG_SET_ORDER);
2364 $ordered_images = [];
2365 foreach ($images as $image) {
2366 $start = iconv_strpos($text, $image[1], 0, "UTF-8");
2367 if (!($start === false)) {
2368 $ordered_images[$start] = ['url' => $image[1], 'alt' => $image[2]];
2372 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2373 foreach ($images[1] as $image) {
2374 $start = iconv_strpos($text, $image, 0, "UTF-8");
2375 if (!($start === false)) {
2376 $ordered_images[$start] = ['url' => $image, 'alt' => ''];
2382 foreach ($ordered_images as $image) {
2383 $url = $image['url'];
2384 $ext_alt_text = $image['alt'];
2386 $display_url = str_replace(["http://www.", "https://www."], ["", ""], $url);
2387 $display_url = str_replace(["http://", "https://"], ["", ""], $display_url);
2389 if (strlen($display_url) > 26) {
2390 $display_url = substr($display_url, 0, 25)."…";
2393 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2394 if (!($start === false)) {
2395 $image = Images::getInfoFromURLCached($url);
2397 $media_url = Post\Link::getByLink($uriid, $url);
2398 $sizes["medium"] = ["w" => $image[0], "h" => $image[1], "resize" => "fit"];
2400 $entities["media"][] = [
2402 "id_str" => (string) ($start + 1),
2403 "indices" => [$start, $start+strlen($url)],
2404 "media_url" => Strings::normaliseLink($media_url),
2405 "media_url_https" => $media_url,
2407 "display_url" => $display_url,
2408 "expanded_url" => $url,
2409 "ext_alt_text" => $ext_alt_text,
2413 $offset = $start + 1;
2422 * @param array $item
2423 * @param string $text
2427 function api_format_items_embeded_images($item, $text)
2429 $text = preg_replace_callback(
2430 '|data:image/([^;]+)[^=]+=*|m',
2431 function () use ($item) {
2432 return DI::baseUrl() . '/display/' . $item['guid'];
2440 * return <a href='url'>name</a> as array
2442 * @param string $txt text
2447 function api_contactlink_to_array($txt)
2450 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2451 if ($r && count($match)==3) {
2453 'name' => $match[2],
2467 * return likes, dislikes and attend status for item
2469 * @param array $item array
2470 * @param string $type Return type (atom, rss, xml, json)
2473 * likes => int count,
2474 * dislikes => int count
2475 * @throws BadRequestException
2476 * @throws ImagickException
2477 * @throws InternalServerErrorException
2478 * @throws UnauthorizedException
2480 function api_format_items_activities($item, $type = "json")
2489 'attendmaybe' => [],
2493 $condition = ['uid' => $item['uid'], 'thr-parent' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY];
2494 $ret = Post::selectForUser($item['uid'], ['author-id', 'verb'], $condition);
2496 while ($parent_item = Post::fetch($ret)) {
2497 // not used as result should be structured like other user data
2498 //builtin_activity_puller($i, $activities);
2500 // get user data and add it to the array of the activity
2501 $user = api_get_user($parent_item['author-id']);
2502 switch ($parent_item['verb']) {
2503 case Activity::LIKE:
2504 $activities['like'][] = $user;
2506 case Activity::DISLIKE:
2507 $activities['dislike'][] = $user;
2509 case Activity::ATTEND:
2510 $activities['attendyes'][] = $user;
2512 case Activity::ATTENDNO:
2513 $activities['attendno'][] = $user;
2515 case Activity::ATTENDMAYBE:
2516 $activities['attendmaybe'][] = $user;
2518 case Activity::ANNOUNCE:
2519 $activities['announce'][] = $user;
2528 if ($type == "xml") {
2529 $xml_activities = [];
2530 foreach ($activities as $k => $v) {
2531 // change xml element from "like" to "friendica:like"
2532 $xml_activities["friendica:".$k] = $v;
2533 // add user data into xml output
2535 foreach ($v as $user) {
2536 $xml_activities["friendica:".$k][$k_user++.":user"] = $user;
2539 $activities = $xml_activities;
2546 * format items to be returned by api
2548 * @param array $items array of items
2549 * @param array $user_info
2550 * @param bool $filter_user filter items by $user_info
2551 * @param string $type Return type (atom, rss, xml, json)
2553 * @throws BadRequestException
2554 * @throws ImagickException
2555 * @throws InternalServerErrorException
2556 * @throws UnauthorizedException
2558 function api_format_items($items, $user_info, $filter_user = false, $type = "json")
2560 $a = Friendica\DI::app();
2564 if (empty($items)) {
2568 foreach ((array)$items as $item) {
2569 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2571 // Look if the posts are matching if they should be filtered by user id
2572 if ($filter_user && ($status_user["id"] != $user_info["id"])) {
2576 $status = api_format_item($item, $type, $status_user, $author_user, $owner_user);
2585 * @param array $item Item record
2586 * @param string $type Return format (atom, rss, xml, json)
2587 * @param array $status_user User record of the item author, can be provided by api_item_get_user()
2588 * @param array $author_user User record of the item author, can be provided by api_item_get_user()
2589 * @param array $owner_user User record of the item owner, can be provided by api_item_get_user()
2590 * @return array API-formatted status
2591 * @throws BadRequestException
2592 * @throws ImagickException
2593 * @throws InternalServerErrorException
2594 * @throws UnauthorizedException
2596 function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null)
2598 $a = Friendica\DI::app();
2600 if (empty($status_user) || empty($author_user) || empty($owner_user)) {
2601 [$status_user, $author_user, $owner_user] = api_item_get_user($a, $item);
2604 DI::contentItem()->localize($item);
2606 $in_reply_to = api_in_reply_to($item);
2608 $converted = api_convert_item($item);
2610 if ($type == "xml") {
2611 $geo = "georss:point";
2617 'text' => $converted["text"],
2618 'truncated' => false,
2619 'created_at'=> api_date($item['created']),
2620 'in_reply_to_status_id' => $in_reply_to['status_id'],
2621 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
2622 'source' => (($item['app']) ? $item['app'] : 'web'),
2623 'id' => intval($item['id']),
2624 'id_str' => (string) intval($item['id']),
2625 'in_reply_to_user_id' => $in_reply_to['user_id'],
2626 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
2627 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
2629 'favorited' => $item['starred'] ? true : false,
2630 'user' => $status_user,
2631 'friendica_author' => $author_user,
2632 'friendica_owner' => $owner_user,
2633 'friendica_private' => $item['private'] == Item::PRIVATE,
2634 //'entities' => NULL,
2635 'statusnet_html' => $converted["html"],
2636 'statusnet_conversation_id' => $item['parent'],
2637 'external_url' => DI::baseUrl() . "/display/" . $item['guid'],
2638 'friendica_activities' => api_format_items_activities($item, $type),
2639 'friendica_title' => $item['title'],
2640 'friendica_html' => BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::EXTERNAL)
2643 if (count($converted["attachments"]) > 0) {
2644 $status["attachments"] = $converted["attachments"];
2647 if (count($converted["entities"]) > 0) {
2648 $status["entities"] = $converted["entities"];
2651 if ($status["source"] == 'web') {
2652 $status["source"] = ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']);
2653 } elseif (ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']) != $status["source"]) {
2654 $status["source"] = trim($status["source"].' ('.ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']).')');
2657 $retweeted_item = [];
2660 if (empty($retweeted_item) && ($item['owner-id'] == $item['author-id'])) {
2661 $announce = api_get_announce($item);
2662 if (!empty($announce)) {
2663 $retweeted_item = $item;
2665 $status['friendica_owner'] = api_get_user($announce['author-id']);
2669 if (!empty($quoted_item)) {
2670 if ($quoted_item['id'] != $item['id']) {
2671 $quoted_status = api_format_item($quoted_item);
2672 /// @todo Only remove the attachments that are also contained in the quotes status
2673 unset($status['attachments']);
2674 unset($status['entities']);
2676 $conv_quoted = api_convert_item($quoted_item);
2677 $quoted_status = $status;
2678 unset($quoted_status['attachments']);
2679 unset($quoted_status['entities']);
2680 unset($quoted_status['statusnet_conversation_id']);
2681 $quoted_status['text'] = $conv_quoted['text'];
2682 $quoted_status['statusnet_html'] = $conv_quoted['html'];
2684 $quoted_status["user"] = api_get_user($quoted_item["author-id"]);
2685 } catch (BadRequestException $e) {
2686 // user not found. should be found?
2687 /// @todo check if the user should be always found
2688 $quoted_status["user"] = [];
2691 unset($quoted_status['friendica_author']);
2692 unset($quoted_status['friendica_owner']);
2693 unset($quoted_status['friendica_activities']);
2694 unset($quoted_status['friendica_private']);
2697 if (!empty($retweeted_item)) {
2698 $retweeted_status = $status;
2699 unset($retweeted_status['friendica_author']);
2700 unset($retweeted_status['friendica_owner']);
2701 unset($retweeted_status['friendica_activities']);
2702 unset($retweeted_status['friendica_private']);
2703 unset($retweeted_status['statusnet_conversation_id']);
2704 $status['user'] = $status['friendica_owner'];
2706 $retweeted_status["user"] = api_get_user($retweeted_item["author-id"]);
2707 } catch (BadRequestException $e) {
2708 // user not found. should be found?
2709 /// @todo check if the user should be always found
2710 $retweeted_status["user"] = [];
2713 $rt_converted = api_convert_item($retweeted_item);
2715 $retweeted_status['text'] = $rt_converted["text"];
2716 $retweeted_status['statusnet_html'] = $rt_converted["html"];
2717 $retweeted_status['friendica_html'] = $rt_converted["html"];
2718 $retweeted_status['created_at'] = api_date($retweeted_item['created']);
2720 if (!empty($quoted_status)) {
2721 $retweeted_status['quoted_status'] = $quoted_status;
2724 $status['friendica_author'] = $retweeted_status['user'];
2725 $status['retweeted_status'] = $retweeted_status;
2726 } elseif (!empty($quoted_status)) {
2727 $root_status = api_convert_item($item);
2729 $status['text'] = $root_status["text"];
2730 $status['statusnet_html'] = $root_status["html"];
2731 $status['quoted_status'] = $quoted_status;
2734 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2735 unset($status["user"]["uid"]);
2736 unset($status["user"]["self"]);
2738 if ($item["coord"] != "") {
2739 $coords = explode(' ', $item["coord"]);
2740 if (count($coords) == 2) {
2741 if ($type == "json") {
2742 $status["geo"] = ['type' => 'Point',
2743 'coordinates' => [(float) $coords[0],
2744 (float) $coords[1]]];
2745 } else {// Not sure if this is the official format - if someone founds a documentation we can check
2746 $status["georss:point"] = $item["coord"];
2755 * Returns all lists the user subscribes to.
2757 * @param string $type Return type (atom, rss, xml, json)
2759 * @return array|string
2760 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-list
2762 function api_lists_list($type)
2765 /// @TODO $ret is not filled here?
2766 return DI::apiResponse()->formatData('lists', $type, ["lists_list" => $ret]);
2769 /// @TODO move to top of file or somewhere better
2770 api_register_func('api/lists/list', 'api_lists_list', true);
2771 api_register_func('api/lists/subscriptions', 'api_lists_list', true);
2774 * Returns all groups the user owns.
2776 * @param string $type Return type (atom, rss, xml, json)
2778 * @return array|string
2779 * @throws BadRequestException
2780 * @throws ForbiddenException
2781 * @throws ImagickException
2782 * @throws InternalServerErrorException
2783 * @throws UnauthorizedException
2784 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2786 function api_lists_ownerships($type)
2790 if (api_user() === false) {
2791 throw new ForbiddenException();
2795 $user_info = api_get_user();
2796 $uid = $user_info['uid'];
2798 $groups = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid]);
2800 // loop through all groups
2802 foreach ($groups as $group) {
2803 if ($group['visible']) {
2809 'name' => $group['name'],
2810 'id' => intval($group['id']),
2811 'id_str' => (string) $group['id'],
2812 'user' => $user_info,
2816 return DI::apiResponse()->formatData("lists", $type, ['lists' => ['lists' => $lists]]);
2819 /// @TODO move to top of file or somewhere better
2820 api_register_func('api/lists/ownerships', 'api_lists_ownerships', true);
2823 * Returns recent statuses from users in the specified group.
2825 * @param string $type Return type (atom, rss, xml, json)
2827 * @return array|string
2828 * @throws BadRequestException
2829 * @throws ForbiddenException
2830 * @throws ImagickException
2831 * @throws InternalServerErrorException
2832 * @throws UnauthorizedException
2833 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-ownerships
2835 function api_lists_statuses($type)
2839 $user_info = api_get_user();
2840 if (api_user() === false || $user_info === false) {
2841 throw new ForbiddenException();
2844 unset($_REQUEST["user_id"]);
2845 unset($_GET["user_id"]);
2847 unset($_REQUEST["screen_name"]);
2848 unset($_GET["screen_name"]);
2850 if (empty($_REQUEST['list_id'])) {
2851 throw new BadRequestException('list_id not specified');
2855 $count = $_REQUEST['count'] ?? 20;
2856 $page = $_REQUEST['page'] ?? 1;
2857 $since_id = $_REQUEST['since_id'] ?? 0;
2858 $max_id = $_REQUEST['max_id'] ?? 0;
2859 $exclude_replies = (!empty($_REQUEST['exclude_replies']) ? 1 : 0);
2860 $conversation_id = $_REQUEST['conversation_id'] ?? 0;
2862 $start = max(0, ($page - 1) * $count);
2864 $groups = DBA::selectToArray('group_member', ['contact-id'], ['gid' => 1]);
2865 $gids = array_column($groups, 'contact-id');
2866 $condition = ['uid' => api_user(), 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'group-id' => $gids];
2867 $condition = DBA::mergeConditions($condition, ["`id` > ?", $since_id]);
2870 $condition[0] .= " AND `id` <= ?";
2871 $condition[] = $max_id;
2873 if ($exclude_replies > 0) {
2874 $condition[0] .= ' AND `gravity` = ?';
2875 $condition[] = GRAVITY_PARENT;
2877 if ($conversation_id > 0) {
2878 $condition[0] .= " AND `parent` = ?";
2879 $condition[] = $conversation_id;
2882 $params = ['order' => ['id' => true], 'limit' => [$start, $count]];
2883 $statuses = Post::selectForUser(api_user(), [], $condition, $params);
2885 $items = api_format_items(Post::toArray($statuses), $user_info, false, $type);
2887 $data = ['status' => $items];
2892 $data = api_rss_extra($a, $data, $user_info);
2896 return DI::apiResponse()->formatData("statuses", $type, $data);
2899 /// @TODO move to top of file or somewhere better
2900 api_register_func('api/lists/statuses', 'api_lists_statuses', true);
2903 * Returns either the friends of the follower list
2905 * Considers friends and followers lists to be private and won't return
2906 * anything if any user_id parameter is passed.
2908 * @param string $qtype Either "friends" or "followers"
2909 * @return boolean|array
2910 * @throws BadRequestException
2911 * @throws ForbiddenException
2912 * @throws ImagickException
2913 * @throws InternalServerErrorException
2914 * @throws UnauthorizedException
2916 function api_statuses_f($qtype)
2920 if (api_user() === false) {
2921 throw new ForbiddenException();
2925 $count = $_GET['count'] ?? 20;
2926 $page = $_GET['page'] ?? 1;
2928 $start = max(0, ($page - 1) * $count);
2930 $user_info = api_get_user();
2932 if (!empty($_GET['cursor']) && $_GET['cursor'] == 'undefined') {
2933 /* this is to stop Hotot to load friends multiple times
2934 * I'm not sure if I'm missing return something or
2935 * is a bug in hotot. Workaround, meantime
2939 return array('$users' => $ret);*/
2944 if ($qtype == 'friends') {
2945 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::SHARING), intval(Contact::FRIEND));
2946 } elseif ($qtype == 'followers') {
2947 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(Contact::FOLLOWER), intval(Contact::FRIEND));
2950 // friends and followers only for self
2951 if ($user_info['self'] == 0) {
2952 $sql_extra = " AND false ";
2955 if ($qtype == 'blocks') {
2956 $sql_filter = 'AND `blocked` AND NOT `pending`';
2957 } elseif ($qtype == 'incoming') {
2958 $sql_filter = 'AND `pending`';
2960 $sql_filter = 'AND (NOT `blocked` OR `pending`)';
2963 // @todo This query most likely can be replaced with a Contact::select...
2964 $r = DBA::toArray(DBA::p(
2979 foreach ($r as $cid) {
2980 $user = api_get_user($cid['nurl']);
2981 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2982 unset($user["uid"]);
2983 unset($user["self"]);
2990 return ['user' => $ret];
2995 * Returns the list of friends of the provided user
2997 * @deprecated By Twitter API in favor of friends/list
2999 * @param string $type Either "json" or "xml"
3000 * @return boolean|string|array
3001 * @throws BadRequestException
3002 * @throws ForbiddenException
3004 function api_statuses_friends($type)
3006 $data = api_statuses_f("friends");
3007 if ($data === false) {
3010 return DI::apiResponse()->formatData("users", $type, $data);
3014 * Returns the list of followers of the provided user
3016 * @deprecated By Twitter API in favor of friends/list
3018 * @param string $type Either "json" or "xml"
3019 * @return boolean|string|array
3020 * @throws BadRequestException
3021 * @throws ForbiddenException
3023 function api_statuses_followers($type)
3025 $data = api_statuses_f("followers");
3026 if ($data === false) {
3029 return DI::apiResponse()->formatData("users", $type, $data);
3032 /// @TODO move to top of file or somewhere better
3033 api_register_func('api/statuses/friends', 'api_statuses_friends', true);
3034 api_register_func('api/statuses/followers', 'api_statuses_followers', true);
3037 * Returns the list of blocked users
3039 * @see https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list
3041 * @param string $type Either "json" or "xml"
3043 * @return boolean|string|array
3044 * @throws BadRequestException
3045 * @throws ForbiddenException
3047 function api_blocks_list($type)
3049 $data = api_statuses_f('blocks');
3050 if ($data === false) {
3053 return DI::apiResponse()->formatData("users", $type, $data);
3056 /// @TODO move to top of file or somewhere better
3057 api_register_func('api/blocks/list', 'api_blocks_list', true);
3060 * Returns the list of pending users IDs
3062 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friendships-incoming
3064 * @param string $type Either "json" or "xml"
3066 * @return boolean|string|array
3067 * @throws BadRequestException
3068 * @throws ForbiddenException
3070 function api_friendships_incoming($type)
3072 $data = api_statuses_f('incoming');
3073 if ($data === false) {
3078 foreach ($data['user'] as $user) {
3079 $ids[] = $user['id'];
3082 return DI::apiResponse()->formatData("ids", $type, ['id' => $ids]);
3085 /// @TODO move to top of file or somewhere better
3086 api_register_func('api/friendships/incoming', 'api_friendships_incoming', true);
3089 * Sends a new direct message.
3091 * @param string $type Return type (atom, rss, xml, json)
3093 * @return array|string
3094 * @throws BadRequestException
3095 * @throws ForbiddenException
3096 * @throws ImagickException
3097 * @throws InternalServerErrorException
3098 * @throws NotFoundException
3099 * @throws UnauthorizedException
3100 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-message
3102 function api_direct_messages_new($type)
3106 if (api_user() === false) {
3107 throw new ForbiddenException();
3110 if (empty($_POST["text"]) || empty($_POST["screen_name"]) && empty($_POST["user_id"])) {
3114 $sender = api_get_user();
3117 if (!empty($_POST['screen_name'])) {
3118 $contacts = Contact::selectToArray(['id', 'nurl', 'network'], ['uid' => api_user(), 'nick' => $_POST['screen_name']]);
3119 if (DBA::isResult($contacts)) {
3120 // Selecting the id by priority, friendica first
3121 api_best_nickname($contacts);
3123 $recipient = api_get_user($contacts[0]['nurl']);
3126 $recipient = api_get_user($_POST['user_id']);
3129 if (empty($recipient)) {
3130 throw new NotFoundException('Recipient not found');
3134 if (!empty($_REQUEST['replyto'])) {
3135 $mail = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uid' => api_user(), 'id' => $_REQUEST['replyto']]);
3136 $replyto = $mail['parent-uri'];
3137 $sub = $mail['title'];
3139 if (!empty($_REQUEST['title'])) {
3140 $sub = $_REQUEST['title'];
3142 $sub = ((strlen($_POST['text'])>10) ? substr($_POST['text'], 0, 10)."...":$_POST['text']);
3146 $id = Mail::send($recipient['cid'], $_POST['text'], $sub, $replyto);
3149 $mail = DBA::selectFirst('mail', [], ['id' => $id]);
3150 $ret = api_format_messages($mail, $recipient, $sender);
3152 $ret = ["error" => $id];
3155 $data = ['direct_message'=>$ret];
3161 $data = api_rss_extra($a, $data, $sender);
3165 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3168 /// @TODO move to top of file or somewhere better
3169 api_register_func('api/direct_messages/new', 'api_direct_messages_new', true, API_METHOD_POST);
3172 * delete a direct_message from mail table through api
3174 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3175 * @return string|array
3176 * @throws BadRequestException
3177 * @throws ForbiddenException
3178 * @throws ImagickException
3179 * @throws InternalServerErrorException
3180 * @throws UnauthorizedException
3181 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/delete-message
3183 function api_direct_messages_destroy($type)
3187 if (api_user() === false) {
3188 throw new ForbiddenException();
3192 $user_info = api_get_user();
3194 $id = $_REQUEST['id'] ?? 0;
3196 $parenturi = $_REQUEST['friendica_parenturi'] ?? '';
3197 $verbose = (!empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false");
3198 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
3200 $uid = $user_info['uid'];
3201 // error if no id or parenturi specified (for clients posting parent-uri as well)
3202 if ($verbose == "true" && ($id == 0 || $parenturi == "")) {
3203 $answer = ['result' => 'error', 'message' => 'message id or parenturi not specified'];
3204 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3207 // BadRequestException if no id specified (for clients using Twitter API)
3209 throw new BadRequestException('Message id not specified');
3212 // add parent-uri to sql command if specified by calling app
3213 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . DBA::escape($parenturi) . "'" : "");
3215 // error message if specified id is not in database
3216 if (!DBA::exists('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id])) {
3217 if ($verbose == "true") {
3218 $answer = ['result' => 'error', 'message' => 'message id not in database'];
3219 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3221 /// @todo BadRequestException ok for Twitter API clients?
3222 throw new BadRequestException('message id not in database');
3226 $result = DBA::delete('mail', ["`uid` = ? AND `id` = ? " . $sql_extra, $uid, $id]);
3228 if ($verbose == "true") {
3231 $answer = ['result' => 'ok', 'message' => 'message deleted'];
3232 return DI::apiResponse()->formatData("direct_message_delete", $type, ['$result' => $answer]);
3234 $answer = ['result' => 'error', 'message' => 'unknown error'];
3235 return DI::apiResponse()->formatData("direct_messages_delete", $type, ['$result' => $answer]);
3238 /// @todo return JSON data like Twitter API not yet implemented
3241 /// @TODO move to top of file or somewhere better
3242 api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
3247 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3248 * @return string|array
3249 * @throws HTTPException\BadRequestException
3250 * @throws HTTPException\ExpectationFailedException
3251 * @throws HTTPException\ForbiddenException
3252 * @throws HTTPException\InternalServerErrorException
3253 * @throws HTTPException\NotFoundException
3254 * @see https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/post-friendships-destroy.html
3256 function api_friendships_destroy($type)
3260 if ($uid === false) {
3261 throw new HTTPException\ForbiddenException();
3264 $owner = User::getOwnerDataById($uid);
3266 Logger::notice(API_LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
3267 throw new HTTPException\NotFoundException('Error Processing Request');
3270 $contact_id = $_REQUEST['user_id'] ?? 0;
3272 if (empty($contact_id)) {
3273 Logger::notice(API_LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
3274 throw new HTTPException\BadRequestException('no user_id specified');
3277 // Get Contact by given id
3278 $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
3280 if(!DBA::isResult($contact)) {
3281 Logger::notice(API_LOG_PREFIX . 'No public contact found for ID {contact}', ['module' => 'api', 'action' => 'friendships_destroy', 'contact' => $contact_id]);
3282 throw new HTTPException\NotFoundException('no contact found to given ID');
3285 $url = $contact['url'];
3287 $condition = ["`uid` = ? AND (`rel` = ? OR `rel` = ?) AND (`nurl` = ? OR `alias` = ? OR `alias` = ?)",
3288 $uid, Contact::SHARING, Contact::FRIEND, Strings::normaliseLink($url),
3289 Strings::normaliseLink($url), $url];
3290 $contact = DBA::selectFirst('contact', [], $condition);
3292 if (!DBA::isResult($contact)) {
3293 Logger::notice(API_LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
3294 throw new HTTPException\NotFoundException('Not following Contact');
3298 $result = Contact::terminateFriendship($owner, $contact);
3300 if ($result === null) {
3301 Logger::notice(API_LOG_PREFIX . 'Not supported for {network}', ['module' => 'api', 'action' => 'friendships_destroy', 'network' => $contact['network']]);
3302 throw new HTTPException\ExpectationFailedException('Unfollowing is currently not supported by this contact\'s network.');
3305 if ($result === false) {
3306 throw new HTTPException\ServiceUnavailableException('Unable to unfollow this contact, please retry in a few minutes or contact your administrator.');
3308 } catch (Exception $e) {
3309 Logger::error(API_LOG_PREFIX . $e->getMessage(), ['owner' => $owner, 'contact' => $contact]);
3310 throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
3313 // "uid" and "self" are only needed for some internal stuff, so remove it from here
3314 unset($contact['uid']);
3315 unset($contact['self']);
3317 // Set screen_name since Twidere requests it
3318 $contact['screen_name'] = $contact['nick'];
3320 return DI::apiResponse()->formatData('friendships-destroy', $type, ['user' => $contact]);
3323 api_register_func('api/friendships/destroy', 'api_friendships_destroy', true, API_METHOD_POST);
3327 * @param string $type Return type (atom, rss, xml, json)
3328 * @param string $box
3329 * @param string $verbose
3331 * @return array|string
3332 * @throws BadRequestException
3333 * @throws ForbiddenException
3334 * @throws ImagickException
3335 * @throws InternalServerErrorException
3336 * @throws UnauthorizedException
3338 function api_direct_messages_box($type, $box, $verbose)
3341 if (api_user() === false) {
3342 throw new ForbiddenException();
3345 $count = $_GET['count'] ?? 20;
3346 $page = $_REQUEST['page'] ?? 1;
3348 $since_id = $_REQUEST['since_id'] ?? 0;
3349 $max_id = $_REQUEST['max_id'] ?? 0;
3351 $user_id = $_REQUEST['user_id'] ?? '';
3352 $screen_name = $_REQUEST['screen_name'] ?? '';
3355 unset($_REQUEST["user_id"]);
3356 unset($_GET["user_id"]);
3358 unset($_REQUEST["screen_name"]);
3359 unset($_GET["screen_name"]);
3361 $user_info = api_get_user();
3362 if ($user_info === false) {
3363 throw new ForbiddenException();
3365 $profile_url = $user_info["url"];
3368 $start = max(0, ($page - 1) * $count);
3373 if ($box=="sentbox") {
3374 $sql_extra = "`mail`.`from-url`='" . DBA::escape($profile_url) . "'";
3375 } elseif ($box == "conversation") {
3376 $sql_extra = "`mail`.`parent-uri`='" . DBA::escape($_GET['uri'] ?? '') . "'";
3377 } elseif ($box == "all") {
3378 $sql_extra = "true";
3379 } elseif ($box == "inbox") {
3380 $sql_extra = "`mail`.`from-url`!='" . DBA::escape($profile_url) . "'";
3384 $sql_extra .= ' AND `mail`.`id` <= ' . intval($max_id);
3387 if ($user_id != "") {
3388 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
3389 } elseif ($screen_name !="") {
3390 $sql_extra .= " AND `contact`.`nick` = '" . DBA::escape($screen_name). "'";
3393 $r = DBA::toArray(DBA::p(
3394 "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 ?,?",
3400 if ($verbose == "true" && !DBA::isResult($r)) {
3401 $answer = ['result' => 'error', 'message' => 'no mails available'];
3402 return DI::apiResponse()->formatData("direct_messages_all", $type, ['$result' => $answer]);
3406 foreach ($r as $item) {
3407 if ($box == "inbox" || $item['from-url'] != $profile_url) {
3408 $recipient = $user_info;
3409 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
3410 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
3411 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
3412 $sender = $user_info;
3415 if (isset($recipient) && isset($sender)) {
3416 $ret[] = api_format_messages($item, $recipient, $sender);
3421 $data = ['direct_message' => $ret];
3426 $data = api_rss_extra($a, $data, $user_info);
3430 return DI::apiResponse()->formatData("direct-messages", $type, $data);
3434 * Returns the most recent direct messages sent by the user.
3436 * @param string $type Return type (atom, rss, xml, json)
3438 * @return array|string
3439 * @throws BadRequestException
3440 * @throws ForbiddenException
3441 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-sent-message
3443 function api_direct_messages_sentbox($type)
3445 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3446 return api_direct_messages_box($type, "sentbox", $verbose);
3450 * Returns the most recent direct messages sent to the user.
3452 * @param string $type Return type (atom, rss, xml, json)
3454 * @return array|string
3455 * @throws BadRequestException
3456 * @throws ForbiddenException
3457 * @see https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/get-messages
3459 function api_direct_messages_inbox($type)
3461 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3462 return api_direct_messages_box($type, "inbox", $verbose);
3467 * @param string $type Return type (atom, rss, xml, json)
3469 * @return array|string
3470 * @throws BadRequestException
3471 * @throws ForbiddenException
3473 function api_direct_messages_all($type)
3475 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3476 return api_direct_messages_box($type, "all", $verbose);
3481 * @param string $type Return type (atom, rss, xml, json)
3483 * @return array|string
3484 * @throws BadRequestException
3485 * @throws ForbiddenException
3487 function api_direct_messages_conversation($type)
3489 $verbose = !empty($_GET['friendica_verbose']) ? strtolower($_GET['friendica_verbose']) : "false";
3490 return api_direct_messages_box($type, "conversation", $verbose);
3493 /// @TODO move to top of file or somewhere better
3494 api_register_func('api/direct_messages/conversation', 'api_direct_messages_conversation', true);
3495 api_register_func('api/direct_messages/all', 'api_direct_messages_all', true);
3496 api_register_func('api/direct_messages/sent', 'api_direct_messages_sentbox', true);
3497 api_register_func('api/direct_messages', 'api_direct_messages_inbox', true);
3500 * list all photos of the authenticated user
3502 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3503 * @return string|array
3504 * @throws ForbiddenException
3505 * @throws InternalServerErrorException
3507 function api_fr_photos_list($type)
3509 if (api_user() === false) {
3510 throw new ForbiddenException();
3512 $r = DBA::toArray(DBA::p(
3513 "SELECT `resource-id`, MAX(scale) AS `scale`, `album`, `filename`, `type`, MAX(`created`) AS `created`,
3514 MAX(`edited`) AS `edited`, MAX(`desc`) AS `desc` FROM `photo`
3515 WHERE `uid` = ? AND NOT `photo-type` IN (?, ?) GROUP BY `resource-id`, `album`, `filename`, `type`",
3516 local_user(), Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER
3519 'image/jpeg' => 'jpg',
3520 'image/png' => 'png',
3521 'image/gif' => 'gif'
3523 $data = ['photo'=>[]];
3524 if (DBA::isResult($r)) {
3525 foreach ($r as $rr) {
3527 $photo['id'] = $rr['resource-id'];
3528 $photo['album'] = $rr['album'];
3529 $photo['filename'] = $rr['filename'];
3530 $photo['type'] = $rr['type'];
3531 $thumb = DI::baseUrl() . "/photo/" . $rr['resource-id'] . "-" . $rr['scale'] . "." . $typetoext[$rr['type']];
3532 $photo['created'] = $rr['created'];
3533 $photo['edited'] = $rr['edited'];
3534 $photo['desc'] = $rr['desc'];
3536 if ($type == "xml") {
3537 $data['photo'][] = ["@attributes" => $photo, "1" => $thumb];
3539 $photo['thumb'] = $thumb;
3540 $data['photo'][] = $photo;
3544 return DI::apiResponse()->formatData("photos", $type, $data);
3548 * upload a new photo or change an existing photo
3550 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3551 * @return string|array
3552 * @throws BadRequestException
3553 * @throws ForbiddenException
3554 * @throws ImagickException
3555 * @throws InternalServerErrorException
3556 * @throws NotFoundException
3558 function api_fr_photo_create_update($type)
3560 if (api_user() === false) {
3561 throw new ForbiddenException();
3564 $photo_id = $_REQUEST['photo_id'] ?? null;
3565 $desc = $_REQUEST['desc'] ?? null;
3566 $album = $_REQUEST['album'] ?? null;
3567 $album_new = $_REQUEST['album_new'] ?? null;
3568 $allow_cid = $_REQUEST['allow_cid'] ?? null;
3569 $deny_cid = $_REQUEST['deny_cid' ] ?? null;
3570 $allow_gid = $_REQUEST['allow_gid'] ?? null;
3571 $deny_gid = $_REQUEST['deny_gid' ] ?? null;
3572 $visibility = !$allow_cid && !$deny_cid && !$allow_gid && !$deny_gid;
3574 // do several checks on input parameters
3575 // we do not allow calls without album string
3576 if ($album == null) {
3577 throw new BadRequestException("no albumname specified");
3579 // if photo_id == null --> we are uploading a new photo
3580 if ($photo_id == null) {
3583 // error if no media posted in create-mode
3584 if (empty($_FILES['media'])) {
3586 throw new BadRequestException("no media data submitted");
3589 // album_new will be ignored in create-mode
3594 // check if photo is existing in databasei
3595 if (!Photo::exists(['resource-id' => $photo_id, 'uid' => api_user(), 'album' => $album])) {
3596 throw new BadRequestException("photo not available");
3600 // checks on acl strings provided by clients
3601 $acl_input_error = false;
3602 $acl_input_error |= check_acl_input($allow_cid);
3603 $acl_input_error |= check_acl_input($deny_cid);
3604 $acl_input_error |= check_acl_input($allow_gid);
3605 $acl_input_error |= check_acl_input($deny_gid);
3606 if ($acl_input_error) {
3607 throw new BadRequestException("acl data invalid");
3609 // now let's upload the new media in create-mode
3610 if ($mode == "create") {
3611 $media = $_FILES['media'];
3612 $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);
3614 // return success of updating or error message
3615 if (!is_null($data)) {
3616 return DI::apiResponse()->formatData("photo_create", $type, $data);
3618 throw new InternalServerErrorException("unknown error - uploading photo failed, see Friendica log for more information");
3622 // now let's do the changes in update-mode
3623 if ($mode == "update") {
3624 $updated_fields = [];
3626 if (!is_null($desc)) {
3627 $updated_fields['desc'] = $desc;
3630 if (!is_null($album_new)) {
3631 $updated_fields['album'] = $album_new;
3634 if (!is_null($allow_cid)) {
3635 $allow_cid = trim($allow_cid);
3636 $updated_fields['allow_cid'] = $allow_cid;
3639 if (!is_null($deny_cid)) {
3640 $deny_cid = trim($deny_cid);
3641 $updated_fields['deny_cid'] = $deny_cid;
3644 if (!is_null($allow_gid)) {
3645 $allow_gid = trim($allow_gid);
3646 $updated_fields['allow_gid'] = $allow_gid;
3649 if (!is_null($deny_gid)) {
3650 $deny_gid = trim($deny_gid);
3651 $updated_fields['deny_gid'] = $deny_gid;
3655 if (count($updated_fields) > 0) {
3656 $nothingtodo = false;
3657 $result = Photo::update($updated_fields, ['uid' => api_user(), 'resource-id' => $photo_id, 'album' => $album]);
3659 $nothingtodo = true;
3662 if (!empty($_FILES['media'])) {
3663 $nothingtodo = false;
3664 $media = $_FILES['media'];
3665 $data = save_media_to_database("photo", $media, $type, $album, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $desc, Photo::DEFAULT, $visibility, $photo_id);
3666 if (!is_null($data)) {
3667 return DI::apiResponse()->formatData("photo_update", $type, $data);
3671 // return success of updating or error message
3673 $answer = ['result' => 'updated', 'message' => 'Image id `' . $photo_id . '` has been updated.'];
3674 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3677 $answer = ['result' => 'cancelled', 'message' => 'Nothing to update for image id `' . $photo_id . '`.'];
3678 return DI::apiResponse()->formatData("photo_update", $type, ['$result' => $answer]);
3680 throw new InternalServerErrorException("unknown error - update photo entry in database failed");
3683 throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
3687 * returns the details of a specified photo id, if scale is given, returns the photo data in base 64
3689 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3690 * @return string|array
3691 * @throws BadRequestException
3692 * @throws ForbiddenException
3693 * @throws InternalServerErrorException
3694 * @throws NotFoundException
3696 function api_fr_photo_detail($type)
3698 if (api_user() === false) {
3699 throw new ForbiddenException();
3701 if (empty($_REQUEST['photo_id'])) {
3702 throw new BadRequestException("No photo id.");
3705 $scale = (!empty($_REQUEST['scale']) ? intval($_REQUEST['scale']) : false);
3706 $photo_id = $_REQUEST['photo_id'];
3708 // prepare json/xml output with data from database for the requested photo
3709 $data = prepare_photo_data($type, $scale, $photo_id);
3711 return DI::apiResponse()->formatData("photo_detail", $type, $data);
3716 * updates the profile image for the user (either a specified profile or the default profile)
3718 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3720 * @return string|array
3721 * @throws BadRequestException
3722 * @throws ForbiddenException
3723 * @throws ImagickException
3724 * @throws InternalServerErrorException
3725 * @throws NotFoundException
3726 * @see https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_image
3728 function api_account_update_profile_image($type)
3730 if (api_user() === false) {
3731 throw new ForbiddenException();
3734 $profile_id = $_REQUEST['profile_id'] ?? 0;
3736 // error if image data is missing
3737 if (empty($_FILES['image'])) {
3738 throw new BadRequestException("no media data submitted");
3741 // check if specified profile id is valid
3742 if ($profile_id != 0) {
3743 $profile = DBA::selectFirst('profile', ['is-default'], ['uid' => api_user(), 'id' => $profile_id]);
3744 // error message if specified profile id is not in database
3745 if (!DBA::isResult($profile)) {
3746 throw new BadRequestException("profile_id not available");
3748 $is_default_profile = $profile['is-default'];
3750 $is_default_profile = 1;
3753 // get mediadata from image or media (Twitter call api/account/update_profile_image provides image)
3755 if (!empty($_FILES['image'])) {
3756 $media = $_FILES['image'];
3757 } elseif (!empty($_FILES['media'])) {
3758 $media = $_FILES['media'];
3760 // save new profile image
3761 $data = save_media_to_database("profileimage", $media, $type, DI::l10n()->t(Photo::PROFILE_PHOTOS), "", "", "", "", "", Photo::USER_AVATAR);
3764 if (is_array($media['type'])) {
3765 $filetype = $media['type'][0];
3767 $filetype = $media['type'];
3769 if ($filetype == "image/jpeg") {
3771 } elseif ($filetype == "image/png") {
3774 throw new InternalServerErrorException('Unsupported filetype');
3777 // change specified profile or all profiles to the new resource-id
3778 if ($is_default_profile) {
3779 $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
3780 Photo::update(['profile' => false, 'photo-type' => Photo::DEFAULT], $condition);
3782 $fields = ['photo' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-4.' . $fileext,
3783 'thumb' => DI::baseUrl() . '/photo/' . $data['photo']['id'] . '-5.' . $fileext];
3784 DBA::update('profile', $fields, ['id' => $_REQUEST['profile'], 'uid' => api_user()]);
3787 Contact::updateSelfFromUserID(api_user(), true);
3789 // Update global directory in background
3790 Profile::publishUpdate(api_user());
3792 // output for client
3794 return api_account_verify_credentials($type);
3796 // SaveMediaToDatabase failed for some reason
3797 throw new InternalServerErrorException("image upload failed");
3801 // place api-register for photoalbum calls before 'api/friendica/photo', otherwise this function is never reached
3802 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3803 api_register_func('api/friendica/photo/create', 'api_fr_photo_create_update', true, API_METHOD_POST);
3804 api_register_func('api/friendica/photo/update', 'api_fr_photo_create_update', true, API_METHOD_POST);
3805 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3806 api_register_func('api/account/update_profile_image', 'api_account_update_profile_image', true, API_METHOD_POST);
3809 * Update user profile
3811 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3813 * @return array|string
3814 * @throws BadRequestException
3815 * @throws ForbiddenException
3816 * @throws ImagickException
3817 * @throws InternalServerErrorException
3818 * @throws UnauthorizedException
3820 function api_account_update_profile($type)
3822 $local_user = api_user();
3823 $api_user = api_get_user();
3825 if (!empty($_POST['name'])) {
3826 DBA::update('profile', ['name' => $_POST['name']], ['uid' => $local_user]);
3827 DBA::update('user', ['username' => $_POST['name']], ['uid' => $local_user]);
3828 Contact::update(['name' => $_POST['name']], ['uid' => $local_user, 'self' => 1]);
3829 Contact::update(['name' => $_POST['name']], ['id' => $api_user['id']]);
3832 if (isset($_POST['description'])) {
3833 DBA::update('profile', ['about' => $_POST['description']], ['uid' => $local_user]);
3834 Contact::update(['about' => $_POST['description']], ['uid' => $local_user, 'self' => 1]);
3835 Contact::update(['about' => $_POST['description']], ['id' => $api_user['id']]);
3838 Profile::publishUpdate($local_user);
3840 return api_account_verify_credentials($type);
3843 /// @TODO move to top of file or somewhere better
3844 api_register_func('api/account/update_profile', 'api_account_update_profile', true, API_METHOD_POST);
3848 * @param string $acl_string
3852 function check_acl_input($acl_string)
3854 if (empty($acl_string)) {
3858 $contact_not_found = false;
3860 // split <x><y><z> into array of cid's
3861 preg_match_all("/<[A-Za-z0-9]+>/", $acl_string, $array);
3863 // check for each cid if it is available on server
3864 $cid_array = $array[0];
3865 foreach ($cid_array as $cid) {
3866 $cid = str_replace("<", "", $cid);
3867 $cid = str_replace(">", "", $cid);
3868 $condition = ['id' => $cid, 'uid' => api_user()];
3869 $contact_not_found |= !DBA::exists('contact', $condition);
3871 return $contact_not_found;
3875 * @param string $mediatype
3876 * @param array $media
3877 * @param string $type
3878 * @param string $album
3879 * @param string $allow_cid
3880 * @param string $deny_cid
3881 * @param string $allow_gid
3882 * @param string $deny_gid
3883 * @param string $desc
3884 * @param integer $phototype
3885 * @param boolean $visibility
3886 * @param string $photo_id
3888 * @throws BadRequestException
3889 * @throws ForbiddenException
3890 * @throws ImagickException
3891 * @throws InternalServerErrorException
3892 * @throws NotFoundException
3893 * @throws UnauthorizedException
3895 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)
3903 if (is_array($media)) {
3904 if (is_array($media['tmp_name'])) {
3905 $src = $media['tmp_name'][0];
3907 $src = $media['tmp_name'];
3909 if (is_array($media['name'])) {
3910 $filename = basename($media['name'][0]);
3912 $filename = basename($media['name']);
3914 if (is_array($media['size'])) {
3915 $filesize = intval($media['size'][0]);
3917 $filesize = intval($media['size']);
3919 if (is_array($media['type'])) {
3920 $filetype = $media['type'][0];
3922 $filetype = $media['type'];
3926 $filetype = Images::getMimeTypeBySource($src, $filename, $filetype);
3929 "File upload src: " . $src . " - filename: " . $filename .
3930 " - size: " . $filesize . " - type: " . $filetype);
3932 // check if there was a php upload error
3933 if ($filesize == 0 && $media['error'] == 1) {
3934 throw new InternalServerErrorException("image size exceeds PHP config settings, file was rejected by server");
3936 // check against max upload size within Friendica instance
3937 $maximagesize = DI::config()->get('system', 'maximagesize');
3938 if ($maximagesize && ($filesize > $maximagesize)) {
3939 $formattedBytes = Strings::formatBytes($maximagesize);
3940 throw new InternalServerErrorException("image size exceeds Friendica config setting (uploaded size: $formattedBytes)");
3943 // create Photo instance with the data of the image
3944 $imagedata = @file_get_contents($src);
3945 $Image = new Image($imagedata, $filetype);
3946 if (!$Image->isValid()) {
3947 throw new InternalServerErrorException("unable to process image data");
3950 // check orientation of image
3951 $Image->orient($src);
3954 // check max length of images on server
3955 $max_length = DI::config()->get('system', 'max_image_length');
3956 if ($max_length > 0) {
3957 $Image->scaleDown($max_length);
3958 logger::info("File upload: Scaling picture to new size " . $max_length);
3960 $width = $Image->getWidth();
3961 $height = $Image->getHeight();
3963 // create a new resource-id if not already provided
3964 $resource_id = ($photo_id == null) ? Photo::newResource() : $photo_id;
3966 if ($mediatype == "photo") {
3967 // upload normal image (scales 0, 1, 2)
3968 logger::info("photo upload: starting new photo upload");
3970 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3972 logger::notice("photo upload: image upload with scale 0 (original size) failed");
3974 if ($width > 640 || $height > 640) {
3975 $Image->scaleDown(640);
3976 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3978 logger::notice("photo upload: image upload with scale 1 (640x640) failed");
3982 if ($width > 320 || $height > 320) {
3983 $Image->scaleDown(320);
3984 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3986 logger::notice("photo upload: image upload with scale 2 (320x320) failed");
3989 logger::info("photo upload: new photo upload ended");
3990 } elseif ($mediatype == "profileimage") {
3991 // upload profile image (scales 4, 5, 6)
3992 logger::info("photo upload: starting new profile image upload");
3994 if ($width > 300 || $height > 300) {
3995 $Image->scaleDown(300);
3996 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 4, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
3998 logger::notice("photo upload: profile image upload with scale 4 (300x300) failed");
4002 if ($width > 80 || $height > 80) {
4003 $Image->scaleDown(80);
4004 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 5, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4006 logger::notice("photo upload: profile image upload with scale 5 (80x80) failed");
4010 if ($width > 48 || $height > 48) {
4011 $Image->scaleDown(48);
4012 $r = Photo::store($Image, local_user(), $visitor, $resource_id, $filename, $album, 6, $phototype, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
4014 logger::notice("photo upload: profile image upload with scale 6 (48x48) failed");
4017 $Image->__destruct();
4018 logger::info("photo upload: new profile image upload ended");
4022 // create entry in 'item'-table on new uploads to enable users to comment/like/dislike the photo
4023 if ($photo_id == null && $mediatype == "photo") {
4024 post_photo_item($resource_id, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility);
4026 // on success return image data in json/xml format (like /api/friendica/photo does when no scale is given)
4027 return prepare_photo_data($type, false, $resource_id);
4029 throw new InternalServerErrorException("image upload failed");
4035 * @param string $hash
4036 * @param string $allow_cid
4037 * @param string $deny_cid
4038 * @param string $allow_gid
4039 * @param string $deny_gid
4040 * @param string $filetype
4041 * @param boolean $visibility
4042 * @throws InternalServerErrorException
4044 function post_photo_item($hash, $allow_cid, $deny_cid, $allow_gid, $deny_gid, $filetype, $visibility = false)
4046 // get data about the api authenticated user
4047 $uri = Item::newURI(intval(api_user()));
4048 $owner_record = DBA::selectFirst('contact', [], ['uid' => api_user(), 'self' => true]);
4051 $arr['guid'] = System::createUUID();
4052 $arr['uid'] = intval(api_user());
4054 $arr['type'] = 'photo';
4056 $arr['resource-id'] = $hash;
4057 $arr['contact-id'] = $owner_record['id'];
4058 $arr['owner-name'] = $owner_record['name'];
4059 $arr['owner-link'] = $owner_record['url'];
4060 $arr['owner-avatar'] = $owner_record['thumb'];
4061 $arr['author-name'] = $owner_record['name'];
4062 $arr['author-link'] = $owner_record['url'];
4063 $arr['author-avatar'] = $owner_record['thumb'];
4065 $arr['allow_cid'] = $allow_cid;
4066 $arr['allow_gid'] = $allow_gid;
4067 $arr['deny_cid'] = $deny_cid;
4068 $arr['deny_gid'] = $deny_gid;
4069 $arr['visible'] = $visibility;
4073 'image/jpeg' => 'jpg',
4074 'image/png' => 'png',
4075 'image/gif' => 'gif'
4078 // adds link to the thumbnail scale photo
4079 $arr['body'] = '[url=' . DI::baseUrl() . '/photos/' . $owner_record['nick'] . '/image/' . $hash . ']'
4080 . '[img]' . DI::baseUrl() . '/photo/' . $hash . '-' . "2" . '.'. $typetoext[$filetype] . '[/img]'
4083 // do the magic for storing the item in the database and trigger the federation to other contacts
4089 * @param string $type
4091 * @param string $photo_id
4094 * @throws BadRequestException
4095 * @throws ForbiddenException
4096 * @throws ImagickException
4097 * @throws InternalServerErrorException
4098 * @throws NotFoundException
4099 * @throws UnauthorizedException
4101 function prepare_photo_data($type, $scale, $photo_id)
4104 $user_info = api_get_user();
4106 if ($user_info === false) {
4107 throw new ForbiddenException();
4110 $scale_sql = ($scale === false ? "" : sprintf("AND scale=%d", intval($scale)));
4111 $data_sql = ($scale === false ? "" : "data, ");
4113 // added allow_cid, allow_gid, deny_cid, deny_gid to output as string like stored in database
4114 // clients needs to convert this in their way for further processing
4115 $r = DBA::toArray(DBA::p(
4116 "SELECT $data_sql `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4117 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`,
4118 MIN(`scale`) AS `minscale`, MAX(`scale`) AS `maxscale`
4119 FROM `photo` WHERE `uid` = ? AND `resource-id` = ? $scale_sql GROUP BY
4120 `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
4121 `type`, `height`, `width`, `datasize`, `profile`, `allow_cid`, `deny_cid`, `allow_gid`, `deny_gid`",
4127 'image/jpeg' => 'jpg',
4128 'image/png' => 'png',
4129 'image/gif' => 'gif'
4132 // prepare output data for photo
4133 if (DBA::isResult($r)) {
4134 $data = ['photo' => $r[0]];
4135 $data['photo']['id'] = $data['photo']['resource-id'];
4136 if ($scale !== false) {
4137 $data['photo']['data'] = base64_encode($data['photo']['data']);
4139 unset($data['photo']['datasize']); //needed only with scale param
4141 if ($type == "xml") {
4142 $data['photo']['links'] = [];
4143 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4144 $data['photo']['links'][$k . ":link"]["@attributes"] = ["type" => $data['photo']['type'],
4146 "href" => DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']]];
4149 $data['photo']['link'] = [];
4150 // when we have profile images we could have only scales from 4 to 6, but index of array always needs to start with 0
4152 for ($k = intval($data['photo']['minscale']); $k <= intval($data['photo']['maxscale']); $k++) {
4153 $data['photo']['link'][$i] = DI::baseUrl() . "/photo/" . $data['photo']['resource-id'] . "-" . $k . "." . $typetoext[$data['photo']['type']];
4157 unset($data['photo']['resource-id']);
4158 unset($data['photo']['minscale']);
4159 unset($data['photo']['maxscale']);
4161 throw new NotFoundException();
4164 // retrieve item element for getting activities (like, dislike etc.) related to photo
4165 $condition = ['uid' => api_user(), 'resource-id' => $photo_id];
4166 $item = Post::selectFirst(['id', 'uid', 'uri', 'parent', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'], $condition);
4167 if (!DBA::isResult($item)) {
4168 throw new NotFoundException('Photo-related item not found.');
4171 $data['photo']['friendica_activities'] = api_format_items_activities($item, $type);
4173 // retrieve comments on photo
4174 $condition = ["`parent` = ? AND `uid` = ? AND `gravity` IN (?, ?)",
4175 $item['parent'], api_user(), GRAVITY_PARENT, GRAVITY_COMMENT];
4177 $statuses = Post::selectForUser(api_user(), [], $condition);
4179 // prepare output of comments
4180 $commentData = api_format_items(Post::toArray($statuses), $user_info, false, $type);
4182 if ($type == "xml") {
4184 foreach ($commentData as $comment) {
4185 $comments[$k++ . ":comment"] = $comment;
4188 foreach ($commentData as $comment) {
4189 $comments[] = $comment;
4192 $data['photo']['friendica_comments'] = $comments;
4194 // include info if rights on photo and rights on item are mismatching
4195 $rights_mismatch = $data['photo']['allow_cid'] != $item['allow_cid'] ||
4196 $data['photo']['deny_cid'] != $item['deny_cid'] ||
4197 $data['photo']['allow_gid'] != $item['allow_gid'] ||
4198 $data['photo']['deny_gid'] != $item['deny_gid'];
4199 $data['photo']['rights_mismatch'] = $rights_mismatch;
4205 * Return an item with announcer data if it had been announced
4207 * @param array $item Item array
4208 * @return array Item array with announce data
4210 function api_get_announce($item)
4212 // Quit if the item already has got a different owner and author
4213 if ($item['owner-id'] != $item['author-id']) {
4217 // Don't change original or Diaspora posts
4218 if ($item['origin'] || in_array($item['network'], [Protocol::DIASPORA])) {
4222 // Quit if we do now the original author and it had been a post from a native network
4223 if (!empty($item['contact-uid']) && in_array($item['network'], Protocol::NATIVE_SUPPORT)) {
4227 $fields = ['author-id', 'author-name', 'author-link', 'author-avatar'];
4228 $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'vid' => Verb::getID(Activity::ANNOUNCE)];
4229 $announce = Post::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]);
4230 if (!DBA::isResult($announce)) {
4234 return array_merge($item, $announce);
4239 * @param array $item
4244 function api_in_reply_to($item)
4248 $in_reply_to['status_id'] = null;
4249 $in_reply_to['user_id'] = null;
4250 $in_reply_to['status_id_str'] = null;
4251 $in_reply_to['user_id_str'] = null;
4252 $in_reply_to['screen_name'] = null;
4254 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] != GRAVITY_PARENT)) {
4255 $parent = Post::selectFirst(['id'], ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
4256 if (DBA::isResult($parent)) {
4257 $in_reply_to['status_id'] = intval($parent['id']);
4259 $in_reply_to['status_id'] = intval($item['parent']);
4262 $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
4264 $fields = ['author-nick', 'author-name', 'author-id', 'author-link'];
4265 $parent = Post::selectFirst($fields, ['id' => $in_reply_to['status_id']]);
4267 if (DBA::isResult($parent)) {
4268 $in_reply_to['screen_name'] = (($parent['author-nick']) ? $parent['author-nick'] : $parent['author-name']);
4269 $in_reply_to['user_id'] = intval($parent['author-id']);
4270 $in_reply_to['user_id_str'] = (string) intval($parent['author-id']);
4273 // There seems to be situation, where both fields are identical:
4274 // https://github.com/friendica/friendica/issues/1010
4275 // This is a bugfix for that.
4276 if (intval($in_reply_to['status_id']) == intval($item['id'])) {
4277 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']]);
4278 $in_reply_to['status_id'] = null;
4279 $in_reply_to['user_id'] = null;
4280 $in_reply_to['status_id_str'] = null;
4281 $in_reply_to['user_id_str'] = null;
4282 $in_reply_to['screen_name'] = null;
4286 return $in_reply_to;
4291 * @param string $text
4294 * @throws InternalServerErrorException
4296 function api_clean_plain_items($text)
4298 $include_entities = strtolower($_REQUEST['include_entities'] ?? 'false');
4300 $text = BBCode::cleanPictureLinks($text);
4301 $URLSearchString = "^\[\]";
4303 $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
4305 if ($include_entities == "true") {
4306 $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
4309 // Simplify "attachment" element
4310 $text = BBCode::removeAttachment($text);
4317 * @param array $contacts
4321 function api_best_nickname(&$contacts)
4325 if (count($contacts) == 0) {
4329 foreach ($contacts as $contact) {
4330 if ($contact["network"] == "") {
4331 $contact["network"] = "dfrn";
4332 $best_contact = [$contact];
4336 if (sizeof($best_contact) == 0) {
4337 foreach ($contacts as $contact) {
4338 if ($contact["network"] == "dfrn") {
4339 $best_contact = [$contact];
4344 if (sizeof($best_contact) == 0) {
4345 foreach ($contacts as $contact) {
4346 if ($contact["network"] == "dspr") {
4347 $best_contact = [$contact];
4352 if (sizeof($best_contact) == 0) {
4353 foreach ($contacts as $contact) {
4354 if ($contact["network"] == "stat") {
4355 $best_contact = [$contact];
4360 if (sizeof($best_contact) == 0) {
4361 foreach ($contacts as $contact) {
4362 if ($contact["network"] == "pump") {
4363 $best_contact = [$contact];
4368 if (sizeof($best_contact) == 0) {
4369 foreach ($contacts as $contact) {
4370 if ($contact["network"] == "twit") {
4371 $best_contact = [$contact];
4376 if (sizeof($best_contact) == 1) {
4377 $contacts = $best_contact;
4379 $contacts = [$contacts[0]];
4384 * Return all or a specified group of the user with the containing contacts.
4386 * @param string $type Return type (atom, rss, xml, json)
4388 * @return array|string
4389 * @throws BadRequestException
4390 * @throws ForbiddenException
4391 * @throws ImagickException
4392 * @throws InternalServerErrorException
4393 * @throws UnauthorizedException
4395 function api_friendica_group_show($type)
4399 if (api_user() === false) {
4400 throw new ForbiddenException();
4404 $user_info = api_get_user();
4405 $gid = $_REQUEST['gid'] ?? 0;
4406 $uid = $user_info['uid'];
4408 // get data of the specified group id or all groups if not specified
4410 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid, 'id' => $gid]);
4412 // error message if specified gid is not in database
4413 if (!DBA::isResult($groups)) {
4414 throw new BadRequestException("gid not available");
4417 $groups = DBA::selectToArray('group', [], ['deleted' => false, 'uid' => $uid]);
4420 // loop through all groups and retrieve all members for adding data in the user array
4422 foreach ($groups as $rr) {
4423 $members = Contact\Group::getById($rr['id']);
4426 if ($type == "xml") {
4427 $user_element = "users";
4429 foreach ($members as $member) {
4430 $user = api_get_user($member['nurl']);
4431 $users[$k++.":user"] = $user;
4434 $user_element = "user";
4435 foreach ($members as $member) {
4436 $user = api_get_user($member['nurl']);
4440 $grps[] = ['name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users];
4442 return DI::apiResponse()->formatData("groups", $type, ['group' => $grps]);
4445 api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
4450 * @param string $type Return type (atom, rss, xml, json)
4452 * @return array|string
4453 * @throws BadRequestException
4454 * @throws ForbiddenException
4455 * @throws ImagickException
4456 * @throws InternalServerErrorException
4457 * @throws UnauthorizedException
4458 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-destroy
4460 function api_lists_destroy($type)
4464 if (api_user() === false) {
4465 throw new ForbiddenException();
4469 $user_info = api_get_user();
4470 $gid = $_REQUEST['list_id'] ?? 0;
4471 $uid = $user_info['uid'];
4473 // error if no gid specified
4475 throw new BadRequestException('gid not specified');
4478 // get data of the specified group id
4479 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4480 // error message if specified gid is not in database
4482 throw new BadRequestException('gid not available');
4485 if (Group::remove($gid)) {
4487 'name' => $group['name'],
4488 'id' => intval($gid),
4489 'id_str' => (string) $gid,
4490 'user' => $user_info
4493 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4497 api_register_func('api/lists/destroy', 'api_lists_destroy', true, API_METHOD_DELETE);
4500 * Add a new group to the database.
4502 * @param string $name Group name
4503 * @param int $uid User ID
4504 * @param array $users List of users to add to the group
4507 * @throws BadRequestException
4509 function group_create($name, $uid, $users = [])
4511 // error if no name specified
4513 throw new BadRequestException('group name not specified');
4516 // error message if specified group name already exists
4517 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => false])) {
4518 throw new BadRequestException('group name already exists');
4521 // Check if the group needs to be reactivated
4522 if (DBA::exists('group', ['uid' => $uid, 'name' => $name, 'deleted' => true])) {
4523 $reactivate_group = true;
4527 $ret = Group::create($uid, $name);
4529 $gid = Group::getIdByName($uid, $name);
4531 throw new BadRequestException('other API error');
4535 $erroraddinguser = false;
4537 foreach ($users as $user) {
4538 $cid = $user['cid'];
4539 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4540 Group::addMember($gid, $cid);
4542 $erroraddinguser = true;
4543 $errorusers[] = $cid;
4547 // return success message incl. missing users in array
4548 $status = ($erroraddinguser ? "missing user" : ((isset($reactivate_group) && $reactivate_group) ? "reactivated" : "ok"));
4550 return ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4554 * Create the specified group with the posted array of contacts.
4556 * @param string $type Return type (atom, rss, xml, json)
4558 * @return array|string
4559 * @throws BadRequestException
4560 * @throws ForbiddenException
4561 * @throws ImagickException
4562 * @throws InternalServerErrorException
4563 * @throws UnauthorizedException
4565 function api_friendica_group_create($type)
4569 if (api_user() === false) {
4570 throw new ForbiddenException();
4574 $user_info = api_get_user();
4575 $name = $_REQUEST['name'] ?? '';
4576 $uid = $user_info['uid'];
4577 $json = json_decode($_POST['json'], true);
4578 $users = $json['user'];
4580 $success = group_create($name, $uid, $users);
4582 return DI::apiResponse()->formatData("group_create", $type, ['result' => $success]);
4585 api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
4588 * Create a new group.
4590 * @param string $type Return type (atom, rss, xml, json)
4592 * @return array|string
4593 * @throws BadRequestException
4594 * @throws ForbiddenException
4595 * @throws ImagickException
4596 * @throws InternalServerErrorException
4597 * @throws UnauthorizedException
4598 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-create
4600 function api_lists_create($type)
4604 if (api_user() === false) {
4605 throw new ForbiddenException();
4609 $user_info = api_get_user();
4610 $name = $_REQUEST['name'] ?? '';
4611 $uid = $user_info['uid'];
4613 $success = group_create($name, $uid);
4614 if ($success['success']) {
4616 'name' => $success['name'],
4617 'id' => intval($success['gid']),
4618 'id_str' => (string) $success['gid'],
4619 'user' => $user_info
4622 return DI::apiResponse()->formatData("lists", $type, ['lists' => $grp]);
4626 api_register_func('api/lists/create', 'api_lists_create', true, API_METHOD_POST);
4629 * Update the specified group with the posted array of contacts.
4631 * @param string $type Return type (atom, rss, xml, json)
4633 * @return array|string
4634 * @throws BadRequestException
4635 * @throws ForbiddenException
4636 * @throws ImagickException
4637 * @throws InternalServerErrorException
4638 * @throws UnauthorizedException
4640 function api_friendica_group_update($type)
4644 if (api_user() === false) {
4645 throw new ForbiddenException();
4649 $user_info = api_get_user();
4650 $uid = $user_info['uid'];
4651 $gid = $_REQUEST['gid'] ?? 0;
4652 $name = $_REQUEST['name'] ?? '';
4653 $json = json_decode($_POST['json'], true);
4654 $users = $json['user'];
4656 // error if no name specified
4658 throw new BadRequestException('group name not specified');
4661 // error if no gid specified
4663 throw new BadRequestException('gid not specified');
4667 $members = Contact\Group::getById($gid);
4668 foreach ($members as $member) {
4669 $cid = $member['id'];
4670 foreach ($users as $user) {
4671 $found = ($user['cid'] == $cid ? true : false);
4673 if (!isset($found) || !$found) {
4674 $gid = Group::getIdByName($uid, $name);
4675 Group::removeMember($gid, $cid);
4680 $erroraddinguser = false;
4682 foreach ($users as $user) {
4683 $cid = $user['cid'];
4685 if (DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
4686 Group::addMember($gid, $cid);
4688 $erroraddinguser = true;
4689 $errorusers[] = $cid;
4693 // return success message incl. missing users in array
4694 $status = ($erroraddinguser ? "missing user" : "ok");
4695 $success = ['success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers];
4696 return DI::apiResponse()->formatData("group_update", $type, ['result' => $success]);
4699 api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
4702 * Update information about a group.
4704 * @param string $type Return type (atom, rss, xml, json)
4706 * @return array|string
4707 * @throws BadRequestException
4708 * @throws ForbiddenException
4709 * @throws ImagickException
4710 * @throws InternalServerErrorException
4711 * @throws UnauthorizedException
4712 * @see https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/post-lists-update
4714 function api_lists_update($type)
4718 if (api_user() === false) {
4719 throw new ForbiddenException();
4723 $user_info = api_get_user();
4724 $gid = $_REQUEST['list_id'] ?? 0;
4725 $name = $_REQUEST['name'] ?? '';
4726 $uid = $user_info['uid'];
4728 // error if no gid specified
4730 throw new BadRequestException('gid not specified');
4733 // get data of the specified group id
4734 $group = DBA::selectFirst('group', [], ['uid' => $uid, 'id' => $gid]);
4735 // error message if specified gid is not in database
4737 throw new BadRequestException('gid not available');
4740 if (Group::update($gid, $name)) {
4743 'id' => intval($gid),
4744 'id_str' => (string) $gid,
4745 'user' => $user_info
4748 return DI::apiResponse()->formatData("lists", $type, ['lists' => $list]);
4752 api_register_func('api/lists/update', 'api_lists_update', true, API_METHOD_POST);
4755 * Set notification as seen and returns associated item (if possible)
4757 * POST request with 'id' param as notification id
4759 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4760 * @return string|array
4761 * @throws BadRequestException
4762 * @throws ForbiddenException
4763 * @throws ImagickException
4764 * @throws InternalServerErrorException
4765 * @throws UnauthorizedException
4767 function api_friendica_notification_seen($type)
4770 $user_info = api_get_user();
4772 if (api_user() === false || $user_info === false) {
4773 throw new ForbiddenException();
4775 if (DI::args()->getArgc() !== 4) {
4776 throw new BadRequestException('Invalid argument count');
4779 $id = intval($_REQUEST['id'] ?? 0);
4782 $Notify = DI::notify()->selectOneById($id);
4783 if ($Notify->uid !== api_user()) {
4784 throw new NotFoundException();
4787 if ($Notify->uriId) {
4788 DI::notification()->setAllSeenForUser($Notify->uid, ['target-uri-id' => $Notify->uriId]);
4792 DI::notify()->save($Notify);
4794 if ($Notify->otype === Notification\ObjectType::ITEM) {
4795 $item = Post::selectFirstForUser(api_user(), [], ['id' => $Notify->iid, 'uid' => api_user()]);
4796 if (DBA::isResult($item)) {
4797 // we found the item, return it to the user
4798 $ret = api_format_items([$item], $user_info, false, $type);
4799 $data = ['status' => $ret];
4800 return DI::apiResponse()->formatData('status', $type, $data);
4802 // the item can't be found, but we set the notification as seen, so we count this as a success
4805 return DI::apiResponse()->formatData('result', $type, ['result' => 'success']);
4806 } catch (NotFoundException $e) {
4807 throw new BadRequestException('Invalid argument', $e);
4808 } catch (Exception $e) {
4809 throw new InternalServerErrorException('Internal Server exception', $e);
4813 /// @TODO move to top of file or somewhere better
4814 api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
4817 * search for direct_messages containing a searchstring through api
4819 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
4820 * @param string $box
4821 * @return string|array (success: success=true if found and search_result contains found messages,
4822 * success=false if nothing was found, search_result='nothing found',
4823 * error: result=error with error message)
4824 * @throws BadRequestException
4825 * @throws ForbiddenException
4826 * @throws ImagickException
4827 * @throws InternalServerErrorException
4828 * @throws UnauthorizedException
4830 function api_friendica_direct_messages_search($type, $box = "")
4834 if (api_user() === false) {
4835 throw new ForbiddenException();
4839 $user_info = api_get_user();
4840 $searchstring = $_REQUEST['searchstring'] ?? '';
4841 $uid = $user_info['uid'];
4843 // error if no searchstring specified
4844 if ($searchstring == "") {
4845 $answer = ['result' => 'error', 'message' => 'searchstring not specified'];
4846 return DI::apiResponse()->formatData("direct_messages_search", $type, ['$result' => $answer]);
4849 // get data for the specified searchstring
4850 $r = DBA::toArray(DBA::p(
4851 "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",
4853 '%'.$searchstring.'%'
4856 $profile_url = $user_info["url"];
4858 // message if nothing was found
4859 if (!DBA::isResult($r)) {
4860 $success = ['success' => false, 'search_results' => 'problem with query'];
4861 } elseif (count($r) == 0) {
4862 $success = ['success' => false, 'search_results' => 'nothing found'];
4865 foreach ($r as $item) {
4866 if ($box == "inbox" || $item['from-url'] != $profile_url) {
4867 $recipient = $user_info;
4868 $sender = api_get_user(Strings::normaliseLink($item['contact-url']));
4869 } elseif ($box == "sentbox" || $item['from-url'] == $profile_url) {
4870 $recipient = api_get_user(Strings::normaliseLink($item['contact-url']));
4871 $sender = $user_info;
4874 if (isset($recipient) && isset($sender)) {
4875 $ret[] = api_format_messages($item, $recipient, $sender);
4878 $success = ['success' => true, 'search_results' => $ret];
4881 return DI::apiResponse()->formatData("direct_message_search", $type, ['$result' => $success]);
4884 /// @TODO move to top of file or somewhere better
4885 api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
4888 * Number of comments
4890 * Bind comment numbers(friendica_comments: Int) on each statuses page of *_timeline / favorites / search
4892 * @param object $data [Status, Status]
4896 function bindComments(&$data)
4898 if (count($data) == 0) {
4904 foreach ($data as $item) {
4905 $ids[] = $item['id'];
4908 $idStr = DBA::escape(implode(', ', $ids));
4909 $sql = "SELECT `parent`, COUNT(*) as comments FROM `post-user-view` WHERE `parent` IN ($idStr) AND `deleted` = ? AND `gravity`= ? GROUP BY `parent`";
4910 $items = DBA::p($sql, 0, GRAVITY_COMMENT);
4911 $itemsData = DBA::toArray($items);
4913 foreach ($itemsData as $item) {
4914 $comments[$item['parent']] = $item['comments'];
4917 foreach ($data as $idx => $item) {
4919 $data[$idx]['friendica_comments'] = isset($comments[$id]) ? $comments[$id] : 0;
4924 @TODO Maybe open to implement?
4926 [pagename] => api/1.1/statuses/lookup.json
4927 [id] => 605138389168451584
4928 [include_cards] => true
4929 [cards_platform] => Android-12
4930 [include_entities] => true
4931 [include_my_retweet] => 1
4933 [include_reply_count] => true
4934 [include_descendent_reply_count] => true
4938 Not implemented by now:
4939 statuses/retweets_of_me
4944 account/update_location
4945 account/update_profile_background_image
4948 friendica/profile/update
4949 friendica/profile/create
4950 friendica/profile/delete
4952 Not implemented in status.net:
4953 statuses/retweeted_to_me
4954 statuses/retweeted_by_me
4955 direct_messages/destroy
4957 account/update_delivery_device
4958 notifications/follow